file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
WireEngine.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/WireEngine.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.matchconf; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Writes out the xml to configure the 'real' deduplication/matching process of this specific * {@link Wire} instance. */ public class WireEngine { Wire wire; private final String[] defaultFalseList = new String[] { "useInSelect", "useInNegativeSelect", "indexLength", "blanksMatch", "addOriginalQueryValue", "addOriginalAuthorityValue", "addTransformedQueryValue", "addTransformedAuthorityValue", "indexInitial", "useWildcard"}; public WireEngine(Wire wire) { this.wire = wire; } public ArrayList<String> toXML(int indentLevel) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { int shiftWidth = 4; String shift = String.format("%" + shiftWidth + "s", " "); String indent = ""; for (int i=0;i<indentLevel;i++) { indent += shift; } ArrayList<String> outXML = new ArrayList<String>(); outXML.add(String.format("%s<bean class=\"org.kew.rmf.core.configuration.Property\"", indent)); outXML.add(String.format("%s%sp:queryColumnName=\"%s\"", indent, shift, this.wire.getQueryColumnName())); if (this.wire.getAuthorityColumnName().length() > 0) { outXML.add(String.format("%s%sp:authorityColumnName=\"%s\"", indent, shift, this.wire.getAuthorityColumnName())); } // all boolean attributes default to false and we only want to write them if they are set to true for (String attr:this.defaultFalseList) { boolean value = (boolean) this.wire.getClass().getField(attr).get(this.wire); if (value) outXML.add(String.format("%s%sp:%s=\"%s\"", indent, shift, attr, value)); } outXML.add(String.format("%s%sp:matcher-ref=\"%s\">", indent, shift, this.wire.getMatcher().getName())); List<WiredTransformer> queryTransens = this.wire.getQueryTransformers(); if (queryTransens.size() > 0) { outXML.add(String.format("%s%s<property name=\"queryTransformers\">", indent, shift)); outXML.add(String.format("%s%s%s<util:list id=\"1\">", indent, shift, shift)); Collections.sort(queryTransens); for (WiredTransformer wTrans:queryTransens) { outXML.add(String.format("%s%s%s%s<ref bean=\"%s\"/>", indent, shift,shift, shift, wTrans.getTransformer().getName())); } outXML.add(String.format("%s%s%s</util:list>", indent, shift, shift)); outXML.add(String.format("%s%s</property>", indent, shift)); } List<WiredTransformer> authorityTransens = this.wire.getAuthorityTransformers(); if (authorityTransens.size() > 0) { outXML.add(String.format("%s%s<property name=\"authorityTransformers\">", indent, shift)); outXML.add(String.format("%s%s%s<util:list id=\"1\">", indent, shift, shift)); Collections.sort(authorityTransens); for (WiredTransformer wTrans:authorityTransens) { outXML.add(String.format("%s%s%s%s<ref bean=\"%s\"/>", indent, shift,shift, shift, wTrans.getTransformer().getName())); } outXML.add(String.format("%s%s%s</util:list>", indent, shift, shift)); outXML.add(String.format("%s%s</property>", indent, shift)); } outXML.add(String.format("%s</bean>", indent)); return outXML; } public ArrayList<String> toXML() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { return toXML(0); } }
4,471
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
Wire.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/Wire.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.matchconf; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import org.hibernate.annotations.Sort; import org.hibernate.annotations.SortType; import org.kew.rmf.matchconf.utils.GetterSetter; import org.springframework.roo.addon.javabean.RooJavaBean; import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord; import org.springframework.roo.addon.tostring.RooToString; /** * This is the ORM equivalent to any implementation of * {@link org.kew.rmf.core.configuration.Property}. * * It maps named columns to a {@link Matcher} per column and 0:n {@link Transformer}s per column. * It also takes care of dealing with the separation of query- and authority- {@link Transformer}s. * * The link to the Transformers is via {@link WiredTransformer}s. */ @RooJavaBean @RooToString @Table(uniqueConstraints = @javax.persistence.UniqueConstraint(columnNames = { "configuration", "queryColumnName", "authorityColumnName" })) @RooJpaActiveRecord(finders = { "findWiresByMatcher" }) public class Wire extends CloneMe<Wire> implements Comparable<Wire> { static String[] CLONE_STRING_FIELDS = new String[] { "authorityColumnName", "queryColumnName" }; static String[] CLONE_BOOL_FIELDS = new String[] { "addOriginalQueryValue", "addOriginalAuthorityValue", "addTransformedAuthorityValue", "addTransformedQueryValue", "blanksMatch", "indexInitial", "indexLength", "useInNegativeSelect", "useInSelect", "useWildcard" }; private String queryColumnName; private String authorityColumnName = ""; public Boolean useInSelect = false; public Boolean useInNegativeSelect = false; public Boolean indexLength = false; public Boolean blanksMatch = false; public Boolean addOriginalQueryValue = false; public Boolean addOriginalAuthorityValue = false; public Boolean addTransformedQueryValue = false; public Boolean addTransformedAuthorityValue = false; public Boolean indexInitial = false; public Boolean useWildcard = false; @ManyToOne private Matcher matcher; @ManyToOne private Configuration configuration; @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) @Sort(type = SortType.NATURAL) private List<WiredTransformer> queryTransformers = new ArrayList<WiredTransformer>(); @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) private List<WiredTransformer> authorityTransformers = new ArrayList<WiredTransformer>(); public String getName() { return this.getQueryColumnName() + "_" + this.getAuthorityColumnName(); } @Override public int compareTo(Wire w) { return this.getName().compareTo(w.getName()); } @Override public String toString() { return this.getName(); } public Wire cloneMe(Configuration configClone) throws Exception { Wire clone = new Wire(); // first the string attributes for (String method : Wire.CLONE_STRING_FIELDS) { clone.setattr(method, this.getattr(method, "")); } for (String method : Wire.CLONE_BOOL_FIELDS) { clone.setattr(method, this.getattr(method, true)); } // then the relational attributes clone.setConfiguration(configClone); clone.setMatcher(this.matcher.cloneMe(configClone)); for (WiredTransformer trans : this.getQueryTransformers()) { clone.getQueryTransformers().add(trans.cloneMe(configClone)); } for (WiredTransformer trans : this.getAuthorityTransformers()) { clone.getAuthorityTransformers().add(trans.cloneMe(configClone)); } return clone; } public WiredTransformer getWiredTransformer(String transformerType, String transformerName) throws Exception { for (WiredTransformer wT : new GetterSetter<List<WiredTransformer>>().getattr(this, transformerType + "Transformers")) { if (wT.getName().equals(transformerName)) return wT; } ; return null; } public WiredTransformer getQueryTransformerForName(String wiredTransformerName) { for (WiredTransformer wiredTransformer : this.getQueryTransformers()) { if (wiredTransformer.getName().equals(wiredTransformerName)) return wiredTransformer; } return null; } public WiredTransformer getAuthorityTransformerForName(String wiredTransformerName) { for (WiredTransformer wiredTransformer : this.getAuthorityTransformers()) { if (wiredTransformer.getName().equals(wiredTransformerName)) return wiredTransformer; } return null; } }
5,529
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
DictionaryEngine.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/DictionaryEngine.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.matchconf; import java.util.ArrayList; /** * Writes out the xml to configure the 'real' deduplication/matching process of this specific * {@link Dictionary} instance. */ public class DictionaryEngine { Dictionary dict; public DictionaryEngine(Dictionary dict) { this.dict = dict; } public ArrayList<String> toXML(int indentLevel) throws Exception { int shiftWidth = 4; String shift = String.format("%" + shiftWidth + "s", " "); String indent = ""; for (int i=0;i<indentLevel;i++) { indent += shift; } ArrayList<String> outXML = new ArrayList<String>(); outXML.add(String.format("%s<bean id=\"%s\" class=\"org.kew.rmf.utils.CsvDictionary\"", indent, this.dict.getName())); outXML.add(String.format("%s%sp:fileDelimiter=\"%s\"", indent, shift, this.dict.getFileDelimiter())); // change path to unix-style for convencience, even if on windows.. outXML.add(String.format("%s%sp:filePath=\"%s\" />", indent, shift, this.dict.getFilePath().replace("\\\\", "/"))); return outXML; } }
1,809
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
BotEngine.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/BotEngine.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.matchconf; import java.util.ArrayList; /** * Writes out the xml to configure the 'real' deduplication/matching process of this specific * <?extends {@link Bot}> instance. */ public class BotEngine { Bot bot; public BotEngine(Bot bot) { this.bot = bot; } /** * Write out nicely formatted xml containing all necessary details for this instance. * * @param indentLevel * @return * @throws Exception */ public ArrayList<String> toXML(int indentLevel) throws Exception { int shiftWidth = 4; String shift = String.format("%" + shiftWidth + "s", " "); String indent = ""; for (int i=0;i<indentLevel;i++) { indent += shift; } ArrayList<String> outXML = new ArrayList<String>(); if (this.bot.getComposedBy().size() > 0) { outXML.add(String.format("%s<bean id=\"%s\" class=\"%s.%s\">", indent, this.bot.getName(), this.bot.getPackageName(), this.bot.getClassName())); outXML.add(String.format("%s%s<property name=\"%s\">", indent, shift, this.bot.getGroup())); outXML.add(String.format("%s%s%s<util:list id=\"1\">", indent, shift, shift)); for (Bot bot:this.bot.getComposedBy()) { outXML.addAll(new BotEngine(bot).toXML(indentLevel+3)); } outXML.add(String.format("%s%s%s</util:list>", indent, shift, shift)); outXML.add(String.format("%s%s</property>", indent, shift)); outXML.add(String.format("%s</bean>", indent)); } else { if (this.bot.getParams().length() > 0) { outXML.add(String.format("%s<bean id=\"%s\" class=\"%s.%s\"", indent, this.bot.getName(), this.bot.getPackageName(), this.bot.getClassName())); for (String param:this.bot.getParams().split(",")) { String key, value; String[] paramTuple = param.split("="); if (paramTuple.length != 2) { throw new Exception(String.format("Wrong params configuration for %s -- params format has to be like < param1=value1, param2=value2, ..>, but was: < %s >)", this.bot.getName(), this.bot.getParams())); } key = paramTuple[0].trim(); value = paramTuple[1].trim().replaceAll("(\"$)|(^\")", ""); // replace surounding quotes on the values of the params if ((this.bot.getClassName().contains("Dict") || this.bot.getClassName().contains("LevenshteinMatcher")) && key.equals("dict")) { outXML.add(String.format("%s%sp:dict-ref=\"%s\"", indent, shift, value)); } else outXML.add(String.format("%s%sp:%s=\"%s\"", indent, shift, key, value)); } outXML.set(outXML.size()-1, outXML.get(outXML.size()-1) + "/>"); } else { outXML.add(String.format("%s<bean id=\"%s\" class=\"%s.%s\" />", indent, this.bot.getName(), this.bot.getPackageName(), this.bot.getClassName())); } } return outXML; } public ArrayList<String> toXML() throws Exception { return toXML(0); } }
3,531
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
Transformer.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/Transformer.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.matchconf; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; import javax.persistence.UniqueConstraint; import org.hibernate.annotations.Sort; import org.hibernate.annotations.SortType; import org.springframework.roo.addon.javabean.RooJavaBean; import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord; import org.springframework.roo.addon.tostring.RooToString; /** * This is the ORM equivalent to any implementation of * {@link org.kew.rmf.transformers.Transformer}. * * It can describe any matcher, the provided params are expected to be a comma-separated * String of key=value pairs. */ @RooJavaBean @RooToString @RooJpaActiveRecord() @Table(uniqueConstraints=@UniqueConstraint(columnNames={"configuration", "name"})) public class Transformer extends Bot { private String name; private String packageName; private String className; private String params; @Transient private final String group = "transformers"; @ManyToMany(cascade = CascadeType.ALL) @Sort(type=SortType.NATURAL) private List<Transformer> composedBy = new ArrayList<>(); @ManyToOne private Configuration configuration; public String toString () { return this.getName(); } public Transformer cloneMe(Configuration configClone) throws Exception { Transformer alreadyCloned = configClone.getTransformerForName(this.name); if (alreadyCloned != null) return alreadyCloned; Transformer clone = new Transformer(); // first the string attributes for (String method:Bot.CLONE_STRING_FIELDS) { clone.setattr(method, this.getattr(method, "")); } // then the relational attributes clone.setConfiguration(configClone); for (Transformer component:this.composedBy) { Transformer compoClone = component.cloneMe(configClone); clone.getComposedBy().add(compoClone); } return clone; } /** * Helper method to deal with the problem of orphaned WiredTransformer instances. * If this problem is sorted please delete! * * @throws Exception */ public void removeWiredTransformers() throws Exception { try { this.removeWiredTransformersLongWay(); } catch (Exception e) { if (e instanceof Exception) { throw new Exception(String.format("It seems that %s is still being used in a wire, please remove it there first in order to delete it.", this)); } } } /** * Helper method to deal with the problem of orphaned WiredTransformer instances. * If this problem is sorted please delete! */ public Wire hasWiredTransformers() { for (Wire wire:this.getConfiguration().getWiring()) { for (WiredTransformer wt:wire.getQueryTransformers()) { if (wt.getTransformer().getName().equals(this.getName())) { return wire; } } for (WiredTransformer wt:wire.getAuthorityTransformers()) { if (wt.getTransformer().getName().equals(this.getName())) { return wire; } } } return null; } /** * Helper method to deal with the problem of orphaned WiredTransformer instances. * If this problem is sorted please delete! */ public void removeOrphanedWiredTransformers() { List<WiredTransformer> all_wts = WiredTransformer.findAllWiredTransformers(); for (WiredTransformer wt:all_wts) { try { if (wt.getTransformer().getName().equals(this.getName())) { if (wt.isWireOrphan()) { logger.warn("Still found orphaned WiredTransformer with id {}!!! trying to remove..", wt.getId()); wt.remove(); logger.info("Released orphaned WiredTransformer into, er, liberty."); } } } catch (Exception e) { if (wt.getTransformer() == null) { logger.warn("Still found orphaned WiredTransformer with id {}!!! trying to remove..", wt.getId()); wt.remove(); logger.info("Released orphaned WiredTransformer into, er, liberty."); } else throw e; } } } /** * Helper method to deal with the problem of orphaned WiredTransformer instances. * If this problem is sorted please delete! */ public void removeWiredTransformersLongWay() { List<WiredTransformer> wts; for (Wire wire:this.getConfiguration().getWiring()) { wts = wire.getQueryTransformers(); for (WiredTransformer wt:new ArrayList<WiredTransformer>(wts)) { if (wt.getTransformer().getName().equals(this.getName())) { wts.remove(wt); } } wts = wire.getAuthorityTransformers(); for (WiredTransformer wt:new ArrayList<WiredTransformer>(wts)) { if (wt.getTransformer().getName().equals(this.getName())) wts.remove(wt); } wire.merge(); } } @Override public String getGroup() { return group; } }
6,261
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
CloneMe.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/CloneMe.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.matchconf; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import javax.persistence.MappedSuperclass; import javax.persistence.PostRemove; import javax.persistence.PreRemove; import org.kew.rmf.matchconf.utils.GetterSetter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.roo.addon.javabean.RooJavaBean; import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord; import org.springframework.roo.addon.tostring.RooToString; /** * Think of this abstract class as if it provided an abstract method 'cloneMe', I didn't get it * working explicitely due to some conflicts between generics, raw types and the way the ORM is * built, but this is how it's used. * * @param <T> */ @RooJavaBean @RooToString @MappedSuperclass @RooJpaActiveRecord(mappedSuperclass=true) public abstract class CloneMe<T> { protected static Logger logger = LoggerFactory.getLogger(CloneMe.class); public int getattr(String fieldName) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { return new GetterSetter<Integer>().getattr(this, fieldName); } public Boolean getattr(String fieldName, Boolean b) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { return new GetterSetter<Boolean>().getattr(this, fieldName); } public String getattr(String fieldName, String s) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { return new GetterSetter<String>().getattr(this, fieldName); } public void setattr(String fieldName, int n) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { new GetterSetter<Integer>().setattr(this, fieldName, n);; } public void setattr(String fieldName, Boolean b) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { new GetterSetter<Boolean>().setattr(this, fieldName, b); } public void setattr(String fieldName, String s) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { if (s!= null) new GetterSetter<String>().setattr(this, fieldName, s); } // conflict of Generics, inheritance and spring roo as far as I understand; have moved this method out of Roo's way, // not using it anyway public static List<CloneMe<Object>> findAllCloneMes() { return new ArrayList<CloneMe<Object>>(); } // conflict of Generics, inheritance and spring roo as far as I understand; have moved this method out of Roo's way, // not using it anyway public static List<CloneMe<Object>> findCloneMeEntries(int firstResult, int maxResults) { return new ArrayList<CloneMe<Object>>(); } @PreRemove public void loggPreRemoval() { logger.warn("Attempt to delete {} with id {}", this, this.getId()); } @PostRemove public void loggRemoval() { logger.info("Deleted {}", this); } }
4,070
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
Matcher.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/Matcher.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.matchconf; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; import javax.persistence.UniqueConstraint; import org.hibernate.annotations.Sort; import org.hibernate.annotations.SortType; import org.springframework.roo.addon.javabean.RooJavaBean; import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord; import org.springframework.roo.addon.tostring.RooToString; /** * This is the ORM equivalent to any implementation of * {@link org.kew.rmf.matchers.Matcher}. * * It can describe any matcher, the provided params are expected to be a comma-separated * String of key=value pairs. */ @RooJavaBean @RooToString @RooJpaActiveRecord @Table(uniqueConstraints=@UniqueConstraint(columnNames={"configuration", "name"})) public class Matcher extends Bot { private String name; private String packageName; private String className; private String params; @Transient private final String group = "matchers"; @ManyToMany(cascade = CascadeType.ALL) @Sort(type=SortType.NATURAL) private List<Matcher> composedBy = new ArrayList<Matcher>(); @ManyToOne private Configuration configuration; public String toString () { return this.getName(); } public Matcher cloneMe(Configuration configClone) throws Exception { Matcher alreadyCloned = configClone.getMatcherForName(this.name); if (alreadyCloned != null) return alreadyCloned; Matcher clone = new Matcher(); // first the string attributes for (String method:Bot.CLONE_STRING_FIELDS) { clone.setattr(method, this.getattr(method, "")); } // then the relational attributes clone.setConfiguration(configClone); for (Matcher component:this.composedBy) { Matcher compoClone = component.cloneMe(configClone); clone.getComposedBy().add(compoClone); } return clone; } @Override public String getGroup() { return group; } }
2,932
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
ReporterEngine.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/ReporterEngine.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.matchconf; import java.util.ArrayList; /** * Writes out the xml to configure the 'real' deduplication/matching process of this specific * {@link Reporter} instance. */ public class ReporterEngine { Reporter reporter; public ReporterEngine(Reporter reporter) { this.reporter = reporter; } public ArrayList<String> toXML(int indentLevel) { int shiftWidth = 4; String shift = String.format("%" + shiftWidth + "s", " "); String indent = ""; for (int i=0;i<indentLevel;i++) { indent += shift; } ArrayList<String> outXML = new ArrayList<String>(); outXML.add(String.format("%s<bean class=\"%s.%s\"", indent, this.reporter.getPackageName(), this.reporter.getClassName())); outXML.add(String.format("%s%sp:name=\"%s\"", indent, shift, this.reporter.getName())); outXML.add(String.format("%s%sp:configName=\"%s\"", indent, shift, this.reporter.getConfig().getName())); // nameSpacePrefix: if not overwritten on reporter-level... if (!this.reporter.getParams().contains("nameSpacePrefix")) { // ..check if it's a dedup config.. if (this.reporter.getConfig().getClassName().equals("DeduplicationConfiguration")) { // and tell it to name-space with the dedup-config's name outXML.add(String.format("%s%sp:nameSpacePrefix=\"%s_\"", indent, shift, this.reporter.getConfig().getName())); } } outXML.add(String.format("%s%sp:delimiter=\"%s\"", indent, shift, this.reporter.getDelimiter())); outXML.add(String.format("%s%sp:idDelimiter=\"%s\"", indent, shift, this.reporter.getIdDelimiter())); if (this.reporter.getParams().length() > 0) { for (String param:this.reporter.getParams().split(",")) { String key, value; String[] paramTuple = param.split("="); key = paramTuple[0]; value = paramTuple[1]; outXML.add(String.format("%s%sp:%s=\"%s\"", indent, shift, key, value)); } } outXML.set(outXML.size()-1, outXML.get(outXML.size()-1) + ">"); outXML.add(String.format("%s%s<property name=\"file\">", indent, shift)); outXML.add(String.format("%s%s%s<bean class=\"java.io.File\">", indent, shift, shift)); // change path to unix-style for convencience, even if on windows.. String rPath = String.format("%s/%s_%s", this.reporter.getConfig().getWorkDirPath(), this.reporter.getConfig().getName(), this.reporter.getFileName()).replace("\\\\", "/"); outXML.add(String.format("%s%s%s%s<constructor-arg value=\"%s\" />", indent, shift, shift, shift, rPath)); outXML.add(String.format("%s%s%s</bean>", indent, shift, shift)); outXML.add(String.format("%s%s</property>", indent, shift)); outXML.add(String.format("%s</bean>", indent)); return outXML; } public ArrayList<String> toXML() { return toXML(0); } }
3,853
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
GetterSetter.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/utils/GetterSetter.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.matchconf.utils; import java.lang.reflect.InvocationTargetException; import org.apache.commons.lang3.StringUtils; /** * A helper class to get and set attributes via conventional getField and setField methods * using generics. * * @param <ReturnType> */ public class GetterSetter<ReturnType> { @SuppressWarnings("unchecked") public <ObjClass> ReturnType getattr(ObjClass obj, String fieldName) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { String method = "get" + StringUtils.capitalize(fieldName); return (ReturnType) obj.getClass().getMethod(method).invoke(obj); } public <T> void setattr(T obj, String fieldName, int n) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { String method = "set" + StringUtils.capitalize(fieldName); obj.getClass().getMethod(method, int.class).invoke(obj, n); } public <T> void setattr(T obj, String fieldName, ReturnType b) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { String method = "set" + StringUtils.capitalize(fieldName); obj.getClass().getMethod(method, b.getClass()).invoke(obj, b); } }
2,125
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
WiredTransformerController.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/web/WiredTransformerController.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.matchconf.web; import org.kew.rmf.matchconf.WiredTransformer; import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @RequestMapping("/wiredtransformers") @Controller @RooWebScaffold(path = "wiredtransformers", formBackingObject = WiredTransformer.class) public class WiredTransformerController { }
1,210
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
LibraryScanner.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/web/LibraryScanner.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.matchconf.web; import java.lang.reflect.Modifier; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import org.kew.rmf.matchers.Matcher; import org.kew.rmf.reporters.Reporter; import org.kew.rmf.transformers.Transformer; import org.reflections.Reflections; /** * The LibraryScanner finds Transformers, Matchers and Reporters and produces a map that groups the classes in packages. */ public class LibraryScanner { /** * Produces a map that groups the classes in packages. */ public static Map<String, Map<String, Set<String>>> availableItems() { Map<String, Map<String, Set<String>>> items = new TreeMap<>(); items.put("matchers", classesImplementingInterface(Matcher.class)); items.put("transformers", classesImplementingInterface(Transformer.class)); items.put("reporters", classesImplementingInterface(Reporter.class)); return items; } private static Map<String, Set<String>> classesImplementingInterface(Class<?> ınterface) { Map<String, Set<String>> classesByPackage = new TreeMap<>(); Reflections reflections = new Reflections(ınterface.getPackage().getName()); for (Class<?> clazz : reflections.getSubTypesOf(ınterface)) { if (Modifier.isAbstract(clazz.getModifiers())) continue; String packageName = clazz.getPackage().getName(); if (classesByPackage.get(packageName) == null) classesByPackage.put(packageName, new TreeSet<String>()); classesByPackage.get(packageName).add(clazz.getSimpleName()); } return classesByPackage; } }
2,308
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
package-info.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/web/package-info.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * This package contains the controllers for the matchconf-UI. You will notice * that most of them are called Custom*.java, the Custom one being the one used * as the original <Classname>Controller was created by Spring Roo and had to be * customized. * * As Roo (given a roo shell is running) automatically updates the controllers * after changes to the model it was convenient to keep the original * <Classname>Controller classes. * * There is not documentation on most of them as it was to boring to document each * delete, create, update, updateForm, show, list, populateEditForm, * encodeUrlPathSegment, .. They all repeat for each controller, read the * documentations for spring based web applications and spring roo. * * A major change I have made is to change the default id-based url-mapping to a * name- or slug-based one. This seems to be much more eye friendly. * * Sometimes I added 'deleteByid', which is a work-around to delete entities based on * their id rather than their name (this should be considered as deprecated now), * and 'customValidation' which is a form validation specific to each controller. */ package org.kew.rmf.matchconf.web;
1,937
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
MatcherController.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/web/MatcherController.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.matchconf.web; import org.kew.rmf.matchconf.Matcher; import org.kew.rmf.matchconf.Wire; import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @RequestMapping("/matchers") @Controller @RooWebScaffold(path = "matchers", formBackingObject = Matcher.class) public class MatcherController { void populateEditForm(Model uiModel, Matcher matcher) { uiModel.addAttribute("matcher", matcher); uiModel.addAttribute("matchers", Matcher.findAllMatchers()); uiModel.addAttribute("wires", Wire.findAllWires()); } }
1,483
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
ConfigurationController.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/web/ConfigurationController.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.matchconf.web; import org.kew.rmf.matchconf.Configuration; import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @RequestMapping("/configurations") @Controller @RooWebScaffold(path = "configurations", formBackingObject = Configuration.class) public class ConfigurationController { }
1,195
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
CustomMatcherController.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/web/CustomMatcherController.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.matchconf.web; import java.io.UnsupportedEncodingException; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.kew.rmf.matchconf.Configuration; import org.kew.rmf.matchconf.Matcher; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.util.UriUtils; import org.springframework.web.util.WebUtils; @Controller public class CustomMatcherController { // GET: matcher creation form for this configuration @RequestMapping(value="/{configType}_configs/{configName}/matchers", params = "form", produces = "text/html") public String createForm(@PathVariable("configType") String configType, @PathVariable("configName") String configName, Model uiModel, @RequestParam(value = "className", required = false) String className, @RequestParam(value = "packageName", required = false) String packageName) { Matcher instance = new Matcher(); instance.setPackageName(packageName); instance.setClassName(className); populateEditForm(uiModel, configType, configName, instance); return "config_matchers/create"; } // POST to create an object and add it to this configuration @RequestMapping(value="/{configType}_configs/{configName}/matchers", method = RequestMethod.POST, produces = "text/html") public String create(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @Valid Matcher matcher, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) { Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult(); // assert unique_together:config&name if (config.getMatcherForName(matcher.getName()) != null) { bindingResult.addError(new ObjectError("matcher.name", "There is already a Matcher set up for this configuration with this name.")); } this.customValidation(configName, matcher, bindingResult); if (bindingResult.hasErrors()) { populateEditForm(uiModel, configType, configName, matcher); return "config_matchers/create"; } uiModel.asMap().clear(); matcher.setConfiguration(config); matcher.persist(); config.getMatchers().add(matcher); config.merge(); return "redirect:/{configType}_configs/" + encodeUrlPathSegment(configName, httpServletRequest) + "/matchers/" + encodeUrlPathSegment(matcher.getName(), httpServletRequest); } // GET indiviual matcher level @RequestMapping(value="/{configType}_configs/{configName}/matchers/{matcherName}", produces = "text/html") public String show(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @PathVariable("matcherName") String matcherName, Model uiModel) { uiModel.addAttribute("availableItems", LibraryScanner.availableItems()); Matcher matcher = Configuration.findConfigurationsByNameEquals(configName).getSingleResult().getMatcherForName(matcherName); uiModel.addAttribute("matcher", matcher); uiModel.addAttribute("itemId", matcher.getName()); uiModel.addAttribute("configName", configName); return "config_matchers/show"; } // GET list of matchers for this config @RequestMapping(value="/{configType}_configs/{configName}/matchers", produces = "text/html") public String list(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) { uiModel.addAttribute("availableItems", LibraryScanner.availableItems()); List<Matcher> matchers = Configuration.findConfigurationsByNameEquals(configName).getSingleResult().getMatchers(); if (page != null || size != null) { int sizeNo = Math.min(size == null ? 10 : size.intValue(), matchers.size()); final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo; uiModel.addAttribute("matchers", matchers.subList(firstResult, sizeNo)); float nrOfPages = (float) Matcher.countMatchers() / sizeNo; uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages)); } else { uiModel.addAttribute("matchers", matchers); } uiModel.addAttribute("configName", configName); return "config_matchers/list"; } // GET the update form for a specific matcher @RequestMapping(value="/{configType}_configs/{configName}/matchers/{matcherName}", params = "form", produces = "text/html") public String updateForm(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @PathVariable("matcherName") String matcherName, Model uiModel) { Matcher matcher = Configuration.findConfigurationsByNameEquals(configName).getSingleResult().getMatcherForName(matcherName); populateEditForm(uiModel, configType, configName, matcher); return "config_matchers/update"; } // PUT: update a specific matcher @RequestMapping(value="/{configType}_configs/{configName}/matchers", method = RequestMethod.PUT, produces = "text/html") public String update(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @Valid Matcher matcher, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) { this.customValidation(configName, matcher, bindingResult); if (bindingResult.hasErrors()) { populateEditForm(uiModel, configType, configName, matcher); return "config_matchers/update"; } uiModel.asMap().clear(); matcher.setConfiguration(Configuration.findConfigurationsByNameEquals(configName).getSingleResult()); matcher.merge(); return "redirect:/{configType}_configs/" + encodeUrlPathSegment(configName, httpServletRequest) + "/matchers/" + encodeUrlPathSegment(matcher.getName(), httpServletRequest); } // DELETE a specific matcher from a collection's list @RequestMapping(value="/{configType}_configs/{configName}/matchers/{matcherName}", method = RequestMethod.DELETE, produces = "text/html") public String delete(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @PathVariable("matcherName") String matcherName, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) { Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult(); config.removeMatcher(matcherName); uiModel.asMap().clear(); uiModel.addAttribute("page", (page == null) ? "1" : page.toString()); uiModel.addAttribute("size", (size == null) ? "10" : size.toString()); return "redirect:/{configType}_configs/" + configName.toString() + "/matchers/"; } // DELETE by id @RequestMapping(value="/{configType}_configs/{configName}/matchers/delete-by-id/{id}", method = RequestMethod.DELETE, produces = "text/html") public String deleteById(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @PathVariable("id") long id, Model uiModel) { Matcher toDelete = Matcher.findMatcher(id); Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult(); config.getMatchers().remove(toDelete); config.merge(); return "redirect:/{configType}_configs/" + configName.toString() + "/matchers/"; } void populateEditForm(Model uiModel, String configType, String configName, Matcher matcher) { uiModel.addAttribute("availableItems", LibraryScanner.availableItems()); Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult(); List<Matcher> matchers = config.getMatchers(); matchers.remove(matcher); uiModel.addAttribute("matcher", matcher); uiModel.addAttribute("matchers", matchers); uiModel.addAttribute("configType", configType); uiModel.addAttribute("configName", configName); } String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) { String enc = httpServletRequest.getCharacterEncoding(); if (enc == null) { enc = WebUtils.DEFAULT_CHARACTER_ENCODING; } try { pathSegment = UriUtils.encodePathSegment(pathSegment, enc); } catch (UnsupportedEncodingException uee) {} return pathSegment; } public void customValidation (String configName, Matcher matcher, BindingResult br) { if (!FieldValidator.validSlug(matcher.getName())) { br.addError(new ObjectError("matcher.name", "The name has to be set and can only contain ASCII letters and/or '-' and/or '_'")); } } }
10,336
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
FieldValidator.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/web/FieldValidator.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.matchconf.web; import org.apache.commons.lang3.StringUtils; public class FieldValidator { /** * We use many strings as part of the REST-ish url structure; * These only want to contain ASCII letters and/or '-', '_' * @param s * @return */ public static boolean validSlug(String s) { return !StringUtils.isBlank(s) && s.matches("[\\w-_]*"); } }
1,163
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
TransformerController.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/web/TransformerController.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.matchconf.web; import org.kew.rmf.matchconf.Transformer; import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @RequestMapping("/transformers") @Controller @RooWebScaffold(path = "transformers", formBackingObject = Transformer.class) public class TransformerController { void populateEditForm(Model uiModel, Transformer transformer) { uiModel.addAttribute("transformer", transformer); uiModel.addAttribute("transformers", Transformer.findAllTransformers()); } }
1,436
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
CustomReporterController.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/web/CustomReporterController.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.matchconf.web; import java.io.UnsupportedEncodingException; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.kew.rmf.matchconf.Configuration; import org.kew.rmf.matchconf.Reporter; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.util.UriUtils; import org.springframework.web.util.WebUtils; @Controller public class CustomReporterController { @RequestMapping(value="/{configType}_configs/{configName}/reporters", params = "form", produces = "text/html") public String createForm(@PathVariable("configType") String configType, @PathVariable("configName") String configName, Model uiModel, @RequestParam(value = "className", required = false) String className, @RequestParam(value = "packageName", required = false) String packageName) { Reporter instance = new Reporter(); instance.setPackageName(packageName); instance.setClassName(className); populateEditForm(uiModel, configType, configName, instance); return "config_reporters/create"; } // Default Post @RequestMapping(value="/{configType}_configs/{configName}/reporters", method = RequestMethod.POST, produces = "text/html") public String create(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @Valid Reporter reporter, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) { // assert unique_together:config&name if (Configuration.findConfigurationsByNameEquals(configName).getSingleResult().getReporterForName(reporter.getName()) != null) { bindingResult.addError(new ObjectError("reporter.name", "There is already a LuceneReporter set up for this configuration with this name.")); } this.customValidation(configName, reporter, bindingResult); if (bindingResult.hasErrors()) { populateEditForm(uiModel, configType, configName, reporter); return "config_reporters/create"; } uiModel.asMap().clear(); Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult(); reporter.setConfig(config); reporter.persist(); config.getReporters().add(reporter); config.merge(); return String.format("redirect:/%s_configs/", configType) + encodeUrlPathSegment(configName, httpServletRequest) + "/reporters/" + encodeUrlPathSegment(reporter.getName(), httpServletRequest); } // default GET indiviual reporter level @RequestMapping(value="/{configType}_configs/{configName}/reporters/{reporterName}", produces = "text/html") public String show(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @PathVariable("reporterName") String reporterName, Model uiModel) { uiModel.addAttribute("availableItems", LibraryScanner.availableItems()); Reporter reporter = Configuration.findConfigurationsByNameEquals(configName).getSingleResult().getReporterForName(reporterName); uiModel.addAttribute("reporter", reporter); uiModel.addAttribute("itemId", reporter.getName()); uiModel.addAttribute("configName", configName); uiModel.addAttribute("transformers", reporter.getConfig().getTransformers()); return "config_reporters/show"; } @RequestMapping(value="/{configType}_configs/{configName}/reporters", produces = "text/html") public String list(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) { uiModel.addAttribute("availableItems", LibraryScanner.availableItems()); List<Reporter> reporters = Configuration.findConfigurationsByNameEquals(configName).getSingleResult().getReporters(); if (page != null || size != null) { int sizeNo = Math.min(size == null ? 10 : size.intValue(), reporters.size()); final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo; uiModel.addAttribute("reporters", reporters.subList(firstResult, sizeNo)); float nrOfPages = (float) reporters.size() / sizeNo; uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages)); } else { uiModel.addAttribute("reporters", reporters); } uiModel.addAttribute("configName", configName); return "config_reporters/list"; } @RequestMapping(value="/{configType}_configs/{configName}/reporters", method = RequestMethod.PUT, produces = "text/html") public String update(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @Valid Reporter reporter, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) { this.customValidation(configName, reporter, bindingResult); if (bindingResult.hasErrors()) { populateEditForm(uiModel, configType, configName, reporter); return String.format("%s_config_reporters/update", configType); } uiModel.asMap().clear(); reporter.setConfig(Configuration.findConfigurationsByNameEquals(configName).getSingleResult()); reporter.merge(); return String.format("redirect:/%s_configs/", configType) + encodeUrlPathSegment(configName, httpServletRequest) + "/reporters/" + encodeUrlPathSegment(reporter.getName(), httpServletRequest); } @RequestMapping(value="/{configType}_configs/{configName}/reporters/{reporterName}", params = "form", produces = "text/html") public String updateForm(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @PathVariable("reporterName") String reporterName, Model uiModel) { Reporter reporter = Configuration.findConfigurationsByNameEquals(configName).getSingleResult().getReporterForName(reporterName); populateEditForm(uiModel, configType, configName, reporter); return "config_reporters/update"; } @RequestMapping(value="/{configType}_configs/{configName}/reporters/{reporterName}", method = RequestMethod.DELETE, produces = "text/html") public String delete(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @PathVariable("reporterName") String reporterName, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) { Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult(); config.removeReporter(reporterName); uiModel.asMap().clear(); uiModel.addAttribute("page", (page == null) ? "1" : page.toString()); uiModel.addAttribute("size", (size == null) ? "10" : size.toString()); return String.format("redirect:/%s_configs/%s/reporters/", configType, configName.toString()); } // DELETE by id @RequestMapping(value="/{configType}_configs/{configName}/reporters/delete-by-id/{id}", method = RequestMethod.DELETE, produces = "text/html") public String deleteById(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @PathVariable("id") long id, Model uiModel) { Reporter toDelete = Reporter.findReporter(id); Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult(); config.getReporters().remove(toDelete); config.merge(); return "redirect:/{configType}_configs/" + configName.toString() + "/reporters/"; } void populateEditForm(Model uiModel, String configType, String configName, Reporter reporter) { uiModel.addAttribute("availableItems", LibraryScanner.availableItems()); uiModel.addAttribute("reporter", reporter); uiModel.addAttribute("configName", configName); uiModel.addAttribute("configType", configType); } String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) { String enc = httpServletRequest.getCharacterEncoding(); if (enc == null) { enc = WebUtils.DEFAULT_CHARACTER_ENCODING; } try { pathSegment = UriUtils.encodePathSegment(pathSegment, enc); } catch (UnsupportedEncodingException uee) {} return pathSegment; } public void customValidation (String configName, Reporter reporter, BindingResult br) { if (!FieldValidator.validSlug(reporter.getName())) { br.addError(new ObjectError("reporter.name", "The name has to be set and can only contain ASCII letters and/or '-' and/or '_'")); } } }
10,105
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
CustomWiredTransformerController.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/web/CustomWiredTransformerController.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.matchconf.web; import java.io.UnsupportedEncodingException; import java.util.HashSet; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.kew.rmf.matchconf.Configuration; import org.kew.rmf.matchconf.Wire; import org.kew.rmf.matchconf.WiredTransformer; import org.kew.rmf.matchconf.utils.GetterSetter; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.util.UriUtils; import org.springframework.web.util.WebUtils; @Controller public class CustomWiredTransformerController { @SuppressWarnings("serial") private final static HashSet<String> T_TYPES = new HashSet<String>() {{add("query"); add("authority");}}; @RequestMapping(value="/{configType}_configs/{configName}/wires/{wireName}/{transformerType}_transformers", method = RequestMethod.POST, produces = "text/html") public String create(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @PathVariable("wireName") String wireName, @PathVariable("transformerType") String transformerType, @Valid WiredTransformer wiredTransformer, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) throws Exception { if (!T_TYPES.contains(transformerType)) throw new Exception(String.format("The transformer type has to be of %s", T_TYPES)); if (bindingResult.hasErrors()) { populateEditForm(uiModel, configType, configName, wiredTransformer); return "wiredtransformers/create"; } uiModel.asMap().clear(); wiredTransformer.persist(); Wire wire = Configuration.findConfigurationsByNameEquals(configName).getSingleResult().getWireForName(wireName); new GetterSetter<List<WiredTransformer>>().getattr(wire, transformerType + "Transformers").add(wiredTransformer); wire.merge(); return String.format("redirect:/%s_configs/%s/wires/%s/%s_transformers/%s", configType, configName, wireName, transformerType, wiredTransformer.getName()); } @RequestMapping(value="/{configType}_configs/{configName}/wires/{wireName}/{transformerType}_transformers", params = "form", produces = "text/html") public String createForm(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @PathVariable("wireName") String wireName, @PathVariable("transformerType") String transformerType, Model uiModel) throws Exception { if (!T_TYPES.contains(transformerType)) throw new Exception(String.format("The transformer type has to be of %s", T_TYPES)); WiredTransformer instance = new WiredTransformer(); populateEditForm(uiModel, configType, configName, instance); return "wired_transformers/create"; } @RequestMapping(value = "/{configType}_configs/{configName}/wires/{wireName}/{transformerType}_transformers/{wiredTransformerName}", produces = "text/html") public String show(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @PathVariable("wireName") String wireName, @PathVariable("transformerType") String transformerType, @PathVariable("wiredTransformerName") String wiredTransformerName, Model uiModel) throws Exception { if (!T_TYPES.contains(transformerType)) throw new Exception(String.format("The transformer type has to be of %s", T_TYPES)); Wire wire = Configuration.findConfigurationsByNameEquals(configName).getSingleResult().getWireForName(wireName); WiredTransformer wTransformer = wire.getWiredTransformer(transformerType, wiredTransformerName); uiModel.addAttribute("wiredTransformer", wTransformer); uiModel.addAttribute("transformerType", transformerType); uiModel.addAttribute("itemId", wiredTransformerName); return "wired_transformers/show"; } @RequestMapping(value = "/{configType}_configs/{configName}/wires/{wireName}/{transformerType}_transformers", produces = "text/html") public String list(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @PathVariable("wireName") String wireName, @PathVariable("transformerType") String transformerType, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) throws Exception { Wire wire = Configuration.findConfigurationsByNameEquals(configName).getSingleResult().getWireForName(wireName); List<WiredTransformer> wTransformers = new GetterSetter<List<WiredTransformer>>().getattr(wire, transformerType + "Transformers"); uiModel.addAttribute("transformerType", transformerType); if (page != null || size != null) { int sizeNo = size == null ? 10 : size.intValue(); final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo; uiModel.addAttribute("wiredTransformers", wTransformers.subList(firstResult, Math.min(firstResult + sizeNo, wTransformers.size()))); float nrOfPages = (float) wTransformers.size() / sizeNo; uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages)); } else { uiModel.addAttribute("wiredTransformers", wTransformers); } return "wired_transformers/list"; } @RequestMapping(value = "/{configType}_configs/{configName}/wires/{wireName}/{transformerType}_transformers", method = RequestMethod.PUT, produces = "text/html") public String update(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @PathVariable("wireName") String wireName, @PathVariable("transformerType") String transformerType, @Valid WiredTransformer wiredTransformer, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) { if (bindingResult.hasErrors()) { populateEditForm(uiModel, configType, configName, wiredTransformer); return "wired_transformers/update"; } uiModel.asMap().clear(); wiredTransformer.merge(); return String.format("redirect:/%s_configs/%s/wires/%s/%s_transformers/%s", configType, configName, wireName, transformerType, wiredTransformer.getName()); } @RequestMapping(value = "/{configType}_configs/{configName}/wires/{wireName}/{transformerType}_transformers/{wiredTransformerName}", params = "form", produces = "text/html") public String updateForm(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @PathVariable("wireName") String wireName, @PathVariable("transformerType") String transformerType, @PathVariable("wiredTransformerName") String wiredTransformerName, Model uiModel) throws Exception { Wire wire = Configuration.findConfigurationsByNameEquals(configName).getSingleResult().getWireForName(wireName); populateEditForm(uiModel, configType, configName, wire.getWiredTransformer(transformerType, wiredTransformerName)); return "wired_transformers/update"; } @RequestMapping(value = "/{configType}_configs/{configName}/wires/{wireName}/{transformerType}_transformers/{wiredTransformerName}", method = RequestMethod.DELETE, produces = "text/html") public String delete(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @PathVariable("wireName") String wireName, @PathVariable("transformerType") String transformerType, @PathVariable("wiredTransformerName") String wiredTransformerName, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) throws Exception { Wire wire = Configuration.findConfigurationsByNameEquals(configName).getSingleResult().getWireForName(wireName); WiredTransformer wiredTransformer = wire.getWiredTransformer(transformerType, wiredTransformerName); new GetterSetter<List<WiredTransformer>>().getattr(wire, transformerType + "Transformers").remove(wiredTransformer); wire.merge(); uiModel.asMap().clear(); uiModel.addAttribute("page", (page == null) ? "1" : page.toString()); uiModel.addAttribute("size", (size == null) ? "10" : size.toString()); return String.format("redirect:/%s_configs/%s/wires/%s/%s_transformers", configType, configName, wireName, transformerType); } void populateEditForm(Model uiModel, String configType, String configName, WiredTransformer wTransformer) { uiModel.addAttribute("availableItems", LibraryScanner.availableItems()); uiModel.addAttribute("wiredTransformer", wTransformer); uiModel.addAttribute("transformers", Configuration.findConfigurationsByNameEquals(configName).getSingleResult().getTransformers()); uiModel.addAttribute("configName", configName); uiModel.addAttribute("configType", configType); } String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) { String enc = httpServletRequest.getCharacterEncoding(); if (enc == null) { enc = WebUtils.DEFAULT_CHARACTER_ENCODING; } try { pathSegment = UriUtils.encodePathSegment(pathSegment, enc); } catch (UnsupportedEncodingException uee) {} return pathSegment; } }
10,503
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
WireController.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/web/WireController.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.matchconf.web; import org.kew.rmf.matchconf.Wire; import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @RequestMapping("/wires") @Controller @RooWebScaffold(path = "wires", formBackingObject = Wire.class) public class WireController { }
1,150
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
CustomWireController.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/web/CustomWireController.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.matchconf.web; import java.io.UnsupportedEncodingException; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.kew.rmf.matchconf.Configuration; import org.kew.rmf.matchconf.Wire; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.util.UriUtils; import org.springframework.web.util.WebUtils; @Controller public class CustomWireController { @RequestMapping(value="/{configType}_configs/{configName}/wires", params = "form", produces = "text/html") public String createForm(@PathVariable("configType") String configType, @PathVariable("configName") String configName, Model uiModel) { populateEditForm(uiModel, configName, new Wire()); return String.format("%s_config_wires/create", configType); } // Default Post @RequestMapping(value="/{configType}_configs/{configName}/wires", method = RequestMethod.POST, produces = "text/html") public String create(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @Valid Wire wire, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) { // assert unique_together:config&name if (Configuration.findConfigurationsByNameEquals(configName).getSingleResult().getWireForName(wire.getName()) != null) { bindingResult.addError(new ObjectError("wire.name", "There is already a Wire set up for this configuration with this name.")); } this.customValidation(configName, wire, bindingResult); if (bindingResult.hasErrors()) { populateEditForm(uiModel, configName, wire); return String.format("%s_config_wires/create", configType); } uiModel.asMap().clear(); Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult(); wire.setConfiguration(config); wire.persist(); config.getWiring().add(wire); config.merge(); return String.format("redirect:/%s_configs/", configType) + encodeUrlPathSegment(configName, httpServletRequest) + "/wires/" + encodeUrlPathSegment(wire.getName(), httpServletRequest); } // default GET indiviual wire level @RequestMapping(value="/{configType}_configs/{configName}/wires/{wireName}", produces = "text/html") public String show(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @PathVariable("wireName") String wireName, Model uiModel) { uiModel.addAttribute("availableItems", LibraryScanner.availableItems()); Wire wire = Configuration.findConfigurationsByNameEquals(configName).getSingleResult().getWireForName(wireName); uiModel.addAttribute("wire", wire); uiModel.addAttribute("itemId", wire.getName()); uiModel.addAttribute("configName", configName); uiModel.addAttribute("transformers", wire.getConfiguration().getTransformers()); return String.format("%s_config_wires/show", configType); } @RequestMapping(value="/{configType}_configs/{configName}/wires", produces = "text/html") public String list(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) { uiModel.addAttribute("availableItems", LibraryScanner.availableItems()); List<Wire> wires = Configuration.findConfigurationsByNameEquals(configName).getSingleResult().getWiring(); if (page != null || size != null) { int sizeNo = Math.min(size == null ? 10 : size.intValue(), wires.size()); final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo; uiModel.addAttribute("wires", wires.subList(firstResult, sizeNo)); float nrOfPages = (float) wires.size() / sizeNo; uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages)); } else { uiModel.addAttribute("wires", wires); } uiModel.addAttribute("configName", configName); return String.format("%s_config_wires/list", ConfigSwitch.getTypeForUrl(configName)); } @RequestMapping(value="/{configType}_configs/{configName}/wires", method = RequestMethod.PUT, produces = "text/html") public String update(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @Valid Wire wire, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) { this.customValidation(configName, wire, bindingResult); if (bindingResult.hasErrors()) { populateEditForm(uiModel, configName, wire); return String.format("%s_config_wires/update", configType); } uiModel.asMap().clear(); wire.setConfiguration(Configuration.findConfigurationsByNameEquals(configName).getSingleResult()); wire.merge(); return String.format("redirect:/%s_configs/", configType) + encodeUrlPathSegment(configName, httpServletRequest) + "/wires/" + encodeUrlPathSegment(wire.getName(), httpServletRequest); } @RequestMapping(value="/{configType}_configs/{configName}/wires/{wireName}", params = "form", produces = "text/html") public String updateForm(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @PathVariable("wireName") String wireName, Model uiModel) { Wire wire = Configuration.findConfigurationsByNameEquals(configName).getSingleResult().getWireForName(wireName); populateEditForm(uiModel, configName, wire); return String.format("%s_config_wires/update", configType); } @RequestMapping(value="/{configType}_configs/{configName}/wires/{wireName}", method = RequestMethod.DELETE, produces = "text/html") public String delete(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @PathVariable("wireName") String wireName, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) { Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult(); config.removeWire(wireName); uiModel.asMap().clear(); uiModel.addAttribute("page", (page == null) ? "1" : page.toString()); uiModel.addAttribute("size", (size == null) ? "10" : size.toString()); return String.format("redirect:/%s_configs/%s/wires/", configType, configName.toString()); } // DELETE by id @RequestMapping(value="/{configType}_configs/{configName}/wires/delete-by-id/{id}", method = RequestMethod.DELETE, produces = "text/html") public String deleteById(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @PathVariable("id") long id, Model uiModel) { Wire toDelete = Wire.findWire(id); Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult(); config.getWiring().remove(toDelete); config.merge(); return "redirect:/{configType}_configs/" + configName.toString() + "/wires/"; } void populateEditForm(Model uiModel, String configName, Wire wire) { uiModel.addAttribute("availableItems", LibraryScanner.availableItems()); Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult(); uiModel.addAttribute("wire", wire); uiModel.addAttribute("configName", configName); uiModel.addAttribute("matchers", config.getMatchers()); uiModel.addAttribute("queryTransformers", wire.getQueryTransformers()); uiModel.addAttribute("authorityTransformers", wire.getAuthorityTransformers()); } String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) { String enc = httpServletRequest.getCharacterEncoding(); if (enc == null) { enc = WebUtils.DEFAULT_CHARACTER_ENCODING; } try { pathSegment = UriUtils.encodePathSegment(pathSegment, enc); } catch (UnsupportedEncodingException uee) {} return pathSegment; } public void customValidation (String configName, Wire wire, BindingResult br) { if (!FieldValidator.validSlug(wire.getName())) { br.addError(new ObjectError("wire.name", "The name can only contain ASCII letters and/or '-' and/or '_'")); } } }
9,820
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
CustomTransformerController.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/web/CustomTransformerController.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.matchconf.web; import java.io.UnsupportedEncodingException; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.kew.rmf.matchconf.Configuration; import org.kew.rmf.matchconf.Transformer; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.util.UriUtils; import org.springframework.web.util.WebUtils; @Controller public class CustomTransformerController { // GET: transformer creation form for this configuration @RequestMapping(value="/{configType}_configs/{configName}/transformers", params = "form", produces = "text/html") public String createForm(@PathVariable("configType") String configType, @PathVariable("configName") String configName, Model uiModel, @RequestParam(value = "className", required = false) String className, @RequestParam(value = "packageName", required = false) String packageName) { Transformer instance = new Transformer(); instance.setPackageName(packageName); instance.setClassName(className); populateEditForm(uiModel, configType, configName, instance); return "config_transformers/create"; } // POST to create an object and add it to this configuration @RequestMapping(value="/{configType}_configs/{configName}/transformers", method = RequestMethod.POST, produces = "text/html") public String create(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @Valid Transformer transformer, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) { // assert unique_together:config&name if (Configuration.findConfigurationsByNameEquals(configName).getSingleResult().getTransformerForName(transformer.getName()) != null) { bindingResult.addError(new ObjectError("transformer.name", "There is already a Transformer set up for this configuration with this name.")); } this.customValidation(configName, transformer, bindingResult); if (bindingResult.hasErrors()) { populateEditForm(uiModel, configType, configName, transformer); return "config_transformers/create"; } uiModel.asMap().clear(); Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult(); transformer.setConfiguration(config); transformer.persist(); config.getTransformers().add(transformer); config.merge(); return "redirect:/{configType}_configs/" + encodeUrlPathSegment(configName, httpServletRequest) + "/transformers/" + encodeUrlPathSegment(transformer.getName(), httpServletRequest); } // GET indiviual transformer level @RequestMapping(value="/{configType}_configs/{configName}/transformers/{transformerName}", produces = "text/html") public String show(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @PathVariable("transformerName") String transformerName, Model uiModel) { uiModel.addAttribute("availableItems", LibraryScanner.availableItems()); Transformer transformer = Configuration.findConfigurationsByNameEquals(configName).getSingleResult().getTransformerForName(transformerName); uiModel.addAttribute("transformer", transformer); uiModel.addAttribute("itemId", transformer.getName()); uiModel.addAttribute("configName", configName); return "config_transformers/show"; } // GET list of transformers for this config @RequestMapping(value="/{configType}_configs/{configName}/transformers", produces = "text/html") public String list(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) { uiModel.addAttribute("availableItems", LibraryScanner.availableItems()); List<Transformer> transformers = Configuration.findConfigurationsByNameEquals(configName).getSingleResult().getTransformers(); if (page != null || size != null) { int sizeNo = Math.min(size == null ? 10 : size.intValue(), transformers.size()); final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo; uiModel.addAttribute("transformers", transformers.subList(firstResult, sizeNo)); float nrOfPages = (float) Transformer.countTransformers() / sizeNo; uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages)); } else { uiModel.addAttribute("transformers", transformers); } uiModel.addAttribute("configName", configName); return "config_transformers/list"; } // GET the update form for a specific transformer @RequestMapping(value="/{configType}_configs/{configName}/transformers/{transformerName}", params = "form", produces = "text/html") public String updateForm(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @PathVariable("transformerName") String transformerName, Model uiModel) { Transformer transformer = Configuration.findConfigurationsByNameEquals(configName).getSingleResult().getTransformerForName(transformerName); populateEditForm(uiModel, configType, configName, transformer); return "config_transformers/update"; } // PUT: update a specific transformer @RequestMapping(value="/{configType}_configs/{configName}/transformers", method = RequestMethod.PUT, produces = "text/html") public String update(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @Valid Transformer transformer, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) { this.customValidation(configName, transformer, bindingResult); if (bindingResult.hasErrors()) { populateEditForm(uiModel, configType, configName, transformer); return "config_transformers/update"; } uiModel.asMap().clear(); transformer.setConfiguration(Configuration.findConfigurationsByNameEquals(configName).getSingleResult()); transformer.merge(); return "redirect:/{configType}_configs/" + encodeUrlPathSegment(configName, httpServletRequest) + "/transformers/" + encodeUrlPathSegment(transformer.getName(), httpServletRequest); } // DELETE a specific transformer from a collection's list @RequestMapping(value="/{configType}_configs/{configName}/transformers/{transformerName}", method = RequestMethod.DELETE, produces = "text/html") public String delete(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @PathVariable("transformerName") String transformerName, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) throws Exception { Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult(); config.removeTransformer(transformerName); uiModel.asMap().clear(); uiModel.addAttribute("page", (page == null) ? "1" : page.toString()); uiModel.addAttribute("size", (size == null) ? "10" : size.toString()); return "redirect:/{configType}_configs/" + configName.toString() + "/transformers/"; } // DELETE by id @RequestMapping(value="/{configType}_configs/{configName}/transformers/delete-by-id/{id}", method = RequestMethod.DELETE, produces = "text/html") public String deleteById(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @PathVariable("id") long id, Model uiModel) { Transformer toDelete = Transformer.findTransformer(id); Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult(); config.getTransformers().remove(toDelete); config.merge(); return "redirect:/{configType}_configs/" + configName.toString() + "/transformers/"; } void populateEditForm(Model uiModel,String configType, String configName, Transformer transformer) { uiModel.addAttribute("availableItems", LibraryScanner.availableItems()); uiModel.addAttribute("transformer", transformer); uiModel.addAttribute("configName", configName); uiModel.addAttribute("configType", configType); } String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) { String enc = httpServletRequest.getCharacterEncoding(); if (enc == null) { enc = WebUtils.DEFAULT_CHARACTER_ENCODING; } try { pathSegment = UriUtils.encodePathSegment(pathSegment, enc); } catch (UnsupportedEncodingException uee) {} return pathSegment; } public void customValidation (String configName, Transformer transformer, BindingResult br) { if (!FieldValidator.validSlug(transformer.getName())) { br.addError(new ObjectError("transformer.name", "The name has to be set and can only contain ASCII letters and/or '-' and/or '_'")); } } }
10,544
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
ConfigSwitch.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/web/ConfigSwitch.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.matchconf.web; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.List; import java.util.Map; import org.kew.rmf.matchconf.Configuration; public class ConfigSwitch { @SuppressWarnings("serial") static final Map<String,String> TYPE_CLASS_MAP = new HashMap<String,String>() {{ put("match", "MatchConfiguration"); put("dedup", "DeduplicationConfiguration"); }}; @SuppressWarnings("serial") static final Map<String,String> CLASS_TYPE_MAP = new HashMap<String,String>() {{ put("MatchConfiguration", "match"); put("DeduplicationConfiguration", "dedup"); }}; public static String getTypeForUrl (String configName) { Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult(); return CLASS_TYPE_MAP.get(config.getClassName()); } @SuppressWarnings("unchecked") public static List<Configuration> findConfigEntries (int firstResult, int size, String configType) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { String method = "findConfigurationEntries"; if (configType.equals("match")) method = "findMatchConfigEntries"; else if (configType.equals("dedup")) method = "findDedupConfigEntries"; return (List<Configuration>) Configuration.class.getMethod(method, int.class, int.class).invoke(null, firstResult, size); } public static long countConfigs(String className) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { String method = "countConfigurations"; if (className.equals("match")) method = "countMatchConfigs"; else if (className.equals("dedup")) method = "countDedupConfigs"; return (long) Configuration.class.getMethod(method).invoke(null); } @SuppressWarnings("unchecked") public static List<Configuration> findAllConfigs(String configType) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { String method = "findAllConfigurations"; if (configType.equals("match")) method = "findAllMatchConfigs"; else if (configType.equals("dedup")) method = "findAllDedupConfigs"; return (List<Configuration>) Configuration.class.getMethod(method).invoke(null); } }
3,240
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
CustomConfigController.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/web/CustomConfigController.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.matchconf.web; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.kew.rmf.matchconf.Configuration; import org.kew.rmf.matchconf.ConfigurationEngine; import org.kew.rmf.matchconf.Transformer; import org.springframework.orm.jpa.JpaSystemException; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.util.UriUtils; import org.springframework.web.util.WebUtils; @Controller public class CustomConfigController { // redirect root (/MatchConf) to default GET configs overview @RequestMapping(value = "/", produces = "text/html") public String root() { return "redirect:/dedup_configs"; } // default GET configs overview @RequestMapping(value = "/{configType}_configs", produces = "text/html") public String list(@PathVariable("configType") String configType, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { List<Configuration> configurations; if (page != null || size != null) { int sizeNo = size == null ? 10 : size.intValue(); final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo; configurations = ConfigSwitch.findConfigEntries(firstResult, sizeNo, configType); float nrOfPages = (float) ConfigSwitch.countConfigs(configType) / sizeNo; uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages)); } else { configurations = ConfigSwitch.findAllConfigs(configType); } uiModel.addAttribute("configurations", configurations); return String.format("%s_configs/list", configType); } // Default POST for configs @RequestMapping(value = "/{configType}_configs", method = RequestMethod.POST, produces = "text/html") public String create(@PathVariable("configType") String configType, @Valid Configuration configuration, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) { configuration.setClassName(ConfigSwitch.TYPE_CLASS_MAP.get(configType)); this.customValidation(configuration, bindingResult); if (bindingResult.hasErrors()) { populateEditForm(uiModel, configuration); return configType + "_configs/create"; } uiModel.asMap().clear(); configuration.persist(); return String.format("redirect:/%s_configs/", configType) + encodeUrlPathSegment(configuration.getName(), httpServletRequest); } @RequestMapping(value = "/{configType}_configs", params = "form", produces = "text/html") public String create(@PathVariable String configType, Model uiModel) { populateEditForm(uiModel, new Configuration()); return configType + "_configs/create"; } // Default GET indiviual config level @RequestMapping(value = "/{configType}_configs/{configName}", produces = "text/html") public String show(@PathVariable("configType") String configType, @PathVariable("configName") String configName, Model uiModel) { uiModel.addAttribute("availableItems", LibraryScanner.availableItems()); Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult(); uiModel.addAttribute("configuration", config); uiModel.addAttribute("itemId", config.getName()); return configType + "_configs/show"; } @RequestMapping(value = "/{configType}_configs", method = RequestMethod.PUT, produces = "text/html") public String update(@PathVariable String configType, @Valid Configuration configuration, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) { uiModel.addAttribute("availableItems", LibraryScanner.availableItems()); configuration.setClassName(ConfigSwitch.TYPE_CLASS_MAP.get(configType)); this.customValidation(configuration, bindingResult); if (bindingResult.hasErrors()) { populateEditForm(uiModel, configuration); return configType + "_configs/update"; } uiModel.asMap().clear(); configuration.merge(); return String.format("redirect:/%s_configs/", configType) + encodeUrlPathSegment(configuration.getName(), httpServletRequest); } @RequestMapping(value = "/{configType}_configs/{configName}", params = "form", produces = "text/html") public String updateForm(@PathVariable String configType, @PathVariable("configName") String configName, Model uiModel) { populateEditForm(uiModel, Configuration.findConfigurationsByNameEquals(configName).getSingleResult()); return configType + "_configs/update"; } @RequestMapping(value = "/{configType}_configs/{configName}", method = RequestMethod.DELETE, produces = "text/html") public String delete(@PathVariable String configType, @PathVariable("configName") String configName, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) throws Exception { Configuration configuration = Configuration.findConfigurationsByNameEquals(configName).getSingleResult(); try { for (Transformer t:configuration.getTransformers()) t.removeOrphanedWiredTransformers(); // this is expensive and should go soon configuration.remove(); } catch (JpaSystemException e) { // assuming a possibly still exotically ocurring legacy error: a wire // of a *different* config uses this matcher, hence it would have a // foreign key into the void and complains so the matcher can't be // deleted and this config neither.. configuration.fixMatchersForAlienWire(); configuration.getWiring().clear(); configuration.merge(); configuration.removeTransformers(); configuration = Configuration.findConfigurationsByNameEquals(configName).getSingleResult(); configuration.remove(); } uiModel.asMap().clear(); uiModel.addAttribute("page", (page == null) ? "1" : page.toString()); uiModel.addAttribute("size", (size == null) ? "10" : size.toString()); return String.format("redirect:/%s_configs", configType); } // DELETE by id @RequestMapping(value="/{configType}_configs/delete-by-id/{id}", method = RequestMethod.DELETE, produces = "text/html") public String deleteById(@PathVariable("configType") String configType, @PathVariable("id") long id, Model uiModel) { Configuration toDelete = Configuration.findConfiguration(id); toDelete.remove(); return "redirect:/{configType}_configs/"; } void populateEditForm(Model uiModel, Configuration configuration) { uiModel.addAttribute("configuration", configuration); uiModel.addAttribute("configName", configuration.getName()); uiModel.addAttribute("wiring", configuration.getWiring()); uiModel.addAttribute("transformers", configuration.getTransformers()); uiModel.addAttribute("matchers", configuration.getMatchers()); uiModel.addAttribute("reporters", configuration.getReporters()); } String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) { String enc = httpServletRequest.getCharacterEncoding(); if (enc == null) { enc = WebUtils.DEFAULT_CHARACTER_ENCODING; } try { pathSegment = UriUtils.encodePathSegment(pathSegment, enc); } catch (UnsupportedEncodingException uee) {} return pathSegment; } public void customValidation (Configuration config, BindingResult br) { // validation for all classes that have their name as part of a REST-ish url if (!FieldValidator.validSlug(config.getName())) { br.addError(new ObjectError("config.name", "The name has to be set and can only contain ASCII letters and/or '-' and/or '_'")); } // MatchConfig specific: has to specify a authorityFileName if (config.getClassName().equals("MatchConfiguration") && config.getAuthorityFileName().equals("")) { br.addError(new ObjectError("configuration.authorityFileName", "A Match Configuration needs to specify an authority File")); } } @RequestMapping(value = "/{configType}_configs/{configName}/clone", produces = "text/html") public String cloneConfig(@PathVariable("configType") String configType, @PathVariable("configName") String configName, Model model) throws Exception { Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult(); config.cloneMe(); return String.format("redirect:/%s_configs", configType); } @RequestMapping(value = "/{configType}_configs/{configName}/run", produces = "text/html") public String runConfig(@PathVariable("configType") String configType, @PathVariable("configName") String configName, Model model) throws Exception { Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult(); Map<String, List<String>> infoMap = new ConfigurationEngine(config).runConfiguration(); model.addAttribute("engineMessages", infoMap.get("messages")); model.addAttribute("config", config); model.addAttribute("exception", infoMap.get("exception")); model.addAttribute("stackTrace", infoMap.get("stackTrace")); return "configurations/run/index"; } }
11,230
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
ReporterController.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/web/ReporterController.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.matchconf.web; import org.kew.rmf.matchconf.Reporter; import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @RequestMapping("/reporters") @Controller @RooWebScaffold(path = "reporters", formBackingObject = Reporter.class) public class ReporterController { }
1,170
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
DictionaryController.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/web/DictionaryController.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.matchconf.web; import java.io.UnsupportedEncodingException; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.kew.rmf.matchconf.Dictionary; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.util.UriUtils; import org.springframework.web.util.WebUtils; @RequestMapping("/dictionaries") @Controller public class DictionaryController { @RequestMapping(params = "form", produces = "text/html") public String createForm(Model uiModel) { populateEditForm(uiModel, new Dictionary()); return "dictionaries/create"; } @RequestMapping(produces = "text/html") public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) { if (page != null || size != null) { int sizeNo = size == null ? 10 : size.intValue(); final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo; uiModel.addAttribute("dictionaries", Dictionary.findDictionaryEntries(firstResult, sizeNo)); float nrOfPages = (float) Dictionary.countDictionarys() / sizeNo; uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages)); } else { uiModel.addAttribute("dictionaries", Dictionary.findAllDictionarys()); } return "dictionaries/list"; } void populateEditForm(Model uiModel, Dictionary dictionary) { uiModel.addAttribute("dictionary", dictionary); } String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) { String enc = httpServletRequest.getCharacterEncoding(); if (enc == null) { enc = WebUtils.DEFAULT_CHARACTER_ENCODING; } try { pathSegment = UriUtils.encodePathSegment(pathSegment, enc); } catch (UnsupportedEncodingException uee) {} return pathSegment; } @RequestMapping(value = "/{name}", produces = "text/html") public String show(@PathVariable("name") String name, Model uiModel) { uiModel.addAttribute("dictionary", Dictionary.findDictionariesByNameEquals(name).getSingleResult()); uiModel.addAttribute("itemId", name); return "dictionaries/show"; } @RequestMapping(method = RequestMethod.POST, produces = "text/html") public String create(@Valid Dictionary dictionary, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) { this.customValidation(dictionary, bindingResult); if (bindingResult.hasErrors()) { populateEditForm(uiModel, dictionary); return "dictionaries/create"; } uiModel.asMap().clear(); dictionary.persist(); return "redirect:/dictionaries/" + encodeUrlPathSegment(dictionary.getName(), httpServletRequest); } @RequestMapping(method = RequestMethod.PUT, produces = "text/html") public String update(@Valid Dictionary dictionary, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) { this.customValidation(dictionary, bindingResult); if (bindingResult.hasErrors()) { populateEditForm(uiModel, dictionary); return "dictionaries/update"; } uiModel.asMap().clear(); dictionary.merge(); return "redirect:/dictionaries/" + encodeUrlPathSegment(dictionary.getName(), httpServletRequest); } @RequestMapping(value = "/{name}", params = "form", produces = "text/html") public String updateForm(@PathVariable("name") String name, Model uiModel) { populateEditForm(uiModel, Dictionary.findDictionariesByNameEquals(name).getSingleResult()); return "dictionaries/update"; } @RequestMapping(value = "/{name}", method = RequestMethod.DELETE, produces = "text/html") public String delete(@PathVariable("name") String name, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) { Dictionary dictionary = Dictionary.findDictionariesByNameEquals(name).getSingleResult(); dictionary.remove(); uiModel.asMap().clear(); uiModel.addAttribute("page", (page == null) ? "1" : page.toString()); uiModel.addAttribute("size", (size == null) ? "10" : size.toString()); return "redirect:/dictionaries"; } public void customValidation (Dictionary dict, BindingResult br) { if (!FieldValidator.validSlug(dict.getName())) { br.addError(new ObjectError("dict.name", "The name has to be set and can only contain ASCII letters and/or '-' and/or '_'")); } } }
5,958
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
ApplicationConversionServiceFactoryBean.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/web/ApplicationConversionServiceFactoryBean.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.matchconf.web; import org.springframework.format.FormatterRegistry; import org.springframework.format.support.FormattingConversionServiceFactoryBean; import org.springframework.roo.addon.web.mvc.controller.converter.RooConversionService; /** * A central place to register application converters and formatters. */ @RooConversionService public class ApplicationConversionServiceFactoryBean extends FormattingConversionServiceFactoryBean { @Override protected void installFormatters(FormatterRegistry registry) { super.installFormatters(registry); // Register application converters and formatters } }
1,384
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
ConversionTest.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service-model/src/test/java/org/kew/rmf/refine/domain/ConversionTest.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.refine.domain; import java.util.ArrayList; import java.util.List; import org.codehaus.jackson.map.ObjectMapper; import org.junit.Assert; import org.junit.Test; import org.kew.rmf.refine.domain.metadata.Metadata; import org.kew.rmf.refine.domain.metadata.MetadataView; import org.kew.rmf.refine.domain.metadata.Type; import org.kew.rmf.refine.domain.query.Property; import org.kew.rmf.refine.domain.query.Query; import org.kew.rmf.refine.domain.response.QueryResponse; import org.kew.rmf.refine.domain.response.QueryResult; public class ConversionTest { /** * Show that we can convert to / from JSON and the POJOs used in communication with reconciliation service. */ @Test public void testConversion() { // We use a Jackson object mapper: ObjectMapper jsonMapper = new ObjectMapper(); /* * Create a metadata object and set some values * Using sample from: * http://code.google.com/p/google-refine/wiki/ReconciliationServiceApi * http://standard-reconcile.freebaseapps.com/reconcile?callback=jsonp */ Metadata metadata = new Metadata(); metadata.setName("Freebase Reconciliation Service"); metadata.setSchemaSpace("http://rdf.freebase.com/ns/type.object.mid"); metadata.setIdentifierSpace("http://rdf.freebase.com/ns/type.object.id"); MetadataView metadataView = new MetadataView(); metadataView.setUrl("http://www.freebase.com/view{{id}}"); metadata.setView(metadataView); try { System.out.println(metadata.toString()); System.out.println(jsonMapper.writeValueAsString(metadata)); } catch (Exception e){ e.printStackTrace(); Assert.fail(e.getMessage()); } /* * Create a query object and set some values: */ Query query = new Query(); query.setQuery("Poa annua"); query.setLimit(3); query.setType("/scientific_name"); query.setType_strict("any"); // Properties are a flexible way to pass more data into the service: Property property = new Property(); property.setP("author"); property.setV("L."); List<Property> properties = new ArrayList<Property>(); properties.add(property); query.setProperties(properties.toArray(new Property[0])); try { System.out.println(query.toString()); String json = jsonMapper.writeValueAsString(query); System.out.println(json); // Now "round trip" it - i.e. use this JSON to build a new Java object representation: Query query_roundtripped = jsonMapper.readValue(json, Query.class); System.out.println(query_roundtripped.toString()); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.getMessage()); } /* * Create a query response object and set some values: */ QueryResponse<QueryResult> queryResponse = new QueryResponse<>(); // A response can contain multiple queryresults List<QueryResult> queryResults = new ArrayList<QueryResult>(); // Build one queryresult QueryResult queryResult = new QueryResult(); queryResult.setId("12345"); queryResult.setName("Poa annua"); List<Type> types = new ArrayList<>(); types.add(new Type("/scientific_name", "Scientific name")); queryResult.setType(types.toArray(new Type[0])); queryResult.setScore(100); queryResult.setMatch(true); // Add to list queryResults.add(queryResult); // Set list of queryresults onto response queryResponse.setResult(queryResults.toArray(new QueryResult[0])); try { System.out.println(queryResponse.toString()); String json = jsonMapper.writeValueAsString(queryResponse); System.out.println(json); // Now "round trip" it - i.e. use this JSON to build a new Java object representation: QueryResponse<QueryResult> queryResponse_roundtripped = jsonMapper.readValue(json, QueryResponse.class); System.out.println(queryResponse_roundtripped.toString()); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.getMessage()); } } }
4,616
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
MetadataView.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service-model/src/main/java/org/kew/rmf/refine/domain/metadata/MetadataView.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.refine.domain.metadata; public class MetadataView { private String url; @Override public String toString() { return "MetadataView [url="+url+"]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MetadataView other = (MetadataView) obj; if (url == null) { if (other.url != null) return false; } else if (!url.equals(other.url)) return false; return true; } /* • Getters and setters • */ public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
1,415
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
MetadataSuggest.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service-model/src/main/java/org/kew/rmf/refine/domain/metadata/MetadataSuggest.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.refine.domain.metadata; public class MetadataSuggest { private MetadataSuggestDetails type; private MetadataSuggestDetails property; private MetadataSuggestDetails entity; @Override public String toString() { return "MetadataSuggest [" + "type=" + type + ", property=" + property + ", entity=" + entity + "]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MetadataSuggest other = (MetadataSuggest) obj; if (entity == null) { if (other.entity != null) return false; } else if (!entity.equals(other.entity)) return false; if (property == null) { if (other.property != null) return false; } else if (!property.equals(other.property)) return false; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } /* • Getters and setters • */ public MetadataSuggestDetails getType() { return type; } public void setType(MetadataSuggestDetails type) { this.type = type; } public MetadataSuggestDetails getProperty() { return property; } public void setProperty(MetadataSuggestDetails property) { this.property = property; } public MetadataSuggestDetails getEntity() { return entity; } public void setEntity(MetadataSuggestDetails entity) { this.entity = entity; } }
2,217
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
MetadataPreview.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service-model/src/main/java/org/kew/rmf/refine/domain/metadata/MetadataPreview.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.refine.domain.metadata; public class MetadataPreview { private String url; private int width; private int height; @Override public String toString() { return "MetadataPreview [" + "url=" + url + ", width=" + width + ", height=" + height + "]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MetadataPreview other = (MetadataPreview) obj; if (height != other.height) return false; if (url == null) { if (other.url != null) return false; } else if (!url.equals(other.url)) return false; if (width != other.width) return false; return true; } /* • Getters and setters • */ public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } }
1,834
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
Type.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service-model/src/main/java/org/kew/rmf/refine/domain/metadata/Type.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.refine.domain.metadata; public class Type { private String id; private String name; public Type() {} public Type(String id, String name) { setId(id); setName(name); } @Override public String toString() { return "Type "+id+" "+name; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Type other = (Type) obj; if (id == null) { if (other.id != null) { return false; } } else if (!id.equals(other.id)) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } /* • Getters and setters • */ public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
1,735
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
Metadata.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service-model/src/main/java/org/kew/rmf/refine/domain/metadata/Metadata.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.refine.domain.metadata; import java.util.Arrays; import javax.xml.bind.annotation.XmlRootElement; /** * Represents the Metadata class of the OpenRefine Reconciliation Service API. * * See https://github.com/OpenRefine/OpenRefine/wiki/Reconciliation-Service-API */ @XmlRootElement public class Metadata { private String name; private String identifierSpace; private String schemaSpace; private MetadataView view; private MetadataPreview preview; private MetadataSuggest suggest; private Type[] defaultTypes; @Override public String toString() { return "Metadata [" + "name=" + name + ", identifierSpace=" + identifierSpace + ", schemaSpace=" + schemaSpace + ", view=" + view + ", preview=" + preview + ", suggest=" + suggest + ", defaultTypes=" + defaultTypes + "]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Metadata other = (Metadata) obj; if (!Arrays.equals(defaultTypes, other.defaultTypes)) return false; if (identifierSpace == null) { if (other.identifierSpace != null) return false; } else if (!identifierSpace.equals(other.identifierSpace)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (preview == null) { if (other.preview != null) return false; } else if (!preview.equals(other.preview)) return false; if (schemaSpace == null) { if (other.schemaSpace != null) return false; } else if (!schemaSpace.equals(other.schemaSpace)) return false; if (suggest == null) { if (other.suggest != null) return false; } else if (!suggest.equals(other.suggest)) return false; if (view == null) { if (other.view != null) return false; } else if (!view.equals(other.view)) return false; return true; } /* • Getters and setters • */ public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIdentifierSpace() { return identifierSpace; } public void setIdentifierSpace(String identifierSpace) { this.identifierSpace = identifierSpace; } public String getSchemaSpace() { return schemaSpace; } public void setSchemaSpace(String schemaSpace) { this.schemaSpace = schemaSpace; } public MetadataView getView() { return view; } public void setView(MetadataView view) { this.view = view; } public MetadataPreview getPreview() { return preview; } public void setPreview(MetadataPreview preview) { this.preview = preview; } public MetadataSuggest getSuggest() { return suggest; } public void setSuggest(MetadataSuggest suggest) { this.suggest = suggest; } public Type[] getDefaultTypes() { return defaultTypes; } public void setDefaultTypes(Type[] defaultTypes) { this.defaultTypes = defaultTypes; } }
3,711
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
MetadataSuggestDetails.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service-model/src/main/java/org/kew/rmf/refine/domain/metadata/MetadataSuggestDetails.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.refine.domain.metadata; public class MetadataSuggestDetails { private String service_url; private String service_path; private String flyout_service_url; private String flyout_service_path; @Override public String toString() { return "MetadataSuggestDetails [" + "service_url=" + service_url + ", service_path=" + service_path + ", flyout_service_url=" + flyout_service_url + ", flyout_service_path=" + flyout_service_path + "]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MetadataSuggestDetails other = (MetadataSuggestDetails) obj; if (flyout_service_path == null) { if (other.flyout_service_path != null) return false; } else if (!flyout_service_path.equals(other.flyout_service_path)) return false; if (flyout_service_url == null) { if (other.flyout_service_url != null) return false; } else if (!flyout_service_url.equals(other.flyout_service_url)) return false; if (service_path == null) { if (other.service_path != null) return false; } else if (!service_path.equals(other.service_path)) return false; if (service_url == null) { if (other.service_url != null) return false; } else if (!service_url.equals(other.service_url)) return false; return true; } /* • Getters and setters • */ public String getService_url() { return service_url; } public void setService_url(String serviceUrl) { this.service_url = serviceUrl; } public String getService_path() { return service_path; } public void setService_path(String servicePath) { this.service_path = servicePath; } public String getFlyout_service_url() { return flyout_service_url; } public void setFlyout_service_url(String flyoutServiceUrl) { this.flyout_service_url = flyoutServiceUrl; } public String getFlyout_service_path() { return flyout_service_path; } public void setFlyout_service_path(String flyoutServicePath) { this.flyout_service_path = flyoutServicePath; } }
2,853
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
Query.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service-model/src/main/java/org/kew/rmf/refine/domain/query/Query.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.refine.domain.query; import java.util.Arrays; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Query { private String query; private String type; private Integer limit; private String type_strict; private Property[] properties; @Override public String toString() { return "Query [query=" + query + ", type=" + type + ", limit=" + limit + ", type_strict=" + type_strict + ", properties=" + Arrays.toString(properties) + "]"; } /* • Getters and setters • */ public String getQuery() { return query; } public void setQuery(String query) { this.query = query; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Integer getLimit() { return limit; } public void setLimit(Integer limit) { this.limit = limit; } public String getType_strict() { return type_strict; } public void setType_strict(String type_strict) { this.type_strict = type_strict; } public Property[] getProperties() { return properties; } public void setProperties(Property[] properties) { this.properties = properties; } }
1,910
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
Property.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service-model/src/main/java/org/kew/rmf/refine/domain/query/Property.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.refine.domain.query; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Property { private String p; private String pid; private String v; @Override public String toString() { return "Property [p=" + p + ", pid=" + pid + ", v=" + v + "]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Property other = (Property) obj; if (p == null) { if (other.p != null) return false; } else if (!p.equals(other.p)) return false; if (pid == null) { if (other.pid != null) return false; } else if (!pid.equals(other.pid)) return false; if (v == null) { if (other.v != null) return false; } else if (!v.equals(other.v)) return false; return true; } /* • Getters and setters • */ public String getP() { return p; } public void setP(String p) { this.p = p; } public String getPid() { return pid; } public void setPid(String pid) { this.pid = pid; } public String getV() { return v; } public void setV(String v) { this.v = v; } }
1,905
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
FlyoutResponse.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service-model/src/main/java/org/kew/rmf/refine/domain/response/FlyoutResponse.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.refine.domain.response; import javax.xml.bind.annotation.XmlRootElement; /** * The flyout response is simply HTML wrapped in JSON. */ @XmlRootElement public class FlyoutResponse { private String html; public FlyoutResponse() {} public FlyoutResponse(String html) { this.html = html; } public String getHtml() { return html; } public void setHtml(String html) { this.html = html; } }
1,175
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
QueryResultComparator.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service-model/src/main/java/org/kew/rmf/refine/domain/response/QueryResultComparator.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.refine.domain.response; import java.util.Comparator; public class QueryResultComparator implements Comparator<QueryResult>{ @Override public int compare(QueryResult o1, QueryResult o2) { return Double.compare(o2.getScore(), o1.getScore()); } }
1,022
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
QueryResult.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service-model/src/main/java/org/kew/rmf/refine/domain/response/QueryResult.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.refine.domain.response; import java.util.Arrays; import javax.xml.bind.annotation.XmlRootElement; import org.kew.rmf.refine.domain.metadata.Type; @XmlRootElement public class QueryResult { private String id; private String name; private Type[] type; private double score; private boolean match; @Override public String toString() { return "QueryResult [id=" + id + ", name=" + name + ", type=" + Arrays.toString(type) + ", score=" + score + ", match=" + match + "]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; QueryResult other = (QueryResult) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (match != other.match) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (Double.doubleToLongBits(score) != Double.doubleToLongBits(other.score)) return false; if (!Arrays.equals(type, other.type)) return false; return true; } /* • Getters and setters • */ public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Type[] getType() { return type; } public void setType(Type[] type) { this.type = type; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } public boolean isMatch() { return match; } public void setMatch(boolean match) { this.match = match; } }
2,506
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
QueryResponse.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service-model/src/main/java/org/kew/rmf/refine/domain/response/QueryResponse.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.refine.domain.response; import java.util.Arrays; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class QueryResponse<T> { private T[] result; @Override public String toString() { return "QueryResponse [result=" + Arrays.toString(result) + "]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; QueryResponse<?> other = (QueryResponse<?>) obj; if (!Arrays.equals(result, other.result)) return false; return true; } /* • Getters and setters • */ public T[] getResult() { return result; } public void setResult(T[] result) { this.result = result; } }
1,507
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
ScientificNameToPropertiesConverterTest.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/test/java/org/kew/rmf/reconciliation/queryextractor/ScientificNameToPropertiesConverterTest.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.queryextractor; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.hasItems; import static org.junit.Assert.assertThat; import org.junit.Test; import org.kew.rmf.refine.domain.query.Property; public class ScientificNameToPropertiesConverterTest { @Test public void testExtractProperties() { QueryStringToPropertiesExtractor extractor = new ScientificNameToPropertiesConverter(); Property expectedEpithet1 = new Property(); Property expectedEpithet2 = new Property(); Property expectedEpithet3 = new Property(); Property expectedBasionymAuthor = new Property(); Property expectedPublishingAuthor = new Property(); expectedEpithet1.setP("epithet_1"); expectedEpithet1.setPid("epithet_1"); expectedEpithet2.setP("epithet_2"); expectedEpithet2.setPid("epithet_2"); expectedEpithet3.setP("epithet_3"); expectedEpithet3.setPid("epithet_3"); expectedBasionymAuthor.setP("basionym_author"); expectedBasionymAuthor.setPid("basionym_author"); expectedPublishingAuthor.setP("publishing_author"); expectedPublishingAuthor.setPid("publishing_author"); // Fagaceae expectedEpithet1.setV("Fagaceae"); assertThat(asList(extractor.extractProperties("Fagaceae")), hasItems(expectedEpithet1)); assertThat(asList(extractor.extractProperties("Fagaceae")).size(), equalTo(1)); // Fagaceae Juss. expectedEpithet1.setV("Fagaceae"); expectedPublishingAuthor.setV("Juss."); assertThat(asList(extractor.extractProperties("Fagaceae Juss.")), hasItems(expectedEpithet1, expectedPublishingAuthor)); assertThat(asList(extractor.extractProperties("Fagaceae Juss.")).size(), equalTo(2)); // Asteraceae subfam. Barnadesioidae K.Bremer & R.K.Jansen expectedEpithet1.setV("Barnadesioidae"); expectedPublishingAuthor.setV("K.Bremer & R.K.Jansen"); assertThat(asList(extractor.extractProperties("Asteraceae subfam. Barnadesioidae K.Bremer & R.K.Jansen")), hasItems(expectedEpithet1, expectedPublishingAuthor)); assertThat(asList(extractor.extractProperties("Asteraceae subfam. Barnadesioidae K.Bremer & R.K.Jansen")).size(), equalTo(2)); // Barnadesioidae K.Bremer & R.K.Jansen expectedEpithet1.setV("Barnadesioidae"); expectedPublishingAuthor.setV("K.Bremer & R.K.Jansen"); assertThat(asList(extractor.extractProperties("Barnadesioidae K.Bremer & R.K.Jansen")), hasItems(expectedEpithet1, expectedPublishingAuthor)); assertThat(asList(extractor.extractProperties("Barnadesioidae K.Bremer & R.K.Jansen")).size(), equalTo(2)); // Asteraceae trib. Chaenactideae B.G.Baldwin expectedEpithet1.setV("Chaenactideae"); expectedPublishingAuthor.setV("B.G.Baldwin"); assertThat(asList(extractor.extractProperties("Asteraceae trib. Chaenactideae B.G.Baldwin")), hasItems(expectedEpithet1, expectedPublishingAuthor)); assertThat(asList(extractor.extractProperties("Asteraceae trib. Chaenactideae B.G.Baldwin")).size(), equalTo(2)); // Asteraceae subtrib. Chaenactidinae Rydb. expectedEpithet1.setV("Chaenactideae"); expectedPublishingAuthor.setV("B.G.Baldwin"); assertThat(asList(extractor.extractProperties("Chaenactideae B.G.Baldwin")), hasItems(expectedEpithet1, expectedPublishingAuthor)); assertThat(asList(extractor.extractProperties("Chaenactideae B.G.Baldwin")).size(), equalTo(2)); // Asteraceae supersubtrib. Chaenactidodinae C.Jeffrey expectedEpithet1.setV("Chaenactidodinae"); expectedPublishingAuthor.setV("C.Jeffrey"); assertThat(asList(extractor.extractProperties("Asteraceae supersubtrib. Chaenactidodinae C.Jeffrey")), hasItems(expectedEpithet1, expectedPublishingAuthor)); assertThat(asList(extractor.extractProperties("Asteraceae supersubtrib. Chaenactidodinae C.Jeffrey")).size(), equalTo(2)); // Quercus expectedEpithet1.setV("Quercus"); assertThat(asList(extractor.extractProperties("Quercus")), hasItems(expectedEpithet1)); assertThat(asList(extractor.extractProperties("Quercus")).size(), equalTo(1)); // Quercus L. expectedEpithet1.setV("Quercus"); expectedPublishingAuthor.setV("L."); assertThat(asList(extractor.extractProperties("Quercus L.")), hasItems(expectedEpithet1, expectedPublishingAuthor)); assertThat(asList(extractor.extractProperties("Quercus L.")).size(), equalTo(2)); // Helichrysum sect. Chrysocephalum (Walp.) Benth. expectedEpithet1.setV("Helichrysum"); expectedEpithet2.setV("Chrysocephalum"); expectedBasionymAuthor.setV("Walp."); expectedPublishingAuthor.setV("Benth."); assertThat(asList(extractor.extractProperties("Helichrysum sect. Chrysocephalum (Walp.) Benth.")), hasItems(expectedEpithet1, expectedEpithet2, expectedBasionymAuthor, expectedPublishingAuthor)); assertThat(asList(extractor.extractProperties("Helichrysum sect. Chrysocephalum (Walp.) Benth.")).size(), equalTo(4)); // Quercus alba expectedEpithet1.setV("Quercus"); expectedEpithet2.setV("alba"); assertThat(asList(extractor.extractProperties("Quercus alba")), hasItems(expectedEpithet1, expectedEpithet2)); assertThat(asList(extractor.extractProperties("Quercus alba")).size(), equalTo(2)); // Quercus alba L. expectedEpithet1.setV("Quercus"); expectedEpithet2.setV("alba"); expectedPublishingAuthor.setV("L."); assertThat(asList(extractor.extractProperties("Quercus alba L.")), hasItems(expectedEpithet1, expectedEpithet2, expectedPublishingAuthor)); assertThat(asList(extractor.extractProperties("Quercus alba L.")).size(), equalTo(3)); // Quercus alba f. alba expectedEpithet1.setV("Quercus"); expectedEpithet2.setV("alba"); expectedEpithet3.setV("alba"); assertThat(asList(extractor.extractProperties("Quercus alba f. alba")), hasItems(expectedEpithet1, expectedEpithet2, expectedEpithet3)); assertThat(asList(extractor.extractProperties("Quercus alba f. alba")).size(), equalTo(3)); // Quercus alba f. viridis Trel. expectedEpithet1.setV("Quercus"); expectedEpithet2.setV("alba"); expectedEpithet3.setV("viridis"); expectedPublishingAuthor.setV("Trel."); assertThat(asList(extractor.extractProperties("Quercus alba f. viridis Trel.")), hasItems(expectedEpithet1, expectedEpithet2, expectedEpithet3, expectedPublishingAuthor)); assertThat(asList(extractor.extractProperties("Quercus alba f. viridis Trel.")).size(), equalTo(4)); // Quercus alba f. latiloba (Sarg.) E.J.Palmer & Steyerm. expectedEpithet1.setV("Quercus"); expectedEpithet2.setV("alba"); expectedEpithet3.setV("latiloba"); expectedBasionymAuthor.setV("Sarg."); expectedPublishingAuthor.setV("E.J.Palmer & Steyerm."); assertThat(asList(extractor.extractProperties("Quercus alba f. latiloba (Sarg.) E.J.Palmer & Steyerm.")), hasItems(expectedEpithet1, expectedEpithet2, expectedEpithet3, expectedBasionymAuthor, expectedPublishingAuthor)); assertThat(asList(extractor.extractProperties("Quercus alba f. latiloba (Sarg.) E.J.Palmer & Steyerm.")).size(), equalTo(5)); // Quercus alba L. f. latiloba (Sarg.) E.J.Palmer & Steyerm. expectedEpithet1.setV("Quercus"); expectedEpithet2.setV("alba"); expectedEpithet3.setV("latiloba"); expectedBasionymAuthor.setV("Sarg."); expectedPublishingAuthor.setV("E.J.Palmer & Steyerm."); assertThat(asList(extractor.extractProperties("Quercus alba L. f. latiloba (Sarg.) E.J.Palmer & Steyerm.")), hasItems(expectedEpithet1, expectedEpithet2, expectedEpithet3, expectedBasionymAuthor, expectedPublishingAuthor)); assertThat(asList(extractor.extractProperties("Quercus alba L. f. latiloba (Sarg.) E.J.Palmer & Steyerm.")).size(), equalTo(5)); } @Test public void testExtractPropertiesMoreExamples() { QueryStringToPropertiesExtractor extractor = new ScientificNameToPropertiesConverter(); Property expectedEpithet1 = new Property(); Property expectedEpithet2 = new Property(); Property expectedEpithet3 = new Property(); Property expectedBasionymAuthor = new Property(); Property expectedPublishingAuthor = new Property(); expectedEpithet1.setP("epithet_1"); expectedEpithet1.setPid("epithet_1"); expectedEpithet2.setP("epithet_2"); expectedEpithet2.setPid("epithet_2"); expectedEpithet3.setP("epithet_3"); expectedEpithet3.setPid("epithet_3"); expectedBasionymAuthor.setP("basionym_author"); expectedBasionymAuthor.setPid("basionym_author"); expectedPublishingAuthor.setP("publishing_author"); expectedPublishingAuthor.setPid("publishing_author"); // Fagaceæ — Æ ligature expectedEpithet1.setV("Fagaceæ"); assertThat(asList(extractor.extractProperties("Fagaceæ")), hasItems(expectedEpithet1)); assertThat(asList(extractor.extractProperties("Fagaceæ")).size(), equalTo(1)); // Quercus alba L. f. latiloba (Sarg.) E.J.Palmer & Steyerm. — spaces are a mess expectedEpithet1.setV("Quercus"); expectedEpithet2.setV("alba"); expectedEpithet3.setV("latiloba"); expectedBasionymAuthor.setV("Sarg."); expectedPublishingAuthor.setV("E.J.Palmer & Steyerm."); assertThat(asList(extractor.extractProperties(" Quercus alba L. f. latiloba (Sarg.) E.J.Palmer & Steyerm. ")), hasItems(expectedEpithet1, expectedEpithet2, expectedEpithet3, expectedBasionymAuthor, expectedPublishingAuthor)); assertThat(asList(extractor.extractProperties(" Quercus alba L. f. latiloba (Sarg.) E.J.Palmer & Steyerm. ")).size(), equalTo(5)); } }
10,088
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
GenusSpeciesInfraspeciesToPropertiesConverterTest.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/test/java/org/kew/rmf/reconciliation/queryextractor/GenusSpeciesInfraspeciesToPropertiesConverterTest.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.queryextractor; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.hasItems; import static org.junit.Assert.assertThat; import org.junit.Test; import org.kew.rmf.refine.domain.query.Property; public class GenusSpeciesInfraspeciesToPropertiesConverterTest { @Test public void testExtractProperties() { QueryStringToPropertiesExtractor extractor = new GenusSpeciesInfraspeciesToPropertiesConverter(); Property expectedGenus = new Property(); Property expectedSpecies = new Property(); Property expectedInfraspecies = new Property(); Property expectedAuthors = new Property(); expectedGenus.setP("genus"); expectedGenus.setPid("genus"); expectedSpecies.setP("species"); expectedSpecies.setPid("species"); expectedInfraspecies.setP("infraspecies"); expectedInfraspecies.setPid("infraspecies"); expectedAuthors.setP("authors"); expectedAuthors.setPid("authors"); // Fagaceae expectedGenus.setV("Fagaceae"); assertThat(asList(extractor.extractProperties("Fagaceae")), hasItems(expectedGenus)); assertThat(asList(extractor.extractProperties("Fagaceae")).size(), equalTo(1)); // Fagaceae Juss. expectedGenus.setV("Fagaceae"); expectedAuthors.setV("Juss."); assertThat(asList(extractor.extractProperties("Fagaceae Juss.")), hasItems(expectedGenus, expectedAuthors)); assertThat(asList(extractor.extractProperties("Fagaceae Juss.")).size(), equalTo(2)); // Asteraceae subfam. Barnadesioidae K.Bremer & R.K.Jansen //expectedGenus.setV("Barnadesioidae"); //expectedAuthors.setV("K.Bremer & R.K.Jansen"); //assertThat(asList(extractor.extractProperties("Asteraceae subfam. Barnadesioidae K.Bremer & R.K.Jansen")), hasItems(expectedGenus, expectedAuthors)); //assertThat(asList(extractor.extractProperties("Asteraceae subfam. Barnadesioidae K.Bremer & R.K.Jansen")).size(), equalTo(2)); // Barnadesioidae K.Bremer & R.K.Jansen expectedGenus.setV("Barnadesioidae"); expectedAuthors.setV("K.Bremer & R.K.Jansen"); assertThat(asList(extractor.extractProperties("Barnadesioidae K.Bremer & R.K.Jansen")), hasItems(expectedGenus, expectedAuthors)); assertThat(asList(extractor.extractProperties("Barnadesioidae K.Bremer & R.K.Jansen")).size(), equalTo(2)); // Asteraceae trib. Chaenactideae B.G.Baldwin //expectedGenus.setV("Chaenactideae"); //expectedAuthors.setV("B.G.Baldwin"); //assertThat(asList(extractor.extractProperties("Asteraceae trib. Chaenactideae B.G.Baldwin")), hasItems(expectedGenus, expectedAuthors)); //assertThat(asList(extractor.extractProperties("Asteraceae trib. Chaenactideae B.G.Baldwin")).size(), equalTo(2)); // Asteraceae subtrib. Chaenactidinae Rydb. expectedGenus.setV("Chaenactideae"); expectedAuthors.setV("B.G.Baldwin"); assertThat(asList(extractor.extractProperties("Chaenactideae B.G.Baldwin")), hasItems(expectedGenus, expectedAuthors)); assertThat(asList(extractor.extractProperties("Chaenactideae B.G.Baldwin")).size(), equalTo(2)); // Asteraceae supersubtrib. Chaenactidodinae C.Jeffrey //expectedGenus.setV("Chaenactidodinae"); //expectedAuthors.setV("C.Jeffrey"); //assertThat(asList(extractor.extractProperties("Asteraceae supersubtrib. Chaenactidodinae C.Jeffrey")), hasItems(expectedGenus, expectedAuthors)); //assertThat(asList(extractor.extractProperties("Asteraceae supersubtrib. Chaenactidodinae C.Jeffrey")).size(), equalTo(2)); // Quercus expectedGenus.setV("Quercus"); assertThat(asList(extractor.extractProperties("Quercus")), hasItems(expectedGenus)); assertThat(asList(extractor.extractProperties("Quercus")).size(), equalTo(1)); // Quercus L. expectedGenus.setV("Quercus"); expectedAuthors.setV("L."); assertThat(asList(extractor.extractProperties("Quercus L.")), hasItems(expectedGenus, expectedAuthors)); assertThat(asList(extractor.extractProperties("Quercus L.")).size(), equalTo(2)); // Helichrysum sect. Chrysocephalum (Walp.) Benth. //expectedGenus.setV("Helichrysum"); //expectedSpecies.setV("Chrysocephalum"); //expectedAuthors.setV("(Walp.) Benth."); //assertThat(asList(extractor.extractProperties("Helichrysum sect. Chrysocephalum (Walp.) Benth.")), hasItems(expectedGenus, expectedSpecies, expectedAuthors)); //assertThat(asList(extractor.extractProperties("Helichrysum sect. Chrysocephalum (Walp.) Benth.")).size(), equalTo(3)); // Quercus alba expectedGenus.setV("Quercus"); expectedSpecies.setV("alba"); assertThat(asList(extractor.extractProperties("Quercus alba")), hasItems(expectedGenus, expectedSpecies)); assertThat(asList(extractor.extractProperties("Quercus alba")).size(), equalTo(2)); // Quercus alba L. expectedGenus.setV("Quercus"); expectedSpecies.setV("alba"); expectedAuthors.setV("L."); assertThat(asList(extractor.extractProperties("Quercus alba L.")), hasItems(expectedGenus, expectedSpecies, expectedAuthors)); assertThat(asList(extractor.extractProperties("Quercus alba L.")).size(), equalTo(3)); // Quercus alba f. alba expectedGenus.setV("Quercus"); expectedSpecies.setV("alba"); expectedInfraspecies.setV("alba"); assertThat(asList(extractor.extractProperties("Quercus alba f. alba")), hasItems(expectedGenus, expectedSpecies, expectedInfraspecies)); assertThat(asList(extractor.extractProperties("Quercus alba f. alba")).size(), equalTo(3)); // Quercus alba f. viridis Trel. expectedGenus.setV("Quercus"); expectedSpecies.setV("alba"); expectedInfraspecies.setV("viridis"); expectedAuthors.setV("Trel."); assertThat(asList(extractor.extractProperties("Quercus alba f. viridis Trel.")), hasItems(expectedGenus, expectedSpecies, expectedInfraspecies, expectedAuthors)); assertThat(asList(extractor.extractProperties("Quercus alba f. viridis Trel.")).size(), equalTo(4)); // Quercus alba f. latiloba (Sarg.) E.J.Palmer & Steyerm. expectedGenus.setV("Quercus"); expectedSpecies.setV("alba"); expectedInfraspecies.setV("latiloba"); expectedAuthors.setV("(Sarg.) E.J.Palmer & Steyerm."); assertThat(asList(extractor.extractProperties("Quercus alba f. latiloba (Sarg.) E.J.Palmer & Steyerm.")), hasItems(expectedGenus, expectedSpecies, expectedInfraspecies, expectedAuthors)); assertThat(asList(extractor.extractProperties("Quercus alba f. latiloba (Sarg.) E.J.Palmer & Steyerm.")).size(), equalTo(4)); // Quercus alba L. f. latiloba (Sarg.) E.J.Palmer & Steyerm. //expectedGenus.setV("Quercus"); //expectedSpecies.setV("alba"); //expectedInfraspecies.setV("latiloba"); //expectedAuthors.setV("(Sarg.) E.J.Palmer & Steyerm."); //assertThat(asList(extractor.extractProperties("Quercus alba L. f. latiloba (Sarg.) E.J.Palmer & Steyerm.")), hasItems(expectedGenus, expectedSpecies, expectedInfraspecies, expectedAuthors)); //assertThat(asList(extractor.extractProperties("Quercus alba L. f. latiloba (Sarg.) E.J.Palmer & Steyerm.")).size(), equalTo(4)); // • Less-perfect examples // Jaffueliobryum arsenei (Thér.) Thér. // (Multiple spaces.) expectedGenus.setV("Jaffueliobryum"); expectedSpecies.setV("arsenei"); expectedAuthors.setV("(Thér.) Thér."); assertThat(asList(extractor.extractProperties("Jaffueliobryum arsenei (Thér.) Thér.")), hasItems(expectedGenus, expectedSpecies, expectedAuthors)); assertThat(asList(extractor.extractProperties("Jaffueliobryum arsenei (Thér.) Thér.")).size(), equalTo(3)); } }
8,197
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
CitationToPropertiesConverterTest.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/test/java/org/kew/rmf/reconciliation/queryextractor/CitationToPropertiesConverterTest.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.queryextractor; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.hasItems; import static org.junit.Assert.assertThat; import org.junit.Test; import org.kew.rmf.refine.domain.query.Property; public class CitationToPropertiesConverterTest { @Test public void testExtractProperties() { QueryStringToPropertiesExtractor extractor = new CitationToPropertiesConverter(); Property expectedPublication = new Property(); Property expectedDate = new Property(); Property expectedAuthors = new Property(); expectedPublication.setP("publication"); expectedPublication.setPid(expectedPublication.getP()); expectedAuthors.setP("authors"); expectedAuthors.setPid(expectedAuthors.getP()); expectedDate.setP("date"); expectedDate.setPid(expectedDate.getP()); // Publication expectedPublication.setV("Reconciliation Service"); assertThat(asList(extractor.extractProperties("Reconciliation Service")), hasItems(expectedPublication)); assertThat(asList(extractor.extractProperties("Reconciliation Service")).size(), equalTo(1)); // Publication and authors expectedPublication.setV("Reconciliation Service"); expectedAuthors.setV("Matthew Blissett et. al."); assertThat(asList(extractor.extractProperties("Reconciliation Service [Matthew Blissett et. al.]")), hasItems(expectedPublication, expectedAuthors)); assertThat(asList(extractor.extractProperties("Reconciliation Service [Matthew Blissett et. al.]")).size(), equalTo(2)); // Publication and date expectedPublication.setV("Reconciliation Service"); expectedDate.setV("2014"); assertThat(asList(extractor.extractProperties("Reconciliation Service, (2014).")), hasItems(expectedPublication, expectedDate)); assertThat(asList(extractor.extractProperties("Reconciliation Service, (2014).")).size(), equalTo(2)); // All three expectedPublication.setV("Reconciliation Service"); expectedAuthors.setV("Matthew Blissett et. al."); expectedDate.setV("2014"); assertThat(asList(extractor.extractProperties("Reconciliation Service [Matthew Blissett et. al.], (2014).")), hasItems(expectedPublication, expectedDate, expectedAuthors)); assertThat(asList(extractor.extractProperties("Reconciliation Service [Matthew Blissett et. al.], (2014).")).size(), equalTo(3)); } }
3,131
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
SpecimenCitationToPropertiesConverterTest.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/test/java/org/kew/rmf/reconciliation/queryextractor/SpecimenCitationToPropertiesConverterTest.java
/* * Reconciliation and Matching Fram!ework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.queryextractor; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.hasItems; import static org.junit.Assert.assertThat; import org.junit.Ignore; import org.junit.Test; import org.kew.rmf.refine.domain.query.Property; public class SpecimenCitationToPropertiesConverterTest { @Test @Ignore public void testExtractProperties() { QueryStringToPropertiesExtractor extractor = new SpecimenCitationToPropertiesConverter(); Property expectedCollectorName = new Property(); Property expectedCollectorNumber = new Property(); Property expectedCollectionDate = new Property(); Property expectedLocality = new Property(); Property expectedCountry = new Property(); Property expectedHerbarium = new Property(); expectedCollectorName.setP("collector_name"); expectedCollectorName.setPid("collector_name"); expectedCollectorNumber.setP("collector_number"); expectedCollectorNumber.setPid("collector_number"); expectedCollectionDate.setP("collection_date"); expectedCollectionDate.setPid("collection_date"); expectedLocality.setP("locality"); expectedLocality.setPid("locality"); expectedCountry.setP("country"); expectedCountry.setPid("country"); expectedHerbarium.setP("herbarium"); expectedHerbarium.setPid("herbarium"); // Zambia: c. 3 km west of Kalabo, foot of escarpment at edge of swamp bordering river, fl. 13.xi.1959, Drummond & Cookson 6442 (E; K; LISC; SRGH). String citation = "Zambia: c. 3 km west of Kalabo, foot of escarpment at edge of swamp bordering river, fl. 13.xi.1959, Drummond & Cookson 6442 (E; K; LISC; SRGH)."; expectedCountry.setV("Zambia"); expectedLocality.setV("c. 3 km west of Kalabo, foot of escarpment at edge of swamp bordering river, fl."); expectedCollectionDate.setV("13.xi.1959"); expectedCollectorName.setV("Drummond & Cookson"); expectedCollectorNumber.setV("6442"); expectedHerbarium.setV("E; K; LISC; SRGH"); assertThat(asList(extractor.extractProperties(citation)), hasItems(expectedCollectorName, expectedCollectorNumber, expectedCollectionDate, expectedLocality, expectedCountry, expectedHerbarium)); assertThat(asList(extractor.extractProperties(citation)).size(), equalTo(6)); } }
3,045
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
ReconciliationResultPropertyFormatterTest.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/test/java/org/kew/rmf/reconciliation/resultformatter/ReconciliationResultPropertyFormatterTest.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.resultformatter; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import java.util.Arrays; import java.util.HashMap; import org.junit.Test; import org.kew.rmf.reconciliation.service.resultformatter.ReconciliationResultPropertyFormatter; public class ReconciliationResultPropertyFormatterTest { @Test public void testFormatResult() { ReconciliationResultPropertyFormatter formatter = new ReconciliationResultPropertyFormatter(); formatter.setFormat("%s * %s : '%s'"); formatter.setProperties(Arrays.asList(new String[]{"x", "a", "f"})); HashMap<String, String> result = new HashMap<>(); result.put("x", "y"); result.put("a", "b"); result.put("f", "g"); result.put("m", "n"); String formattedResult = formatter.formatResult(result); assertThat(formattedResult, equalTo("y * b : 'g'")); } }
1,648
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
WebInterfaceStepdefs.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/test/java/org/kew/rmf/reconciliation/ws/WebInterfaceStepdefs.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.ws; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import cucumber.api.PendingException; import cucumber.api.java.Before; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; @WebAppConfiguration @ContextConfiguration("classpath:/META-INF/spring/cucumber.xml") public class WebInterfaceStepdefs { //private static Logger log = LoggerFactory.getLogger(WebInterfaceStepdefs.class); //private static final String TEXT_HTML_UTF8 = "text/html;charset=UTF-8"; @Autowired private WebApplicationContext wac; private MockMvc mockMvc; //private MvcResult result; //private Document html; //private Element propertyTransformers; //private Element propertyMatcher; @Before public void setup() { mockMvc = MockMvcBuilders.webAppContextSetup(wac) .build(); // TODO: Temporary fix to allow test configuration to have loaded. // Once the ReconciliatioService allows querying for this, this should be replaced. try { Thread.sleep(2L * 1000L); } catch (InterruptedException e) {} } @Given("^I am on the about page for \"(.*?)\"$") public void i_am_on_the_about_page_for(String configName) throws Throwable { // Call //result = mockMvc.perform(get("/about/"+configName)) //.accept(MediaType.TEXT_HTML)) .andDo(print()) .andExpect(status().isOk()) //.andExpect(content().contentType(TEXT_HTML_UTF8)) .andExpect(view().name("about-matcher")) .andExpect(MockMvcResultMatchers.model().attribute("configName", "generalTest")) .andReturn(); // Because we are using JSPs it's not possible to check their execution — we need a servlet container to execute them. //Document html = Jsoup.parse(result.getResponse().getContentAsString()); } @When("^I look at the detail for the property \"(.*?)\"$") public void i_look_at_the_detail_for_the_property(String property) throws Throwable { throw new PendingException("Can't check contents of JSPs without a servlet container to execute them."); //log.info("Want to select {}", "#"+property+"_transformers"); //propertyTransformers = html.select("#"+property+"_transformers").first(); //propertyMatcher = html.select("#"+property+"_matcher").first(); } @Then("^the transformers are$") public void the_transformers_are(List<Map<String,String>> values) throws Throwable { //for (Element transformer : propertyTransformers.children()) { // transformer.select("span").first().text().equals("Epithet Transformer"); // transformer.select("span").first().attr("title").equals("org.kew.stuff"); // transformer.select("span").get(1).text().equals("replacement: \"\""); //} throw new PendingException(); } @Then("^the matcher is$") public void the_matcher_is(List<Map<String,String>> values) throws Throwable { throw new PendingException(); } @When("^I type in the atomized name details:$") public void i_type_in_the_atomized_name_details(Map<String,String> details) throws Throwable { throw new PendingException(); } @When("^run the query$") public void run_the_query() throws Throwable { throw new PendingException(); } @Then("^the results are$") public void the_results_are(Map<String,String> results) throws Throwable { throw new PendingException(); } @When("^I type in the unatomized name \"(.*?)\"$") public void i_type_in_the_unatomized_name(String arg1) throws Throwable { throw new PendingException(); } }
4,892
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
RunCucumberWsTest.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/test/java/org/kew/rmf/reconciliation/ws/RunCucumberWsTest.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.ws; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions(format = {"pretty", "html:target/site/cukes/ws", "json:target/site/cukes/ws/cucumber.json"}, monochrome = false) public class RunCucumberWsTest { }
1,089
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
GeneralReconciliationServiceStepdefs.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/test/java/org/kew/rmf/reconciliation/ws/GeneralReconciliationServiceStepdefs.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.ws; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import java.util.Map; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion; import org.codehaus.jackson.type.TypeReference; import org.hamcrest.Matchers; import org.junit.Assert; import org.kew.rmf.refine.domain.metadata.Metadata; import org.kew.rmf.refine.domain.query.Query; import org.kew.rmf.refine.domain.response.QueryResponse; import org.kew.rmf.refine.domain.response.QueryResult; import org.skyscreamer.jsonassert.JSONAssert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import cucumber.api.PendingException; import cucumber.api.java.Before; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; @WebAppConfiguration @ContextConfiguration("classpath:/META-INF/spring/cucumber.xml") public class GeneralReconciliationServiceStepdefs extends WebMvcConfigurationSupport { private static Logger log = LoggerFactory.getLogger(GeneralReconciliationServiceStepdefs.class); private static final String JSON_UTF8_S = "application/json;charset=UTF-8"; private static final MediaType JSON_UTF8 = MediaType.parseMediaType(JSON_UTF8_S); @Autowired private WebApplicationContext wac; private ObjectMapper mapper = new ObjectMapper(); private MockMvc mockMvc; private String responseJson; private ResultActions resultActions; private MvcResult result; public GeneralReconciliationServiceStepdefs() { mapper.setSerializationInclusion(Inclusion.NON_NULL); } @Before public void setup() { mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); // TODO: Temporary fix to allow test configuration to have loaded. // Once the ReconciliatioService allows querying for this, this should be replaced. try { Thread.sleep(2L * 1000L); } catch (InterruptedException e) {} } @When("^I query for metadata of the \"(.*?)\" reconciliation service$") public void i_query_for_metadata_of_the_reconciliation_service(String configName) throws Throwable { // Call resultActions = mockMvc.perform(get("/reconcile/"+configName).accept(JSON_UTF8)) // .andExpect(status().isOk()) .andExpect(content().contentType(JSON_UTF8_S)); result = resultActions.andReturn(); if (result.getResponse().getStatus() == HttpStatus.OK.value()) { responseJson = result.getResponse().getContentAsString(); log.debug("Response as string was {}", responseJson); } } @Then("^I receive an HTTP (\\d+) result\\.$") public void i_receive_an_HTTP_result(int expectedStatus) throws Throwable { Assert.assertThat("Expected HTTP Status "+expectedStatus, result.getResponse().getStatus(), Matchers.equalTo(expectedStatus)); } @Then("^cross-site access is permitted$") public void cross_site_access_is_permitted() throws Throwable { resultActions.andExpect(header().string("Access-Control-Allow-Origin", "*")); } @Then("^I receive the following metadata response:$") public void i_receive_the_following_metadata_response(String expectedResponseString) throws Throwable { Metadata responseMetadata = mapper.readValue(responseJson, Metadata.class); // Check response log.info("Received response {}", responseMetadata); Metadata expectedResponse = new ObjectMapper().readValue(expectedResponseString, Metadata.class); Assert.assertThat("Metadata response correct", responseMetadata, Matchers.equalTo(expectedResponse)); } @When("^I make a match query for \"(.*?)\"$") public void i_make_a_match_query_for(String queryString) throws Throwable { // Call resultActions = mockMvc.perform(get("/match/generalTest?"+queryString).accept(JSON_UTF8)) .andExpect(status().isOk()) .andExpect(content().contentType(JSON_UTF8_S)); result = resultActions.andReturn(); responseJson = result.getResponse().getContentAsString(); log.debug("Response as string was {}", responseJson); } @Then("^I receive the following match response:$") public void i_receive_the_following_match_response(String expectedJson) throws Throwable { JSONAssert.assertEquals(expectedJson, responseJson, true); } @When("^I make the reconciliation query:$") public void i_make_the_reconciliation_query(String queryJson) throws Throwable { Query query = mapper.readValue(queryJson, Query.class); log.debug("Query is {}", "/reconcile/generalTest?query="+mapper.writeValueAsString(query)); resultActions = mockMvc.perform(post("/reconcile/generalTest?query={query}", mapper.writeValueAsString(query)).accept(JSON_UTF8)) .andExpect(status().isOk()) .andExpect(content().contentType(JSON_UTF8_S)); result = resultActions.andReturn(); responseJson = result.getResponse().getContentAsString(); log.debug("Response as string was {}", responseJson); } @Then("^I receive the following reconciliation response:$") public void i_receive_the_following_reconciliation_response(String expectedResponseString) throws Throwable { QueryResponse<QueryResult> actualResponse = mapper.readValue(responseJson, new TypeReference<QueryResponse<QueryResult>>(){}); // Check response log.info("Received response {}", actualResponse); QueryResponse<QueryResult> expectedResponse = mapper.readValue(expectedResponseString, new TypeReference<QueryResponse<QueryResult>>(){}); Assert.assertThat("QueryResponse<QueryResult> response correct", actualResponse, Matchers.equalTo(expectedResponse)); } @When("^I make the reconciliation queries:$") public void i_make_the_reconciliation_queries(String queriesJson) throws Throwable { Map<String,Query> queries = mapper.readValue(queriesJson, new TypeReference<Map<String,Query>>() {}); log.debug("Query is {}", "/reconcile/generalTest?queries="+mapper.writeValueAsString(queries)); resultActions = mockMvc.perform(post("/reconcile/generalTest?queries={queries}", mapper.writeValueAsString(queries)).accept(JSON_UTF8)) .andExpect(status().isOk()) .andExpect(content().contentType(JSON_UTF8_S)); result = resultActions.andReturn(); responseJson = result.getResponse().getContentAsString(); log.debug("Response as string was {}", responseJson); } @Then("^I receive the following reconciliation multiple response:$") public void i_receive_the_following_reconciliation_multiple_response(String expectedResponseString) throws Throwable { Map<String,QueryResponse<QueryResult>> actualResponse = mapper.readValue(responseJson, new TypeReference<Map<String,QueryResponse<QueryResult>>>() {}); // Check response log.info("Received response {}", actualResponse); Map<String,QueryResponse<QueryResult>> expectedResponse = mapper.readValue(expectedResponseString, new TypeReference<Map<String,QueryResponse<QueryResult>>>() {}); Assert.assertThat("QueryResponse<QueryResult> multiple response correct", actualResponse, Matchers.equalTo(expectedResponse)); } @When("^I make the reconciliation suggest query with prefix \"(.*?)\"$") public void i_make_the_reconciliation_suggest_query_with_prefix(String prefix) throws Throwable { resultActions = mockMvc.perform(get("/reconcile/generalTest?prefix="+prefix).accept(JSON_UTF8)) .andExpect(status().isOk()) .andExpect(content().contentType(JSON_UTF8_S)); result = resultActions.andReturn(); responseJson = result.getResponse().getContentAsString(); log.debug("Response as string was {}", responseJson); } @When("^I make the reconciliation suggest property query with prefix \"(.*?)\"$") public void i_make_the_reconciliation_suggest_property_query_with_prefix(String prefix) throws Throwable { resultActions = mockMvc.perform(get("/reconcile/generalTest/suggestProperty?prefix="+prefix).accept(JSON_UTF8)) .andExpect(status().isOk()) .andExpect(content().contentType(JSON_UTF8_S)); result = resultActions.andReturn(); responseJson = result.getResponse().getContentAsString(); log.debug("Response as string was {}", responseJson); } @When("^I make the reconciliation suggest type query with prefix \"(.*?)\"$") public void i_make_the_reconciliation_suggest_type_query_with_prefix(String prefix) throws Throwable { resultActions = mockMvc.perform(get("/reconcile/generalTest/suggestType?prefix="+prefix).accept(JSON_UTF8)) .andExpect(status().isOk()) .andExpect(content().contentType(JSON_UTF8_S)); result = resultActions.andReturn(); responseJson = result.getResponse().getContentAsString(); log.debug("Response as string was {}", responseJson); } @When("^I make a bulk match query with a file containing these rows:$") public void i_make_a_bulk_match_query_with_a_file_containing_these_rows(String allRows) throws Throwable { MockMultipartFile multipartFile = new MockMultipartFile("file", allRows.getBytes()); resultActions = mockMvc.perform(MockMvcRequestBuilders.fileUpload("/filematch/generalTest/") .file(multipartFile) .param("charset", "UTF-8")) .andExpect(status().is(200)); result = resultActions.andReturn(); } @Then("^I receive the following result file:$") public void i_receive_the_following_result_file(String expectedFile) throws Throwable { String fileName = result.getResponse().getHeader("X-File-Download"); resultActions = mockMvc.perform(get("/download/"+fileName)) .andExpect(status().is(200)); result = resultActions.andReturn(); String actualFile = result.getResponse().getContentAsString(); log.info("File received is\n{}", actualFile); String[] expectedFileLines = expectedFile.split("\r?\n|\r"); String[] actualFileLines = actualFile.split("\r?\n|\r"); for (int i=0; i < expectedFileLines.length; i++) { String expectedLine = expectedFileLines[i]; String actualLine = actualFileLines[i]; try { log.debug("Expecting line «{}», got «{}»", expectedLine, actualLine); assertThat(actualLine, is(expectedLine)); } catch (IndexOutOfBoundsException e) { throw new IndexOutOfBoundsException(String.format("→ line %s not found in match output.", expectedLine)); } } assertThat(actualFileLines.length, is(expectedFileLines.length)); } @When("^I make the reconciliation suggest flyout request with id \"(.*?)\"$") public void i_make_the_reconciliation_suggest_flyout_request_with_id(String id) throws Throwable { throw new PendingException("Not bothering to add WireMock or similar to test something so simple."); //result = mockMvc.perform(get("/reconcile/generalTest/flyout/"+id).accept(JSON_UTF8)) // .andExpect(status().isOk()) // .andExpect(content().contentType(JSON_UTF8_S)) // .andReturn(); //responseJson = result.getResponse().getContentAsString(); //log.debug("Response as string was {}", responseJson); } @Then("^I receive the following flyout response:$") public void i_receive_the_following_flyout_response(String expectedJson) throws Throwable { JSONAssert.assertEquals(expectedJson, responseJson, true); } }
12,593
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
MatchConfigurationTestingStepdefs.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/test/java/org/kew/rmf/reconciliation/configurations/MatchConfigurationTestingStepdefs.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.configurations; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.hamcrest.Matchers; import org.junit.Assert; import org.kew.rmf.core.configuration.ReconciliationServiceConfiguration; import org.kew.rmf.core.exception.MatchExecutionException; import org.kew.rmf.core.exception.TooManyMatchesException; import org.kew.rmf.core.lucene.LuceneMatcher; import org.kew.rmf.reconciliation.queryextractor.QueryStringToPropertiesExtractor; import org.kew.rmf.refine.domain.query.Property; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.context.support.GenericWebApplicationContext; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; @WebAppConfiguration @ContextConfiguration("classpath:/META-INF/spring/cucumber.xml") public class MatchConfigurationTestingStepdefs { private final static Logger logger = LoggerFactory.getLogger(MatchConfigurationTestingStepdefs.class); @Autowired private GenericWebApplicationContext wac; LuceneMatcher currentMatcher; List<Map<String,String>> queryResults; @Given("^I have loaded the \"(.*?)\" configuration$") public void i_have_loaded_the_configuration(String fileName) throws Throwable { currentMatcher = getConfiguration(fileName); Assert.assertNotNull("Failed to load matcher", currentMatcher); } @When("^I query for$") public void i_query_for(List<Map<String,String>> queries) throws Throwable { Assert.assertNotNull("No matcher selected", currentMatcher); // Go through the list of queries one at a time, execute the query, store the result in a new key "result". queryResults = new ArrayList<>(); for (Map<String,String> testQuery : queries) { Map<String,String> result = doSingleTestQuery(testQuery); logger.debug("Query result: {}", result); queryResults.add(result); } } @When("^I query with only a single string for$") public void i_query_with_only_a_single_string_for(List<Map<String,String>> singleStringQueries) throws Throwable { Assert.assertNotNull("No matcher selected", currentMatcher); // Go through the list of queries one at a time, execute the query, store the result in a new key "result". queryResults = new ArrayList<>(); for (Map<String,String> testQuery : singleStringQueries) { Map<String,String> result = doSingleStringTestQuery(testQuery.get("queryId"), testQuery.get("queryString")); logger.debug("Query result: {}", result); queryResults.add(result); } } @Then("^the results are$") public void the_results_are(List<Map<String,String>> expectedResults) throws Throwable { for (Map<String,String> expectedResult : expectedResults) { checkResult(expectedResult); } } private void checkResult(Map<String,String> expectedResult) { String targetId = expectedResult.get("queryId"); Map<String,String> actualResult = null; for (Map<String,String> result : queryResults) { if (targetId.equals(result.get("queryId"))) { actualResult = result; break; } } Assert.assertNotNull("No result found for query "+targetId, actualResult); Assert.assertThat("Match results not correct for query "+expectedResult.get("queryId"), actualResult.get("results"), Matchers.equalTo(expectedResult.get("results"))); } private Map<String,String> doSingleStringTestQuery(String queryId, String query) throws TooManyMatchesException, MatchExecutionException { ReconciliationServiceConfiguration reconConfig = (ReconciliationServiceConfiguration) currentMatcher.getConfig(); QueryStringToPropertiesExtractor propertiesExtractor = reconConfig.getQueryStringToPropertiesExtractor(); Property[] properties = propertiesExtractor.extractProperties(query); Map<String, String> suppliedRecord = new HashMap<String, String>(); suppliedRecord.put("queryId", queryId); for (Property p : properties) { logger.trace("Setting: {} to {}", p.getPid(), p.getV()); suppliedRecord.put(p.getPid(), p.getV()); } return doSingleTestQuery(suppliedRecord); } private Map<String,String> doSingleTestQuery(Map<String,String> origQuery) throws TooManyMatchesException, MatchExecutionException { // Copy the map, as Cucumber supplies an UnmodifiableMap Map<String,String> query = new HashMap<>(); query.putAll(origQuery); query.put("id", query.get("queryId")); // Means the id can show up in the debug output. List<Map<String,String>> matches = currentMatcher.getMatches(query); logger.debug("Found some matches: {}", matches.size()); if (matches.size() < 4) { logger.debug("Matches for {} are {}", query, matches); } // Construct result string (list of ids) ArrayList<String> matchedIds = new ArrayList<>(); for (Map<String,String> match : matches) { matchedIds.add(match.get("id")); } Collections.sort(matchedIds); query.put("results", StringUtils.join(matchedIds, " ")); return query; } private static final Map<String, LuceneMatcher> matchers = new HashMap<String, LuceneMatcher>(); private LuceneMatcher getConfiguration(String config) throws Throwable { logger.debug("Considering initialising match controller with configuration {}", config); // Load up the matchers from the specified files if (!matchers.containsKey(config)){ String configurationFile = "/META-INF/spring/reconciliation-service/" + config + ".xml"; logger.debug("Loading configuration {} from {}", config, configurationFile); ConfigurableApplicationContext context = new GenericXmlApplicationContext(configurationFile); LuceneMatcher matcher = context.getBean("engine", LuceneMatcher.class); matcher.loadData(); logger.debug("Loaded data for configuration {}", config); matchers.put(config, matcher); logger.debug("Stored matcher with name {} from configuration {}", matcher.getConfig().getName(), config); } return matchers.get(config); } }
7,088
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
RunCucumberMatchConfigurationTest.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/test/java/org/kew/rmf/reconciliation/configurations/RunCucumberMatchConfigurationTest.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.configurations; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions(format = {"pretty", "html:target/site/cukes/configurations", "json:target/site/cukes/configurations/cucumber.json"}, monochrome = false) public class RunCucumberMatchConfigurationTest { // TODO: These tests, and the configurations they test, do not depend on the webservice and should be refactored into a separate module. }
1,279
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
QueryStringToPropertiesExtractor.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/main/java/org/kew/rmf/reconciliation/queryextractor/QueryStringToPropertiesExtractor.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.queryextractor; import org.kew.rmf.refine.domain.query.Property; public interface QueryStringToPropertiesExtractor { public Property[] extractProperties(String queryString); }
965
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
SpecimenCitationToPropertiesConverter.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/main/java/org/kew/rmf/reconciliation/queryextractor/SpecimenCitationToPropertiesConverter.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.queryextractor; import java.util.ArrayList; import java.util.List; import org.kew.rmf.refine.domain.query.Property; import org.perf4j.LoggingStopWatch; import org.perf4j.slf4j.Slf4JStopWatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Converts a specimen citation into a set of properties. */ public class SpecimenCitationToPropertiesConverter implements QueryStringToPropertiesExtractor { private static final Logger logger = LoggerFactory.getLogger(SpecimenCitationToPropertiesConverter.class); // Zambia: c. 3 km west of Kalabo, foot of escarpment at edge of swamp bordering river, fl. 13.xi.1959, Drummond & Cookson 6442 (E; K; LISC; SRGH). @Override public Property[] extractProperties(String queryString) { // Log the query if it takes more than 250ms. LoggingStopWatch speedCheck = new Slf4JStopWatch("SpecimenCitationParsing:"+queryString, logger, Slf4JStopWatch.WARN_LEVEL).setTimeThreshold(250); speedCheck.stop(); return makeProperties(queryString); } private Property[] makeProperties(String recordedBy) { List<org.kew.rmf.refine.domain.query.Property> properties = new ArrayList<>(); if (recordedBy != null) { org.kew.rmf.refine.domain.query.Property p = new org.kew.rmf.refine.domain.query.Property(); p.setP("recorded_by"); p.setPid("recorded_by"); p.setV(recordedBy); properties.add(p); } return properties.toArray(new Property[properties.size()]); } }
2,225
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
GenusSpeciesInfraspeciesToPropertiesConverter.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/main/java/org/kew/rmf/reconciliation/queryextractor/GenusSpeciesInfraspeciesToPropertiesConverter.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.queryextractor; import java.util.ArrayList; import java.util.List; import org.kew.rmf.refine.domain.query.Property; public class GenusSpeciesInfraspeciesToPropertiesConverter implements QueryStringToPropertiesExtractor { @Override public Property[] extractProperties(String queryString) { /* * Example scientific names: * Fagaceae * Fagaceae Juss. * Quercus * Quercus L. * Quercus alba * Quercus alba L. * Quercus alba f. alba * Quercus alba f. viridis Trel. * Quercus alba f. latiloba (Sarg.) E.J.Palmer & Steyerm. * Quercus alba L. f. latiloba (Sarg.) E.J.Palmer & Steyerm. * * For the moment, this is just a very basic implementation to satisfy the requirements of the * Reconciliation Service "suggest" and "preview" queries. */ queryString = queryString.replace(" ", " "); String[] parts = queryString.split(" "); String genus = null, species = null, infraspecies = null, authors = null; // Assume first part is generic epithet genus = parts[0]; if (parts.length == 1) return makeProperties(genus, species, infraspecies, authors); // If second part has capital letter or "(", assume rest of name is authors if (isCapital(parts[1].charAt(0)) || parts[1].charAt(0) == '(') { authors = joinRest(parts, 1); } // Otherwise, assume second part is species else { species = parts[1]; if (parts.length == 2) return makeProperties(genus, species, infraspecies, authors); // If third part has capital letter or "(", assume rest of name is authors if (isCapital(parts[2].charAt(0)) || parts[2].charAt(0) == '(') { authors = joinRest(parts, 2); } // Otherwise, infraspecific rank (ignore) and infraspecific epithet else { // parts[2] is infraspecific rank if (parts.length == 3) return makeProperties(genus, species, infraspecies, authors); infraspecies = parts[3]; // bounds check if (parts.length == 4) return makeProperties(genus, species, infraspecies, authors); authors = joinRest(parts, 4); } } return makeProperties(genus, species, infraspecies, authors); } private boolean isCapital(char letter) { return letter >= 'A' && letter <= 'Z'; } /** * Joins from index'th to last element of array with space. * * If index is out of bounds, returns empty string. */ private String joinRest(String[] array, int index) { StringBuilder joined = new StringBuilder(); while (index < array.length) { if (joined.length() > 0) joined.append(' '); joined.append(array[index]); index++; } return joined.toString(); } private Property[] makeProperties(String genus, String species, String infraspecies, String authors) { List<org.kew.rmf.refine.domain.query.Property> properties = new ArrayList<>(); if (genus != null) { org.kew.rmf.refine.domain.query.Property p = new org.kew.rmf.refine.domain.query.Property(); p.setP("genus"); p.setPid("genus"); p.setV(genus); properties.add(p); } if (species != null) { org.kew.rmf.refine.domain.query.Property p = new org.kew.rmf.refine.domain.query.Property(); p.setP("species"); p.setPid("species"); p.setV(species); properties.add(p); } if (infraspecies != null) { org.kew.rmf.refine.domain.query.Property p = new org.kew.rmf.refine.domain.query.Property(); p.setP("infraspecies"); p.setPid("infraspecies"); p.setV(infraspecies); properties.add(p); } if (authors != null) { org.kew.rmf.refine.domain.query.Property p = new org.kew.rmf.refine.domain.query.Property(); p.setP("authors"); p.setPid("authors"); p.setV(authors); properties.add(p); } return properties.toArray(new Property[properties.size()]); } }
4,483
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
ScientificNameToPropertiesConverter.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/main/java/org/kew/rmf/reconciliation/queryextractor/ScientificNameToPropertiesConverter.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.queryextractor; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.gbif.api.model.checklistbank.ParsedName; import org.gbif.nameparser.NameParser; import org.gbif.nameparser.UnparsableException; import org.kew.rmf.refine.domain.query.Property; import org.kew.rmf.transformers.authors.StripBasionymAuthorTransformer; import org.kew.rmf.transformers.authors.StripPublishingAuthorTransformer; import org.perf4j.LoggingStopWatch; import org.perf4j.slf4j.Slf4JStopWatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Converts a scientific name string — of any reasonable rank — into * a first, second and third epithet, plus authors, using the GBIF {@link NameParser}. */ public class ScientificNameToPropertiesConverter implements QueryStringToPropertiesExtractor { private static final Logger logger = LoggerFactory.getLogger(ScientificNameToPropertiesConverter.class); private NameParser gbifNameParser = new NameParser(); private StripPublishingAuthorTransformer stripPublishingAuthor = new StripPublishingAuthorTransformer(); private StripBasionymAuthorTransformer stripBasionymAuthors = new StripBasionymAuthorTransformer(); @Override public Property[] extractProperties(String queryString) { // Log the query if it takes more than 250ms — there are suggestions the GBIF Name Parser may be slow in some cases. LoggingStopWatch speedCheck = new Slf4JStopWatch("NameParsing:"+queryString, logger, Slf4JStopWatch.WARN_LEVEL).setTimeThreshold(250); queryString = stripUnwantedFamilyEpithet(queryString); try { String epithet1, epithet2, epithet3, basionymAuthors, publishingAuthors; ParsedName parsedName = gbifNameParser.parse(queryString); /* * May return combinations of genusOrAbove, infraGeneric, infraSpecific, specific. */ // genusOrAbove should always be present epithet1 = parsedName.getGenusOrAbove(); // if infraGeneric is present it's the second epithet and the rank will be infrageneric if (parsedName.getInfraGeneric() != null) { epithet2 = parsedName.getInfraGeneric(); epithet3 = null; } // otherwise we may have species epithets else { epithet2 = parsedName.getSpecificEpithet(); epithet3 = parsedName.getInfraSpecificEpithet(); } basionymAuthors = parsedName.getBracketAuthorship(); publishingAuthors = parsedName.getAuthorship(); //parsedName.getNomStatus(); //parsedName.getRank(); //parsedName.getRankMarker(); speedCheck.stop(); return makeProperties(epithet1, epithet2, epithet3, basionymAuthors, publishingAuthors); } catch (UnparsableException e) { logger.info("GBIF NameParser couldn't handle «"+queryString+"»", e); // Have a go at the fallback parsing return fallbackParsing(queryString); } } private Pattern unwantedFamilyEpithet = Pattern.compile( "^" + /* * ICBN Art 18.1: * The name of a family is a plural adjective used as a noun; … termination -aceae */ "(\\p{L}+aceae" + /* * ICBN Art 18.4: * When a name of a family has been published with an improper Latin termination… */ /* * ICBN Art. 18.5: * <blockquote> * The following names, of long usage, are treated as validly published: * Palmae (Arecaceae; type, Areca L.); * Gramineae (Poaceae; type, Poa L.); * Cruciferae (Brassicaceae; type, Brassica L.); * Leguminosae (Fabaceae; type, Faba Mill. [= Vicia L.]); * Guttiferae (Clusiaceae; type, Clusia L.); * Umbelliferae (Apiaceae; type, Apium L.); * Labiatae (Lamiaceae; type, Lamium L.); * Compositae (Asteraceae; type, Aster L.). * When the Papilionaceae (Fabaceae; type, Faba Mill.) are regarded as a family distinct from the remainder of the * Leguminosae, the name Papilionaceae is conserved against Leguminosae. * </blockquote> */ "|Palmae" + "|Gramineae" + "|Cruciferae" + "|Leguminosae" + "|Guttiferae" + "|Umbelliferae" + "|Labiatae" + "|Compositae)" + /* * Followed by an infrafamilial rank (subfam., supsubtrib. etc) */ "\\s+[a-z]+\\."); /** * Removes an initial family + infrafamilial rank from a string, so the GBIF name parser * returns the rest of the name, not just a family. */ private String stripUnwantedFamilyEpithet(String s) { if (s == null) return null; return unwantedFamilyEpithet.matcher(s).replaceFirst(""); } /** * Fallback parsing, in case the GBIF parser fails. */ private Property[] fallbackParsing(String queryString) { /* * Example scientific names: * Fagaceae * Fagaceae Juss. * Quercus * Quercus L. * Quercus alba * Quercus alba L. * Quercus alba f. alba * Quercus alba f. viridis Trel. * Quercus alba f. latiloba (Sarg.) E.J.Palmer & Steyerm. * Quercus alba L. f. latiloba (Sarg.) E.J.Palmer & Steyerm. * * For the moment, this is just a very basic implementation to satisfy the requirements of the * Reconciliation Service "suggest" and "preview" queries. */ queryString.replace(" ", " "); String[] parts = queryString.split(" "); String genus = null, species = null, infraspecies = null, authors = null; // Assume first part is generic epithet genus = parts[0]; if (parts.length == 1) return makeProperties(genus, species, infraspecies, authors); // If second part has capital letter, assume rest of name is authors if (isCapital(parts[1].charAt(0))) { authors = joinRest(parts, 1); } // Otherwise, assume second part is species else { species = parts[1]; if (parts.length == 2) return makeProperties(genus, species, infraspecies, authors); // If third part has capital letter, assume rest of name is authors if (isCapital(parts[2].charAt(0))) { authors = joinRest(parts, 2); } // Otherwise, infraspecific rank (ignore) and infraspecific epithet else { // parts[2] is infraspecific rank if (parts.length == 3) return makeProperties(genus, species, infraspecies, authors); infraspecies = parts[3]; // bounds check if (parts.length == 4) return makeProperties(genus, species, infraspecies, authors); authors = joinRest(parts, 4); } } return makeProperties(genus, species, infraspecies, authors); } private boolean isCapital(char letter) { return letter >= 'A' && letter <= 'Z'; } /** * Joins from index'th to last element of array with space. * * If index is out of bounds, returns empty string. */ private String joinRest(String[] array, int index) { StringBuilder joined = new StringBuilder(); while (index < array.length) { if (joined.length() > 0) joined.append(' '); joined.append(array[index]); index++; } return joined.toString(); } private Property[] makeProperties(String genus, String species, String infraspecies, String authors) { String basionymAuthors = stripPublishingAuthor.transform(authors); String publishingAuthors = stripBasionymAuthors.transform(authors); return makeProperties(genus, species, infraspecies, basionymAuthors, publishingAuthors); } private Property[] makeProperties(String genus, String species, String infraspecies, String basionymAuthors, String publishingAuthors) { List<org.kew.rmf.refine.domain.query.Property> properties = new ArrayList<>(); if (genus != null) { org.kew.rmf.refine.domain.query.Property p = new org.kew.rmf.refine.domain.query.Property(); p.setP("epithet_1"); p.setPid("epithet_1"); p.setV(genus); properties.add(p); } if (species != null) { org.kew.rmf.refine.domain.query.Property p = new org.kew.rmf.refine.domain.query.Property(); p.setP("epithet_2"); p.setPid("epithet_2"); p.setV(species); properties.add(p); } if (infraspecies != null) { org.kew.rmf.refine.domain.query.Property p = new org.kew.rmf.refine.domain.query.Property(); p.setP("epithet_3"); p.setPid("epithet_3"); p.setV(infraspecies); properties.add(p); } if (basionymAuthors != null) { org.kew.rmf.refine.domain.query.Property p = new org.kew.rmf.refine.domain.query.Property(); p.setP("basionym_author"); p.setPid("basionym_author"); p.setV(basionymAuthors); properties.add(p); } if (publishingAuthors != null) { org.kew.rmf.refine.domain.query.Property p = new org.kew.rmf.refine.domain.query.Property(); p.setP("publishing_author"); p.setPid("publishing_author"); p.setV(publishingAuthors); properties.add(p); } return properties.toArray(new Property[properties.size()]); } }
9,325
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
CitationToPropertiesConverter.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/main/java/org/kew/rmf/reconciliation/queryextractor/CitationToPropertiesConverter.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.queryextractor; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.kew.rmf.refine.domain.query.Property; import com.google.common.base.Strings; /** * Extracts the publication, date and authors from a full reference. */ public class CitationToPropertiesConverter implements QueryStringToPropertiesExtractor { Pattern pattern = Pattern.compile("^([^\\[,(]*)(\\[(.*)\\]|)(, \\((\\d*)\\)|)"); @Override public Property[] extractProperties(String queryString) { /* * Expected format: * Publication abbreviation [Authors], (YEAR). */ queryString.replace(" ", " "); String publication = null, authors = null, date = null; if (queryString != null) { java.util.regex.Matcher m = pattern.matcher(queryString); if (m.find()) { publication = m.group(1).trim(); authors = Strings.emptyToNull(m.group(3)); date = Strings.emptyToNull(m.group(5)); } } return makeProperties(publication, authors, date); } private Property[] makeProperties(String publication, String authors, String date) { List<org.kew.rmf.refine.domain.query.Property> properties = new ArrayList<>(); if (publication != null) { org.kew.rmf.refine.domain.query.Property p = new org.kew.rmf.refine.domain.query.Property(); p.setP("publication"); p.setPid("publication"); p.setV(publication); properties.add(p); } if (authors != null) { org.kew.rmf.refine.domain.query.Property p = new org.kew.rmf.refine.domain.query.Property(); p.setP("authors"); p.setPid("authors"); p.setV(authors); properties.add(p); } if (date != null) { org.kew.rmf.refine.domain.query.Property p = new org.kew.rmf.refine.domain.query.Property(); p.setP("date"); p.setPid("date"); p.setV(date); properties.add(p); } return properties.toArray(new Property[properties.size()]); } }
2,657
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
WebAppInitializer.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/main/java/org/kew/rmf/reconciliation/config/WebAppInitializer.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.config; import java.util.Set; import javax.servlet.ServletContext; import javax.servlet.ServletRegistration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; public class WebAppInitializer implements WebApplicationInitializer { private static Logger log = LoggerFactory.getLogger(WebAppInitializer.class); @Override public void onStartup(ServletContext servletContext) { WebApplicationContext rootContext = createRootContext(servletContext); configureSpringMvc(servletContext, rootContext); // Add Perf4J graphing servlet ServletRegistration.Dynamic servletRegistration = servletContext.addServlet("perf4j", org.perf4j.logback.servlet.GraphingServlet.class); servletRegistration.setInitParameter("graphNames", "graphOtherTimes,graphQueryTimes,graphQueriesPerSecond"); servletRegistration.addMapping("/perf4j"); } private WebApplicationContext createRootContext(ServletContext servletContext) { AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); rootContext.register(CoreConfig.class); rootContext.refresh(); servletContext.addListener(new ContextLoaderListener(rootContext)); servletContext.setInitParameter("defaultHtmlEscape", "true"); return rootContext; } private void configureSpringMvc(ServletContext servletContext, WebApplicationContext rootContext) { AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext(); mvcContext.register(MvcConfig.class); mvcContext.setParent(rootContext); ServletRegistration.Dynamic appServlet = servletContext.addServlet("reconciliation-service", new DispatcherServlet(mvcContext)); appServlet.setLoadOnStartup(1); Set<String> mappingConflicts = appServlet.addMapping("/"); if (!mappingConflicts.isEmpty()) { for (String s : mappingConflicts) { log.error("Mapping conflict: " + s); } throw new IllegalStateException("'webservice' cannot be mapped to '/'"); } } }
3,078
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
CoreConfig.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/main/java/org/kew/rmf/reconciliation/config/CoreConfig.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.config; import javax.annotation.Resource; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; @Configuration //@EnableCaching public class CoreConfig { @Resource private Environment env; // Doesn't do anything yet. Custom beans can be defined here. }
1,104
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
MvcConfig.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/main/java/org/kew/rmf/reconciliation/config/MvcConfig.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.config; import java.util.Properties; import org.codehaus.jackson.map.ObjectMapper; import org.kew.rmf.reconciliation.ws.ReconciliationExceptionResolver; import org.perf4j.slf4j.aop.TimingAspect; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.task.TaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.ui.context.ThemeSource; import org.springframework.ui.context.support.ResourceBundleThemeSource; import org.springframework.web.multipart.MultipartResolver; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.ThemeResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver; import org.springframework.web.servlet.theme.CookieThemeResolver; import org.springframework.web.servlet.theme.ThemeChangeInterceptor; import org.springframework.web.servlet.view.UrlBasedViewResolver; import org.springframework.web.servlet.view.tiles2.TilesConfigurer; import org.springframework.web.servlet.view.tiles2.TilesView; @Configuration @EnableWebMvc @ComponentScan(basePackageClasses = { org.kew.rmf.reconciliation.service.ReconciliationService.class, org.kew.rmf.reconciliation.ws.BaseController.class }) @EnableAspectJAutoProxy public class MvcConfig extends WebMvcConfigurerAdapter { static @Bean public PropertySourcesPlaceholderConfigurer myPropertySourcesPlaceholderConfigurer() { PropertySourcesPlaceholderConfigurer p = new PropertySourcesPlaceholderConfigurer(); Resource[] resourceLocations = new Resource[] { new ClassPathResource("/META-INF/spring/reconciliation-service.properties") }; p.setLocations(resourceLocations); return p; } @Bean public ObjectMapper jsonMapper() { return new ObjectMapper(); } /** * Increase maximum upload size. * TODO: Test. */ @Bean public MultipartResolver multipartResolver() { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); multipartResolver.setMaxUploadSize(100 * 1024 * 1024); return multipartResolver; } /** * Static resources configuration */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/css/**").addResourceLocations("/css/").setCachePeriod(3600 * 30); registry.addResourceHandler("/img/**").addResourceLocations("/img/").setCachePeriod(3600 * 30); registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(3600 * 30); } /** * Default servlet handler for resources */ @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } /** * Theme source */ @Bean public ThemeSource themeSource() { ResourceBundleThemeSource themeSource = new ResourceBundleThemeSource(); themeSource.setBasenamePrefix("kew2014-"); return themeSource; } /** * Theme resolver */ @Bean public ThemeResolver themeResolver() { CookieThemeResolver themeResolver = new CookieThemeResolver(); themeResolver.setDefaultThemeName("default"); return themeResolver; } /** * Theme interceptor (optional, without it the theme won't be changed). */ @Override public void addInterceptors(InterceptorRegistry registry) { ThemeChangeInterceptor themeChangeInterceptor = new ThemeChangeInterceptor(); themeChangeInterceptor.setParamName("theme"); registry.addInterceptor(themeChangeInterceptor); } /** * Tiles2 views configuration. */ @Bean public TilesConfigurer tilesConfigurer() { TilesConfigurer tilesConfig = new TilesConfigurer(); tilesConfig.setDefinitions(new String[] { "/WEB-INF/kew-layouts/layouts.xml", "/WEB-INF/layouts/layouts.xml", "/WEB-INF/views/**/views.xml" }); tilesConfig.setCheckRefresh(true); return tilesConfig; } /** * ViewResolver configuration for Tiles2-based views. */ @Bean public UrlBasedViewResolver viewResolver() { UrlBasedViewResolver viewResolver = new UrlBasedViewResolver(); viewResolver.setViewClass(TilesView.class); viewResolver.setContentType("text/html;charset=UTF-8"); return viewResolver; } /** * TaskExecutor for asynchronous pooled tasks */ @Bean public TaskExecutor taskExecutor() { ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.setCorePoolSize(2); taskExecutor.setMaxPoolSize(2); // Wait up to 30 seconds for the tasks to exit themselves, after receiving an interrupt from the executor. taskExecutor.setDaemon(true); taskExecutor.setAwaitTerminationSeconds(30); taskExecutor.initialize(); return taskExecutor; } @Bean public TimingAspect timingAspect() { return new TimingAspect(); } /** * Generate error pages for unhandled exceptions. */ @Bean public SimpleMappingExceptionResolver simpleMappingExceptionResolver() { ReconciliationExceptionResolver r = new ReconciliationExceptionResolver(); Properties mappings = new Properties(); mappings.setProperty("UnknownReconciliationServiceException", "404"); r.setExceptionMappings(mappings); r.setDefaultErrorView("500"); r.setDefaultStatusCode(500); r.setPreventResponseCaching(true); r.setWarnLogCategory("org.kew.rmf.reconciliation.error"); return r; } }
6,834
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
ReconciliationService.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/main/java/org/kew/rmf/reconciliation/service/ReconciliationService.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.service; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import org.kew.rmf.core.configuration.MatchConfiguration; import org.kew.rmf.core.configuration.ReconciliationServiceConfiguration; import org.kew.rmf.core.exception.MatchExecutionException; import org.kew.rmf.core.exception.TooManyMatchesException; import org.kew.rmf.core.lucene.LuceneMatcher; import org.kew.rmf.reconciliation.exception.ReconciliationServiceException; import org.kew.rmf.reconciliation.exception.UnknownReconciliationServiceException; import org.kew.rmf.reconciliation.queryextractor.QueryStringToPropertiesExtractor; import org.kew.rmf.reconciliation.service.resultformatter.ReconciliationResultFormatter; import org.kew.rmf.reconciliation.service.resultformatter.ReconciliationResultPropertyFormatter; import org.kew.rmf.refine.domain.metadata.Metadata; import org.perf4j.StopWatch; import org.perf4j.aop.Profiled; import org.perf4j.slf4j.Slf4JStopWatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.core.task.TaskExecutor; import org.springframework.stereotype.Service; /** * The ReconciliationService handles loading and using multiple reconciliation configurations. */ @Service public class ReconciliationService { private static final Logger logger = LoggerFactory.getLogger(ReconciliationService.class); private static final Logger timingLogger = LoggerFactory.getLogger("org.kew.rmf.reconciliation.TimingLogger"); private static final String queryTimingLoggerName = "org.kew.rmf.reconciliation.QueryTimingLogger"; @Value("${environment:unknown}") private String environment; @Value("#{'${configurations}'.split(',')}") private List<String> initialConfigurations; @Autowired private TaskExecutor taskExecutor; private final Map<String,ConfigurationStatus> configurationStatuses = new HashMap<String,ConfigurationStatus>(); public enum ConfigurationStatus { NOT_LOADED, LOADED, LOADING; } private final String CONFIG_BASE = "/META-INF/spring/reconciliation-service/"; private final String CONFIG_EXTENSION = ".xml"; private final Map<String, ConfigurableApplicationContext> contexts = new HashMap<String, ConfigurableApplicationContext>(); private final Map<String, LuceneMatcher> matchers = new HashMap<String, LuceneMatcher>(); private final Map<String, Integer> totals = new HashMap<String, Integer>(); /** * Kicks off tasks (threads) to load the initial configurations. */ @PostConstruct public void init() { logger.debug("Initialising reconciliation service"); // Load up the matchers from the specified files if (initialConfigurations != null) { for (String config : initialConfigurations) { try { loadConfigurationInBackground(config + CONFIG_EXTENSION); } catch (ReconciliationServiceException e) { throw new RuntimeException("Error kicking off data load for Reconciliation Service", e); } } } } /** * For loading a configuration in the background (i.e. in a thread). */ private class BackgroundConfigurationLoaderTask implements Runnable { private String configFileName; public BackgroundConfigurationLoaderTask(String configFileName) { this.configFileName = configFileName; } @Override public void run() { try { loadConfiguration(configFileName); } catch (ReconciliationServiceException e) { logger.error(configFileName + ": Error while loading", e); } } } /** * Lists the available configuration files from the classpath. */ public List<String> listAvailableConfigurationFiles() throws ReconciliationServiceException { List<String> availableConfigurations = new ArrayList<>(); ResourcePatternResolver pmrpr = new PathMatchingResourcePatternResolver(); try { Resource[] configurationResources = pmrpr.getResources("classpath*:"+CONFIG_BASE+"*Match.xml"); logger.debug("Found {} configuration file resources", configurationResources.length); for (Resource resource : configurationResources) { availableConfigurations.add(resource.getFilename()); } } catch (IOException e) { throw new ReconciliationServiceException("Unable to list available configurations", e); } return availableConfigurations; } /** * Loads a single configuration in the background. */ public void loadConfigurationInBackground(String configFileName) throws ReconciliationServiceException { synchronized (configurationStatuses) { ConfigurationStatus status = configurationStatuses.get(configFileName); if (status == ConfigurationStatus.LOADED) { throw new ReconciliationServiceException("Match configuration "+configFileName+" is already loaded."); } else if (status == ConfigurationStatus.LOADING) { throw new ReconciliationServiceException("Match configuration "+configFileName+" is loading."); } configurationStatuses.put(configFileName, ConfigurationStatus.LOADING); } taskExecutor.execute(new BackgroundConfigurationLoaderTask(configFileName)); } /** * Loads a single configuration. */ private void loadConfiguration(String configFileName) throws ReconciliationServiceException { synchronized (configurationStatuses) { ConfigurationStatus status = configurationStatuses.get(configFileName); assert (status == ConfigurationStatus.LOADING); } StopWatch sw = new Slf4JStopWatch(timingLogger); String configurationFile = CONFIG_BASE + configFileName; logger.info("{}: Loading configuration from file {}", configFileName, configurationFile); ConfigurableApplicationContext context = new GenericXmlApplicationContext(configurationFile); context.registerShutdownHook(); LuceneMatcher matcher = context.getBean("engine", LuceneMatcher.class); String configName = matcher.getConfig().getName(); contexts.put(configFileName, context); matchers.put(configName, matcher); try { matcher.loadData(); totals.put(configName, matcher.getIndexReader().numDocs()); logger.debug("{}: Loaded data", configName); // Append " (environment)" to Metadata name, to help with interactive testing Metadata metadata = getMetadata(configName); if (metadata != null) { if (!"prod".equals(environment)) { metadata.setName(metadata.getName() + " (" + environment + ")"); } } synchronized (configurationStatuses) { ConfigurationStatus status = configurationStatuses.get(configFileName); if (status != ConfigurationStatus.LOADING) { logger.error("Unexpected configuration status '"+status+"' after loading "+configFileName); } configurationStatuses.put(configFileName, ConfigurationStatus.LOADED); } } catch (Exception e) { logger.error("Problem loading configuration "+configFileName, e); context.close(); totals.remove(configName); matchers.remove(configName); contexts.remove(configFileName); synchronized (configurationStatuses) { ConfigurationStatus status = configurationStatuses.get(configFileName); if (status != ConfigurationStatus.LOADING) { logger.error("Unexpected configuration status '"+status+"' after loading "+configFileName); } configurationStatuses.remove(configFileName); } sw.stop("LoadConfiguration:"+configFileName+".failure"); throw new ReconciliationServiceException("Problem loading configuration "+configFileName, e); } sw.stop("LoadConfiguration:"+configFileName+".success"); } /** * Unloads a single configuration. */ public void unloadConfiguration(String configFileName) throws ReconciliationServiceException { synchronized (configurationStatuses) { ConfigurationStatus status = configurationStatuses.get(configFileName); if (status == ConfigurationStatus.LOADING) { throw new ReconciliationServiceException("Match configuration "+configFileName+" is loading, wait until it has completed."); } else if (status == null) { throw new ReconciliationServiceException("Match configuration "+configFileName+" is not loaded."); } StopWatch sw = new Slf4JStopWatch(timingLogger); logger.info("{}: Unloading configuration", configFileName); ConfigurableApplicationContext context = contexts.get(configFileName); String configName = configFileName.substring(0, configFileName.length() - 4); totals.remove(configName); matchers.remove(configName); contexts.remove(configFileName); context.close(); configurationStatuses.remove(configFileName); sw.stop("UnloadConfiguration:"+configFileName+".success"); } } /** * Retrieve reconciliation service metadata. * @throws UnknownReconciliationServiceException if the requested matcher doesn't exist. * @throws MatchExecutionException if no default type is specified */ public Metadata getMetadata(String configName) throws UnknownReconciliationServiceException, MatchExecutionException { ReconciliationServiceConfiguration reconcilationConfig = getReconciliationServiceConfiguration(configName); if (reconcilationConfig != null) { Metadata metadata = reconcilationConfig.getReconciliationServiceMetadata(); if (metadata.getDefaultTypes() == null || metadata.getDefaultTypes().length == 0) { throw new MatchExecutionException("No default type specified, OpenRefine 2.6 would fail"); } return metadata; } return null; } /** * Convert single query string into query properties. * @throws UnknownReconciliationServiceException if the requested matcher doesn't exist. */ public QueryStringToPropertiesExtractor getPropertiesExtractor(String configName) throws UnknownReconciliationServiceException { ReconciliationServiceConfiguration reconcilationConfig = getReconciliationServiceConfiguration(configName); if (reconcilationConfig != null) { return reconcilationConfig.getQueryStringToPropertiesExtractor(); } return null; } /** * Formatter to convert result into single string. * @throws UnknownReconciliationServiceException if the requested matcher doesn't exist. */ public ReconciliationResultFormatter getReconciliationResultFormatter(String configName) throws UnknownReconciliationServiceException { ReconciliationServiceConfiguration reconcilationConfig = getReconciliationServiceConfiguration(configName); if (reconcilationConfig != null) { ReconciliationResultFormatter reconciliationResultFormatter = reconcilationConfig.getReconciliationResultFormatter(); if (reconciliationResultFormatter != null) { return reconciliationResultFormatter; } else { // Set it to the default one ReconciliationResultPropertyFormatter formatter = new ReconciliationResultPropertyFormatter(reconcilationConfig); reconcilationConfig.setReconciliationResultFormatter(formatter); return formatter; } } return null; } /** * Perform match query against specified configuration. */ @Profiled(tag="MatchQuery:{$0}", logger=queryTimingLoggerName, logFailuresSeparately=true) public synchronized List<Map<String,String>> doQuery(String configName, Map<String, String> userSuppliedRecord) throws TooManyMatchesException, UnknownReconciliationServiceException, MatchExecutionException { List<Map<String,String>> matches = null; LuceneMatcher matcher = getMatcher(configName); if (matcher == null) { // When no matcher specified with that configuration logger.warn("Invalid match configuration «{}» requested", configName); return null; } matches = matcher.getMatches(userSuppliedRecord); // Just write out some matches to std out: logger.debug("Found some matches: {}", matches.size()); if (matches.size() < 4) { logger.debug("Matches for {} are {}", userSuppliedRecord, matches); } return matches; } /** * Retrieve reconciliation service configuration. * @throws UnknownReconciliationServiceException if the requested configuration doesn't exist. */ public ReconciliationServiceConfiguration getReconciliationServiceConfiguration(String configName) throws UnknownReconciliationServiceException { MatchConfiguration matchConfig = getMatcher(configName).getConfig(); if (matchConfig instanceof ReconciliationServiceConfiguration) { ReconciliationServiceConfiguration reconcilationConfig = (ReconciliationServiceConfiguration) matchConfig; return reconcilationConfig; } return null; } /* • Getters and setters • */ public Map<String, LuceneMatcher> getMatchers() { return matchers; } public LuceneMatcher getMatcher(String matcher) throws UnknownReconciliationServiceException { if (matchers.get(matcher) == null) { throw new UnknownReconciliationServiceException("No matcher called '"+matcher+"' exists."); } return matchers.get(matcher); } public List<String> getInitialConfigurations() { return initialConfigurations; } public void setInitialConfigurations(List<String> initialConfigurations) { this.initialConfigurations = initialConfigurations; } public Map<String, ConfigurationStatus> getConfigurationStatuses() { return configurationStatuses; } public Map<String, Integer> getTotals() { return totals; } }
14,349
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
DatabaseCursorRecordReader.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/main/java/org/kew/rmf/reconciliation/service/DatabaseCursorRecordReader.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.service; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.sql.DataSource; import org.kew.rmf.core.DatabaseRecordSource; /** * Reads records from a database using a cursor. */ public class DatabaseCursorRecordReader implements DatabaseRecordSource { private Connection connection; private DataSource dataSource; private String sql; private String countSql; private int fetchSize = 5000; private PreparedStatement preparedStatement; private ResultSet rs; private void openCursor() throws SQLException { preparedStatement = getConnection().prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); if (getConnection().getMetaData().getDatabaseProductName().equals("MySQL")) { preparedStatement.setFetchSize(Integer.MIN_VALUE); } else { preparedStatement.setFetchSize(fetchSize); } preparedStatement.setFetchDirection(ResultSet.FETCH_FORWARD); this.rs = preparedStatement.executeQuery(); } @Override public int count() throws SQLException { if (countSql == null) { return -1; } Statement s = getConnection().createStatement(); ResultSet r = s.executeQuery(countSql); r.next(); return r.getInt(1); } /* • Getters and setters */ private synchronized Connection getConnection() throws SQLException { if (connection == null) { connection = dataSource.getConnection(); connection.setAutoCommit(false); // Cursors in PostgreSQL (at least) don't work in autocommit mode. } return connection; } @Override public ResultSet getResultSet() throws SQLException { if (rs == null) { openCursor(); } return rs; } @Override public void close() throws SQLException { if (rs != null) { rs.close(); } if (preparedStatement != null) { preparedStatement.close(); } if (connection != null) { connection.close(); } } public DataSource getDataSource() { return dataSource; } public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public String getSql() { return sql; } public void setSql(String sql) { this.sql = sql; } public String getCountSql() { return countSql; } public void setCountSql(String countSql) { this.countSql = countSql; } public int getFetchSize() { return fetchSize; } public void setFetchSize(int fetchSize) { this.fetchSize = fetchSize; } }
3,233
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
ReconciliationResultPropertyFormatter.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/main/java/org/kew/rmf/reconciliation/service/resultformatter/ReconciliationResultPropertyFormatter.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.service.resultformatter; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.kew.rmf.core.configuration.Property; import org.kew.rmf.core.configuration.ReconciliationServiceConfiguration; /** * Formats results according to the specified string format, with values chosen by property (result keys). */ public class ReconciliationResultPropertyFormatter implements ReconciliationResultFormatter { private String format; private List<String> properties; private String stripRepeats; public ReconciliationResultPropertyFormatter() { } /** * Create a formatter based on the configured columns, in order, separated by commas. */ public ReconciliationResultPropertyFormatter(ReconciliationServiceConfiguration reconcilationConfig) { properties = new ArrayList<>(); StringBuilder sbFormat = new StringBuilder(); List<Property> columns = reconcilationConfig.getProperties(); for (Property p : columns) { properties.add(p.getAuthorityColumnName()); if (sbFormat.length() > 0) sbFormat.append(", "); sbFormat.append("%s"); } format = sbFormat.toString(); stripRepeats = null; } @Override public String formatResult(Map<String, String> result) { Object[] resultProperties = new Object[properties.size()]; for (int i = 0; i < resultProperties.length; i++) { resultProperties[i] = result.get(properties.get(i)); } if (stripRepeats != null) { return String.format(getFormat(), resultProperties).replace(stripRepeats+stripRepeats, stripRepeats); } else { return String.format(getFormat(), resultProperties); } } /* • Getters and setters • */ public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } public List<String> getProperties() { return properties; } public void setProperties(List<String> properties) { this.properties = properties; } public String getStripRepeats() { return stripRepeats; } public void setStripRepeats(String stripRepeats) { this.stripRepeats = stripRepeats; } }
2,845
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
ReconciliationResultFormatter.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/main/java/org/kew/rmf/reconciliation/service/resultformatter/ReconciliationResultFormatter.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.service.resultformatter; import java.util.Map; /** * Defines how a result should be formatted in the JSON response to a reconciliation query. */ public interface ReconciliationResultFormatter { public String formatResult(Map<String, String> result); }
1,043
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
UnknownReconciliationServiceException.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/main/java/org/kew/rmf/reconciliation/exception/UnknownReconciliationServiceException.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.exception; public class UnknownReconciliationServiceException extends Exception { private static final long serialVersionUID = 1L; public UnknownReconciliationServiceException() { super(); } public UnknownReconciliationServiceException(String message) { super(message); } public UnknownReconciliationServiceException(String message, Throwable cause) { super(message, cause); } }
1,182
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
ReconciliationServiceException.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/main/java/org/kew/rmf/reconciliation/exception/ReconciliationServiceException.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.exception; public class ReconciliationServiceException extends Exception { private static final long serialVersionUID = 1L; public ReconciliationServiceException() { super(); } public ReconciliationServiceException(String message) { super(message); } public ReconciliationServiceException(String message, Throwable cause) { super(message, cause); } }
1,154
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
OtherController.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/main/java/org/kew/rmf/reconciliation/ws/OtherController.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.ws; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * Information, help pages etc. */ @Controller public class OtherController { //private static Logger logger = LoggerFactory.getLogger(OtherController.class); @Autowired private BaseController baseController; @RequestMapping(produces="text/html", value = "/", method = RequestMethod.GET) public String doWelcome(Model model) { baseController.menuAndBreadcrumbs("/", model); return "index"; } @RequestMapping(produces="text/html", value = "/help", method = RequestMethod.GET) public String doHelp(Model model) { baseController.menuAndBreadcrumbs("/help", model); return "help"; } }
1,673
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
ConfigurationController.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/main/java/org/kew/rmf/reconciliation/ws/ConfigurationController.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.ws; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.servlet.http.HttpServletRequest; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.kew.rmf.core.configuration.Property; import org.kew.rmf.core.configuration.ReconciliationServiceConfiguration; import org.kew.rmf.matchers.Matcher; import org.kew.rmf.reconciliation.exception.ReconciliationServiceException; import org.kew.rmf.reconciliation.exception.UnknownReconciliationServiceException; import org.kew.rmf.reconciliation.service.ReconciliationService; import org.kew.rmf.reconciliation.service.ReconciliationService.ConfigurationStatus; import org.kew.rmf.reconciliation.ws.dto.DisplayBean; import org.kew.rmf.transformers.Transformer; import org.kew.rmf.transformers.WeightedTransformer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; /** * Administration, configuration information pages etc. */ @Controller public class ConfigurationController { private static Logger logger = LoggerFactory.getLogger(ConfigurationController.class); @Autowired private ReconciliationService reconciliationService; @Autowired private BaseController baseController; private List<String> charsetNames = new ArrayList<>(); public ConfigurationController() { // Initialise the list of available character sets. for (String charsetName : Charset.availableCharsets().keySet()) { if (!charsetName.startsWith("x-") && !charsetName.startsWith("X-")) { charsetNames.add(charsetName); } } } @RequestMapping(produces="text/html", value = "/admin", method = RequestMethod.GET) public String doConfigurationAdmin(Model model) throws ReconciliationServiceException { logger.info("Request for configuration admin page"); Map<String,ConfigurationStatus> configurationStatuses = reconciliationService.getConfigurationStatuses(); logger.debug("Loaded/loading config files: {}", configurationStatuses); Map<String,ConfigurationStatus> configurations = new TreeMap<>(); for (String configurationFileName : reconciliationService.listAvailableConfigurationFiles()) { configurations.put(configurationFileName, configurationStatuses.get(configurationFileName) == null ? ConfigurationStatus.NOT_LOADED : configurationStatuses.get(configurationFileName)); } model.addAttribute("configurations", configurations); baseController.menuAndBreadcrumbs("/admin", model); return "configuration-admin"; } @RequestMapping(produces="text/html", value = "/admin", method = RequestMethod.POST) public String doConfigurationAdmin( HttpServletRequest request, @RequestParam(required=false) String load, @RequestParam(required=false) String reload, @RequestParam(required=false) String unload, Model model) throws JsonGenerationException, JsonMappingException, IOException, ReconciliationServiceException { logger.info("Request for configuration loading L:{} R:{} U:{}", load, reload, unload); if (reload != null) { // TODO ••• Check user input! ••• String configName = reload; logger.info("Request to reload {}", configName); reconciliationService.unloadConfiguration(configName); reconciliationService.loadConfigurationInBackground(configName); } if (unload != null) { // TODO ••• Check user input! ••• String configName = unload; logger.info("Request to unload {}", configName); reconciliationService.unloadConfiguration(configName); } if (load != null) { // TODO ••• Check user input! ••• String configName = load; logger.info("Request to load {}", configName); reconciliationService.loadConfigurationInBackground(configName); } return "redirect:/admin"; } @RequestMapping(produces="text/html", value = "/about", method = RequestMethod.GET) public String doWelcome(Model model) { model.addAttribute("availableMatchers", reconciliationService.getMatchers().keySet()); baseController.menuAndBreadcrumbs("/about", model); return "about-general"; } @RequestMapping(produces="text/html", value = "/about/{configName}", method = RequestMethod.GET) public String doAbout(@PathVariable String configName, Model model) throws UnknownReconciliationServiceException { logger.info("Request for about page for {}", configName); List<String> properties = new ArrayList<String>(); Map<String,DisplayBean<Matcher>> p_matchers = new HashMap<>(); Map<String,List<DisplayBean<Transformer>>> p_transformers = new HashMap<>(); ReconciliationServiceConfiguration configuration = reconciliationService.getReconciliationServiceConfiguration(configName); model.addAttribute("reconciliationConfiguration", configuration); for (Property p : configuration.getProperties()) { properties.add(p.getQueryColumnName()); p_matchers.put(p.getQueryColumnName(), new DisplayBean<Matcher>(p.getMatcher())); List<DisplayBean<Transformer>> p_t = new ArrayList<>(); for (Transformer t : p.getQueryTransformers()) { // Ignore WeightedTransformers, use the wrapped transformer instead. if (t instanceof WeightedTransformer) { p_t.add(new DisplayBean<Transformer>(((WeightedTransformer)t).getTransformer())); } else { p_t.add(new DisplayBean<Transformer>(t)); } } p_transformers.put(p.getQueryColumnName(), p_t); } model.addAttribute("total", reconciliationService.getTotals().get(configName)); model.addAttribute("configName", configName); model.addAttribute("properties", properties); model.addAttribute("matchers", p_matchers); model.addAttribute("transformers", p_transformers); model.addAttribute("charsetNames", charsetNames); baseController.menuAndBreadcrumbs("/about/"+configName, model); return "about-matcher"; } }
7,077
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
ReconciliationExceptionResolver.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/main/java/org/kew/rmf/reconciliation/ws/ReconciliationExceptionResolver.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.ws; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver; /** * Adds the date, URL and contact email address details to exception messages. (Also, menu and breadcrumbs.) */ public class ReconciliationExceptionResolver extends SimpleMappingExceptionResolver { @Autowired private BaseController baseController; private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); @Override protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) { ModelAndView mav = super.doResolveException(request, response, handler, exception); mav.addObject("url", request.getRequestURL()); mav.addObject("datetime", simpleDateFormat.format(new Date())); mav.addObject("contactemail", "[email protected]"); mav.addObject("statusCode", response.getStatus()); mav.addObject("statusMessage", HttpStatus.valueOf(response.getStatus()).getReasonPhrase()); baseController.menuAndBreadcrumbs("/#", mav); return mav; } }
2,160
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
CsvMatchController.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/main/java/org/kew/rmf/reconciliation/ws/CsvMatchController.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.ws; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.kew.rmf.core.configuration.Configuration; import org.kew.rmf.core.configuration.Property; import org.kew.rmf.core.exception.MatchExecutionException; import org.kew.rmf.core.exception.TooManyMatchesException; import org.kew.rmf.core.lucene.LuceneMatcher; import org.kew.rmf.reconciliation.exception.UnknownReconciliationServiceException; import org.kew.rmf.reconciliation.service.ReconciliationService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.supercsv.io.CsvMapReader; import org.supercsv.prefs.CsvPreference; /** * Implements a CSV query interface to the reconciliation configurations, providing file upload processing. */ @Controller public class CsvMatchController { private static Logger logger = LoggerFactory.getLogger(CsvMatchController.class); private static String tmpDir = System.getProperty("java.io.tmpdir"); @Autowired private ReconciliationService reconciliationService; @Autowired private BaseController baseController; /** * Matches the records in the uploaded file. * * Results are put into a temporary file (available for download) and also shown in the web page. */ @RequestMapping(value = "/filematch/{configName}", method = RequestMethod.POST) public String doFileMatch (@PathVariable String configName, @RequestParam("file") MultipartFile file, @RequestParam("charset") String charset, HttpServletResponse response, Model model) throws UnknownReconciliationServiceException, IOException { logger.info("{}: File match query {}, {}", configName, file, charset); if (file.isEmpty()) { logger.warn("File is empty"); baseController.menuAndBreadcrumbs("/filematch/"+configName, model); model.addAttribute("error", "CSV file is empty."); return "file-matcher-error"; } logger.debug("Looking for: {}", configName); LuceneMatcher matcher = reconciliationService.getMatcher(configName); // Map of matches // Key is the ID of supplied records // Entries are a List of Map<String,String> Map<String,List<Map<String,String>>> matches = new HashMap<String,List<Map<String,String>>>(); // Map of supplied data (useful for display) List<Map<String,String>> suppliedData = new ArrayList<Map<String,String>>(); // Temporary file for results File resultsFile; OutputStreamWriter resultsFileWriter; List<String> unusedCsvFields = new ArrayList<>(); // Property field names List<String> properties = new ArrayList<String>(); for (Property p : matcher.getConfig().getProperties()) { properties.add(p.getQueryColumnName()); } // Open file and read first line to determine line ending BufferedReader fileReader = new BufferedReader(new InputStreamReader(file.getInputStream(), Charset.forName(charset))); String lineEnding; String userLineEnding; boolean crlf = useCrLfEndings(fileReader); lineEnding = crlf ? "\r\n" : "\n"; userLineEnding = crlf ? "Windows (CR+LF)" : "Linux/Mac (LF)"; logger.debug("Line endings are {}", userLineEnding); // Read CSV from file CsvPreference customCsvPref = new CsvPreference.Builder('"', ',', lineEnding).build(); // lineEnding is only used for writing anyway. CsvMapReader mr = new CsvMapReader(fileReader, customCsvPref); final String[] header = mr.getHeader(true); // Check CSV file has appropriate headers // Need "id" and at least one from properties if (!validateCsvFields(header, properties, unusedCsvFields)) { mr.close(); fileReader.close(); logger.warn("Uploaded CSV doesn't contain id column."); baseController.menuAndBreadcrumbs("/filematch/"+configName, model); model.addAttribute("error", "CSV file doesn't contain 'id' column, or is corrupt."); return "file-matcher-error"; } // Open results file and write header resultsFile = File.createTempFile("match-results-", ".csv"); resultsFileWriter = new OutputStreamWriter(new FileOutputStream(resultsFile), "UTF-8"); resultsFileWriter.write("queryId,matchId"); resultsFileWriter.write(lineEnding); // Process each line of the input CSV, append results to output file Map<String, String> record = null; while ((record = mr.read(header)) != null) { logger.debug("Next record is {}", record); suppliedData.add(record); try { List<Map<String,String>> theseMatches = matcher.getMatches(record); if (theseMatches != null) { logger.debug("Record ID {}, matched: {}", record.get(Configuration.ID_FIELD_NAME), theseMatches.size()); } else { logger.debug("Record ID {}, matched: null", record.get(Configuration.ID_FIELD_NAME)); } matches.put(record.get(Configuration.ID_FIELD_NAME), theseMatches); // Append match results to file StringBuilder sb = new StringBuilder(); for (Map<String,String> result : theseMatches) { if (sb.length() > 0) sb.append('|'); sb.append(result.get(Configuration.ID_FIELD_NAME)); } sb.insert(0, ',').insert(0, record.get(Configuration.ID_FIELD_NAME)).append(lineEnding); resultsFileWriter.write(sb.toString()); } catch (TooManyMatchesException | MatchExecutionException e) { logger.warn("Problem handling match", e); } } // Close file etc mr.close(); resultsFileWriter.close(); model.addAttribute("resultsFile", resultsFile.getName()); response.setHeader("X-File-Download", resultsFile.getName()); // Putting this in a header saves the unit tests from needing to parse the HTML. model.addAttribute("suppliedData", suppliedData); model.addAttribute("matches", matches); model.addAttribute("properties", properties); model.addAttribute("unusedCsvFields", unusedCsvFields); model.addAttribute("userLineEnding", userLineEnding); model.addAttribute("charset", charset); baseController.menuAndBreadcrumbs("/filematch/"+configName, model); return "file-matcher-results"; } /** * Returns true if the input file's line endings are likely to be Windows-style (\r\n). */ private boolean useCrLfEndings(Reader inputStream) { if (inputStream.markSupported()) { try { inputStream.mark(4096); int i = 0; int c; while(i++ < 4096 && inputStream.ready() && ((c = inputStream.read()) > 0)) { if (c == '\n') { inputStream.reset(); return false; } if (c == '\r') { inputStream.reset(); return true; } } logger.warn("Detecting line endings not possible, first line is very long"); return false; } catch (IOException e) { logger.warn("Exception determining CSV input file line ending", e); return false; } } else { logger.warn("Detecting line endings not possible, mark not supported"); return false; } } /** * Checks for the presence of an "id" field, and returns all strings in fields but not in properties. */ private boolean validateCsvFields(String[] fields, List<String> properties, List<String> unusedFields) { boolean containsId = false; if (fields == null) return false; for (String f : fields) { if (Configuration.ID_FIELD_NAME.equals(f)) { containsId = true; } else { if (!properties.contains(f)) { unusedFields.add(f); } } } return containsId; } /** * Downloads a match result file. */ @RequestMapping(value = "/download/{fileName}", method = RequestMethod.GET) public ResponseEntity<String> doDownload(@PathVariable String fileName, Model model) { logger.info("User attempting to download file named «{}»", fileName); // Check for the user trying to do something suspicious if (fileName.contains(File.separator)) { logger.error("User attempting to download file named «{}»", fileName); return new ResponseEntity<String>("Looks dodgy.", baseController.getResponseHeaders(), HttpStatus.FORBIDDEN); } // Put back the .csv, as Spring has chopped it off. File downloadFile = new File(tmpDir, fileName + ".csv"); try { if (downloadFile.canRead()) { return new ResponseEntity<String>(FileUtils.readFileToString(downloadFile, "UTF-8"), baseController.getResponseHeaders(), HttpStatus.OK); } else { logger.warn("User attempted to download file «{}» but it doesn't exist", fileName); return new ResponseEntity<String>("This download does not exist", baseController.getResponseHeaders(), HttpStatus.NOT_FOUND); } } catch (IOException e) { logger.error("Exception when user attempted to download file «{}»", fileName); return new ResponseEntity<String>("Error retrieving download: "+e.getMessage(), baseController.getResponseHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } } }
10,301
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
ReconciliationServiceController.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/main/java/org/kew/rmf/reconciliation/ws/ReconciliationServiceController.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.ws; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import org.kew.rmf.core.configuration.Configuration; import org.kew.rmf.core.configuration.Property; import org.kew.rmf.core.exception.MatchExecutionException; import org.kew.rmf.core.exception.TooManyMatchesException; import org.kew.rmf.reconciliation.exception.UnknownReconciliationServiceException; import org.kew.rmf.reconciliation.queryextractor.QueryStringToPropertiesExtractor; import org.kew.rmf.reconciliation.service.ReconciliationService; import org.kew.rmf.refine.domain.metadata.Metadata; import org.kew.rmf.refine.domain.metadata.Type; import org.kew.rmf.refine.domain.query.Query; import org.kew.rmf.refine.domain.response.FlyoutResponse; import org.kew.rmf.refine.domain.response.QueryResponse; import org.kew.rmf.refine.domain.response.QueryResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.client.RestTemplate; /** * Implements an <a href="https://github.com/OpenRefine/OpenRefine/wiki/Reconciliation-Service-Api">OpenRefine Reconciliation Service</a> * on top of a match configuration. */ @Controller public class ReconciliationServiceController { private static Logger logger = LoggerFactory.getLogger(ReconciliationServiceController.class); @Autowired private ReconciliationService reconciliationService; @Autowired private BaseController baseController; @Autowired private ServletContext servletContext; @Autowired private ObjectMapper jsonMapper; private RestTemplate template = new RestTemplate(); /** * Retrieve reconciliation service metadata. */ @RequestMapping(value = "/reconcile/{configName}", method={RequestMethod.GET,RequestMethod.POST}, produces="application/json; charset=UTF-8") public ResponseEntity<String> getMetadata(HttpServletRequest request, @PathVariable String configName, @RequestParam(value="callback",required=false) String callback, Model model) throws JsonGenerationException, JsonMappingException, IOException { logger.info("{}: Get Metadata request", configName); String myUrl = request.getScheme() + "://" + request.getServerName() + (request.getServerPort() == 80 ? "" : (":" + request.getServerPort())); String basePath = servletContext.getContextPath() + "/reconcile/" + configName; Metadata metadata; try { metadata = reconciliationService.getMetadata(configName); } catch (UnknownReconciliationServiceException e) { return new ResponseEntity<String>(e.toString(), baseController.getResponseHeaders(), HttpStatus.NOT_FOUND); } catch (MatchExecutionException e) { return new ResponseEntity<String>(e.toString(), baseController.getResponseHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } if (metadata != null) { String metadataJson = jsonMapper.writeValueAsString(metadata).replace("LOCAL", myUrl).replace("BASE", basePath); return new ResponseEntity<String>(wrapResponse(callback, metadataJson), baseController.getResponseHeaders(), HttpStatus.OK); } return null; } /** * Perform multiple reconciliation queries (no callback) */ @RequestMapping(value = "/reconcile/{configName}", method={RequestMethod.GET,RequestMethod.POST}, params={"queries"}, produces="application/json; charset=UTF-8") public ResponseEntity<String> doMultipleQueries(@PathVariable String configName, @RequestParam("queries") String queries) { return doMultipleQueries(configName, queries, null); } /** * Perform multiple reconciliation queries (no callback) */ @RequestMapping(value = "/reconcile/{configName}", method={RequestMethod.GET,RequestMethod.POST}, params={"queries","callback"}, produces="application/json; charset=UTF-8") public ResponseEntity<String> doMultipleQueries(@PathVariable String configName, @RequestParam("queries") String queries, @RequestParam(value="callback",required=false) String callback) { logger.info("{}: Multiple query request {}", configName, queries); String jsonres = null; Map<String,QueryResponse<QueryResult>> res = new HashMap<>(); try { // Convert JSON to map of queries Map<String,Query> qs = jsonMapper.readValue(queries, new TypeReference<Map<String,Query>>() {}); for (String key : qs.keySet()) { try { Query q = qs.get(key); QueryResult[] qres = doQuery(q, configName); QueryResponse<QueryResult> response = new QueryResponse<>(); response.setResult(qres); res.put(key,response); } catch (MatchExecutionException | TooManyMatchesException e) { // Only fail the one query, not the whole batch logger.warn("{}: Query with key {} of multiple query call failed: {}", configName, key, e.getMessage()); } } jsonres = jsonMapper.writeValueAsString(res); } catch (Exception e) { logger.error(configName + ": Error with multiple query call", e); } return new ResponseEntity<String>(wrapResponse(callback, jsonres), baseController.getResponseHeaders(), HttpStatus.OK); } /** * Single reconciliation query, no callback. */ @RequestMapping(value = "/reconcile/{configName}", method={RequestMethod.GET,RequestMethod.POST}, params={"query"}, produces="application/json; charset=UTF-8") public ResponseEntity<String> doSingleQuery(@PathVariable String configName, @RequestParam("query") String query) { return doSingleQuery(configName, query, null); } /** * Single reconciliation query. */ @RequestMapping(value = "/reconcile/{configName}", method={RequestMethod.GET,RequestMethod.POST}, params={"query","callback"}, produces="application/json; charset=UTF-8") public ResponseEntity<String> doSingleQuery(@PathVariable String configName, @RequestParam("query") String query, @RequestParam(value="callback",required=false) String callback) { logger.info("{}: Single query request {}", configName, query); String jsonres = null; try { Query q = jsonMapper.readValue(query, Query.class); QueryResult[] qres = doQuery(q, configName); QueryResponse<QueryResult> response = new QueryResponse<>(); response.setResult(qres); jsonres = jsonMapper.writeValueAsString(response); } catch (JsonMappingException | JsonGenerationException e) { logger.warn(configName + ": Error parsing JSON query", e); return new ResponseEntity<String>(e.toString(), baseController.getResponseHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } catch (IOException e) { logger.error(configName + ": Query failed:", e); return new ResponseEntity<String>(e.toString(), baseController.getResponseHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } catch (UnknownReconciliationServiceException e) { logger.warn(configName + ": Query failed:", e); return new ResponseEntity<String>(e.toString(), baseController.getResponseHeaders(), HttpStatus.NOT_FOUND); } catch (MatchExecutionException e) { logger.error(configName + ": Query failed:", e); return new ResponseEntity<String>(e.toString(), baseController.getResponseHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } catch (TooManyMatchesException e) { logger.warn(configName + ": Query failed:", e); return new ResponseEntity<String>(e.toString(), baseController.getResponseHeaders(), HttpStatus.CONFLICT); } return new ResponseEntity<String>(wrapResponse(callback, jsonres), baseController.getResponseHeaders(), HttpStatus.OK); } /** * Single suggest query, no callback. */ @RequestMapping(value = "/reconcile/{configName}", method={RequestMethod.GET,RequestMethod.POST}, params={"prefix"}, produces="application/json; charset=UTF-8") public ResponseEntity<String> doSuggest(@PathVariable String configName, @RequestParam("prefix") String prefix) { return doSuggest(configName, prefix, null); } /** * Single suggest query. */ @RequestMapping(value = "/reconcile/{configName}", method={RequestMethod.GET,RequestMethod.POST}, params={"prefix","callback"}, produces="application/json; charset=UTF-8") public ResponseEntity<String> doSuggest(@PathVariable String configName, @RequestParam("prefix") String prefix, @RequestParam(value="callback",required=false) String callback) { logger.info("{}: Suggest query, prefix {}", configName, prefix); Query q = new Query(); q.setQuery(prefix); try { return doSingleQuery(configName, jsonMapper.writeValueAsString(q), callback); } catch (IOException e) { return new ResponseEntity<String>(e.toString(), baseController.getResponseHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } } /** * Type suggest, no callback. */ @RequestMapping(value = "/reconcile/{configName}/suggestType", method={RequestMethod.GET,RequestMethod.POST}, params={"prefix"}, produces="application/json; charset=UTF-8") public ResponseEntity<String> doSuggestType(@PathVariable String configName, @RequestParam("prefix") String prefix) { return doSuggestType(configName, prefix, null); } /** * Type suggest. */ @RequestMapping(value = "/reconcile/{configName}/suggestType", method={RequestMethod.GET,RequestMethod.POST}, params={"prefix","callback"}, produces="application/json; charset=UTF-8") public ResponseEntity<String> doSuggestType(@PathVariable String configName, @RequestParam("prefix") String prefix, @RequestParam(value="callback",required=false) String callback) { logger.info("{}: Type suggest query, prefix {}", configName, prefix); String jsonres = null; try { Type[] defaultTypes = reconciliationService.getMetadata(configName).getDefaultTypes(); QueryResponse<Type> response = new QueryResponse<>(); response.setResult(defaultTypes); jsonres = jsonMapper.writeValueAsString(response); } catch (JsonMappingException | JsonGenerationException e) { logger.warn(configName + ": Error parsing JSON query", e); return new ResponseEntity<String>(e.toString(), baseController.getResponseHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } catch (IOException e) { return new ResponseEntity<String>(e.toString(), baseController.getResponseHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } catch (UnknownReconciliationServiceException e) { return new ResponseEntity<String>(e.toString(), baseController.getResponseHeaders(), HttpStatus.NOT_FOUND); } catch (MatchExecutionException e) { return new ResponseEntity<String>(e.toString(), baseController.getResponseHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } return new ResponseEntity<String>(wrapResponse(callback, jsonres), baseController.getResponseHeaders(), HttpStatus.OK); } /** * Type suggest flyout */ @RequestMapping(value = "/reconcile/{configName}/flyoutType/{id:.+}", method={RequestMethod.GET,RequestMethod.POST}, produces="application/json; charset=UTF-8") public ResponseEntity<String> doTypeFlyout(@PathVariable String configName, @PathVariable String id, @RequestParam(value="callback",required=false) String callback) { logger.info("{}: Type flyout for id {}", configName, id); try { Type[] defaultTypes = reconciliationService.getMetadata(configName).getDefaultTypes(); Type type = null; for (Type t : defaultTypes) { if (t.getId().equals(id)) { type = t; } } String html = "<html><body><ul><li>"+type.getName()+" ("+type.getId()+")</li></ul></body></html>\n"; FlyoutResponse jsonWrappedHtml = new FlyoutResponse(html); return new ResponseEntity<String>(wrapResponse(callback, jsonMapper.writeValueAsString(jsonWrappedHtml)), baseController.getResponseHeaders(), HttpStatus.OK); } catch (IOException e) { logger.warn(configName + ": Error in type flyout for id "+id, e); return new ResponseEntity<String>(e.toString(), baseController.getResponseHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } catch (UnknownReconciliationServiceException e) { return new ResponseEntity<String>(e.toString(), baseController.getResponseHeaders(), HttpStatus.NOT_FOUND); } catch (MatchExecutionException | NullPointerException e) { return new ResponseEntity<String>(e.toString(), baseController.getResponseHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } } /** * Properties suggest, no callback. */ @RequestMapping(value = "/reconcile/{configName}/suggestProperty", method={RequestMethod.GET,RequestMethod.POST}, params={"prefix"}, produces="application/json; charset=UTF-8") public ResponseEntity<String> doSuggestProperty(@PathVariable String configName, @RequestParam("prefix") String prefix) { return doSuggestProperty(configName, prefix, null); } /** * Properties suggest. */ @RequestMapping(value = "/reconcile/{configName}/suggestProperty", method={RequestMethod.GET,RequestMethod.POST}, params={"prefix","callback"}, produces="application/json; charset=UTF-8") public ResponseEntity<String> doSuggestProperty(@PathVariable String configName, @RequestParam("prefix") String prefix, @RequestParam(value="callback",required=false) String callback) { logger.info("{}: Property suggest query, prefix {}", configName, prefix); String jsonres = null; try { List<Type> filteredProperties = new ArrayList<>(); List<Property> properties = reconciliationService.getReconciliationServiceConfiguration(configName).getProperties(); for (Property p : properties) { String name = p.getQueryColumnName(); // Filter by prefix if (name != null && name.toUpperCase().startsWith(prefix.toUpperCase())) { Type t = new Type(); t.setId(name); t.setName(name); filteredProperties.add(t); } } logger.debug("Suggest Property query for {} filtered {} properties to {}", prefix, properties.size(), filteredProperties); QueryResponse<Type> response = new QueryResponse<>(); response.setResult(filteredProperties.toArray(new Type[1])); jsonres = jsonMapper.writeValueAsString(response); } catch (JsonMappingException | JsonGenerationException e) { logger.warn(configName + ": Error parsing JSON query", e); return new ResponseEntity<String>(e.toString(), baseController.getResponseHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } catch (IOException e) { return new ResponseEntity<String>(e.toString(), baseController.getResponseHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } catch (UnknownReconciliationServiceException e) { return new ResponseEntity<String>(e.toString(), baseController.getResponseHeaders(), HttpStatus.NOT_FOUND); } return new ResponseEntity<String>(wrapResponse(callback, jsonres), baseController.getResponseHeaders(), HttpStatus.OK); } /** * Properties suggest flyout */ @RequestMapping(value = "/reconcile/{configName}/flyoutProperty/{id:.+}", method={RequestMethod.GET,RequestMethod.POST}, produces="application/json; charset=UTF-8") public ResponseEntity<String> doPropertiesFlyout(@PathVariable String configName, @PathVariable String id, @RequestParam(value="callback",required=false) String callback) { logger.info("{}: In property flyout for id {}", configName, id); try { String html = "<html><body><ul><li>"+id+"</li></ul></body></html>\n"; FlyoutResponse jsonWrappedHtml = new FlyoutResponse(html); return new ResponseEntity<String>(wrapResponse(callback, jsonMapper.writeValueAsString(jsonWrappedHtml)), baseController.getResponseHeaders(), HttpStatus.OK); } catch (IOException e) { logger.warn(configName + ": Error in properties flyout for id "+id, e); return new ResponseEntity<String>(e.toString(), baseController.getResponseHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } } /** * Entity suggest flyout. * <br/> * Either calls the URL provided in the configuration, or generates an HTML snippet containing the known Property fields (in order) in a table. */ @RequestMapping(value = "/reconcile/{configName}/flyout/{id:.+}", method={RequestMethod.GET,RequestMethod.POST}, produces="application/json; charset=UTF-8") public ResponseEntity<String> doSuggestFlyout(@PathVariable String configName, @PathVariable String id, @RequestParam(value="callback",required=false) String callback) { logger.info("{}: Suggest flyout request for {}", configName, id); // TODO: This should be replaced by a class which is customisable, e.g. to return HTML, or transform RDF. String targetUrl; try { targetUrl = reconciliationService.getReconciliationServiceConfiguration(configName).getSuggestFlyoutUrl(); } catch (UnknownReconciliationServiceException e) { return new ResponseEntity<String>(e.toString(), baseController.getResponseHeaders(), HttpStatus.NOT_FOUND); } // If the configuration has a flyout configured use it if (targetUrl != null) { try { ResponseEntity<String> httpResponse = template.getForEntity(targetUrl, String.class, id); if (httpResponse.getStatusCode() != HttpStatus.OK) { logger.debug("{}: Received HTTP {} from URL {} with id {}", configName, httpResponse.getStatusCode(), targetUrl, id); } String domainUpToSlash = targetUrl.substring(0, targetUrl.indexOf('/', 10)); String html = httpResponse.getBody(); html = html.replaceFirst("</head>", "<base href='"+domainUpToSlash+"/'/></head>"); FlyoutResponse jsonWrappedHtml = new FlyoutResponse(html); logger.debug("JSON response is {}", wrapResponse(callback, jsonMapper.writeValueAsString(jsonWrappedHtml))); return new ResponseEntity<String>(wrapResponse(callback, jsonMapper.writeValueAsString(jsonWrappedHtml)), baseController.getResponseHeaders(), httpResponse.getStatusCode()); } catch (NullPointerException e) { logger.info(configName + ": Not found when retrieving URL for id "+id, e); return new ResponseEntity<String>(e.toString(), baseController.getResponseHeaders(), HttpStatus.NOT_FOUND); } catch (IOException e) { logger.warn(configName + ": Exception retrieving URL for id "+id, e); return new ResponseEntity<String>(e.toString(), baseController.getResponseHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } } // Otherwise create something very simple from the Properties else { try { StringBuilder flyout = new StringBuilder(); flyout.append("<!DOCTYPE HTML><html><body><table>\n"); Map<String,String> doc = reconciliationService.getMatcher(configName).getRecordById(id); List<Property> properties = reconciliationService.getReconciliationServiceConfiguration(configName).getProperties(); for (Property p : properties) { String name = p.getQueryColumnName(); flyout.append("<tr><th>"); flyout.append(name); flyout.append("</th><td>"); flyout.append(doc.get(name)); flyout.append("</td></tr>\n"); } flyout.append("</table></body></html>\n"); FlyoutResponse jsonWrappedHtml = new FlyoutResponse(flyout.toString()); logger.debug("JSON response is {}", wrapResponse(callback, jsonMapper.writeValueAsString(jsonWrappedHtml))); return new ResponseEntity<String>(wrapResponse(callback, jsonMapper.writeValueAsString(jsonWrappedHtml)), baseController.getResponseHeaders(), HttpStatus.OK); } catch (UnknownReconciliationServiceException e) { return new ResponseEntity<String>(e.toString(), baseController.getResponseHeaders(), HttpStatus.NOT_FOUND); } catch (IOException e) { logger.warn(configName + ": Exception creating entity flyout for id "+id, e); return new ResponseEntity<String>(e.toString(), baseController.getResponseHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } } } /** * Wrap response into JSON-P if necessary. */ private String wrapResponse(String callback, String jsonres){ if (callback != null) { return callback + "(" + jsonres + ")"; } else { return jsonres; } } /** * Perform match query against specified configuration. */ private QueryResult[] doQuery(Query q, String configName) throws TooManyMatchesException, MatchExecutionException, UnknownReconciliationServiceException { ArrayList<QueryResult> qr = new ArrayList<QueryResult>(); org.kew.rmf.refine.domain.query.Property[] properties = q.getProperties(); // If user didn't supply any properties, try converting the query string into properties. if (properties == null || properties.length == 0) { QueryStringToPropertiesExtractor propertiesExtractor = reconciliationService.getPropertiesExtractor(configName); if (propertiesExtractor != null) { properties = propertiesExtractor.extractProperties(q.getQuery()); logger.debug("No properties provided, parsing query «{}» into properties {}", q.getQuery(), properties); } else { logger.info("No properties provided, no properties resulted from parsing query string «{}»", q.getQuery()); } } else { // If the user supplied some properties, but didn't supply the key property, then it comes from the query String keyColumnName = reconciliationService.getReconciliationServiceConfiguration(configName).getProperties().get(0).getQueryColumnName(); if (!containsProperty(properties, keyColumnName)) { properties = Arrays.copyOf(properties, properties.length + 1); org.kew.rmf.refine.domain.query.Property keyProperty = new org.kew.rmf.refine.domain.query.Property(); keyProperty.setP(keyColumnName); keyProperty.setPid(keyColumnName); keyProperty.setV(q.getQuery()); logger.debug("Key property {} taken from query {}", keyColumnName, q.getQuery()); properties[properties.length-1] = keyProperty; } } if (properties == null || properties.length == 0) { logger.info("No properties provided for query «{}», query fails", q.getQuery()); // no query return null; } // Build a map by looping over each property in the config, reading its value from the // request object, and applying any transformations specified in the config Map<String, String> userSuppliedRecord = new HashMap<String, String>(); for (org.kew.rmf.refine.domain.query.Property p : properties) { if (logger.isTraceEnabled()) { logger.trace("Setting: {} to {}", p.getPid(), p.getV()); } userSuppliedRecord.put(p.getPid(), p.getV()); } List<Map<String,String>> matches = reconciliationService.doQuery(configName, userSuppliedRecord); logger.debug("Found {} matches", matches.size()); for (Map<String,String> match : matches) { QueryResult res = new QueryResult(); res.setId(match.get("id")); // Set match to true if there's only one (which allows OpenRefine to autoselect it), false otherwise res.setMatch(matches.size() == 1); // Set score to 100 * match score (which is in range 0..1) res.setScore(100 * Double.parseDouble(match.get(Configuration.MATCH_SCORE))); // Set name according to format res.setName(reconciliationService.getReconciliationResultFormatter(configName).formatResult(match)); // Set type to default type res.setType(reconciliationService.getMetadata(configName).getDefaultTypes()); qr.add(res); } return qr.toArray(new QueryResult[qr.size()]); } private boolean containsProperty(org.kew.rmf.refine.domain.query.Property[] properties, String property) { if (property == null) return false; for (org.kew.rmf.refine.domain.query.Property p : properties) { if (property.equals(p.getPid())) return true; } return false; } }
24,642
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
BaseController.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/main/java/org/kew/rmf/reconciliation/ws/BaseController.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.ws; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.kew.rmf.reconciliation.service.ReconciliationService; import org.kew.web.model.MenuItem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.google.common.base.Throwables; @Controller public class BaseController { private static Logger logger = LoggerFactory.getLogger(BaseController.class); @Autowired private ReconciliationService reconciliationService; private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); private HttpHeaders responseHeaders = new HttpHeaders(); /* • Constructors • */ public BaseController() { responseHeaders.set("Access-Control-Allow-Origin", "*"); } /* • HTTP • */ public HttpHeaders getResponseHeaders() { return responseHeaders; } /* • Menus • */ public void menuAndBreadcrumbs(String activeHref, Model model) { MenuItem menu = makeMenu(activeHref); List<MenuItem> breadcrumbs = menu.toBreadcrumbTrail(); model.addAttribute("menu", menu); model.addAttribute("breadcrumbs", breadcrumbs); } public void menuAndBreadcrumbs(String activeHref, ModelAndView mav) { MenuItem menu = makeMenu(activeHref); List<MenuItem> breadcrumbs = menu.toBreadcrumbTrail(); mav.addObject("menu", menu); mav.addObject("breadcrumbs", breadcrumbs); } /** * Generates the website menu with the active trail set accordingly. */ private MenuItem makeMenu(String activeHref) { MenuItem topMenu = new MenuItem("http://www.kew.org/science-conservation/research-data/resources", "Resources and databases"); MenuItem mainMenu = new MenuItem("/#", "Reconciliation Service"); mainMenu.add(new MenuItem("/", "Introduction")); MenuItem aboutMenu = new MenuItem("/about", "Available configurations"); if (reconciliationService.getMatchers() != null) { for (String matcher : reconciliationService.getMatchers().keySet()) { aboutMenu.add( new MenuItem("/about/" + matcher, matcher) ); } } mainMenu.add(aboutMenu); MenuItem helpMenu = new MenuItem("/help", "Usage"); helpMenu.add(new MenuItem("/help#installation", "Overview and installation")); helpMenu.add(new MenuItem("/help#data-preparation", "Data preparation")); helpMenu.add(new MenuItem("/help#reconciling", "Querying the Reconciliation Service")); helpMenu.add(new MenuItem("/help#extending", "Extending data using MQL")); helpMenu.add(new MenuItem("/help#exporting", "Exporting data")); helpMenu.add(new MenuItem("/help#troubleshooting", "Troubleshooting")); helpMenu.add(new MenuItem("/help#advanced", "Advanced data manipulation")); helpMenu.add(new MenuItem("/help#sourcecode", "Source code")); mainMenu.add(helpMenu); topMenu.add(mainMenu); topMenu.setActiveTrail(activeHref); return topMenu; } /* • Errors • */ /** * Error handler for things not caught by the Exception Resolver. */ @RequestMapping("/error") public String customError(HttpServletRequest request, HttpServletResponse response, Model model) { // retrieve some useful information from the request Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); if (statusCode == null) statusCode = 500; Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception"); String exceptionMessage = getExceptionMessage(throwable, statusCode); String requestUri = (String) request.getAttribute("javax.servlet.error.request_uri"); if (requestUri == null) { requestUri = "Unknown"; } logger.warn("Web error {} {}: {}", statusCode, requestUri, exceptionMessage); model.addAttribute("url", requestUri); model.addAttribute("datetime", simpleDateFormat.format(new Date())); model.addAttribute("contactemail", "[email protected]"); model.addAttribute("statusCode", statusCode); model.addAttribute("statusMessage", HttpStatus.valueOf(statusCode).getReasonPhrase()); menuAndBreadcrumbs("/#", model); if (statusCode == 404) { return "404"; } else { return "500"; } } private String getExceptionMessage(Throwable throwable, Integer statusCode) { if (throwable != null) { return Throwables.getRootCause(throwable).getMessage(); } HttpStatus httpStatus = HttpStatus.valueOf(statusCode); return httpStatus.getReasonPhrase(); } }
5,576
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
MatchController.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/main/java/org/kew/rmf/reconciliation/ws/MatchController.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.ws; import java.util.HashMap; import java.util.List; import java.util.Map; import org.kew.rmf.core.exception.MatchExecutionException; import org.kew.rmf.core.exception.TooManyMatchesException; import org.kew.rmf.reconciliation.exception.UnknownReconciliationServiceException; import org.kew.rmf.reconciliation.service.ReconciliationService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; /** * Implements a custom HTTP query interface to the reconciliation configurations, providing JSON responses. */ @Controller public class MatchController { private static Logger logger = LoggerFactory.getLogger(MatchController.class); @Autowired private ReconciliationService reconciliationService; @Autowired private BaseController baseController; /** * Performs a single match query. */ @RequestMapping(value = "/match/{configName}", method = RequestMethod.GET) public ResponseEntity<List<Map<String,String>>> doMatch (@PathVariable String configName, @RequestParam Map<String,String> requestParams, Model model) throws UnknownReconciliationServiceException { logger.info("{}: Match query {}", configName, requestParams); // Build a map by looping over each property in the config, reading its value from the // request object, and applying any transformations specified in the config Map<String, String> userSuppliedRecord = new HashMap<String, String>(); for (String key : requestParams.keySet()) { userSuppliedRecord.put(key, requestParams.get(key)); if (logger.isTraceEnabled()) { logger.trace("Setting: {} to {}", key, requestParams.get(key)); } } List<Map<String, String>> matches = null; try { matches = reconciliationService.doQuery(configName, userSuppliedRecord); logger.debug("Found {} matches", matches.size()); if (matches.size() < 4) { logger.debug("Matches for {} are {}", requestParams, matches); } } catch (TooManyMatchesException | MatchExecutionException e) { logger.error(configName + ": Problem handling match", e); return new ResponseEntity<List<Map<String,String>>>(null, baseController.getResponseHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } // TODO: Reporter is needed to cause only configured properties to be returned in the JSON. // matches will be returned as JSON return new ResponseEntity<List<Map<String,String>>>(matches, baseController.getResponseHeaders(), HttpStatus.OK); } }
3,672
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
DisplayBean.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/main/java/org/kew/rmf/reconciliation/ws/dto/DisplayBean.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.reconciliation.ws.dto; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.kew.rmf.utils.Dictionary; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Generates properties necessary to display a bean nicely in the web interface. */ public class DisplayBean<T> { private static Logger logger = LoggerFactory.getLogger(DisplayBean.class); private String name; private String qualifiedName; private List<String> configuration; public DisplayBean(T javaBean) { Class<? extends Object> clazz = javaBean.getClass(); setName(clazz.getSimpleName().replaceAll("([a-z])([A-Z])", "$1 $2")); setQualifiedName(clazz.getCanonicalName()); List<String> configuration = new ArrayList<>(); // Find getter/setter pairs, display the name and value. try { BeanInfo beanInfo = Introspector.getBeanInfo(clazz, Object.class); for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) { String configurationItem; try { Method getter = descriptor.getReadMethod(); Method setter = descriptor.getWriteMethod(); if (setter != null) { configurationItem = descriptor.getName().replaceAll("([a-z])([A-Z])", "$1 $2").toLowerCase(); if (getter != null) { Class<?> propertyType = descriptor.getPropertyType(); // Quote string values if (propertyType.equals(String.class)) { configurationItem += ": \"<code>" + getter.invoke(javaBean) + "</code>\""; } // Recurse for lists else if (Iterable.class.isAssignableFrom(propertyType)) { Iterable<?> l = (Iterable<?>) getter.invoke(javaBean); configurationItem += ": {\n"; for (Object li : l) { DisplayBean<?> dto = new DisplayBean<Object>(li); configurationItem += "\t• " + dto.getName(); if (dto.getConfiguration() != null && dto.getConfiguration().size() > 0) { configurationItem += " " + dto.getConfiguration(); } configurationItem += ";\n"; } configurationItem = configurationItem.substring(0, configurationItem.length()-2); configurationItem += "\n}"; } // Dictionaries else if (propertyType.equals(Dictionary.class)) { configurationItem += ": \"<code>" + getter.invoke(javaBean) + "</code>\""; } // Otherwise else { configurationItem += ": <code>" + getter.invoke(javaBean) + "</code>"; } } else { configurationItem += ": [Unknown]"; } configuration.add(configurationItem); } } catch (ReflectiveOperationException | IllegalArgumentException e) { logger.warn("Error retrieving property details of "+javaBean+"."+descriptor, e); } } } catch (IntrospectionException e) { logger.warn("Error retrieving properties of "+javaBean, e); } setConfiguration(configuration); } /* • Getters and setters • */ public String getName() { return name; } public void setName(String name) { this.name = name; } public String getQualifiedName() { return qualifiedName; } public void setQualifiedName(String qualifiedName) { this.qualifiedName = qualifiedName; } public List<String> getConfiguration() { return configuration; } public void setConfiguration(List<String> configuration) { this.configuration = configuration; } }
4,277
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
ReconciliationServiceConfiguration.java
/FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/reconciliation-service/src/main/java/org/kew/rmf/core/configuration/ReconciliationServiceConfiguration.java
/* * Reconciliation and Matching Framework * Copyright © 2014 Royal Botanic Gardens, Kew * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kew.rmf.core.configuration; import java.util.List; import org.kew.rmf.reconciliation.queryextractor.QueryStringToPropertiesExtractor; import org.kew.rmf.reconciliation.service.resultformatter.ReconciliationResultFormatter; import org.kew.rmf.refine.domain.metadata.Metadata; import org.kew.rmf.refine.domain.metadata.MetadataPreview; import org.kew.rmf.refine.domain.metadata.MetadataSuggest; import org.kew.rmf.refine.domain.metadata.MetadataSuggestDetails; import org.kew.rmf.refine.domain.metadata.MetadataView; import org.kew.rmf.refine.domain.metadata.Type; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; public class ReconciliationServiceConfiguration extends MatchConfiguration implements InitializingBean { private ApplicationContext context; private Metadata reconciliationServiceMetadata; private QueryStringToPropertiesExtractor queryStringToPropertiesExtractor; private ReconciliationResultFormatter reconciliationResultFormatter; private String description; // Metadata values private String title; private String identifierSpace; private String schemaSpace; private String viewUrl; private String previewUrl; private int previewWidth; private int previewHeight; private List<Type> defaultTypes; private String suggestFlyoutUrl; @Override public void afterPropertiesSet() throws Exception { // Generate Metadata object reconciliationServiceMetadata = new Metadata(); reconciliationServiceMetadata.setName(title); reconciliationServiceMetadata.setIdentifierSpace(identifierSpace); reconciliationServiceMetadata.setSchemaSpace(schemaSpace); if (viewUrl != null) { MetadataView metadataView = new MetadataView(); metadataView.setUrl(viewUrl); reconciliationServiceMetadata.setView(metadataView); } if (previewUrl != null) { MetadataPreview metadataPreview = new MetadataPreview(); metadataPreview.setUrl(previewUrl); metadataPreview.setWidth(previewWidth); metadataPreview.setHeight(previewHeight); reconciliationServiceMetadata.setPreview(metadataPreview); } MetadataSuggestDetails metadataSuggestTypeDetails = new MetadataSuggestDetails(); metadataSuggestTypeDetails.setService_url("LOCAL"); metadataSuggestTypeDetails.setService_path("BASE/suggestType"); metadataSuggestTypeDetails.setFlyout_service_url("LOCAL"); metadataSuggestTypeDetails.setFlyout_service_path("BASE/flyoutType/${id}"); MetadataSuggestDetails metadataSuggestPropertyDetails = new MetadataSuggestDetails(); metadataSuggestPropertyDetails.setService_url("LOCAL"); metadataSuggestPropertyDetails.setService_path("BASE/suggestProperty"); metadataSuggestPropertyDetails.setFlyout_service_url("LOCAL"); metadataSuggestPropertyDetails.setFlyout_service_path("BASE/flyoutProperty/${id}"); MetadataSuggestDetails metadataSuggestEntityDetails = new MetadataSuggestDetails(); metadataSuggestEntityDetails.setService_url("LOCAL"); metadataSuggestEntityDetails.setService_path("BASE"); metadataSuggestEntityDetails.setFlyout_service_url("LOCAL"); metadataSuggestEntityDetails.setFlyout_service_path("BASE/flyout/${id}"); MetadataSuggest metadataSuggest = new MetadataSuggest(); metadataSuggest.setType(metadataSuggestTypeDetails); metadataSuggest.setProperty(metadataSuggestPropertyDetails); metadataSuggest.setEntity(metadataSuggestEntityDetails); reconciliationServiceMetadata.setSuggest(metadataSuggest); reconciliationServiceMetadata.setDefaultTypes(defaultTypes.toArray(new Type[defaultTypes.size()])); } /* ••• Getters and setters ••• */ public ApplicationContext getContext() { return context; } public void setContext(ApplicationContext context) { this.context = context; } public Metadata getReconciliationServiceMetadata() { return reconciliationServiceMetadata; } protected void setReconciliationServiceMetadata(Metadata reconciliationServiceMetadata) { this.reconciliationServiceMetadata = reconciliationServiceMetadata; } public QueryStringToPropertiesExtractor getQueryStringToPropertiesExtractor() { return queryStringToPropertiesExtractor; } /** * Turns a single query into a set of properties for matching. */ public void setQueryStringToPropertiesExtractor(QueryStringToPropertiesExtractor queryStringToPropertiesExtractor) { this.queryStringToPropertiesExtractor = queryStringToPropertiesExtractor; } public ReconciliationResultFormatter getReconciliationResultFormatter() { return reconciliationResultFormatter; } /** * Formats results for JSON responses. */ public void setReconciliationResultFormatter(ReconciliationResultFormatter reconciliationResultFormatter) { this.reconciliationResultFormatter = reconciliationResultFormatter; } public String getDescription() { return description; } /** * Longer description of the purpose of the service, for display etc. */ public void setDescription(String description) { this.description = description; } public String getTitle() { return title; } /** * The Metadata service title for the service. */ public void setTitle(String title) { this.title = title; } public String getIdentifierSpace() { return identifierSpace; } /** * Metadata identifier space. */ public void setIdentifierSpace(String identifierSpace) { this.identifierSpace = identifierSpace; } public String getSchemaSpace() { return schemaSpace; } /** * Metadata schema space. */ public void setSchemaSpace(String schemaSpace) { this.schemaSpace = schemaSpace; } public String getViewUrl() { return viewUrl; } /** * URL to view web page for record. */ public void setViewUrl(String viewUrl) { this.viewUrl = viewUrl; } public String getPreviewUrl() { return previewUrl; } /** * URL for preview web page, should be compact as it's shown in a popup. */ public void setPreviewUrl(String previewUrl) { this.previewUrl = previewUrl; } public Integer getPreviewWidth() { return previewWidth; } /** * Preview popup width. */ public void setPreviewWidth(Integer previewWidth) { this.previewWidth = previewWidth; } public Integer getPreviewHeight() { return previewHeight; } /** * Preview popup height. */ public void setPreviewHeight(Integer previewHeight) { this.previewHeight = previewHeight; } public List<Type> getDefaultTypes() { return defaultTypes; } /** * Default type(s) used by the service. */ public void setDefaultTypes(List<Type> defaultTypes) { this.defaultTypes = defaultTypes; } public String getSuggestFlyoutUrl() { return suggestFlyoutUrl; } /** * URL template for suggest entity flyouts. <code>{id}</code> will be replaced with the entity id. * <br/> * <strong>Do not have Javascript or wide-ranging CSS in here — it could break OpenRefine.</strong> */ public void setSuggestFlyoutUrl(String suggestFlyoutUrl) { this.suggestFlyoutUrl = suggestFlyoutUrl; } }
7,724
Java
.java
RBGKew/Reconciliation-and-Matching-Framework
28
3
9
2014-09-24T13:39:19Z
2017-04-18T13:37:52Z
AlternateUsbInterfaceTest.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/usbxfer/src/test/java/info/martinmarinov/usbxfer/AlternateUsbInterfaceTest.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.usbxfer; import android.hardware.usb.UsbDeviceConnection; import android.hardware.usb.UsbInterface; import org.junit.Test; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class AlternateUsbInterfaceTest { @Test public void getAlternateSetting() throws Exception { UsbDeviceConnection usbDeviceConnection = mockConnectionWithRawDescriptors(new byte[] { 18, 1, 0, 2, 0, 0, 0, 64, -38, 11, 56, 40, 0, 1, 1, 2, 3, 1, // Device Descriptor 9, 2, 34, 0, 2, 1, 4, -128, -6, // Configuration Descriptor 9, 4, 0, 0, 1, -1, -1, -1, 5, // Interface Descriptor for interface 0 with alternate setting 0 9, 4, 0, 1, 1, -1, -1, -1, 5, // Interface Descriptor for interface 0 with alternate setting 1 7, 5, -127, 2, 0, 2, 0, // Endpoint Descriptor 9, 4, 1, 0, 0, -1, -1, -1, 5 // Interface Descriptor for interface 1 with alternate setting 0 }); // Interface 0 has alternate settings {0, 1} UsbInterface i0 = mockInterface(0); assertThat(AlternateUsbInterface.forUsbInterface(usbDeviceConnection, i0), equalTo(asList(new AlternateUsbInterface(i0, 0), new AlternateUsbInterface(i0, 1)))); // Interface 1 has alternate settings {0} UsbInterface i1 = mockInterface(1); assertThat(AlternateUsbInterface.forUsbInterface(usbDeviceConnection, i1), equalTo(singletonList(new AlternateUsbInterface(i1, 0)))); } private static UsbInterface mockInterface(int id) { UsbInterface usbInterface = mock(UsbInterface.class); when(usbInterface.getId()).thenReturn(id); return usbInterface; } private static UsbDeviceConnection mockConnectionWithRawDescriptors(byte[] rawDescriptors) { UsbDeviceConnection usbDeviceConnection = mock(UsbDeviceConnection.class); when(usbDeviceConnection.getRawDescriptors()).thenReturn(rawDescriptors); return usbDeviceConnection; } }
3,115
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z
AlternateUsbInterface.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/usbxfer/src/main/java/info/martinmarinov/usbxfer/AlternateUsbInterface.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.usbxfer; import android.hardware.usb.UsbDeviceConnection; import android.hardware.usb.UsbInterface; import androidx.annotation.VisibleForTesting; import java.util.ArrayList; import java.util.List; /** * Sometimes there could be multiple UsbInterfaces with same ID. Android API only allows * using the UsbInterface#getAlternateSettings after Android 5.0 so this is a compatibility layer */ public class AlternateUsbInterface { public static List<AlternateUsbInterface> forUsbInterface(UsbDeviceConnection deviceConnection, UsbInterface usbInterface) { byte[] rawDescriptors = deviceConnection.getRawDescriptors(); List<AlternateUsbInterface> alternateSettings = new ArrayList<>(2); int offset = 0; while(offset < rawDescriptors.length) { int bLength = rawDescriptors[offset] & 0xFF; int bDescriptorType = rawDescriptors[offset + 1] & 0xFF; if (bDescriptorType == 0x04) { // interface descriptor, we are not interested int bInterfaceNumber = rawDescriptors[offset + 2] & 0xFF; int bAlternateSetting = rawDescriptors[offset + 3] & 0xFF; if (bInterfaceNumber == usbInterface.getId()) { alternateSettings.add(new AlternateUsbInterface(usbInterface, bAlternateSetting)); } } // go to next structure offset += bLength; } if (alternateSettings.size() < 1) throw new IllegalStateException(); return alternateSettings; } private final UsbInterface usbInterface; private final int alternateSettings; @VisibleForTesting AlternateUsbInterface(UsbInterface usbInterface, int alternateSettings) { this.usbInterface = usbInterface; this.alternateSettings = alternateSettings; } public UsbInterface getUsbInterface() { return usbInterface; } int getAlternateSettings() { return alternateSettings; } @SuppressWarnings("SimplifiableIfStatement") @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AlternateUsbInterface that = (AlternateUsbInterface) o; if (alternateSettings != that.alternateSettings) return false; return usbInterface != null ? usbInterface.equals(that.usbInterface) : that.usbInterface == null; } @Override public int hashCode() { int result = usbInterface != null ? usbInterface.hashCode() : 0; result = 31 * result + alternateSettings; return result; } }
3,542
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z
IoctlUtils.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/usbxfer/src/main/java/info/martinmarinov/usbxfer/IoctlUtils.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.usbxfer; import java.io.IOException; class IoctlUtils { /** * Handles return value of an ioctl request and throws an exception if necessary * @param ioctlRes * @throws IOException if return value is negative */ public static void res(int ioctlRes) throws IOException { if (ioctlRes < 0) throw new IOException("ioctl returned "+ioctlRes); } }
1,272
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z
ByteSink.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/usbxfer/src/main/java/info/martinmarinov/usbxfer/ByteSink.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.usbxfer; import java.io.IOException; public interface ByteSink { void consume(byte[] data, int length) throws IOException; }
1,019
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z
UsbBulkSource.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/usbxfer/src/main/java/info/martinmarinov/usbxfer/UsbBulkSource.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.usbxfer; import android.hardware.usb.UsbDeviceConnection; import android.hardware.usb.UsbEndpoint; import java.io.IOException; public class UsbBulkSource implements ByteSource { private final static int INITIAL_DELAY_BEFORE_BACKOFF = 1_000; private final static int MAX_BACKOFF = 10; private final UsbDeviceConnection usbDeviceConnection; private final UsbEndpoint usbEndpoint; private final AlternateUsbInterface usbInterface; private final int numRequests; private final int numPacketsPerReq; private UsbHiSpeedBulk usbHiSpeedBulk; private int backoff = -INITIAL_DELAY_BEFORE_BACKOFF; public UsbBulkSource(UsbDeviceConnection usbDeviceConnection, UsbEndpoint usbEndpoint, AlternateUsbInterface usbInterface, int numRequests, int numPacketsPerReq) { this.usbDeviceConnection = usbDeviceConnection; this.usbEndpoint = usbEndpoint; this.usbInterface = usbInterface; this.numRequests = numRequests; this.numPacketsPerReq = numPacketsPerReq; } @Override public void open() throws IOException { usbHiSpeedBulk = new UsbHiSpeedBulk(usbDeviceConnection, usbEndpoint, numRequests, numPacketsPerReq); usbHiSpeedBulk.setInterface(usbInterface); usbDeviceConnection.claimInterface(usbInterface.getUsbInterface(), true); usbHiSpeedBulk.start(); } @Override public void readNext(ByteSink sink) throws IOException, InterruptedException { UsbHiSpeedBulk.Buffer read = usbHiSpeedBulk.read(false); if (read == null) { backoff++; if (backoff > 0) { Thread.sleep(backoff); } else { if (backoff % 3 == 0) Thread.sleep(1); } if (backoff > MAX_BACKOFF) { backoff = MAX_BACKOFF; } } else { backoff = -INITIAL_DELAY_BEFORE_BACKOFF; sink.consume(read.getData(), read.getLength()); } } @Override public void close() throws IOException { usbHiSpeedBulk.stop(); usbHiSpeedBulk.unsetInterface(usbInterface); usbDeviceConnection.releaseInterface(usbInterface.getUsbInterface()); } }
3,104
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z
ByteSource.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/usbxfer/src/main/java/info/martinmarinov/usbxfer/ByteSource.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.usbxfer; import java.io.Closeable; import java.io.IOException; public interface ByteSource extends Closeable { void open() throws IOException; void readNext(ByteSink sink) throws IOException, InterruptedException; }
1,114
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z
IsoRequest.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/usbxfer/src/main/java/info/martinmarinov/usbxfer/IsoRequest.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.usbxfer; import android.hardware.usb.UsbDeviceConnection; import android.hardware.usb.UsbEndpoint; import java.io.IOException; class IsoRequest { private final long urbPtr; private final int fd; IsoRequest(UsbDeviceConnection usbDeviceConnection, UsbEndpoint usbEndpoint, int id, int maxPackets, int packetSize) { this.fd = usbDeviceConnection.getFileDescriptor(); urbPtr = jni_allocate_urb(usbEndpoint.getAddress(), id, maxPackets, packetSize); jni_reset_urb(urbPtr); } void reset() { jni_reset_urb(urbPtr); } void submit() throws IOException { IoctlUtils.res(jni_submit(urbPtr, fd)); } void cancel() throws IOException { IoctlUtils.res(jni_cancel(urbPtr, fd)); } int read(byte[] data) { return jni_read(urbPtr, data); } static int getReadyRequestId(UsbDeviceConnection usbDeviceConnection, boolean wait) { return jni_get_ready_packet_id(usbDeviceConnection.getFileDescriptor(), wait); } @Override protected void finalize() throws Throwable { super.finalize(); jni_free_urb(urbPtr); } private static native long jni_allocate_urb(int endpointAddr, int id, int maxPackets, int packetSize); private static native void jni_reset_urb(long ptr); private static native void jni_free_urb(long ptr); private static native int jni_submit(long ptr, int fd); private static native int jni_cancel(long ptr, int fd); private static native int jni_read(long ptr, byte[] data); private static native int jni_get_ready_packet_id(int fd, boolean wait); }
2,513
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z
UsbHiSpeedBulk.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/usbxfer/src/main/java/info/martinmarinov/usbxfer/UsbHiSpeedBulk.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.usbxfer; import android.hardware.usb.UsbDeviceConnection; import android.hardware.usb.UsbEndpoint; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Android USB API drops packets when high speeds are needed. * * This is why we need this framework to allow us to use the kernel to handle the transfer for us * * Inspired by http://www.source-code.biz/snippets/java/UsbIso * * This is not thread safe! Call only from one thread. */ public class UsbHiSpeedBulk { public final static boolean IS_PLATFORM_SUPPORTED; static { boolean isPlatformSupported = false; try { System.loadLibrary("UsbXfer"); isPlatformSupported = true; } catch (Throwable t) { t.printStackTrace(); } IS_PLATFORM_SUPPORTED = isPlatformSupported; } private final int fileDescriptor; private final UsbDeviceConnection usbDeviceConnection; private final List<IsoRequest> requests; private final int nrequests, packetsPerRequests, packetSize; private final UsbEndpoint usbEndpoint; private final Buffer buffer; public UsbHiSpeedBulk(UsbDeviceConnection usbDeviceConnection, UsbEndpoint usbEndpoint, int nrequests, int packetsPerRequests) { this.usbDeviceConnection = usbDeviceConnection; this.fileDescriptor = usbDeviceConnection.getFileDescriptor(); this.nrequests = nrequests; this.requests = new ArrayList<>(nrequests); this.packetSize = usbEndpoint.getMaxPacketSize(); this.usbEndpoint = usbEndpoint; this.packetsPerRequests = packetsPerRequests; this.buffer = new Buffer(packetsPerRequests * packetSize); } // API public void setInterface(AlternateUsbInterface usbInterface) throws IOException { IoctlUtils.res(jni_setInterface(fileDescriptor, usbInterface.getUsbInterface().getId(), usbInterface.getAlternateSettings())); } public void unsetInterface(AlternateUsbInterface usbInterface) throws IOException { // According to original UsbHiSpeedBulk alternatesetting of 0 stops the streaming IoctlUtils.res(jni_setInterface(fileDescriptor, usbInterface.getUsbInterface().getId(), 0)); } public void start() throws IOException { for (int i = 0; i < nrequests; i++) { IsoRequest req = new IsoRequest(usbDeviceConnection, usbEndpoint, i, packetsPerRequests, packetSize); try { req.submit(); requests.add(req); } catch (IOException e) { // No more memory for allocating packets e.printStackTrace(); break; } } if (requests.isEmpty()) throw new IOException("Cannot initialize any USB requests"); } /** * Buffer is not immutable! Next time you call #read, its value will be invalid and overwriten. * The buffer is reused for efficiency. * @param wait whther to block until data is available * @return a buffer or null if nothing is available * @throws IOException */ public Buffer read(boolean wait) throws IOException { IsoRequest req = getReadyRequest(wait); if (req == null) return null; buffer.length = req.read(buffer.data); req.reset(); req.submit(); return buffer; } public void stop() throws IOException { for (IsoRequest r : requests) { r.cancel(); } requests.clear(); } public class Buffer { private final byte[] data; private int length; private Buffer(int bufferSize) { this.data = new byte[bufferSize]; } public byte[] getData() { return data; } public int getLength() { return length; } } // helpers private IsoRequest getReadyRequest(boolean wait) throws IOException { int readyRequestId = IsoRequest.getReadyRequestId(usbDeviceConnection, wait); if (readyRequestId < 0) return null; return requests.get(readyRequestId); } // native private static native int jni_setInterface(int fd, int interfaceId, int alternateSettings); }
5,133
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z
RequestTest.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/dvbservice/src/test/java/info/martinmarinov/dvbservice/RequestTest.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.dvbservice; import android.util.Log; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import info.martinmarinov.drivers.DvbDevice; import info.martinmarinov.drivers.DvbStatus; import info.martinmarinov.drivers.tools.SetUtils; import info.martinmarinov.drivers.DeliverySystem; import static info.martinmarinov.drivers.tools.SetUtils.setOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Answers.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import static org.powermock.api.mockito.PowerMockito.mockStatic; @RunWith(PowerMockRunner.class) @PrepareForTest({Log.class}) @PowerMockIgnore("jdk.internal.reflect.*") public class RequestTest { @Mock(answer = RETURNS_DEEP_STUBS) private DvbDevice dvbDevice; @Before public void setUp() { initMocks(this); mockStatic(Log.class); } @Test public void testProtocolVersion() { long[] response = getRawResponse(0); assertThat(response.length, is(3)); assertThat(response[0], is(1L)); // success assertThat(response[1], is(0L)); // version of protocol assertThat(response[2], is((long) Request.values().length)); // number of available requests } @Test public void testExit() { long[] response = getRawResponse(1); assertThat(response.length, is(1)); assertThat(response[0], is(1L)); // success } @Test public void testTune() throws Exception { long[] response = getRawResponse(2, 506_000_000L, 8_000_000L, 1L); assertThat(response.length, is(1)); assertThat(response[0], is(1L)); // success // verify hardware was called verify(dvbDevice).tune(506_000_000L, 8_000_000L, DeliverySystem.DVBT2); } @Test public void testGetStatus() throws Exception { when(dvbDevice.getStatus()).thenReturn(setOf(DvbStatus.FE_HAS_SIGNAL, DvbStatus.FE_HAS_CARRIER, DvbStatus.FE_HAS_VITERBI)); when(dvbDevice.readBitErrorRate()).thenReturn(123); when(dvbDevice.readDroppedUsbFps()).thenReturn(456); when(dvbDevice.readRfStrengthPercentage()).thenReturn(10); when(dvbDevice.readSnr()).thenReturn(300); long[] response = getRawResponse(3); assertThat(response.length, is(9)); assertThat(response[0], is(1L)); // success assertThat(response[1], is(300L)); // SNR assertThat(response[2], is(123L)); // BER assertThat(response[3], is(456L)); // Dropped FPS assertThat(response[4], is(10L)); // RF strength as percentage assertThat(response[5], is(1L)); // has signal assertThat(response[6], is(1L)); // has carrier assertThat(response[7], is(0L)); // no sync assertThat(response[8], is(0L)); // no lock } @Test public void setPids() throws Exception { long[] response = getRawResponse(4, 0x1FF0L, 0x1277L, 0x0010L); assertThat(response.length, is(1)); assertThat(response[0], is(1L)); // success // verify hardware was called verify(dvbDevice).setPidFilter(0x1FF0, 0x1277, 0x0010); } @Test public void testGetCapabilities() throws Exception { when(dvbDevice.readCapabilities().getFrequencyMin()).thenReturn(174000000L); when(dvbDevice.readCapabilities().getFrequencyMax()).thenReturn(862000000L); when(dvbDevice.readCapabilities().getFrequencyStepSize()).thenReturn(166667L); when(dvbDevice.readCapabilities().getSupportedDeliverySystems()).thenReturn(SetUtils.setOf(DeliverySystem.DVBT, DeliverySystem.DVBT2, DeliverySystem.DVBC)); when(dvbDevice.getDeviceFilter().getVendorId()).thenReturn(0x0BDA); when(dvbDevice.getDeviceFilter().getProductId()).thenReturn(0x2838); long[] response = getRawResponse(5); assertThat(response.length, is(7)); assertThat(response[0], is(1L)); // success assertThat(response[1], is(0x7L)); // Capabilities flags assertThat(response[2], is(174000000L)); // freq min assertThat(response[3], is(862000000L)); // freq max assertThat(response[4], is(166667L)); // step assertThat(response[5], is(0x0BDAL)); // USB vendor id assertThat(response[6], is(0x2838L)); // USB product id } /** Helper to do serialization/deserialization to bytes */ private long[] getRawResponse(int requestOrdinal, long ... reqArgs) { try { // Serialize request into bytes ByteArrayOutputStream reqArgStream = new ByteArrayOutputStream(); DataOutputStream reqArgsWriter = new DataOutputStream(reqArgStream); reqArgsWriter.write(requestOrdinal); reqArgsWriter.write(reqArgs.length); for (Long arg : reqArgs) reqArgsWriter.writeLong(arg); byte[] requestBytes = reqArgStream.toByteArray(); // Run request ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // to store output DataInputStream dataInputStream = new DataInputStream(new ByteArrayInputStream(requestBytes)); DataOutputStream dataOutputStream = new DataOutputStream(outputStream); Request.parseAndExecute(dataInputStream, dataOutputStream, dvbDevice); // De-serialize response DataInputStream payloadStream = new DataInputStream(new ByteArrayInputStream(outputStream.toByteArray())); assertThat(payloadStream.read(), is(requestOrdinal)); int size = payloadStream.readByte(); long[] rawPayload = new long[size]; for (int i = 0; i < size; i++) rawPayload[i] = payloadStream.readLong(); assertThat(payloadStream.available(), is(0)); // Some cleanup dataInputStream.close(); dataOutputStream.close(); payloadStream.close(); reqArgStream.close(); return rawPayload; } catch (Exception e) { throw new RuntimeException(e); } } }
7,441
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z
TsDumpFileUtilsTest.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/dvbservice/src/test/java/info/martinmarinov/dvbservice/tools/TsDumpFileUtilsTest.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.dvbservice.tools; import android.content.Context; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import java.io.File; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; public class TsDumpFileUtilsTest { private final static File ROOT = new File("/imaginary/root"); @Mock private Context context; @Before public void setUp() { initMocks(this); when(context.getExternalFilesDir(anyString())).thenReturn(ROOT); } @Test public void testNameCreation() { File actual = TsDumpFileUtils.getFor(context, 506_000_000L, 8_000_000L, date(2017, 1, 10, 13, 4, 24)); assertThat(actual, equalTo(new File(ROOT, "mux_506000000_8000000_20170110130424.ts"))); } @SuppressWarnings("ConstantConditions") // yeah I know res could be know @Test public void testParsing() { TsDumpFileUtils.FreqBandwidth res = TsDumpFileUtils.getFreqAndBandwidth(new File(ROOT, "mux_506000000_8000000_20170110130424.ts")); assertThat(res.freq, is(506_000_000L)); assertThat(res.bandwidth, is(8_000_000L)); } @SuppressWarnings("ConstantConditions") // yeah I know res could be know @Test public void testParsing_withoutDate() { TsDumpFileUtils.FreqBandwidth res = TsDumpFileUtils.getFreqAndBandwidth(new File(ROOT, "mux_506000000_8000000_randomSuffix.ts")); assertThat(res.freq, is(506_000_000L)); assertThat(res.bandwidth, is(8_000_000L)); } @Test public void testUnparseable_RandomString() { TsDumpFileUtils.FreqBandwidth res = TsDumpFileUtils.getFreqAndBandwidth(new File(ROOT, "fsdjfmadjk3312")); assertThat(res, nullValue()); } @Test public void testUnparseable_noExt() { TsDumpFileUtils.FreqBandwidth res = TsDumpFileUtils.getFreqAndBandwidth(new File(ROOT, "mux_506000000_8000000_20170110130424")); assertThat(res, nullValue()); } @Test public void testUnparseable_noPrefix() { TsDumpFileUtils.FreqBandwidth res = TsDumpFileUtils.getFreqAndBandwidth(new File(ROOT, "506000000_8000000_20170110130424.ts")); assertThat(res, nullValue()); } private static Date date(int year, int month, int day, int hour, int minute, int second) { Calendar c = new GregorianCalendar(); c.set(Calendar.YEAR, year); c.set(Calendar.MONTH, month - 1); c.set(Calendar.DAY_OF_MONTH, day); c.set(Calendar.HOUR_OF_DAY, hour); c.set(Calendar.MINUTE, minute); c.set(Calendar.SECOND, second); return c.getTime(); } }
3,932
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z
StackTraceSerializerTest.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/dvbservice/src/test/java/info/martinmarinov/dvbservice/tools/StackTraceSerializerTest.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.dvbservice.tools; import org.junit.Test; import java.io.IOException; import static junit.framework.Assert.assertTrue; public class StackTraceSerializerTest { @Test public void testSerialize() throws Exception { String serialization = StackTraceSerializer.serialize(new IOException("Test message")); assertTrue(serialization.startsWith("java.io.IOException: Test message\n" + "\tat "+StackTraceSerializerTest.class.getName()+".")); } }
1,371
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z
Response.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/dvbservice/src/main/java/info/martinmarinov/dvbservice/Response.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.dvbservice; import java.io.IOException; import java.io.OutputStream; /** * This is send to the client as a result of every Request received * * byte 0 will be the Request.ordinal of the Request * byte 1 will be N the number of longs in the payload * byte 3 to byte 6 will be the success flag (0 or 1). This indicates whether the request was succesful. * byte 7 till the end the rest of the longs in the payload follow * * Basically the success flag is always part of the payload, so the payload * always consists of at least one value. */ class Response { static Response ERROR = error(); static Response SUCCESS = success(); private final boolean success; private final long[] payload; static Response success(long... payload) { return new Response(true, payload); } private static Response error(long... payload) { return new Response(false, payload); } private Response(boolean success, long ... payload) { this.success = success; this.payload = payload; } private static void writeLong(byte[] buff, int off, long v) { buff[off] = (byte)(v >>> 56); buff[off+1] = (byte)(v >>> 48); buff[off+2] = (byte)(v >>> 40); buff[off+3] = (byte)(v >>> 32); buff[off+4] = (byte)(v >>> 24); buff[off+5] = (byte)(v >>> 16); buff[off+6] = (byte)(v >>> 8); buff[off+7] = (byte)(v); } void serialize(Request request, OutputStream dataOutputStream) throws IOException { byte[] payload_raw = new byte[2 + 8 + payload.length * 8]; payload_raw[0] = (byte) request.ordinal(); // what request called it payload_raw[1] = (byte) (payload.length + 1); // the success flag is part of the payload writeLong(payload_raw, 2, success ? 1 : 0); // success flag for (int i = 0; i < payload.length; i++) { writeLong(payload_raw, 2 + 8 + i * 8, payload[i]); // write actual payload if any } dataOutputStream.write(payload_raw); // raw payload in one chunk to avoid any TCP partitioning dataOutputStream.flush(); // force send over the pipe, don't wait } }
3,060
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z
Request.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/dvbservice/src/main/java/info/martinmarinov/dvbservice/Request.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.dvbservice; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.SocketException; import java.util.Set; import info.martinmarinov.drivers.DeliverySystem; import info.martinmarinov.drivers.DvbCapabilities; import info.martinmarinov.drivers.DvbDevice; import info.martinmarinov.drivers.DvbException; import info.martinmarinov.drivers.DvbStatus; /** * The client sends a command consisting of a variable number of Longs in the following format: * <p> * byte 0 will be the Request.ordinal of the request * byte 1 will be N the number of longs in the payload * byte 2 to 8*N+1 will consist the actual values of the payload * <p> * After the request has been processed it returns a Response, which is in a similar format. * Please refer to the Response documentation for more info * <p> * Warning: For backwards compatibility order of the enum will be always preserved */ enum Request { REQ_PROTOCOL_VERSION( new Executor() { @Override public Response execute(DvbDevice dvbDevice, long... payload) throws DvbException { // Clients can use it to determine whether new features // are available. // WARNING: Backward compatibility should always be ensured return Response.success( 0L, // parameter 1, version, when adding capabilities, change that number. ALL_REQUESTS.length // parameter 2, can be useful for determining supported commands ); } } ), REQ_EXIT(new Executor() { @Override public Response execute(DvbDevice dvbDevice, long... payload) { Log.d(TAG, "Client requested to close the connection"); return Response.SUCCESS; } }), REQ_TUNE(new Executor() { @Override public Response execute(DvbDevice dvbDevice, long... payload) throws DvbException { long frequency = payload[0]; // frequency in herz long bandwidth = payload[1]; // bandwidth in herz. // Typical value for DVB-T is 8_000_000 DeliverySystem deliverySystem = DeliverySystem.values()[(int) payload[2]]; // Check enum for actual values Log.d(TAG, "Client requested tune to " + frequency + " Hz with bandwidth " + bandwidth + " Hz with delivery system " + deliverySystem); dvbDevice.tune(frequency, bandwidth, deliverySystem); return Response.SUCCESS; } }), REQ_GET_STATUS(new Executor() { @Override public Response execute(DvbDevice dvbDevice, long... ignored) throws DvbException { int snr = dvbDevice.readSnr(); int bitErrorRate = dvbDevice.readBitErrorRate(); int droppedUsbFps = dvbDevice.readDroppedUsbFps(); int rfStrengthPercentage = dvbDevice.readRfStrengthPercentage(); Set<DvbStatus> status = dvbDevice.getStatus(); boolean hasSignal = status.contains(DvbStatus.FE_HAS_SIGNAL); boolean hasCarrier = status.contains(DvbStatus.FE_HAS_CARRIER); boolean hasSync = status.contains(DvbStatus.FE_HAS_SYNC); boolean hasLock = status.contains(DvbStatus.FE_HAS_LOCK); return Response.success( (long) snr, // parameter 1 (long) bitErrorRate, // parameter 2 (long) droppedUsbFps, // parameter 3 (long) rfStrengthPercentage, // parameter 4 hasSignal ? 1L : 0L, // parameter 5 hasCarrier ? 1L : 0L, // parameter 6 hasSync ? 1L : 0L, // parameter 7 hasLock ? 1L : 0L // parameter 8 ); } }), REQ_SET_PIDS(new Executor() { @Override public Response execute(DvbDevice dvbDevice, long... payload) throws DvbException { int[] pids = new int[payload.length]; for (int i = 0; i < payload.length; i++) pids[i] = (int) payload[i]; dvbDevice.setPidFilter(pids); return Response.SUCCESS; } }), REQ_GET_CAPABILITIES(new Executor() { @Override public Response execute(DvbDevice dvbDevice, long... payload) throws DvbException { DvbCapabilities frontendProperties = dvbDevice.readCapabilities(); // Only up to 62 deliverySystems are supported under current encoding method if (frontendProperties.getSupportedDeliverySystems().size() > 62) throw new IllegalStateException(); long supportedDeliverySystems = 0; for (DeliverySystem deliverySystem : frontendProperties.getSupportedDeliverySystems()) { supportedDeliverySystems |= 1 << deliverySystem.ordinal(); } return Response.success( supportedDeliverySystems, // parameter 1 frontendProperties.getFrequencyMin(), // parameter 2 frontendProperties.getFrequencyMax(), // parameter 3 frontendProperties.getFrequencyStepSize(), // parameter 4 (long) dvbDevice.getDeviceFilter().getVendorId(), // parameter 5 (long) dvbDevice.getDeviceFilter().getProductId() // parameter 6 ); } }); private final static String TAG = Request.class.getSimpleName(); private final static Request[] ALL_REQUESTS = values(); private final Executor executor; Request(Executor executor) { this.executor = executor; } private Response execute(DvbDevice dvbDevice, long... payload) { try { return executor.execute(dvbDevice, payload); } catch (Exception e) { e.printStackTrace(); return Response.ERROR; } } private static void readBytes(InputStream inputStream, byte[] read_buffer) throws IOException { int bytesRead = 0; while (bytesRead < read_buffer.length) { int count = inputStream.read(read_buffer, bytesRead, read_buffer.length - bytesRead); if (count < 0) { throw new SocketException("End of stream reached before reading required number of bytes"); } bytesRead += count; } } private static long readLongAtByte(byte[] read_buffer, int offset) { return (((long) read_buffer[offset] << 56) + ((long) (read_buffer[offset + 1] & 255) << 48) + ((long) (read_buffer[offset + 2] & 255) << 40) + ((long) (read_buffer[offset + 3] & 255) << 32) + ((long) (read_buffer[offset + 4] & 255) << 24) + ((read_buffer[offset + 5] & 255) << 16) + ((read_buffer[offset + 6] & 255) << 8) + ((read_buffer[offset + 7] & 255))); } private static long[] parsePayload(InputStream inputStream, int size) throws IOException { byte[] payload_buffer = new byte[size * 8]; readBytes(inputStream, payload_buffer); long[] payload = new long[size]; for (int i = 0; i < payload.length; i++) { payload[i] = readLongAtByte(payload_buffer, i * 8); } return payload; } public static Request parseAndExecute(InputStream inputStream, OutputStream outputStream, DvbDevice dvbDevice) throws IOException { Request req = null; byte[] head_buffer = new byte[2]; readBytes(inputStream, head_buffer); int ordinal = head_buffer[0] & 0xFF; int size = head_buffer[1] & 0xFF; long[] payload = parsePayload(inputStream, size); if (ordinal < ALL_REQUESTS.length) { req = ALL_REQUESTS[ordinal]; // This command is recognized, execute and get response Response r = req.execute(dvbDevice, payload); // Send response back over the wire r.serialize(req, outputStream); } return req; } private interface Executor { Response execute(DvbDevice dvbDevice, long... payload) throws DvbException; } }
9,172
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z
DvbServerPorts.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/dvbservice/src/main/java/info/martinmarinov/dvbservice/DvbServerPorts.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.dvbservice; import java.io.Serializable; class DvbServerPorts implements Serializable { private final int controlPort; private final int transferPort; DvbServerPorts(int controlPort, int transferPort) { this.controlPort = controlPort; this.transferPort = transferPort; } int getControlPort() { return controlPort; } int getTransferPort() { return transferPort; } }
1,321
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z
UsbDelegate.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/dvbservice/src/main/java/info/martinmarinov/dvbservice/UsbDelegate.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.dvbservice; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbManager; import android.os.Bundle; import android.util.Log; public class UsbDelegate extends Activity { private static final String TAG = UsbDelegate.class.getSimpleName(); private static final String ACTION_DVB_DEVICE_ATTACHED = "info.martinmarinov.dvbdriver.DVB_DEVICE_ATTACHED"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(intent.getAction())) { UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); Log.d(TAG, "USB DVB-T attached: " + usbDevice.getDeviceName()); Intent newIntent = new Intent(ACTION_DVB_DEVICE_ATTACHED); newIntent.putExtra(UsbManager.EXTRA_DEVICE, usbDevice); try { startActivity(newIntent); } catch (ActivityNotFoundException e) { Log.d(TAG, "No activity found for DVB-T handling"); } } finish(); } }
2,134
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z
DvbServer.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/dvbservice/src/main/java/info/martinmarinov/dvbservice/DvbServer.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.dvbservice; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import info.martinmarinov.drivers.DvbDevice; import info.martinmarinov.drivers.DvbException; class DvbServer implements Closeable { private final static int SOCKET_TIMEOUT_MS = 60 * 1_000; private final ServerSocket controlSocket = new ServerSocket(); private final ServerSocket transferSocket = new ServerSocket(); private final DvbDevice dvbDevice; DvbServer(DvbDevice dvbDevice) throws IOException { this.dvbDevice = dvbDevice; } DvbServerPorts bind(InetAddress address) throws IOException { return bind(new InetSocketAddress(address, 0)); } private DvbServerPorts bind(InetSocketAddress address) throws IOException { try { controlSocket.bind(address); transferSocket.bind(address); controlSocket.setSoTimeout(SOCKET_TIMEOUT_MS); transferSocket.setSoTimeout(SOCKET_TIMEOUT_MS); if (!controlSocket.getInetAddress().equals(transferSocket.getInetAddress())) throw new IllegalStateException(); return new DvbServerPorts(controlSocket.getLocalPort(), transferSocket.getLocalPort()); } catch (IOException e) { close(); throw e; } } void open() throws DvbException { dvbDevice.open(); } @Override public void close() { quietClose(dvbDevice); quietClose(controlSocket); quietClose(transferSocket); } void serve() throws IOException { InputStream inputStream = null; OutputStream outputStream = null; Socket control = null; try { control = controlSocket.accept(); control.setTcpNoDelay(true); inputStream = control.getInputStream(); outputStream = control.getOutputStream(); final InputStream finInputStream = inputStream; TransferThread worker = new TransferThread(dvbDevice, transferSocket, new TransferThread.OnClosedCallback() { @Override public void onClosed() { // Close input stream to cancel the request parsing quietClose(finInputStream); } }); try { worker.start(); while (worker.isAlive() && !Thread.currentThread().isInterrupted()) { Request c = Request.parseAndExecute(inputStream, outputStream, dvbDevice); if (c == Request.REQ_EXIT) break; } } catch (SocketException e) { IOException workerException = worker.signalAndWaitToDie(); if (workerException != null) throw workerException; throw e; } // Finish successfully due to exit command, if worker failed for anything other // than a socket exception, throw it IOException workerException = worker.signalAndWaitToDie(); if (workerException != null && !(workerException instanceof SocketException)) throw workerException; } finally { quietClose(inputStream); quietClose(outputStream); quietClose(control); } } private static void quietClose(Closeable c) { if (c != null) { try { c.close(); } catch (IOException e) { e.printStackTrace(); } } } private static void quietClose(Socket socket) { if (socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } private static void quietClose(ServerSocket socket) { if (socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
5,087
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z
DvbService.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/dvbservice/src/main/java/info/martinmarinov/dvbservice/DvbService.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.dvbservice; import android.app.Activity; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.IBinder; import androidx.annotation.Nullable; import androidx.core.app.NotificationCompat; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import android.util.Log; import java.io.Serializable; import java.util.List; import info.martinmarinov.drivers.DeviceFilter; import info.martinmarinov.drivers.DvbDevice; import info.martinmarinov.drivers.DvbException; import info.martinmarinov.drivers.usb.DvbUsbDeviceRegistry; import info.martinmarinov.dvbservice.tools.InetAddressTools; import info.martinmarinov.dvbservice.tools.TsDumpFileUtils; import static info.martinmarinov.drivers.DvbException.ErrorCode.CANNOT_OPEN_USB; public class DvbService extends Service { private static final String TAG = DvbService.class.getSimpleName(); private final static int ONGOING_NOTIFICATION_ID = 743713489; // random id public static final String BROADCAST_ACTION = "info.martinmarinov.dvbservice.DvbService.BROADCAST"; private final static String DEVICE_FILTER = "DeviceFilter"; private final static String STATUS_MESSAGE = "StatusMessage"; private static Thread worker; static void requestOpen(Activity activity, DeviceFilter deviceFilter) { Intent intent = new Intent(activity, DvbService.class) .putExtra(DEVICE_FILTER, deviceFilter); activity.startService(intent); } static StatusMessage parseMessage(Intent intent) { return (StatusMessage) intent.getSerializableExtra(STATUS_MESSAGE); } @Override public int onStartCommand(Intent intent, int flags, int startId) { final DeviceFilter deviceFilter = (DeviceFilter) intent.getSerializableExtra(DEVICE_FILTER); // Kill existing connection if (worker != null && worker.isAlive()) { worker.interrupt(); try { worker.join(15_000L); } catch (InterruptedException ignored) {} if (worker != null && worker.isAlive()) { throw new RuntimeException("Cannot stop existing service"); } } worker = new Thread() { @Override public void run() { DvbServer dvbServer = null; try { dvbServer = new DvbServer(getDeviceFromFilter(deviceFilter)); DvbServerPorts dvbServerPorts = dvbServer.bind(InetAddressTools.getLocalLoopback()); dvbServer.open(); // Device was opened! Tell client it's time to connect broadcastStatus(new StatusMessage(null, dvbServerPorts, deviceFilter)); startForeground(); dvbServer.serve(); } catch (Exception e) { e.printStackTrace(); broadcastStatus(new StatusMessage(e, null, deviceFilter)); } finally { if (dvbServer != null) dvbServer.close(); } Log.d(TAG, "Finished"); worker = null; stopSelf(); } }; worker.start(); return START_NOT_STICKY; } private void startForeground() { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); String NOTIFICATION_CHANNEL_ID = "DvbDriver"; if (notificationManager != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID, "DVB-T driver notifications", NotificationManager.IMPORTANCE_HIGH ); // Configure the notification channel. notificationChannel.setDescription("When DVB-T driver operates"); notificationChannel.enableVibration(false); notificationManager.createNotificationChannel(notificationChannel); } NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID) .setAutoCancel(false) .setOngoing(true) .setContentTitle(getText(R.string.app_name)) .setContentText(getText(R.string.driver_description)) .setSmallIcon(R.drawable.ic_notification); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) { builder = builder .setPriority(Notification.PRIORITY_MAX); } startForeground(ONGOING_NOTIFICATION_ID, builder.build()); } private DvbDevice getDeviceFromFilter(DeviceFilter deviceFilter) throws DvbException { List<DvbDevice> dvbDevices = DvbUsbDeviceRegistry.getUsbDvbDevices(this); dvbDevices.addAll(TsDumpFileUtils.getDevicesForAllRecordings(this)); for (DvbDevice dvbDevice : dvbDevices) { if (dvbDevice.getDeviceFilter().equals(deviceFilter)) return dvbDevice; } throw new DvbException(CANNOT_OPEN_USB, getString(R.string.device_no_longer_available)); } private void broadcastStatus(StatusMessage statusMessage) { Intent intent = new Intent(BROADCAST_ACTION) .putExtra(STATUS_MESSAGE, statusMessage); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } static class StatusMessage implements Serializable { final Exception exception; final DvbServerPorts serverAddresses; final DeviceFilter deviceFilter; private StatusMessage(Exception exception, DvbServerPorts serverAddresses, DeviceFilter deviceFilter) { this.exception = exception; this.serverAddresses = serverAddresses; this.deviceFilter = deviceFilter; } } }
7,069
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z
DeviceChooserActivity.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/dvbservice/src/main/java/info/martinmarinov/dvbservice/DeviceChooserActivity.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.dvbservice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbManager; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.FragmentActivity; import androidx.fragment.app.FragmentActivity; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import info.martinmarinov.drivers.DeviceFilter; import info.martinmarinov.drivers.DvbDevice; import info.martinmarinov.drivers.DvbException; import info.martinmarinov.drivers.usb.DvbUsbDeviceRegistry; import info.martinmarinov.dvbservice.dialogs.ListPickerFragmentDialog; import info.martinmarinov.dvbservice.tools.StackTraceSerializer; import info.martinmarinov.dvbservice.tools.TsDumpFileUtils; import static info.martinmarinov.drivers.DvbException.ErrorCode.NO_DVB_DEVICES_FOUND; public class DeviceChooserActivity extends FragmentActivity implements ListPickerFragmentDialog.OnSelected<DeviceFilter> { private final static int RESULT_ERROR = RESULT_FIRST_USER; private final static String CONTRACT_ERROR_CODE = "ErrorCode"; private final static String CONTRACT_CONTROL_PORT = "ControlPort"; private final static String CONTRACT_TRANSFER_PORT = "TransferPort"; private final static String CONTRACT_DEVICE_NAME = "DeviceName"; private final static String CONTRACT_RAW_TRACE = "RawTrace"; private final static String CONTRACT_USB_PRODUCT_IDS = "ProductIds"; private final static String CONTRACT_USB_VENDOR_IDS = "VendorIds"; private final Intent response = new Intent(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.progress); // Set to receive info from the DvbService IntentFilter statusIntentFilter = new IntentFilter(DvbService.BROADCAST_ACTION); LocalBroadcastManager.getInstance(this).registerReceiver(new DvbServiceResponseReceiver(), statusIntentFilter); } @Override protected void onStart() { super.onStart(); try { List<DvbDevice> dvbDevices = DvbUsbDeviceRegistry.getUsbDvbDevices(this); List<DvbDevice> dvbFileDevices = TsDumpFileUtils.getDevicesForAllRecordings(this); // these are only for debugging purposes dvbDevices.addAll(dvbFileDevices); if (dvbDevices.isEmpty()) throw new DvbException(NO_DVB_DEVICES_FOUND, getString(info.martinmarinov.drivers.R.string.no_devices_found)); List<DeviceFilter> deviceFilters = new ArrayList<>(dvbDevices.size()); for (DvbDevice dvbDevice : dvbDevices) { deviceFilters.add(dvbDevice.getDeviceFilter()); } if (deviceFilters.size() > 1 || !dvbFileDevices.isEmpty()) { ListPickerFragmentDialog.showOneInstanceOnly(getSupportFragmentManager(), deviceFilters); } else { DvbService.requestOpen(this, deviceFilters.get(0)); } } catch (DvbException e) { handleException(e); } } @Override public void onListPickerDialogItemSelected(@NonNull DeviceFilter deviceFilter) { DvbService.requestOpen(this, deviceFilter); } @Override public void onListPickerDialogCanceled() { finishWith(RESULT_CANCELED); } // Open selected device private class DvbServiceResponseReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { DvbService.StatusMessage statusMessage = DvbService.parseMessage(intent); if (statusMessage.exception != null) { Exception exception = statusMessage.exception; if (exception instanceof DvbException) { handleException((DvbException) exception); } else if (exception instanceof IOException) { handleException(new DvbException(DvbException.ErrorCode.IO_EXCEPTION, exception)); } else if (exception instanceof RuntimeException) { throw (RuntimeException) exception; } else { throw new RuntimeException(exception); } } else { handleSuccess(statusMessage.deviceFilter, statusMessage.serverAddresses); } } } // API for returning response to caller private void handleSuccess(DeviceFilter deviceFilter, DvbServerPorts addresses) { int[] productIds = new int[] {deviceFilter.getProductId()}; int[] vendorIds = new int[] {deviceFilter.getVendorId()}; response.putExtra(CONTRACT_DEVICE_NAME, deviceFilter.getName()); response.putExtra(CONTRACT_USB_PRODUCT_IDS, productIds); response.putExtra(CONTRACT_USB_VENDOR_IDS, vendorIds); response.putExtra(CONTRACT_CONTROL_PORT, addresses.getControlPort()); response.putExtra(CONTRACT_TRANSFER_PORT, addresses.getTransferPort()); finishWith(RESULT_OK); } private void handleException(DvbException e) { UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE); Collection<UsbDevice> availableDevices = manager.getDeviceList().values(); int[] productIds = new int[availableDevices.size()]; int[] vendorIds = new int[availableDevices.size()]; int id = 0; for (UsbDevice usbDevice : availableDevices) { productIds[id] = usbDevice.getProductId(); vendorIds[id] = usbDevice.getVendorId(); id++; } response.putExtra(CONTRACT_ERROR_CODE, e.getErrorCode().name()); response.putExtra(CONTRACT_RAW_TRACE, StackTraceSerializer.serialize(e)); response.putExtra(CONTRACT_USB_PRODUCT_IDS, productIds); response.putExtra(CONTRACT_USB_VENDOR_IDS, vendorIds); finishWith(RESULT_ERROR); } private void finishWith(int code) { if (getParent() == null) { setResult(code, response); } else { getParent().setResult(code, response); } finish(); } }
7,241
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z
TransferThread.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/dvbservice/src/main/java/info/martinmarinov/dvbservice/TransferThread.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.dvbservice; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import info.martinmarinov.drivers.DvbDevice; class TransferThread extends Thread { private final DvbDevice dvbDevice; private final ServerSocket serverSocket; private final OnClosedCallback callback; private IOException lastException = null; private InputStream transportStream; TransferThread(DvbDevice dvbDevice, ServerSocket serverSocket, OnClosedCallback callback) { this.dvbDevice = dvbDevice; this.serverSocket = serverSocket; this.callback = callback; } @Override public void interrupt() { super.interrupt(); quietClose(serverSocket); quietClose(transportStream); } @Override public void run() { setName(TransferThread.class.getSimpleName()); setPriority(NORM_PRIORITY); OutputStream os = null; Socket socket = null; try { socket = serverSocket.accept(); socket.setTcpNoDelay(true); byte[] buf = new byte[5 * 188]; os = socket.getOutputStream(); transportStream = dvbDevice.getTransportStream(new DvbDevice.StreamCallback() { @Override public void onStreamException(IOException exception) { lastException = exception; interrupt(); } @Override public void onStoppedStreaming() { interrupt(); } }); while (!isInterrupted()) { int inlength = transportStream.read(buf); if (inlength > 0) { os.write(buf, 0, inlength); } else { // No data, sleep for a bit until available quietSleep(10); } } } catch (IOException e) { lastException = e; } finally { quietClose(os); quietClose(socket); quietClose(transportStream); callback.onClosed(); } } private void quietSleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { interrupt(); } } private void quietClose(Closeable c) { if (c != null) { try { c.close(); } catch (IOException e) { if (lastException == null) lastException = e; } } } private void quietClose(Socket s) { if (s != null) { try { s.close(); } catch (IOException e) { if (lastException == null) lastException = e; } } } private void quietClose(ServerSocket s) { if (s != null) { try { s.close(); } catch (IOException e) { if (lastException == null) lastException = e; } } } IOException signalAndWaitToDie() { if (isAlive()) { interrupt(); try { join(); } catch (InterruptedException e) { e.printStackTrace(); } } return lastException; } interface OnClosedCallback { void onClosed(); } }
4,362
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z
StackTraceSerializer.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/dvbservice/src/main/java/info/martinmarinov/dvbservice/tools/StackTraceSerializer.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.dvbservice.tools; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.io.UnsupportedEncodingException; public class StackTraceSerializer { public static String serialize(Throwable t) { ByteArrayOutputStream buff = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(buff); t.printStackTrace(ps); try { return buff.toString("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } }
1,419
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z
InetAddressTools.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/dvbservice/src/main/java/info/martinmarinov/dvbservice/tools/InetAddressTools.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.dvbservice.tools; import java.net.InetAddress; import java.net.UnknownHostException; public class InetAddressTools { private final static InetAddress LOCAL_LOOPBACK; static { try { LOCAL_LOOPBACK = InetAddress.getByName("127.0.0.1"); } catch (UnknownHostException e) { throw new RuntimeException(e); } } public static InetAddress getLocalLoopback() { return LOCAL_LOOPBACK; } }
1,345
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z
TsDumpFileUtils.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/dvbservice/src/main/java/info/martinmarinov/dvbservice/tools/TsDumpFileUtils.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.dvbservice.tools; import android.content.Context; import android.content.res.Resources; import androidx.annotation.VisibleForTesting; import android.util.Log; import java.io.File; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Locale; import info.martinmarinov.drivers.DvbDevice; import info.martinmarinov.drivers.file.DvbFileDevice; public class TsDumpFileUtils { private final static String TAG = TsDumpFileUtils.class.getSimpleName(); private final static Locale DEFAULT_LOCALE = Locale.US; private final static DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss", DEFAULT_LOCALE); private static File getRoot(Context ctx) { return ctx.getExternalFilesDir(null); } public static File getFor(Context ctx, long freq, long bandwidth, Date date) { File root = getRoot(ctx); String timestamp = DATE_FORMAT.format(date); String filename = String.format(DEFAULT_LOCALE, "mux_%d_%d_%s.ts", freq, bandwidth, timestamp); return new File(root, filename); } public static List<DvbDevice> getDevicesForAllRecordings(Context ctx) { LinkedList<DvbDevice> devices = new LinkedList<>(); Resources resources = ctx.getResources(); File root = getRoot(ctx); if (root == null) return devices; Log.d(TAG, "You can place ts files in "+root.getPath()); File[] files = root.listFiles(); for (File file : files) { FreqBandwidth freqAndBandwidth = getFreqAndBandwidth(file); if (freqAndBandwidth != null) { devices.add(new DvbFileDevice(resources, file, freqAndBandwidth.freq, freqAndBandwidth.bandwidth)); } } return devices; } @VisibleForTesting static FreqBandwidth getFreqAndBandwidth(File file) { if (!"ts".equals(getExtension(file))) return null; String[] parts = file.getName().toLowerCase().split("_"); if (parts.length != 4) return null; if (!"mux".equals(parts[0])) return null; try { long freq = Long.parseLong(parts[1]); long bandwidth = Long.parseLong(parts[2]); return new FreqBandwidth(freq, bandwidth); } catch (NumberFormatException ignored) { return null; } } private static String getExtension(File file) { String[] parts = file.getName().toLowerCase().split("\\."); if (parts.length == 0) return null; return parts[parts.length-1]; } @VisibleForTesting static class FreqBandwidth { @VisibleForTesting final long freq, bandwidth; private FreqBandwidth(long freq, long bandwidth) { this.freq = freq; this.bandwidth = bandwidth; } } }
3,765
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z
ShowOneInstanceFragmentDialog.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/dvbservice/src/main/java/info/martinmarinov/dvbservice/dialogs/ShowOneInstanceFragmentDialog.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.dvbservice.dialogs; import android.os.Bundle; import androidx.appcompat.app.AppCompatDialogFragment; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; public class ShowOneInstanceFragmentDialog extends AppCompatDialogFragment { public void showOneInstanceOnly(FragmentManager fragmentManager, String tag, Bundle args) { // ensure only one instance is present and close existing instances FragmentTransaction ft = fragmentManager.beginTransaction(); Fragment prev = fragmentManager.findFragmentByTag(tag); if (prev != null) ft.remove(prev); ft.addToBackStack(null); // set arguments and launch setArguments(args); try { show(ft, tag); } catch (IllegalStateException e) { // If we try to show an exception while driver is dying e.printStackTrace(); } } }
1,854
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z
ListPickerFragmentDialog.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/dvbservice/src/main/java/info/martinmarinov/dvbservice/dialogs/ListPickerFragmentDialog.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.dvbservice.dialogs; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.FragmentManager; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class ListPickerFragmentDialog<T extends Serializable> extends ShowOneInstanceFragmentDialog { private static final String DIALOG_TAG = ListPickerFragmentDialog.class.getSimpleName(); private static final String ARGS_SIZE = "argsSize"; private static final String ARG_ID = "arg"; private static String getArgKey(int id) { return ARG_ID + id; } public static <T extends Serializable> void showOneInstanceOnly(FragmentManager fragmentManager, List<T> options) { ListPickerFragmentDialog<T> dialog = new ListPickerFragmentDialog<>(); Bundle args = new Bundle(); args.putInt(ARGS_SIZE, options.size()); for (int i = 0; i < options.size(); i++) { args.putSerializable(getArgKey(i), options.get(i)); } dialog.showOneInstanceOnly(fragmentManager, DIALOG_TAG, args); } private OnSelected<T> callback; private List<T> options; @SuppressWarnings("unchecked") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); int size = args.getInt(ARGS_SIZE); options = new ArrayList<>(size); for (int i = 0; i < size; i++) { options.add((T) args.getSerializable(getArgKey(i))); } } @SuppressWarnings("unchecked") @Override public void onAttach(Context context) { super.onAttach(context); callback = (OnSelected<T>) getActivity(); } @Override public @NonNull Dialog onCreateDialog(Bundle savedInstanceState) { String[] strings = new String[options.size()]; for (int i = 0; i < strings.length; i++) strings[i] = options.get(i).toString(); return new AlertDialog.Builder(getActivity()) .setCancelable(true) .setItems(strings, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { callback.onListPickerDialogItemSelected(options.get(which)); } }) .create(); } @Override public void onCancel(DialogInterface dialog) { callback.onListPickerDialogCanceled(); } public interface OnSelected<T> { void onListPickerDialogItemSelected(T item); void onListPickerDialogCanceled(); } }
3,664
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z
DeviceFilterXmlEquivalenceTester.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/dvbservice/src/androidTest/java/info/martinmarinov/dvbservice/DeviceFilterXmlEquivalenceTester.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.dvbservice; import static androidx.test.core.app.ApplicationProvider.getApplicationContext; import android.content.res.Resources; import android.content.res.XmlResourceParser; import android.util.AttributeSet; import android.util.Xml; import org.junit.Test; import org.junit.runner.RunWith; import org.xmlpull.v1.XmlPullParser; import java.util.HashSet; import java.util.Set; import info.martinmarinov.drivers.DeviceFilter; import info.martinmarinov.drivers.usb.DvbUsbDevice; import info.martinmarinov.drivers.usb.DvbUsbDeviceRegistry; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.filters.MediumTest; @RunWith(AndroidJUnit4.class) @MediumTest public class DeviceFilterXmlEquivalenceTester { @Test public void allDevicesAreInXml() { Set<DeviceFilter> devicesInXml = getDeviceData(getApplicationContext().getResources(), R.xml.device_filter); Set<DeviceFilter> supportedDecvices = getDevicesInApp(); if (!supportedDecvices.equals(devicesInXml)) { System.out.println("Devices needed to be added to the xml"); for (DeviceFilter supportedDevice : supportedDecvices) { if (!devicesInXml.contains(supportedDevice)) { System.out.printf(" <usb-device vendor-id=\"0x%x\" product-id=\"0x%x\"/> <!-- %s -->\n", supportedDevice.getVendorId(), supportedDevice.getProductId(), supportedDevice.getName() ); } } System.out.println("Devices in xml but not supported"); for (DeviceFilter deviceInXml : devicesInXml) { if (!supportedDecvices.contains(deviceInXml)) { System.out.printf("vendor-id=0x%x, product-id=0x%x\n", deviceInXml.getVendorId(), deviceInXml.getProductId() ); } } } assertThat(supportedDecvices, equalTo(devicesInXml)); } private static HashSet<DeviceFilter> getDevicesInApp() { HashSet<DeviceFilter> supportedDevices = new HashSet<>(); for (DvbUsbDevice.Creator d : DvbUsbDeviceRegistry.AVAILABLE_DRIVERS) { supportedDevices.addAll(d.getSupportedDevices()); } return supportedDevices; } private static Set<DeviceFilter> getDeviceData(Resources resources, int xmlResourceId) { Set<DeviceFilter> ans = new HashSet<>(); try { XmlResourceParser xml = resources.getXml(xmlResourceId); xml.next(); int eventType; while ((eventType = xml.getEventType()) != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { if (xml.getName().equals("usb-device")) { AttributeSet as = Xml.asAttributeSet(xml); Integer vendorId = parseInt(as.getAttributeValue(null, "vendor-id")); Integer productId = parseInt(as.getAttributeValue(null, "product-id")); ans.add(new DeviceFilter(vendorId, productId, null)); } } xml.next(); } } catch (Exception e) { throw new RuntimeException(e); } return ans; } private static Integer parseInt(String number) { if (number.startsWith("0x")) { return Integer.valueOf( number.substring(2), 16); } else { return Integer.valueOf( number, 10); } } }
4,554
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z
WelcomeActivity.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/app/src/main/java/info/martinmarinov/dvbdriver/WelcomeActivity.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.dvbdriver; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.app.Activity; import android.view.View; public class WelcomeActivity extends Activity { private final static Uri SOURCE_URL = Uri.parse("https://github.com/signalwareltd/AndroidDvbDriver"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome); findViewById(R.id.btn_close).setOnClickListener(v -> finish()); findViewById(R.id.btn_advanced_mode).setOnClickListener(v -> startActivity(new Intent(WelcomeActivity.this, DvbFrontendActivity.class))); findViewById(R.id.btn_source_code).setOnClickListener(v -> startActivity(new Intent(Intent.ACTION_VIEW, SOURCE_URL))); findViewById(R.id.btn_license).setOnClickListener(v -> startActivity(new Intent(WelcomeActivity.this, GplLicenseActivity.class))); } }
1,855
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z
DeviceController.java
/FileExtraction/Java_unseen/signalwareltd_AndroidDvbDriver/app/src/main/java/info/martinmarinov/dvbdriver/DeviceController.java
/* * This is an Android user space port of DVB-T Linux kernel modules. * * Copyright (C) 2022 by Signalware Ltd <driver at aerialtv.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package info.martinmarinov.dvbdriver; import java.io.IOException; import java.util.List; import java.util.Set; import info.martinmarinov.drivers.DvbDevice; import info.martinmarinov.drivers.DvbException; import info.martinmarinov.drivers.DvbStatus; import info.martinmarinov.drivers.DeliverySystem; import info.martinmarinov.drivers.usb.DvbUsbDeviceRegistry; import static info.martinmarinov.drivers.DvbException.ErrorCode.NO_DVB_DEVICES_FOUND; class DeviceController extends Thread { private final DvbFrontendActivity dvbFrontendActivity; private volatile long desiredFreq, desiredBand; private volatile long currFreq, currBand; private volatile DeliverySystem currDelSystem, desiredDelSystem; private DataHandler dataHandler; DeviceController(DvbFrontendActivity dvbFrontendActivity, long desiredFreq, long desiredBand, DeliverySystem deliverySystem) { this.dvbFrontendActivity = dvbFrontendActivity; tuneTo(desiredFreq, desiredBand, deliverySystem); } void tuneTo(long desiredFreq, long desiredBand, DeliverySystem deliverySystem) { // Avoid accessing the DvbDevice from multiple threads this.desiredFreq = desiredFreq; this.desiredBand = desiredBand; this.desiredDelSystem = deliverySystem; } DataHandler getDataHandler() { return dataHandler; } @Override public void run() { try { List<DvbDevice> availableFrontends = DvbUsbDeviceRegistry.getUsbDvbDevices(dvbFrontendActivity.getApplicationContext()); if (availableFrontends.isEmpty()) throw new DvbException(NO_DVB_DEVICES_FOUND, dvbFrontendActivity.getString(R.string.no_devices_found)); DvbDevice dvbDevice = availableFrontends.get(0); dvbDevice.open(); dvbFrontendActivity.announceOpen(true, dvbDevice.getDebugString()); dataHandler = new DataHandler(dvbFrontendActivity, dvbDevice.getTransportStream(new DvbDevice.StreamCallback() { @Override public void onStreamException(IOException e) { dvbFrontendActivity.handleException(e); } @Override public void onStoppedStreaming() { interrupt(); } })); dataHandler.start(); try { while (!isInterrupted()) { if (desiredFreq != currFreq || desiredBand != currBand || desiredDelSystem != currDelSystem) { dvbDevice.tune(desiredFreq, desiredBand, desiredDelSystem); dvbDevice.disablePidFilter(); currFreq = desiredFreq; currBand = desiredBand; currDelSystem = desiredDelSystem; dataHandler.setFreqAndBandwidth(currFreq, currBand); dataHandler.reset(); } int snr = dvbDevice.readSnr(); int qualityPercentage = Math.round(100.0f * (0xFFFF - dvbDevice.readBitErrorRate()) / (float) 0xFFFF); int droppedUsbFps = dvbDevice.readDroppedUsbFps(); int rfStrength = dvbDevice.readRfStrengthPercentage(); Set<DvbStatus> status = dvbDevice.getStatus(); boolean hasSignal = status.contains(DvbStatus.FE_HAS_SIGNAL); boolean hasCarrier = status.contains(DvbStatus.FE_HAS_CARRIER); boolean hasSync = status.contains(DvbStatus.FE_HAS_SYNC); boolean hasLock = status.contains(DvbStatus.FE_HAS_LOCK); dvbFrontendActivity.announceMeasurements(snr, qualityPercentage, droppedUsbFps, rfStrength, hasSignal, hasCarrier, hasSync, hasLock); Thread.sleep(1_000); } } catch (InterruptedException ie) { // Interrupted exceptions are ok } finally { dataHandler.interrupt(); //noinspection ThrowFromFinallyBlock dataHandler.join(); try { dvbDevice.close(); } catch (IOException e) { dvbFrontendActivity.handleException(e); } } } catch (Exception e) { dvbFrontendActivity.handleException(e); } finally { dvbFrontendActivity.announceOpen(false, null); } } }
5,382
Java
.java
signalwareltd/AndroidDvbDriver
183
65
39
2017-02-22T15:41:19Z
2023-04-29T01:10:41Z