repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
realrolfje/anonimatron
src/main/java/com/rolfje/anonimatron/anonymizer/UUIDAnonymizer.java
// Path: src/main/java/com/rolfje/anonimatron/synonyms/StringSynonym.java // public class StringSynonym implements Synonym { // private String type; // private String from; // private String to; // private boolean shortlived = false; // // public StringSynonym() { // } // // public StringSynonym(String type, String from, String to, boolean shortlived) { // this.type = type; // this.from = from; // this.to = to; // this.shortlived = shortlived; // } // // @Override // public String getType() { // return type; // } // // @Override // public Object getFrom() { // return from; // } // // @Override // public Object getTo() { // return to; // } // // public void setType(String type) { // this.type = type; // } // // public void setFrom(String from) { // this.from = from; // } // // public void setTo(String to) { // this.to = to; // } // // public void setShortlived(boolean shortlived) { // this.shortlived = shortlived; // } // // @Override // public boolean isShortLived() { // return shortlived; // } // // @Override // public boolean equals(Object obj) { // return (obj != null) && (this.getClass() == obj.getClass()) && (this.hashCode() == obj.hashCode()); // } // // @Override // public int hashCode() { // return from.hashCode() + to.hashCode() + type.hashCode(); // } // } // // Path: src/main/java/com/rolfje/anonimatron/synonyms/Synonym.java // public interface Synonym { // // /** // * Indicates if this Synonym is short-lived or transient, meaning that // * it should not be stored in the synonyms file. Transient Synonyms // * are not stored, need to be calculated each run time. // * // * Transient synonyms are: // * // * <ol> // * <li>Not stored in memory.</li> // * <li>Not stored in the synonym file.</li> // * </ol> // * // * @return <code>true</code> if the synonym should be thrown away // * after use (not stored in the synonym file). // */ // boolean isShortLived(); // // /** // * @return The semantic data type of this Synonym, usually something // * descriptive as "NAME" or "STREET". // */ // String getType(); // // /** // * @return The data which was in the original database for this Synonym // */ // Object getFrom(); // // /** // * // * @return The data with which the original data in the database will be or // * is replaced when the Anonymizer runs. // */ // Object getTo(); // }
import com.rolfje.anonimatron.synonyms.StringSynonym; import com.rolfje.anonimatron.synonyms.Synonym; import java.util.UUID;
package com.rolfje.anonimatron.anonymizer; public class UUIDAnonymizer implements Anonymizer { private static final String TYPE = "UUID"; @Override public Synonym anonymize(Object from, int size, boolean shortlived) { String to = getString(from, size);
// Path: src/main/java/com/rolfje/anonimatron/synonyms/StringSynonym.java // public class StringSynonym implements Synonym { // private String type; // private String from; // private String to; // private boolean shortlived = false; // // public StringSynonym() { // } // // public StringSynonym(String type, String from, String to, boolean shortlived) { // this.type = type; // this.from = from; // this.to = to; // this.shortlived = shortlived; // } // // @Override // public String getType() { // return type; // } // // @Override // public Object getFrom() { // return from; // } // // @Override // public Object getTo() { // return to; // } // // public void setType(String type) { // this.type = type; // } // // public void setFrom(String from) { // this.from = from; // } // // public void setTo(String to) { // this.to = to; // } // // public void setShortlived(boolean shortlived) { // this.shortlived = shortlived; // } // // @Override // public boolean isShortLived() { // return shortlived; // } // // @Override // public boolean equals(Object obj) { // return (obj != null) && (this.getClass() == obj.getClass()) && (this.hashCode() == obj.hashCode()); // } // // @Override // public int hashCode() { // return from.hashCode() + to.hashCode() + type.hashCode(); // } // } // // Path: src/main/java/com/rolfje/anonimatron/synonyms/Synonym.java // public interface Synonym { // // /** // * Indicates if this Synonym is short-lived or transient, meaning that // * it should not be stored in the synonyms file. Transient Synonyms // * are not stored, need to be calculated each run time. // * // * Transient synonyms are: // * // * <ol> // * <li>Not stored in memory.</li> // * <li>Not stored in the synonym file.</li> // * </ol> // * // * @return <code>true</code> if the synonym should be thrown away // * after use (not stored in the synonym file). // */ // boolean isShortLived(); // // /** // * @return The semantic data type of this Synonym, usually something // * descriptive as "NAME" or "STREET". // */ // String getType(); // // /** // * @return The data which was in the original database for this Synonym // */ // Object getFrom(); // // /** // * // * @return The data with which the original data in the database will be or // * is replaced when the Anonymizer runs. // */ // Object getTo(); // } // Path: src/main/java/com/rolfje/anonimatron/anonymizer/UUIDAnonymizer.java import com.rolfje.anonimatron.synonyms.StringSynonym; import com.rolfje.anonimatron.synonyms.Synonym; import java.util.UUID; package com.rolfje.anonimatron.anonymizer; public class UUIDAnonymizer implements Anonymizer { private static final String TYPE = "UUID"; @Override public Synonym anonymize(Object from, int size, boolean shortlived) { String to = getString(from, size);
return new StringSynonym(
realrolfje/anonimatron
src/test/java/com/rolfje/anonimatron/anonymizer/CharacterStringPrefetchAnonymizerTest.java
// Path: src/main/java/com/rolfje/anonimatron/synonyms/Synonym.java // public interface Synonym { // // /** // * Indicates if this Synonym is short-lived or transient, meaning that // * it should not be stored in the synonyms file. Transient Synonyms // * are not stored, need to be calculated each run time. // * // * Transient synonyms are: // * // * <ol> // * <li>Not stored in memory.</li> // * <li>Not stored in the synonym file.</li> // * </ol> // * // * @return <code>true</code> if the synonym should be thrown away // * after use (not stored in the synonym file). // */ // boolean isShortLived(); // // /** // * @return The semantic data type of this Synonym, usually something // * descriptive as "NAME" or "STREET". // */ // String getType(); // // /** // * @return The data which was in the original database for this Synonym // */ // Object getFrom(); // // /** // * // * @return The data with which the original data in the database will be or // * is replaced when the Anonymizer runs. // */ // Object getTo(); // }
import com.rolfje.anonimatron.synonyms.Synonym; import junit.framework.TestCase; import java.util.HashMap; import java.util.Map;
package com.rolfje.anonimatron.anonymizer; public class CharacterStringPrefetchAnonymizerTest extends TestCase { CharacterStringPrefetchAnonymizer anonimyzer; @Override protected void setUp() throws Exception { super.setUp(); anonimyzer = new CharacterStringPrefetchAnonymizer(); } public void testPrefetch() { String sourceData = "ABC"; anonimyzer.prefetch(sourceData); String from = "TEST1";
// Path: src/main/java/com/rolfje/anonimatron/synonyms/Synonym.java // public interface Synonym { // // /** // * Indicates if this Synonym is short-lived or transient, meaning that // * it should not be stored in the synonyms file. Transient Synonyms // * are not stored, need to be calculated each run time. // * // * Transient synonyms are: // * // * <ol> // * <li>Not stored in memory.</li> // * <li>Not stored in the synonym file.</li> // * </ol> // * // * @return <code>true</code> if the synonym should be thrown away // * after use (not stored in the synonym file). // */ // boolean isShortLived(); // // /** // * @return The semantic data type of this Synonym, usually something // * descriptive as "NAME" or "STREET". // */ // String getType(); // // /** // * @return The data which was in the original database for this Synonym // */ // Object getFrom(); // // /** // * // * @return The data with which the original data in the database will be or // * is replaced when the Anonymizer runs. // */ // Object getTo(); // } // Path: src/test/java/com/rolfje/anonimatron/anonymizer/CharacterStringPrefetchAnonymizerTest.java import com.rolfje.anonimatron.synonyms.Synonym; import junit.framework.TestCase; import java.util.HashMap; import java.util.Map; package com.rolfje.anonimatron.anonymizer; public class CharacterStringPrefetchAnonymizerTest extends TestCase { CharacterStringPrefetchAnonymizer anonimyzer; @Override protected void setUp() throws Exception { super.setUp(); anonimyzer = new CharacterStringPrefetchAnonymizer(); } public void testPrefetch() { String sourceData = "ABC"; anonimyzer.prefetch(sourceData); String from = "TEST1";
Synonym synonym = anonimyzer.anonymize(from, 5, false);
realrolfje/anonimatron
src/test/java/com/rolfje/anonimatron/anonymizer/AbstractElevenProofAnonymizerTest.java
// Path: src/main/java/com/rolfje/anonimatron/synonyms/Synonym.java // public interface Synonym { // // /** // * Indicates if this Synonym is short-lived or transient, meaning that // * it should not be stored in the synonyms file. Transient Synonyms // * are not stored, need to be calculated each run time. // * // * Transient synonyms are: // * // * <ol> // * <li>Not stored in memory.</li> // * <li>Not stored in the synonym file.</li> // * </ol> // * // * @return <code>true</code> if the synonym should be thrown away // * after use (not stored in the synonym file). // */ // boolean isShortLived(); // // /** // * @return The semantic data type of this Synonym, usually something // * descriptive as "NAME" or "STREET". // */ // String getType(); // // /** // * @return The data which was in the original database for this Synonym // */ // Object getFrom(); // // /** // * // * @return The data with which the original data in the database will be or // * is replaced when the Anonymizer runs. // */ // Object getTo(); // }
import com.rolfje.anonimatron.synonyms.Synonym; import org.junit.Before; import org.junit.Test; import java.util.Map; import static org.junit.Assert.*;
package com.rolfje.anonimatron.anonymizer; public class AbstractElevenProofAnonymizerTest { AbstractElevenProofAnonymizer testdummy; @Before public void setUp() { testdummy = new AbstractElevenProofAnonymizer() { @Override public String getType() { return null; } @Override
// Path: src/main/java/com/rolfje/anonimatron/synonyms/Synonym.java // public interface Synonym { // // /** // * Indicates if this Synonym is short-lived or transient, meaning that // * it should not be stored in the synonyms file. Transient Synonyms // * are not stored, need to be calculated each run time. // * // * Transient synonyms are: // * // * <ol> // * <li>Not stored in memory.</li> // * <li>Not stored in the synonym file.</li> // * </ol> // * // * @return <code>true</code> if the synonym should be thrown away // * after use (not stored in the synonym file). // */ // boolean isShortLived(); // // /** // * @return The semantic data type of this Synonym, usually something // * descriptive as "NAME" or "STREET". // */ // String getType(); // // /** // * @return The data which was in the original database for this Synonym // */ // Object getFrom(); // // /** // * // * @return The data with which the original data in the database will be or // * is replaced when the Anonymizer runs. // */ // Object getTo(); // } // Path: src/test/java/com/rolfje/anonimatron/anonymizer/AbstractElevenProofAnonymizerTest.java import com.rolfje.anonimatron.synonyms.Synonym; import org.junit.Before; import org.junit.Test; import java.util.Map; import static org.junit.Assert.*; package com.rolfje.anonimatron.anonymizer; public class AbstractElevenProofAnonymizerTest { AbstractElevenProofAnonymizer testdummy; @Before public void setUp() { testdummy = new AbstractElevenProofAnonymizer() { @Override public String getType() { return null; } @Override
public Synonym anonymize(Object from, int size, boolean shortlived) {
realrolfje/anonimatron
src/test/java/com/rolfje/anonimatron/anonymizer/DutchZipCodeAnonymizerTest.java
// Path: src/main/java/com/rolfje/anonimatron/synonyms/Synonym.java // public interface Synonym { // // /** // * Indicates if this Synonym is short-lived or transient, meaning that // * it should not be stored in the synonyms file. Transient Synonyms // * are not stored, need to be calculated each run time. // * // * Transient synonyms are: // * // * <ol> // * <li>Not stored in memory.</li> // * <li>Not stored in the synonym file.</li> // * </ol> // * // * @return <code>true</code> if the synonym should be thrown away // * after use (not stored in the synonym file). // */ // boolean isShortLived(); // // /** // * @return The semantic data type of this Synonym, usually something // * descriptive as "NAME" or "STREET". // */ // String getType(); // // /** // * @return The data which was in the original database for this Synonym // */ // Object getFrom(); // // /** // * // * @return The data with which the original data in the database will be or // * is replaced when the Anonymizer runs. // */ // Object getTo(); // }
import com.rolfje.anonimatron.synonyms.Synonym; import org.junit.Test; import java.util.regex.Pattern; import static org.junit.Assert.*;
package com.rolfje.anonimatron.anonymizer; /** * Tests for {@link DutchZipCodeAnonymizer}. * * @author Erik-Berndt Scheper */ public class DutchZipCodeAnonymizerTest { private DutchZipCodeAnonymizer anonymizer = new DutchZipCodeAnonymizer(); private Pattern pattern = Pattern.compile("[1-9][0-9]{3} ?(?!SA|SD|SS)[A-Z]{2}$"); @Test public void anonymize() { for (int i = 0; i < 1000000; i++) { String from = anonymizer.buildZipCode(); assertTrue(isValidZipCode(from)); assertEquals(6, from.length()); internalAnonymize(6, from); } } private void internalAnonymize(int size, String from) {
// Path: src/main/java/com/rolfje/anonimatron/synonyms/Synonym.java // public interface Synonym { // // /** // * Indicates if this Synonym is short-lived or transient, meaning that // * it should not be stored in the synonyms file. Transient Synonyms // * are not stored, need to be calculated each run time. // * // * Transient synonyms are: // * // * <ol> // * <li>Not stored in memory.</li> // * <li>Not stored in the synonym file.</li> // * </ol> // * // * @return <code>true</code> if the synonym should be thrown away // * after use (not stored in the synonym file). // */ // boolean isShortLived(); // // /** // * @return The semantic data type of this Synonym, usually something // * descriptive as "NAME" or "STREET". // */ // String getType(); // // /** // * @return The data which was in the original database for this Synonym // */ // Object getFrom(); // // /** // * // * @return The data with which the original data in the database will be or // * is replaced when the Anonymizer runs. // */ // Object getTo(); // } // Path: src/test/java/com/rolfje/anonimatron/anonymizer/DutchZipCodeAnonymizerTest.java import com.rolfje.anonimatron.synonyms.Synonym; import org.junit.Test; import java.util.regex.Pattern; import static org.junit.Assert.*; package com.rolfje.anonimatron.anonymizer; /** * Tests for {@link DutchZipCodeAnonymizer}. * * @author Erik-Berndt Scheper */ public class DutchZipCodeAnonymizerTest { private DutchZipCodeAnonymizer anonymizer = new DutchZipCodeAnonymizer(); private Pattern pattern = Pattern.compile("[1-9][0-9]{3} ?(?!SA|SD|SS)[A-Z]{2}$"); @Test public void anonymize() { for (int i = 0; i < 1000000; i++) { String from = anonymizer.buildZipCode(); assertTrue(isValidZipCode(from)); assertEquals(6, from.length()); internalAnonymize(6, from); } } private void internalAnonymize(int size, String from) {
Synonym synonym = anonymizer.anonymize(from, size, false);
realrolfje/anonimatron
src/test/java/com/rolfje/anonimatron/anonymizer/CountryCodeAnonymizerTest.java
// Path: src/main/java/com/rolfje/anonimatron/synonyms/Synonym.java // public interface Synonym { // // /** // * Indicates if this Synonym is short-lived or transient, meaning that // * it should not be stored in the synonyms file. Transient Synonyms // * are not stored, need to be calculated each run time. // * // * Transient synonyms are: // * // * <ol> // * <li>Not stored in memory.</li> // * <li>Not stored in the synonym file.</li> // * </ol> // * // * @return <code>true</code> if the synonym should be thrown away // * after use (not stored in the synonym file). // */ // boolean isShortLived(); // // /** // * @return The semantic data type of this Synonym, usually something // * descriptive as "NAME" or "STREET". // */ // String getType(); // // /** // * @return The data which was in the original database for this Synonym // */ // Object getFrom(); // // /** // * // * @return The data with which the original data in the database will be or // * is replaced when the Anonymizer runs. // */ // Object getTo(); // }
import com.rolfje.anonimatron.synonyms.Synonym; import junit.framework.TestCase; import java.util.*; import static org.junit.Assert.assertNotEquals;
package com.rolfje.anonimatron.anonymizer; public class CountryCodeAnonymizerTest extends TestCase { private static final Set<String> ISO_3_COUNTRY_CODES = getISO3CountryCodes(); public void testAnonymize() { testInternal(2, "EN"); testInternal(3, "NLD"); testInternal(4, "BLR"); } private void testInternal(int size, String from) { CountryCodeAnonymizer countryCodeAnonymizer = new CountryCodeAnonymizer();
// Path: src/main/java/com/rolfje/anonimatron/synonyms/Synonym.java // public interface Synonym { // // /** // * Indicates if this Synonym is short-lived or transient, meaning that // * it should not be stored in the synonyms file. Transient Synonyms // * are not stored, need to be calculated each run time. // * // * Transient synonyms are: // * // * <ol> // * <li>Not stored in memory.</li> // * <li>Not stored in the synonym file.</li> // * </ol> // * // * @return <code>true</code> if the synonym should be thrown away // * after use (not stored in the synonym file). // */ // boolean isShortLived(); // // /** // * @return The semantic data type of this Synonym, usually something // * descriptive as "NAME" or "STREET". // */ // String getType(); // // /** // * @return The data which was in the original database for this Synonym // */ // Object getFrom(); // // /** // * // * @return The data with which the original data in the database will be or // * is replaced when the Anonymizer runs. // */ // Object getTo(); // } // Path: src/test/java/com/rolfje/anonimatron/anonymizer/CountryCodeAnonymizerTest.java import com.rolfje.anonimatron.synonyms.Synonym; import junit.framework.TestCase; import java.util.*; import static org.junit.Assert.assertNotEquals; package com.rolfje.anonimatron.anonymizer; public class CountryCodeAnonymizerTest extends TestCase { private static final Set<String> ISO_3_COUNTRY_CODES = getISO3CountryCodes(); public void testAnonymize() { testInternal(2, "EN"); testInternal(3, "NLD"); testInternal(4, "BLR"); } private void testInternal(int size, String from) { CountryCodeAnonymizer countryCodeAnonymizer = new CountryCodeAnonymizer();
Synonym nld = countryCodeAnonymizer.anonymize(from, size, false);
realrolfje/anonimatron
src/main/java/com/rolfje/anonimatron/anonymizer/SynonymCache.java
// Path: src/main/java/com/rolfje/anonimatron/synonyms/HashedFromSynonym.java // public class HashedFromSynonym implements Synonym { // // private String from; // private Object to; // private String type; // private boolean shortLived = false; // // public HashedFromSynonym() { // } // // public HashedFromSynonym(Hasher hasher, Synonym synonym) { // from = hasher.base64Hash(synonym.getFrom()); // to = synonym.getTo(); // type = synonym.getType(); // } // // @Override // public String getType() { // return type; // } // // @Override // public Object getFrom() { // return from; // } // // @Override // public Object getTo() { // return to; // } // // @Override // public boolean isShortLived() { // return shortLived; // } // // public void setFrom(String from) { // this.from = from; // } // // public void setTo(Object to) { // this.to = to; // } // // public void setType(String type) { // this.type = type; // } // } // // Path: src/main/java/com/rolfje/anonimatron/synonyms/Synonym.java // public interface Synonym { // // /** // * Indicates if this Synonym is short-lived or transient, meaning that // * it should not be stored in the synonyms file. Transient Synonyms // * are not stored, need to be calculated each run time. // * // * Transient synonyms are: // * // * <ol> // * <li>Not stored in memory.</li> // * <li>Not stored in the synonym file.</li> // * </ol> // * // * @return <code>true</code> if the synonym should be thrown away // * after use (not stored in the synonym file). // */ // boolean isShortLived(); // // /** // * @return The semantic data type of this Synonym, usually something // * descriptive as "NAME" or "STREET". // */ // String getType(); // // /** // * @return The data which was in the original database for this Synonym // */ // Object getFrom(); // // /** // * // * @return The data with which the original data in the database will be or // * is replaced when the Anonymizer runs. // */ // Object getTo(); // } // // Path: src/main/java/com/rolfje/anonimatron/synonyms/SynonymMapper.java // public class SynonymMapper { // // @SuppressWarnings("unchecked") // public static List<Synonym> readFromFile(String filename) throws IOException, XMLException, MappingException { // Mapping mapping = getMapping(); // Unmarshaller unmarshaller = new Unmarshaller(ArrayList.class); // unmarshaller.setMapping(mapping); // // File file = new File(filename); // // if (file.exists() && !file.isFile()) { // throw new IOException("File " + file.getAbsolutePath() + " exists but is not a file."); // } // // if (!file.exists() || file.length() == 0) { // return Collections.emptyList(); // } // // Reader reader = new FileReader(file); // return (List<Synonym>) unmarshaller.unmarshal(reader); // } // // public static void writeToFile(List<Synonym> synonyms, String filename) throws IOException, MappingException, XMLException { // Mapping mapping = getMapping(); // // Writer writer = new FileWriter(new File(filename)); // Marshaller marshaller = new Marshaller(writer); // // // I have no idea why this does not work, so I added a castor.propeties // // file in the root as workaround. // // marshaller.setProperty("org.exolab.castor.indent", "true"); // // marshaller.setRootElement("synonyms"); // marshaller.setMapping(mapping); // marshaller.setSuppressXSIType(true); // marshaller.marshal(synonyms); // writer.close(); // } // // private static Mapping getMapping() throws IOException, MappingException { // URL url = SynonymMapper.class.getResource("castor-synonym-mapping.xml"); // Mapping mapping = new Mapping(); // mapping.loadMapping(url); // return mapping; // } // }
import com.rolfje.anonimatron.synonyms.HashedFromSynonym; import com.rolfje.anonimatron.synonyms.Synonym; import com.rolfje.anonimatron.synonyms.SynonymMapper; import org.exolab.castor.mapping.MappingException; import org.exolab.castor.xml.XMLException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map;
package com.rolfje.anonimatron.anonymizer; public class SynonymCache { private Map<String, Map<Object, Synonym>> synonymCache = new HashMap<>(); private Hasher hasher; private long size = 0; public SynonymCache() { } /** * Reads the synonyms from the specified file and (re-)initializes the * {@link #synonymCache} with it. * * @param synonymXMLfile the xml file containing the synonyms, as written by * {@link #toFile(File)} * @return Synonyms as the were stored on last run. * @throws MappingException When synonyms can not be read from file. * @throws IOException When synonyms can not be read from file. * @throws XMLException When synonyms can not be read from file. */ public static SynonymCache fromFile(File synonymXMLfile) throws MappingException, IOException, XMLException { SynonymCache synonymCache = new SynonymCache();
// Path: src/main/java/com/rolfje/anonimatron/synonyms/HashedFromSynonym.java // public class HashedFromSynonym implements Synonym { // // private String from; // private Object to; // private String type; // private boolean shortLived = false; // // public HashedFromSynonym() { // } // // public HashedFromSynonym(Hasher hasher, Synonym synonym) { // from = hasher.base64Hash(synonym.getFrom()); // to = synonym.getTo(); // type = synonym.getType(); // } // // @Override // public String getType() { // return type; // } // // @Override // public Object getFrom() { // return from; // } // // @Override // public Object getTo() { // return to; // } // // @Override // public boolean isShortLived() { // return shortLived; // } // // public void setFrom(String from) { // this.from = from; // } // // public void setTo(Object to) { // this.to = to; // } // // public void setType(String type) { // this.type = type; // } // } // // Path: src/main/java/com/rolfje/anonimatron/synonyms/Synonym.java // public interface Synonym { // // /** // * Indicates if this Synonym is short-lived or transient, meaning that // * it should not be stored in the synonyms file. Transient Synonyms // * are not stored, need to be calculated each run time. // * // * Transient synonyms are: // * // * <ol> // * <li>Not stored in memory.</li> // * <li>Not stored in the synonym file.</li> // * </ol> // * // * @return <code>true</code> if the synonym should be thrown away // * after use (not stored in the synonym file). // */ // boolean isShortLived(); // // /** // * @return The semantic data type of this Synonym, usually something // * descriptive as "NAME" or "STREET". // */ // String getType(); // // /** // * @return The data which was in the original database for this Synonym // */ // Object getFrom(); // // /** // * // * @return The data with which the original data in the database will be or // * is replaced when the Anonymizer runs. // */ // Object getTo(); // } // // Path: src/main/java/com/rolfje/anonimatron/synonyms/SynonymMapper.java // public class SynonymMapper { // // @SuppressWarnings("unchecked") // public static List<Synonym> readFromFile(String filename) throws IOException, XMLException, MappingException { // Mapping mapping = getMapping(); // Unmarshaller unmarshaller = new Unmarshaller(ArrayList.class); // unmarshaller.setMapping(mapping); // // File file = new File(filename); // // if (file.exists() && !file.isFile()) { // throw new IOException("File " + file.getAbsolutePath() + " exists but is not a file."); // } // // if (!file.exists() || file.length() == 0) { // return Collections.emptyList(); // } // // Reader reader = new FileReader(file); // return (List<Synonym>) unmarshaller.unmarshal(reader); // } // // public static void writeToFile(List<Synonym> synonyms, String filename) throws IOException, MappingException, XMLException { // Mapping mapping = getMapping(); // // Writer writer = new FileWriter(new File(filename)); // Marshaller marshaller = new Marshaller(writer); // // // I have no idea why this does not work, so I added a castor.propeties // // file in the root as workaround. // // marshaller.setProperty("org.exolab.castor.indent", "true"); // // marshaller.setRootElement("synonyms"); // marshaller.setMapping(mapping); // marshaller.setSuppressXSIType(true); // marshaller.marshal(synonyms); // writer.close(); // } // // private static Mapping getMapping() throws IOException, MappingException { // URL url = SynonymMapper.class.getResource("castor-synonym-mapping.xml"); // Mapping mapping = new Mapping(); // mapping.loadMapping(url); // return mapping; // } // } // Path: src/main/java/com/rolfje/anonimatron/anonymizer/SynonymCache.java import com.rolfje.anonimatron.synonyms.HashedFromSynonym; import com.rolfje.anonimatron.synonyms.Synonym; import com.rolfje.anonimatron.synonyms.SynonymMapper; import org.exolab.castor.mapping.MappingException; import org.exolab.castor.xml.XMLException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; package com.rolfje.anonimatron.anonymizer; public class SynonymCache { private Map<String, Map<Object, Synonym>> synonymCache = new HashMap<>(); private Hasher hasher; private long size = 0; public SynonymCache() { } /** * Reads the synonyms from the specified file and (re-)initializes the * {@link #synonymCache} with it. * * @param synonymXMLfile the xml file containing the synonyms, as written by * {@link #toFile(File)} * @return Synonyms as the were stored on last run. * @throws MappingException When synonyms can not be read from file. * @throws IOException When synonyms can not be read from file. * @throws XMLException When synonyms can not be read from file. */ public static SynonymCache fromFile(File synonymXMLfile) throws MappingException, IOException, XMLException { SynonymCache synonymCache = new SynonymCache();
List<Synonym> synonymsFromFile = SynonymMapper
realrolfje/anonimatron
src/main/java/com/rolfje/anonimatron/anonymizer/SynonymCache.java
// Path: src/main/java/com/rolfje/anonimatron/synonyms/HashedFromSynonym.java // public class HashedFromSynonym implements Synonym { // // private String from; // private Object to; // private String type; // private boolean shortLived = false; // // public HashedFromSynonym() { // } // // public HashedFromSynonym(Hasher hasher, Synonym synonym) { // from = hasher.base64Hash(synonym.getFrom()); // to = synonym.getTo(); // type = synonym.getType(); // } // // @Override // public String getType() { // return type; // } // // @Override // public Object getFrom() { // return from; // } // // @Override // public Object getTo() { // return to; // } // // @Override // public boolean isShortLived() { // return shortLived; // } // // public void setFrom(String from) { // this.from = from; // } // // public void setTo(Object to) { // this.to = to; // } // // public void setType(String type) { // this.type = type; // } // } // // Path: src/main/java/com/rolfje/anonimatron/synonyms/Synonym.java // public interface Synonym { // // /** // * Indicates if this Synonym is short-lived or transient, meaning that // * it should not be stored in the synonyms file. Transient Synonyms // * are not stored, need to be calculated each run time. // * // * Transient synonyms are: // * // * <ol> // * <li>Not stored in memory.</li> // * <li>Not stored in the synonym file.</li> // * </ol> // * // * @return <code>true</code> if the synonym should be thrown away // * after use (not stored in the synonym file). // */ // boolean isShortLived(); // // /** // * @return The semantic data type of this Synonym, usually something // * descriptive as "NAME" or "STREET". // */ // String getType(); // // /** // * @return The data which was in the original database for this Synonym // */ // Object getFrom(); // // /** // * // * @return The data with which the original data in the database will be or // * is replaced when the Anonymizer runs. // */ // Object getTo(); // } // // Path: src/main/java/com/rolfje/anonimatron/synonyms/SynonymMapper.java // public class SynonymMapper { // // @SuppressWarnings("unchecked") // public static List<Synonym> readFromFile(String filename) throws IOException, XMLException, MappingException { // Mapping mapping = getMapping(); // Unmarshaller unmarshaller = new Unmarshaller(ArrayList.class); // unmarshaller.setMapping(mapping); // // File file = new File(filename); // // if (file.exists() && !file.isFile()) { // throw new IOException("File " + file.getAbsolutePath() + " exists but is not a file."); // } // // if (!file.exists() || file.length() == 0) { // return Collections.emptyList(); // } // // Reader reader = new FileReader(file); // return (List<Synonym>) unmarshaller.unmarshal(reader); // } // // public static void writeToFile(List<Synonym> synonyms, String filename) throws IOException, MappingException, XMLException { // Mapping mapping = getMapping(); // // Writer writer = new FileWriter(new File(filename)); // Marshaller marshaller = new Marshaller(writer); // // // I have no idea why this does not work, so I added a castor.propeties // // file in the root as workaround. // // marshaller.setProperty("org.exolab.castor.indent", "true"); // // marshaller.setRootElement("synonyms"); // marshaller.setMapping(mapping); // marshaller.setSuppressXSIType(true); // marshaller.marshal(synonyms); // writer.close(); // } // // private static Mapping getMapping() throws IOException, MappingException { // URL url = SynonymMapper.class.getResource("castor-synonym-mapping.xml"); // Mapping mapping = new Mapping(); // mapping.loadMapping(url); // return mapping; // } // }
import com.rolfje.anonimatron.synonyms.HashedFromSynonym; import com.rolfje.anonimatron.synonyms.Synonym; import com.rolfje.anonimatron.synonyms.SynonymMapper; import org.exolab.castor.mapping.MappingException; import org.exolab.castor.xml.XMLException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map;
*/ public void toFile(File synonymXMLfile) throws XMLException, IOException, MappingException { List<Synonym> allSynonyms = new ArrayList<>(); // Flatten the type -> From -> Synonym map. Collection<Map<Object, Synonym>> allObjectMaps = synonymCache.values(); for (Map<Object, Synonym> typeMap : allObjectMaps) { allSynonyms.addAll(typeMap.values()); } SynonymMapper .writeToFile(allSynonyms, synonymXMLfile.getAbsolutePath()); } /** * Stores the given {@link Synonym} in the synonym cache, except when the * given synonym is short-lived. Short-lived synonyms are not stored or * re-used. * * @param synonym to store */ public void put(Synonym synonym) { if (synonym.isShortLived()) { return; } Map<Object, Synonym> map = synonymCache.computeIfAbsent(synonym.getType(), k -> new HashMap<>()); if (hasher != null) { // Hash sensitive data before storing
// Path: src/main/java/com/rolfje/anonimatron/synonyms/HashedFromSynonym.java // public class HashedFromSynonym implements Synonym { // // private String from; // private Object to; // private String type; // private boolean shortLived = false; // // public HashedFromSynonym() { // } // // public HashedFromSynonym(Hasher hasher, Synonym synonym) { // from = hasher.base64Hash(synonym.getFrom()); // to = synonym.getTo(); // type = synonym.getType(); // } // // @Override // public String getType() { // return type; // } // // @Override // public Object getFrom() { // return from; // } // // @Override // public Object getTo() { // return to; // } // // @Override // public boolean isShortLived() { // return shortLived; // } // // public void setFrom(String from) { // this.from = from; // } // // public void setTo(Object to) { // this.to = to; // } // // public void setType(String type) { // this.type = type; // } // } // // Path: src/main/java/com/rolfje/anonimatron/synonyms/Synonym.java // public interface Synonym { // // /** // * Indicates if this Synonym is short-lived or transient, meaning that // * it should not be stored in the synonyms file. Transient Synonyms // * are not stored, need to be calculated each run time. // * // * Transient synonyms are: // * // * <ol> // * <li>Not stored in memory.</li> // * <li>Not stored in the synonym file.</li> // * </ol> // * // * @return <code>true</code> if the synonym should be thrown away // * after use (not stored in the synonym file). // */ // boolean isShortLived(); // // /** // * @return The semantic data type of this Synonym, usually something // * descriptive as "NAME" or "STREET". // */ // String getType(); // // /** // * @return The data which was in the original database for this Synonym // */ // Object getFrom(); // // /** // * // * @return The data with which the original data in the database will be or // * is replaced when the Anonymizer runs. // */ // Object getTo(); // } // // Path: src/main/java/com/rolfje/anonimatron/synonyms/SynonymMapper.java // public class SynonymMapper { // // @SuppressWarnings("unchecked") // public static List<Synonym> readFromFile(String filename) throws IOException, XMLException, MappingException { // Mapping mapping = getMapping(); // Unmarshaller unmarshaller = new Unmarshaller(ArrayList.class); // unmarshaller.setMapping(mapping); // // File file = new File(filename); // // if (file.exists() && !file.isFile()) { // throw new IOException("File " + file.getAbsolutePath() + " exists but is not a file."); // } // // if (!file.exists() || file.length() == 0) { // return Collections.emptyList(); // } // // Reader reader = new FileReader(file); // return (List<Synonym>) unmarshaller.unmarshal(reader); // } // // public static void writeToFile(List<Synonym> synonyms, String filename) throws IOException, MappingException, XMLException { // Mapping mapping = getMapping(); // // Writer writer = new FileWriter(new File(filename)); // Marshaller marshaller = new Marshaller(writer); // // // I have no idea why this does not work, so I added a castor.propeties // // file in the root as workaround. // // marshaller.setProperty("org.exolab.castor.indent", "true"); // // marshaller.setRootElement("synonyms"); // marshaller.setMapping(mapping); // marshaller.setSuppressXSIType(true); // marshaller.marshal(synonyms); // writer.close(); // } // // private static Mapping getMapping() throws IOException, MappingException { // URL url = SynonymMapper.class.getResource("castor-synonym-mapping.xml"); // Mapping mapping = new Mapping(); // mapping.loadMapping(url); // return mapping; // } // } // Path: src/main/java/com/rolfje/anonimatron/anonymizer/SynonymCache.java import com.rolfje.anonimatron.synonyms.HashedFromSynonym; import com.rolfje.anonimatron.synonyms.Synonym; import com.rolfje.anonimatron.synonyms.SynonymMapper; import org.exolab.castor.mapping.MappingException; import org.exolab.castor.xml.XMLException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; */ public void toFile(File synonymXMLfile) throws XMLException, IOException, MappingException { List<Synonym> allSynonyms = new ArrayList<>(); // Flatten the type -> From -> Synonym map. Collection<Map<Object, Synonym>> allObjectMaps = synonymCache.values(); for (Map<Object, Synonym> typeMap : allObjectMaps) { allSynonyms.addAll(typeMap.values()); } SynonymMapper .writeToFile(allSynonyms, synonymXMLfile.getAbsolutePath()); } /** * Stores the given {@link Synonym} in the synonym cache, except when the * given synonym is short-lived. Short-lived synonyms are not stored or * re-used. * * @param synonym to store */ public void put(Synonym synonym) { if (synonym.isShortLived()) { return; } Map<Object, Synonym> map = synonymCache.computeIfAbsent(synonym.getType(), k -> new HashMap<>()); if (hasher != null) { // Hash sensitive data before storing
Synonym hashed = new HashedFromSynonym(hasher, synonym);
realrolfje/anonimatron
src/main/java/com/rolfje/anonimatron/anonymizer/DutchBankAccountAnononymizer.java
// Path: src/main/java/com/rolfje/anonimatron/synonyms/StringSynonym.java // public class StringSynonym implements Synonym { // private String type; // private String from; // private String to; // private boolean shortlived = false; // // public StringSynonym() { // } // // public StringSynonym(String type, String from, String to, boolean shortlived) { // this.type = type; // this.from = from; // this.to = to; // this.shortlived = shortlived; // } // // @Override // public String getType() { // return type; // } // // @Override // public Object getFrom() { // return from; // } // // @Override // public Object getTo() { // return to; // } // // public void setType(String type) { // this.type = type; // } // // public void setFrom(String from) { // this.from = from; // } // // public void setTo(String to) { // this.to = to; // } // // public void setShortlived(boolean shortlived) { // this.shortlived = shortlived; // } // // @Override // public boolean isShortLived() { // return shortlived; // } // // @Override // public boolean equals(Object obj) { // return (obj != null) && (this.getClass() == obj.getClass()) && (this.hashCode() == obj.hashCode()); // } // // @Override // public int hashCode() { // return from.hashCode() + to.hashCode() + type.hashCode(); // } // } // // Path: src/main/java/com/rolfje/anonimatron/synonyms/Synonym.java // public interface Synonym { // // /** // * Indicates if this Synonym is short-lived or transient, meaning that // * it should not be stored in the synonyms file. Transient Synonyms // * are not stored, need to be calculated each run time. // * // * Transient synonyms are: // * // * <ol> // * <li>Not stored in memory.</li> // * <li>Not stored in the synonym file.</li> // * </ol> // * // * @return <code>true</code> if the synonym should be thrown away // * after use (not stored in the synonym file). // */ // boolean isShortLived(); // // /** // * @return The semantic data type of this Synonym, usually something // * descriptive as "NAME" or "STREET". // */ // String getType(); // // /** // * @return The data which was in the original database for this Synonym // */ // Object getFrom(); // // /** // * // * @return The data with which the original data in the database will be or // * is replaced when the Anonymizer runs. // */ // Object getTo(); // }
import com.rolfje.anonimatron.synonyms.StringSynonym; import com.rolfje.anonimatron.synonyms.Synonym; import org.apache.log4j.Logger; import java.security.SecureRandom;
package com.rolfje.anonimatron.anonymizer; /** * Generates valid Dutch Bank Account number with the same length as the given * number. * <p> * A Dutch Bank Account Number is passes the "11 proof" if it is 9 digits long. * If it is less than 9 digits, there is no way to check the validity of the * number. * <p> * See http://nl.wikipedia.org/wiki/Elfproef */ public class DutchBankAccountAnononymizer extends AbstractElevenProofAnonymizer implements BankAccountAnonymizer { private static final Logger LOG = Logger.getLogger(DutchBankAccountAnononymizer.class); private static final int LENGTH = 9; private final SecureRandom random = new SecureRandom(); @Override public String getType() { return "DUTCHBANKACCOUNT"; } @Override
// Path: src/main/java/com/rolfje/anonimatron/synonyms/StringSynonym.java // public class StringSynonym implements Synonym { // private String type; // private String from; // private String to; // private boolean shortlived = false; // // public StringSynonym() { // } // // public StringSynonym(String type, String from, String to, boolean shortlived) { // this.type = type; // this.from = from; // this.to = to; // this.shortlived = shortlived; // } // // @Override // public String getType() { // return type; // } // // @Override // public Object getFrom() { // return from; // } // // @Override // public Object getTo() { // return to; // } // // public void setType(String type) { // this.type = type; // } // // public void setFrom(String from) { // this.from = from; // } // // public void setTo(String to) { // this.to = to; // } // // public void setShortlived(boolean shortlived) { // this.shortlived = shortlived; // } // // @Override // public boolean isShortLived() { // return shortlived; // } // // @Override // public boolean equals(Object obj) { // return (obj != null) && (this.getClass() == obj.getClass()) && (this.hashCode() == obj.hashCode()); // } // // @Override // public int hashCode() { // return from.hashCode() + to.hashCode() + type.hashCode(); // } // } // // Path: src/main/java/com/rolfje/anonimatron/synonyms/Synonym.java // public interface Synonym { // // /** // * Indicates if this Synonym is short-lived or transient, meaning that // * it should not be stored in the synonyms file. Transient Synonyms // * are not stored, need to be calculated each run time. // * // * Transient synonyms are: // * // * <ol> // * <li>Not stored in memory.</li> // * <li>Not stored in the synonym file.</li> // * </ol> // * // * @return <code>true</code> if the synonym should be thrown away // * after use (not stored in the synonym file). // */ // boolean isShortLived(); // // /** // * @return The semantic data type of this Synonym, usually something // * descriptive as "NAME" or "STREET". // */ // String getType(); // // /** // * @return The data which was in the original database for this Synonym // */ // Object getFrom(); // // /** // * // * @return The data with which the original data in the database will be or // * is replaced when the Anonymizer runs. // */ // Object getTo(); // } // Path: src/main/java/com/rolfje/anonimatron/anonymizer/DutchBankAccountAnononymizer.java import com.rolfje.anonimatron.synonyms.StringSynonym; import com.rolfje.anonimatron.synonyms.Synonym; import org.apache.log4j.Logger; import java.security.SecureRandom; package com.rolfje.anonimatron.anonymizer; /** * Generates valid Dutch Bank Account number with the same length as the given * number. * <p> * A Dutch Bank Account Number is passes the "11 proof" if it is 9 digits long. * If it is less than 9 digits, there is no way to check the validity of the * number. * <p> * See http://nl.wikipedia.org/wiki/Elfproef */ public class DutchBankAccountAnononymizer extends AbstractElevenProofAnonymizer implements BankAccountAnonymizer { private static final Logger LOG = Logger.getLogger(DutchBankAccountAnononymizer.class); private static final int LENGTH = 9; private final SecureRandom random = new SecureRandom(); @Override public String getType() { return "DUTCHBANKACCOUNT"; } @Override
public Synonym anonymize(Object from, int size, boolean shortlived) {
realrolfje/anonimatron
src/main/java/com/rolfje/anonimatron/anonymizer/DutchBankAccountAnononymizer.java
// Path: src/main/java/com/rolfje/anonimatron/synonyms/StringSynonym.java // public class StringSynonym implements Synonym { // private String type; // private String from; // private String to; // private boolean shortlived = false; // // public StringSynonym() { // } // // public StringSynonym(String type, String from, String to, boolean shortlived) { // this.type = type; // this.from = from; // this.to = to; // this.shortlived = shortlived; // } // // @Override // public String getType() { // return type; // } // // @Override // public Object getFrom() { // return from; // } // // @Override // public Object getTo() { // return to; // } // // public void setType(String type) { // this.type = type; // } // // public void setFrom(String from) { // this.from = from; // } // // public void setTo(String to) { // this.to = to; // } // // public void setShortlived(boolean shortlived) { // this.shortlived = shortlived; // } // // @Override // public boolean isShortLived() { // return shortlived; // } // // @Override // public boolean equals(Object obj) { // return (obj != null) && (this.getClass() == obj.getClass()) && (this.hashCode() == obj.hashCode()); // } // // @Override // public int hashCode() { // return from.hashCode() + to.hashCode() + type.hashCode(); // } // } // // Path: src/main/java/com/rolfje/anonimatron/synonyms/Synonym.java // public interface Synonym { // // /** // * Indicates if this Synonym is short-lived or transient, meaning that // * it should not be stored in the synonyms file. Transient Synonyms // * are not stored, need to be calculated each run time. // * // * Transient synonyms are: // * // * <ol> // * <li>Not stored in memory.</li> // * <li>Not stored in the synonym file.</li> // * </ol> // * // * @return <code>true</code> if the synonym should be thrown away // * after use (not stored in the synonym file). // */ // boolean isShortLived(); // // /** // * @return The semantic data type of this Synonym, usually something // * descriptive as "NAME" or "STREET". // */ // String getType(); // // /** // * @return The data which was in the original database for this Synonym // */ // Object getFrom(); // // /** // * // * @return The data with which the original data in the database will be or // * is replaced when the Anonymizer runs. // */ // Object getTo(); // }
import com.rolfje.anonimatron.synonyms.StringSynonym; import com.rolfje.anonimatron.synonyms.Synonym; import org.apache.log4j.Logger; import java.security.SecureRandom;
package com.rolfje.anonimatron.anonymizer; /** * Generates valid Dutch Bank Account number with the same length as the given * number. * <p> * A Dutch Bank Account Number is passes the "11 proof" if it is 9 digits long. * If it is less than 9 digits, there is no way to check the validity of the * number. * <p> * See http://nl.wikipedia.org/wiki/Elfproef */ public class DutchBankAccountAnononymizer extends AbstractElevenProofAnonymizer implements BankAccountAnonymizer { private static final Logger LOG = Logger.getLogger(DutchBankAccountAnononymizer.class); private static final int LENGTH = 9; private final SecureRandom random = new SecureRandom(); @Override public String getType() { return "DUTCHBANKACCOUNT"; } @Override public Synonym anonymize(Object from, int size, boolean shortlived) { if (size < LENGTH) { throw new UnsupportedOperationException( "Can not generate a Dutch Bank Account number that fits in a " + size + " character string. Must be " + LENGTH + " characters or more."); } String fromString = (String) from; int originalLength = (fromString).length(); if (originalLength > LENGTH) { LOG.warn("Original bank account number had more than " + LENGTH + " digits. The resulting anonymous bank account number with the same length will not be a valid account number."); } String toString = fromString; do { toString = generateBankAccount(originalLength); } while (fromString.equals(toString));
// Path: src/main/java/com/rolfje/anonimatron/synonyms/StringSynonym.java // public class StringSynonym implements Synonym { // private String type; // private String from; // private String to; // private boolean shortlived = false; // // public StringSynonym() { // } // // public StringSynonym(String type, String from, String to, boolean shortlived) { // this.type = type; // this.from = from; // this.to = to; // this.shortlived = shortlived; // } // // @Override // public String getType() { // return type; // } // // @Override // public Object getFrom() { // return from; // } // // @Override // public Object getTo() { // return to; // } // // public void setType(String type) { // this.type = type; // } // // public void setFrom(String from) { // this.from = from; // } // // public void setTo(String to) { // this.to = to; // } // // public void setShortlived(boolean shortlived) { // this.shortlived = shortlived; // } // // @Override // public boolean isShortLived() { // return shortlived; // } // // @Override // public boolean equals(Object obj) { // return (obj != null) && (this.getClass() == obj.getClass()) && (this.hashCode() == obj.hashCode()); // } // // @Override // public int hashCode() { // return from.hashCode() + to.hashCode() + type.hashCode(); // } // } // // Path: src/main/java/com/rolfje/anonimatron/synonyms/Synonym.java // public interface Synonym { // // /** // * Indicates if this Synonym is short-lived or transient, meaning that // * it should not be stored in the synonyms file. Transient Synonyms // * are not stored, need to be calculated each run time. // * // * Transient synonyms are: // * // * <ol> // * <li>Not stored in memory.</li> // * <li>Not stored in the synonym file.</li> // * </ol> // * // * @return <code>true</code> if the synonym should be thrown away // * after use (not stored in the synonym file). // */ // boolean isShortLived(); // // /** // * @return The semantic data type of this Synonym, usually something // * descriptive as "NAME" or "STREET". // */ // String getType(); // // /** // * @return The data which was in the original database for this Synonym // */ // Object getFrom(); // // /** // * // * @return The data with which the original data in the database will be or // * is replaced when the Anonymizer runs. // */ // Object getTo(); // } // Path: src/main/java/com/rolfje/anonimatron/anonymizer/DutchBankAccountAnononymizer.java import com.rolfje.anonimatron.synonyms.StringSynonym; import com.rolfje.anonimatron.synonyms.Synonym; import org.apache.log4j.Logger; import java.security.SecureRandom; package com.rolfje.anonimatron.anonymizer; /** * Generates valid Dutch Bank Account number with the same length as the given * number. * <p> * A Dutch Bank Account Number is passes the "11 proof" if it is 9 digits long. * If it is less than 9 digits, there is no way to check the validity of the * number. * <p> * See http://nl.wikipedia.org/wiki/Elfproef */ public class DutchBankAccountAnononymizer extends AbstractElevenProofAnonymizer implements BankAccountAnonymizer { private static final Logger LOG = Logger.getLogger(DutchBankAccountAnononymizer.class); private static final int LENGTH = 9; private final SecureRandom random = new SecureRandom(); @Override public String getType() { return "DUTCHBANKACCOUNT"; } @Override public Synonym anonymize(Object from, int size, boolean shortlived) { if (size < LENGTH) { throw new UnsupportedOperationException( "Can not generate a Dutch Bank Account number that fits in a " + size + " character string. Must be " + LENGTH + " characters or more."); } String fromString = (String) from; int originalLength = (fromString).length(); if (originalLength > LENGTH) { LOG.warn("Original bank account number had more than " + LENGTH + " digits. The resulting anonymous bank account number with the same length will not be a valid account number."); } String toString = fromString; do { toString = generateBankAccount(originalLength); } while (fromString.equals(toString));
return new StringSynonym(
UKPLab/emnlp2017-claim-identification
src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/io/ParagraphTest.java
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/utils/ArgUtils.java // public class ArgUtils { // // // public static String getID(String s) { // String[] tmp = s.split("/"); // return tmp[tmp.length-1].replace(".xmi","").replace(".bin", ""); // } // // // public static String getID(File f) { // return getID(f.getName()); // } // // // public static boolean isClaim(Sentence s, JCas cas) { // return selectOverlapping(Claim.class, s, cas).size()>0 || selectOverlapping(MajorClaim.class, s, cas).size()>0; // } // // // public static boolean isPremise(Sentence s, JCas cas) { // return selectOverlapping(Premise.class, s, cas).size()>0; // } // // // public static <T extends TOP> List<T> selectOverlapping(Class<T> type,Annotation annotation, JCas jCas) { // Collection<T> allAnnotations = JCasUtil.select(jCas, type); // // List<T> result = new ArrayList<T>(); // // for (T a : allAnnotations) { // if ((a instanceof Annotation) && (doOverlap(annotation, (Annotation) a))) { // result.add(a); // } // } // // return result; // } // // // public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { // return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); // } // // // public static JCas readCas(File f) throws ResourceInitializationException, SAXException, IOException, CASException { // CAS loadedCas = CasCreationUtils.createCas(TypeSystemDescriptionFactory.createTypeSystemDescription(), null, null); // FileInputStream in = new FileInputStream(f); // XmiCasDeserializer.deserialize(in, loadedCas); // IOUtils.closeQuietly(in); // return loadedCas.getJCas(); // } // // public static void writeFile(String fileName, String content) throws Exception { // BufferedWriter br = new BufferedWriter(new FileWriter(new File(fileName))); // br.write(content); // br.close(); // } // // // }
import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.utils.ArgUtils; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Collection;
/* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.dkpro.argumentation.io; public class ParagraphTest { private static final String path = "/Users/zemes/Desktop/NLP/Papers/TACL2016/data/prep4/WTP"; public static void main(String[] args) throws Exception { File dir = new File(path); boolean containsParagraph = false; for (File f : dir.listFiles()) { if (!f.getName().endsWith(".xmi")) continue;
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/utils/ArgUtils.java // public class ArgUtils { // // // public static String getID(String s) { // String[] tmp = s.split("/"); // return tmp[tmp.length-1].replace(".xmi","").replace(".bin", ""); // } // // // public static String getID(File f) { // return getID(f.getName()); // } // // // public static boolean isClaim(Sentence s, JCas cas) { // return selectOverlapping(Claim.class, s, cas).size()>0 || selectOverlapping(MajorClaim.class, s, cas).size()>0; // } // // // public static boolean isPremise(Sentence s, JCas cas) { // return selectOverlapping(Premise.class, s, cas).size()>0; // } // // // public static <T extends TOP> List<T> selectOverlapping(Class<T> type,Annotation annotation, JCas jCas) { // Collection<T> allAnnotations = JCasUtil.select(jCas, type); // // List<T> result = new ArrayList<T>(); // // for (T a : allAnnotations) { // if ((a instanceof Annotation) && (doOverlap(annotation, (Annotation) a))) { // result.add(a); // } // } // // return result; // } // // // public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { // return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); // } // // // public static JCas readCas(File f) throws ResourceInitializationException, SAXException, IOException, CASException { // CAS loadedCas = CasCreationUtils.createCas(TypeSystemDescriptionFactory.createTypeSystemDescription(), null, null); // FileInputStream in = new FileInputStream(f); // XmiCasDeserializer.deserialize(in, loadedCas); // IOUtils.closeQuietly(in); // return loadedCas.getJCas(); // } // // public static void writeFile(String fileName, String content) throws Exception { // BufferedWriter br = new BufferedWriter(new FileWriter(new File(fileName))); // br.write(content); // br.close(); // } // // // } // Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/io/ParagraphTest.java import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.utils.ArgUtils; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Collection; /* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.dkpro.argumentation.io; public class ParagraphTest { private static final String path = "/Users/zemes/Desktop/NLP/Papers/TACL2016/data/prep4/WTP"; public static void main(String[] args) throws Exception { File dir = new File(path); boolean containsParagraph = false; for (File f : dir.listFiles()) { if (!f.getName().endsWith(".xmi")) continue;
JCas cas = ArgUtils.readCas(f);
UKPLab/emnlp2017-claim-identification
src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/reader/XmiToTextReader.java
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/utils/ArgUtils.java // public class ArgUtils { // // // public static String getID(String s) { // String[] tmp = s.split("/"); // return tmp[tmp.length-1].replace(".xmi","").replace(".bin", ""); // } // // // public static String getID(File f) { // return getID(f.getName()); // } // // // public static boolean isClaim(Sentence s, JCas cas) { // return selectOverlapping(Claim.class, s, cas).size()>0 || selectOverlapping(MajorClaim.class, s, cas).size()>0; // } // // // public static boolean isPremise(Sentence s, JCas cas) { // return selectOverlapping(Premise.class, s, cas).size()>0; // } // // // public static <T extends TOP> List<T> selectOverlapping(Class<T> type,Annotation annotation, JCas jCas) { // Collection<T> allAnnotations = JCasUtil.select(jCas, type); // // List<T> result = new ArrayList<T>(); // // for (T a : allAnnotations) { // if ((a instanceof Annotation) && (doOverlap(annotation, (Annotation) a))) { // result.add(a); // } // } // // return result; // } // // // public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { // return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); // } // // // public static JCas readCas(File f) throws ResourceInitializationException, SAXException, IOException, CASException { // CAS loadedCas = CasCreationUtils.createCas(TypeSystemDescriptionFactory.createTypeSystemDescription(), null, null); // FileInputStream in = new FileInputStream(f); // XmiCasDeserializer.deserialize(in, loadedCas); // IOUtils.closeQuietly(in); // return loadedCas.getJCas(); // } // // public static void writeFile(String fileName, String content) throws Exception { // BufferedWriter br = new BufferedWriter(new FileWriter(new File(fileName))); // br.write(content); // br.close(); // } // // // }
import org.apache.uima.util.CasCreationUtils; import org.xml.sax.SAXException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Collection; import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.utils.ArgUtils; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token; import org.apache.commons.io.IOUtils; import org.apache.uima.cas.CAS; import org.apache.uima.cas.CASException; import org.apache.uima.cas.impl.XmiCasDeserializer; import org.apache.uima.fit.factory.TypeSystemDescriptionFactory; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException;
/* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.reader; public class XmiToTextReader { public static String path = "/Users/zemes/Desktop/NLP/Papers/TACL2016/data/prep3/Stab201X"; public static void main(String[] args) throws Exception { File dir = new File(path); for (File f : dir.listFiles()) { if (f.getName().endsWith(".xmi")) { JCas cas = readCas(f);
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/utils/ArgUtils.java // public class ArgUtils { // // // public static String getID(String s) { // String[] tmp = s.split("/"); // return tmp[tmp.length-1].replace(".xmi","").replace(".bin", ""); // } // // // public static String getID(File f) { // return getID(f.getName()); // } // // // public static boolean isClaim(Sentence s, JCas cas) { // return selectOverlapping(Claim.class, s, cas).size()>0 || selectOverlapping(MajorClaim.class, s, cas).size()>0; // } // // // public static boolean isPremise(Sentence s, JCas cas) { // return selectOverlapping(Premise.class, s, cas).size()>0; // } // // // public static <T extends TOP> List<T> selectOverlapping(Class<T> type,Annotation annotation, JCas jCas) { // Collection<T> allAnnotations = JCasUtil.select(jCas, type); // // List<T> result = new ArrayList<T>(); // // for (T a : allAnnotations) { // if ((a instanceof Annotation) && (doOverlap(annotation, (Annotation) a))) { // result.add(a); // } // } // // return result; // } // // // public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { // return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); // } // // // public static JCas readCas(File f) throws ResourceInitializationException, SAXException, IOException, CASException { // CAS loadedCas = CasCreationUtils.createCas(TypeSystemDescriptionFactory.createTypeSystemDescription(), null, null); // FileInputStream in = new FileInputStream(f); // XmiCasDeserializer.deserialize(in, loadedCas); // IOUtils.closeQuietly(in); // return loadedCas.getJCas(); // } // // public static void writeFile(String fileName, String content) throws Exception { // BufferedWriter br = new BufferedWriter(new FileWriter(new File(fileName))); // br.write(content); // br.close(); // } // // // } // Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/reader/XmiToTextReader.java import org.apache.uima.util.CasCreationUtils; import org.xml.sax.SAXException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Collection; import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.utils.ArgUtils; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token; import org.apache.commons.io.IOUtils; import org.apache.uima.cas.CAS; import org.apache.uima.cas.CASException; import org.apache.uima.cas.impl.XmiCasDeserializer; import org.apache.uima.fit.factory.TypeSystemDescriptionFactory; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; /* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.reader; public class XmiToTextReader { public static String path = "/Users/zemes/Desktop/NLP/Papers/TACL2016/data/prep3/Stab201X"; public static void main(String[] args) throws Exception { File dir = new File(path); for (File f : dir.listFiles()) { if (f.getName().endsWith(".xmi")) { JCas cas = readCas(f);
String id = ArgUtils.getID(f);
UKPLab/emnlp2017-claim-identification
src/main/java/de/tudarmstadt/ukp/dkpro/discourse/pdtbparser/PDTBDiscourseAnnotator.java
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/core/api/discourse/DiscourseDumpWriter.java // public class DiscourseDumpWriter // extends JCasAnnotator_ImplBase // { // /** // * Output file. If multiple CASes as processed, their contents are concatenated into this file. // * When this file is set to "-", the dump does to{@link System#out} (default). // */ // public static final String PARAM_OUTPUT_FILE = "outputFile"; // // @ConfigurationParameter(name = PARAM_OUTPUT_FILE, mandatory = true, defaultValue = "-") // private File outputFile; // // private PrintWriter out; // // @Override // public void initialize(UimaContext context) // throws ResourceInitializationException // { // super.initialize(context); // // try { // if (out == null) { // if ("-".equals(outputFile.getName())) { // out = new PrintWriter(new CloseShieldOutputStream(System.out)); // } // else { // if (outputFile.getParentFile() != null) { // outputFile.getParentFile().mkdirs(); // } // out = new PrintWriter( // new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); // } // } // } // catch (IOException e) { // throw new ResourceInitializationException(e); // } // // } // // @Override // public void process(JCas jCas) // throws AnalysisEngineProcessException // { // out.println("++ Document: " + DocumentMetaData.get(jCas).getDocumentId()); // // for (DiscourseRelation relation : JCasUtil.select(jCas, DiscourseRelation.class)) { // out.println(debugRelation(relation)); // } // // out.flush(); // } // // /** // * Debugs discourse relation to String // * // * @param relation relation // */ // public static String debugRelation(DiscourseRelation relation) // { // // // StringWriter out = new StringWriter(); // StringWriter stringWriter = new StringWriter(); // PrintWriter out = new PrintWriter(stringWriter); // // out.println("---- discourse relation " + relation.getRelationId()); // out.println(" relation class: " + relation.getClass().getSimpleName()); // out.println(" coveredText: " + relation.getCoveredText()); // for (DiscourseArgument argument : Arrays // .asList(relation.getArg1(), relation.getArg2())) { // out.println(" -- arg" + argument.getArgumentNumber() + ": "); // out.println(" argumentType: " + (argument.getArgumentType() != null ? // argument.getArgumentType() : "-")); // out.println(" coveredText: " + argument.getCoveredText()); // // } // // if (relation instanceof ExplicitDiscourseRelation) { // ExplicitDiscourseRelation explicitRelation = (ExplicitDiscourseRelation) relation; // // for (DiscourseConnective connective : Arrays // .asList(explicitRelation.getDiscourseConnective1(), // explicitRelation.getDiscourseConnective2())) { // if (connective != null) { // out.println(" -- connectiveType: " + connective.getConnectiveType()); // out.println(" coveredText: " + connective.getCoveredText()); // } // } // } // // for (DiscourseAttribution attribution : JCasUtil // .selectCovered(DiscourseAttribution.class, relation)) { // out.println(" -- attribution " + attribution.getAttributeId()); // out.println(" coveredText: " + attribution.getCoveredText()); // } // // out.println("---- end of relation " + relation.getRelationId()); // out.flush(); // // return stringWriter.toString(); // } // }
import de.tudarmstadt.ukp.dkpro.core.api.discourse.DiscourseDumpWriter; import de.tudarmstadt.ukp.dkpro.core.api.metadata.type.DocumentMetaData; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token; import de.tudarmstadt.ukp.dkpro.core.discourse.pdtb.*; import de.tudarmstadt.ukp.dkpro.core.io.xmi.XmiReader; import de.tudarmstadt.ukp.dkpro.core.io.xmi.XmiWriter; import nu.xom.*; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.apache.uima.UimaContext; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.fit.component.JCasAnnotator_ImplBase; import org.apache.uima.fit.descriptor.ConfigurationParameter; import org.apache.uima.fit.factory.AnalysisEngineFactory; import org.apache.uima.fit.factory.CollectionReaderFactory; import org.apache.uima.fit.pipeline.SimplePipeline; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; import java.io.File; import java.io.IOException; import java.util.*;
int begin = arg1.getBegin() < arg2.getBegin() ? arg1.getBegin() : arg2.getBegin(); int end = arg1.getEnd() > arg2.getEnd() ? arg1.getEnd() : arg2.getEnd(); discourseRelation.setBegin(begin); discourseRelation.setEnd(end); arg1.addToIndexes(); arg2.addToIndexes(); discourseRelation.addToIndexes(); } else { System.err.println("Both arguments must be properly closed"); } } else { System.err.println("Cannot find both arguments to relation " + relationId); } } // annotate all non-null Attributions for (DiscourseAttribution attribution : discourseAttributions) { if (attribution.getEnd() > 0) { attribution.addToIndexes(); } } if (verbose) { for (DiscourseRelation discourseRelation : JCasUtil .select(jCas, DiscourseRelation.class)) {
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/core/api/discourse/DiscourseDumpWriter.java // public class DiscourseDumpWriter // extends JCasAnnotator_ImplBase // { // /** // * Output file. If multiple CASes as processed, their contents are concatenated into this file. // * When this file is set to "-", the dump does to{@link System#out} (default). // */ // public static final String PARAM_OUTPUT_FILE = "outputFile"; // // @ConfigurationParameter(name = PARAM_OUTPUT_FILE, mandatory = true, defaultValue = "-") // private File outputFile; // // private PrintWriter out; // // @Override // public void initialize(UimaContext context) // throws ResourceInitializationException // { // super.initialize(context); // // try { // if (out == null) { // if ("-".equals(outputFile.getName())) { // out = new PrintWriter(new CloseShieldOutputStream(System.out)); // } // else { // if (outputFile.getParentFile() != null) { // outputFile.getParentFile().mkdirs(); // } // out = new PrintWriter( // new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); // } // } // } // catch (IOException e) { // throw new ResourceInitializationException(e); // } // // } // // @Override // public void process(JCas jCas) // throws AnalysisEngineProcessException // { // out.println("++ Document: " + DocumentMetaData.get(jCas).getDocumentId()); // // for (DiscourseRelation relation : JCasUtil.select(jCas, DiscourseRelation.class)) { // out.println(debugRelation(relation)); // } // // out.flush(); // } // // /** // * Debugs discourse relation to String // * // * @param relation relation // */ // public static String debugRelation(DiscourseRelation relation) // { // // // StringWriter out = new StringWriter(); // StringWriter stringWriter = new StringWriter(); // PrintWriter out = new PrintWriter(stringWriter); // // out.println("---- discourse relation " + relation.getRelationId()); // out.println(" relation class: " + relation.getClass().getSimpleName()); // out.println(" coveredText: " + relation.getCoveredText()); // for (DiscourseArgument argument : Arrays // .asList(relation.getArg1(), relation.getArg2())) { // out.println(" -- arg" + argument.getArgumentNumber() + ": "); // out.println(" argumentType: " + (argument.getArgumentType() != null ? // argument.getArgumentType() : "-")); // out.println(" coveredText: " + argument.getCoveredText()); // // } // // if (relation instanceof ExplicitDiscourseRelation) { // ExplicitDiscourseRelation explicitRelation = (ExplicitDiscourseRelation) relation; // // for (DiscourseConnective connective : Arrays // .asList(explicitRelation.getDiscourseConnective1(), // explicitRelation.getDiscourseConnective2())) { // if (connective != null) { // out.println(" -- connectiveType: " + connective.getConnectiveType()); // out.println(" coveredText: " + connective.getCoveredText()); // } // } // } // // for (DiscourseAttribution attribution : JCasUtil // .selectCovered(DiscourseAttribution.class, relation)) { // out.println(" -- attribution " + attribution.getAttributeId()); // out.println(" coveredText: " + attribution.getCoveredText()); // } // // out.println("---- end of relation " + relation.getRelationId()); // out.flush(); // // return stringWriter.toString(); // } // } // Path: src/main/java/de/tudarmstadt/ukp/dkpro/discourse/pdtbparser/PDTBDiscourseAnnotator.java import de.tudarmstadt.ukp.dkpro.core.api.discourse.DiscourseDumpWriter; import de.tudarmstadt.ukp.dkpro.core.api.metadata.type.DocumentMetaData; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token; import de.tudarmstadt.ukp.dkpro.core.discourse.pdtb.*; import de.tudarmstadt.ukp.dkpro.core.io.xmi.XmiReader; import de.tudarmstadt.ukp.dkpro.core.io.xmi.XmiWriter; import nu.xom.*; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.apache.uima.UimaContext; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.fit.component.JCasAnnotator_ImplBase; import org.apache.uima.fit.descriptor.ConfigurationParameter; import org.apache.uima.fit.factory.AnalysisEngineFactory; import org.apache.uima.fit.factory.CollectionReaderFactory; import org.apache.uima.fit.pipeline.SimplePipeline; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; import java.io.File; import java.io.IOException; import java.util.*; int begin = arg1.getBegin() < arg2.getBegin() ? arg1.getBegin() : arg2.getBegin(); int end = arg1.getEnd() > arg2.getEnd() ? arg1.getEnd() : arg2.getEnd(); discourseRelation.setBegin(begin); discourseRelation.setEnd(end); arg1.addToIndexes(); arg2.addToIndexes(); discourseRelation.addToIndexes(); } else { System.err.println("Both arguments must be properly closed"); } } else { System.err.println("Cannot find both arguments to relation " + relationId); } } // annotate all non-null Attributions for (DiscourseAttribution attribution : discourseAttributions) { if (attribution.getEnd() > 0) { attribution.addToIndexes(); } } if (verbose) { for (DiscourseRelation discourseRelation : JCasUtil .select(jCas, DiscourseRelation.class)) {
DiscourseDumpWriter.debugRelation(discourseRelation);
UKPLab/emnlp2017-claim-identification
src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/reader/ClaimSentenceReader.java
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/utils/ArgUtils.java // public class ArgUtils { // // // public static String getID(String s) { // String[] tmp = s.split("/"); // return tmp[tmp.length-1].replace(".xmi","").replace(".bin", ""); // } // // // public static String getID(File f) { // return getID(f.getName()); // } // // // public static boolean isClaim(Sentence s, JCas cas) { // return selectOverlapping(Claim.class, s, cas).size()>0 || selectOverlapping(MajorClaim.class, s, cas).size()>0; // } // // // public static boolean isPremise(Sentence s, JCas cas) { // return selectOverlapping(Premise.class, s, cas).size()>0; // } // // // public static <T extends TOP> List<T> selectOverlapping(Class<T> type,Annotation annotation, JCas jCas) { // Collection<T> allAnnotations = JCasUtil.select(jCas, type); // // List<T> result = new ArrayList<T>(); // // for (T a : allAnnotations) { // if ((a instanceof Annotation) && (doOverlap(annotation, (Annotation) a))) { // result.add(a); // } // } // // return result; // } // // // public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { // return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); // } // // // public static JCas readCas(File f) throws ResourceInitializationException, SAXException, IOException, CASException { // CAS loadedCas = CasCreationUtils.createCas(TypeSystemDescriptionFactory.createTypeSystemDescription(), null, null); // FileInputStream in = new FileInputStream(f); // XmiCasDeserializer.deserialize(in, loadedCas); // IOUtils.closeQuietly(in); // return loadedCas.getJCas(); // } // // public static void writeFile(String fileName, String content) throws Exception { // BufferedWriter br = new BufferedWriter(new FileWriter(new File(fileName))); // br.write(content); // br.close(); // } // // // }
import org.apache.uima.resource.ResourceInitializationException; import java.io.IOException; import java.util.Collection; import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.utils.ArgUtils; import de.tudarmstadt.ukp.dkpro.core.api.metadata.type.DocumentMetaData; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import de.tudarmstadt.ukp.dkpro.core.io.xmi.XmiReader; import de.tudarmstadt.ukp.dkpro.tc.api.type.TextClassificationOutcome; import de.tudarmstadt.ukp.dkpro.tc.api.type.TextClassificationUnit; import org.apache.uima.UimaContext; import org.apache.uima.cas.CAS; import org.apache.uima.cas.CASException; import org.apache.uima.collection.CollectionException; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas;
/* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.reader; /** * * @author Christian Stab */ public class ClaimSentenceReader extends XmiReader { @Override public void initialize(UimaContext context) throws ResourceInitializationException { super.initialize(context); } @Override public void getNext(CAS aCAS) throws IOException, CollectionException { super.getNext(aCAS); JCas jcas; try { jcas = aCAS.getJCas(); } catch (CASException e) { throw new CollectionException(); } DocumentMetaData.get(jcas).setDocumentTitle(DocumentMetaData.get(jcas).getDocumentId()); Collection<Sentence> sentences = JCasUtil.select(jcas, Sentence.class); for (Sentence s : sentences) { new TextClassificationUnit(jcas, s.getBegin(), s.getEnd()).addToIndexes(); TextClassificationOutcome outcome = new TextClassificationOutcome(jcas, s.getBegin(), s.getEnd());
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/utils/ArgUtils.java // public class ArgUtils { // // // public static String getID(String s) { // String[] tmp = s.split("/"); // return tmp[tmp.length-1].replace(".xmi","").replace(".bin", ""); // } // // // public static String getID(File f) { // return getID(f.getName()); // } // // // public static boolean isClaim(Sentence s, JCas cas) { // return selectOverlapping(Claim.class, s, cas).size()>0 || selectOverlapping(MajorClaim.class, s, cas).size()>0; // } // // // public static boolean isPremise(Sentence s, JCas cas) { // return selectOverlapping(Premise.class, s, cas).size()>0; // } // // // public static <T extends TOP> List<T> selectOverlapping(Class<T> type,Annotation annotation, JCas jCas) { // Collection<T> allAnnotations = JCasUtil.select(jCas, type); // // List<T> result = new ArrayList<T>(); // // for (T a : allAnnotations) { // if ((a instanceof Annotation) && (doOverlap(annotation, (Annotation) a))) { // result.add(a); // } // } // // return result; // } // // // public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { // return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); // } // // // public static JCas readCas(File f) throws ResourceInitializationException, SAXException, IOException, CASException { // CAS loadedCas = CasCreationUtils.createCas(TypeSystemDescriptionFactory.createTypeSystemDescription(), null, null); // FileInputStream in = new FileInputStream(f); // XmiCasDeserializer.deserialize(in, loadedCas); // IOUtils.closeQuietly(in); // return loadedCas.getJCas(); // } // // public static void writeFile(String fileName, String content) throws Exception { // BufferedWriter br = new BufferedWriter(new FileWriter(new File(fileName))); // br.write(content); // br.close(); // } // // // } // Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/reader/ClaimSentenceReader.java import org.apache.uima.resource.ResourceInitializationException; import java.io.IOException; import java.util.Collection; import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.utils.ArgUtils; import de.tudarmstadt.ukp.dkpro.core.api.metadata.type.DocumentMetaData; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import de.tudarmstadt.ukp.dkpro.core.io.xmi.XmiReader; import de.tudarmstadt.ukp.dkpro.tc.api.type.TextClassificationOutcome; import de.tudarmstadt.ukp.dkpro.tc.api.type.TextClassificationUnit; import org.apache.uima.UimaContext; import org.apache.uima.cas.CAS; import org.apache.uima.cas.CASException; import org.apache.uima.collection.CollectionException; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; /* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.reader; /** * * @author Christian Stab */ public class ClaimSentenceReader extends XmiReader { @Override public void initialize(UimaContext context) throws ResourceInitializationException { super.initialize(context); } @Override public void getNext(CAS aCAS) throws IOException, CollectionException { super.getNext(aCAS); JCas jcas; try { jcas = aCAS.getJCas(); } catch (CASException e) { throw new CollectionException(); } DocumentMetaData.get(jcas).setDocumentTitle(DocumentMetaData.get(jcas).getDocumentId()); Collection<Sentence> sentences = JCasUtil.select(jcas, Sentence.class); for (Sentence s : sentences) { new TextClassificationUnit(jcas, s.getBegin(), s.getEnd()).addToIndexes(); TextClassificationOutcome outcome = new TextClassificationOutcome(jcas, s.getBegin(), s.getEnd());
if (ArgUtils.isClaim(s, jcas)) {
UKPLab/emnlp2017-claim-identification
src/main/java/de/tudarmstadt/ukp/dkpro/tc/core/io/CustomFoldDimensionBundle2.java
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/utils/ArgUtils.java // public class ArgUtils { // // // public static String getID(String s) { // String[] tmp = s.split("/"); // return tmp[tmp.length-1].replace(".xmi","").replace(".bin", ""); // } // // // public static String getID(File f) { // return getID(f.getName()); // } // // // public static boolean isClaim(Sentence s, JCas cas) { // return selectOverlapping(Claim.class, s, cas).size()>0 || selectOverlapping(MajorClaim.class, s, cas).size()>0; // } // // // public static boolean isPremise(Sentence s, JCas cas) { // return selectOverlapping(Premise.class, s, cas).size()>0; // } // // // public static <T extends TOP> List<T> selectOverlapping(Class<T> type,Annotation annotation, JCas jCas) { // Collection<T> allAnnotations = JCasUtil.select(jCas, type); // // List<T> result = new ArrayList<T>(); // // for (T a : allAnnotations) { // if ((a instanceof Annotation) && (doOverlap(annotation, (Annotation) a))) { // result.add(a); // } // } // // return result; // } // // // public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { // return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); // } // // // public static JCas readCas(File f) throws ResourceInitializationException, SAXException, IOException, CASException { // CAS loadedCas = CasCreationUtils.createCas(TypeSystemDescriptionFactory.createTypeSystemDescription(), null, null); // FileInputStream in = new FileInputStream(f); // XmiCasDeserializer.deserialize(in, loadedCas); // IOUtils.closeQuietly(in); // return loadedCas.getJCas(); // } // // public static void writeFile(String fileName, String content) throws Exception { // BufferedWriter br = new BufferedWriter(new FileWriter(new File(fileName))); // br.write(content); // br.close(); // } // // // }
import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.utils.ArgUtils; import de.tudarmstadt.ukp.dkpro.lab.task.Dimension; import de.tudarmstadt.ukp.dkpro.lab.task.impl.DynamicDimension; import de.tudarmstadt.ukp.dkpro.lab.task.impl.FoldDimensionBundle; import java.io.BufferedReader; import java.io.FileReader; import java.util.*;
/* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.dkpro.tc.core.io; public class CustomFoldDimensionBundle2<T> extends FoldDimensionBundle<T> { private Dimension<T> foldedDimension; private List<T>[] test; private List<T>[] train; private int validationBucket = -1; private int foldID = -1; private String foldFile; private boolean useDevSet = false; public CustomFoldDimensionBundle2(String aName, Dimension<T> aFoldedDimension, String aFoldFile, boolean useDevSet, int foldID) { super(aName, aFoldedDimension, 5); foldedDimension = aFoldedDimension; foldFile = aFoldFile; this.foldID = foldID; this.useDevSet = useDevSet; } @SuppressWarnings("unchecked") private void init() { // get mapping from file names to ids HashMap<String, T> idToPath = new HashMap<String, T>(); while (foldedDimension.hasNext()) { T path = foldedDimension.next(); //String currentID = getEssayIDFromPath((String)path).replace("_0","");
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/utils/ArgUtils.java // public class ArgUtils { // // // public static String getID(String s) { // String[] tmp = s.split("/"); // return tmp[tmp.length-1].replace(".xmi","").replace(".bin", ""); // } // // // public static String getID(File f) { // return getID(f.getName()); // } // // // public static boolean isClaim(Sentence s, JCas cas) { // return selectOverlapping(Claim.class, s, cas).size()>0 || selectOverlapping(MajorClaim.class, s, cas).size()>0; // } // // // public static boolean isPremise(Sentence s, JCas cas) { // return selectOverlapping(Premise.class, s, cas).size()>0; // } // // // public static <T extends TOP> List<T> selectOverlapping(Class<T> type,Annotation annotation, JCas jCas) { // Collection<T> allAnnotations = JCasUtil.select(jCas, type); // // List<T> result = new ArrayList<T>(); // // for (T a : allAnnotations) { // if ((a instanceof Annotation) && (doOverlap(annotation, (Annotation) a))) { // result.add(a); // } // } // // return result; // } // // // public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { // return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); // } // // // public static JCas readCas(File f) throws ResourceInitializationException, SAXException, IOException, CASException { // CAS loadedCas = CasCreationUtils.createCas(TypeSystemDescriptionFactory.createTypeSystemDescription(), null, null); // FileInputStream in = new FileInputStream(f); // XmiCasDeserializer.deserialize(in, loadedCas); // IOUtils.closeQuietly(in); // return loadedCas.getJCas(); // } // // public static void writeFile(String fileName, String content) throws Exception { // BufferedWriter br = new BufferedWriter(new FileWriter(new File(fileName))); // br.write(content); // br.close(); // } // // // } // Path: src/main/java/de/tudarmstadt/ukp/dkpro/tc/core/io/CustomFoldDimensionBundle2.java import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.utils.ArgUtils; import de.tudarmstadt.ukp.dkpro.lab.task.Dimension; import de.tudarmstadt.ukp.dkpro.lab.task.impl.DynamicDimension; import de.tudarmstadt.ukp.dkpro.lab.task.impl.FoldDimensionBundle; import java.io.BufferedReader; import java.io.FileReader; import java.util.*; /* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.dkpro.tc.core.io; public class CustomFoldDimensionBundle2<T> extends FoldDimensionBundle<T> { private Dimension<T> foldedDimension; private List<T>[] test; private List<T>[] train; private int validationBucket = -1; private int foldID = -1; private String foldFile; private boolean useDevSet = false; public CustomFoldDimensionBundle2(String aName, Dimension<T> aFoldedDimension, String aFoldFile, boolean useDevSet, int foldID) { super(aName, aFoldedDimension, 5); foldedDimension = aFoldedDimension; foldFile = aFoldFile; this.foldID = foldID; this.useDevSet = useDevSet; } @SuppressWarnings("unchecked") private void init() { // get mapping from file names to ids HashMap<String, T> idToPath = new HashMap<String, T>(); while (foldedDimension.hasNext()) { T path = foldedDimension.next(); //String currentID = getEssayIDFromPath((String)path).replace("_0","");
String currentID = ArgUtils.getID((String)path);
UKPLab/emnlp2017-claim-identification
src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/experiments/utils/ExperimentUtils.java
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/utils/ArgUtils.java // public class ArgUtils { // // // public static String getID(String s) { // String[] tmp = s.split("/"); // return tmp[tmp.length-1].replace(".xmi","").replace(".bin", ""); // } // // // public static String getID(File f) { // return getID(f.getName()); // } // // // public static boolean isClaim(Sentence s, JCas cas) { // return selectOverlapping(Claim.class, s, cas).size()>0 || selectOverlapping(MajorClaim.class, s, cas).size()>0; // } // // // public static boolean isPremise(Sentence s, JCas cas) { // return selectOverlapping(Premise.class, s, cas).size()>0; // } // // // public static <T extends TOP> List<T> selectOverlapping(Class<T> type,Annotation annotation, JCas jCas) { // Collection<T> allAnnotations = JCasUtil.select(jCas, type); // // List<T> result = new ArrayList<T>(); // // for (T a : allAnnotations) { // if ((a instanceof Annotation) && (doOverlap(annotation, (Annotation) a))) { // result.add(a); // } // } // // return result; // } // // // public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { // return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); // } // // // public static JCas readCas(File f) throws ResourceInitializationException, SAXException, IOException, CASException { // CAS loadedCas = CasCreationUtils.createCas(TypeSystemDescriptionFactory.createTypeSystemDescription(), null, null); // FileInputStream in = new FileInputStream(f); // XmiCasDeserializer.deserialize(in, loadedCas); // IOUtils.closeQuietly(in); // return loadedCas.getJCas(); // } // // public static void writeFile(String fileName, String content) throws Exception { // BufferedWriter br = new BufferedWriter(new FileWriter(new File(fileName))); // br.write(content); // br.close(); // } // // // }
import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.collect.Table; import com.google.common.collect.TreeBasedTable; import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.utils.ArgUtils; import de.tudarmstadt.ukp.dkpro.tc.weka.report.WekaClassificationReport; import org.apache.commons.io.FileUtils; import org.apache.commons.io.LineIterator; import org.apache.commons.io.filefilter.DirectoryFileFilter; import org.apache.commons.io.filefilter.FileFileFilter; import org.apache.commons.io.filefilter.RegexFileFilter; import java.io.*; import java.text.NumberFormat;
if (subFolder.getName().contains("TestTask")) { FileUtils .copyFile(new File(subFolder.getAbsoluteFile() + "/id2outcome.txt"), new File(resultFilePath + "/" + ExperimentUtils.OUTCOME_PATH + "/id2outcome" + String.format("%03d", oCounter) + ".txt")); oCounter++; } } // get scores StringBuilder sb = new StringBuilder(); double sumAcc = 0.0; double sumF1 = 0.0; File matrices = new File(resultFilePath + "/" + ExperimentUtils.MATRIX_PATH); double folds = 0.0; for (File cm : matrices.listFiles()) { if (!cm.getName().endsWith(".csv")) continue; ConfusionMatrix c = new ConfusionMatrix(cm); sb.append(c.Fmacro() + "\n"); sumF1 += c.Fmacro(); sumAcc += c.Acc(); folds++; } NumberFormat percentFormat = NumberFormat.getPercentInstance(Locale.US); percentFormat.setMaximumFractionDigits(3); String results = "Accuracy = " + (percentFormat.format(sumAcc / folds)) + "\n"; results += "Macro-F1 = " + (percentFormat.format(sumF1 / folds)); System.out.println(results);
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/utils/ArgUtils.java // public class ArgUtils { // // // public static String getID(String s) { // String[] tmp = s.split("/"); // return tmp[tmp.length-1].replace(".xmi","").replace(".bin", ""); // } // // // public static String getID(File f) { // return getID(f.getName()); // } // // // public static boolean isClaim(Sentence s, JCas cas) { // return selectOverlapping(Claim.class, s, cas).size()>0 || selectOverlapping(MajorClaim.class, s, cas).size()>0; // } // // // public static boolean isPremise(Sentence s, JCas cas) { // return selectOverlapping(Premise.class, s, cas).size()>0; // } // // // public static <T extends TOP> List<T> selectOverlapping(Class<T> type,Annotation annotation, JCas jCas) { // Collection<T> allAnnotations = JCasUtil.select(jCas, type); // // List<T> result = new ArrayList<T>(); // // for (T a : allAnnotations) { // if ((a instanceof Annotation) && (doOverlap(annotation, (Annotation) a))) { // result.add(a); // } // } // // return result; // } // // // public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { // return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); // } // // // public static JCas readCas(File f) throws ResourceInitializationException, SAXException, IOException, CASException { // CAS loadedCas = CasCreationUtils.createCas(TypeSystemDescriptionFactory.createTypeSystemDescription(), null, null); // FileInputStream in = new FileInputStream(f); // XmiCasDeserializer.deserialize(in, loadedCas); // IOUtils.closeQuietly(in); // return loadedCas.getJCas(); // } // // public static void writeFile(String fileName, String content) throws Exception { // BufferedWriter br = new BufferedWriter(new FileWriter(new File(fileName))); // br.write(content); // br.close(); // } // // // } // Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/experiments/utils/ExperimentUtils.java import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.collect.Table; import com.google.common.collect.TreeBasedTable; import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.utils.ArgUtils; import de.tudarmstadt.ukp.dkpro.tc.weka.report.WekaClassificationReport; import org.apache.commons.io.FileUtils; import org.apache.commons.io.LineIterator; import org.apache.commons.io.filefilter.DirectoryFileFilter; import org.apache.commons.io.filefilter.FileFileFilter; import org.apache.commons.io.filefilter.RegexFileFilter; import java.io.*; import java.text.NumberFormat; if (subFolder.getName().contains("TestTask")) { FileUtils .copyFile(new File(subFolder.getAbsoluteFile() + "/id2outcome.txt"), new File(resultFilePath + "/" + ExperimentUtils.OUTCOME_PATH + "/id2outcome" + String.format("%03d", oCounter) + ".txt")); oCounter++; } } // get scores StringBuilder sb = new StringBuilder(); double sumAcc = 0.0; double sumF1 = 0.0; File matrices = new File(resultFilePath + "/" + ExperimentUtils.MATRIX_PATH); double folds = 0.0; for (File cm : matrices.listFiles()) { if (!cm.getName().endsWith(".csv")) continue; ConfusionMatrix c = new ConfusionMatrix(cm); sb.append(c.Fmacro() + "\n"); sumF1 += c.Fmacro(); sumAcc += c.Acc(); folds++; } NumberFormat percentFormat = NumberFormat.getPercentInstance(Locale.US); percentFormat.setMaximumFractionDigits(3); String results = "Accuracy = " + (percentFormat.format(sumAcc / folds)) + "\n"; results += "Macro-F1 = " + (percentFormat.format(sumF1 / folds)); System.out.println(results);
ArgUtils.writeFile(resultFilePath + "/Results.txt", results);
UKPLab/emnlp2017-claim-identification
src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/statistics/ClaimSentenceDist.java
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/utils/ArgUtils.java // public class ArgUtils { // // // public static String getID(String s) { // String[] tmp = s.split("/"); // return tmp[tmp.length-1].replace(".xmi","").replace(".bin", ""); // } // // // public static String getID(File f) { // return getID(f.getName()); // } // // // public static boolean isClaim(Sentence s, JCas cas) { // return selectOverlapping(Claim.class, s, cas).size()>0 || selectOverlapping(MajorClaim.class, s, cas).size()>0; // } // // // public static boolean isPremise(Sentence s, JCas cas) { // return selectOverlapping(Premise.class, s, cas).size()>0; // } // // // public static <T extends TOP> List<T> selectOverlapping(Class<T> type,Annotation annotation, JCas jCas) { // Collection<T> allAnnotations = JCasUtil.select(jCas, type); // // List<T> result = new ArrayList<T>(); // // for (T a : allAnnotations) { // if ((a instanceof Annotation) && (doOverlap(annotation, (Annotation) a))) { // result.add(a); // } // } // // return result; // } // // // public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { // return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); // } // // // public static JCas readCas(File f) throws ResourceInitializationException, SAXException, IOException, CASException { // CAS loadedCas = CasCreationUtils.createCas(TypeSystemDescriptionFactory.createTypeSystemDescription(), null, null); // FileInputStream in = new FileInputStream(f); // XmiCasDeserializer.deserialize(in, loadedCas); // IOUtils.closeQuietly(in); // return loadedCas.getJCas(); // } // // public static void writeFile(String fileName, String content) throws Exception { // BufferedWriter br = new BufferedWriter(new FileWriter(new File(fileName))); // br.write(content); // br.close(); // } // // // }
import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.utils.ArgUtils; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import java.io.File; import java.text.MessageFormat; import java.util.Collection;
/* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.statistics; public class ClaimSentenceDist { private static final String path = "/Users/zemes/Desktop/NLP/Papers/TACL2016/data/prep3/VG"; public static void main(String[] args) throws Exception { File dir = new File(path); double numDocs = 0.0; double numSentences = 0.0; double numTokens = 0.0; double sentClaims = 0.0; double sentPremises = 0.0; for (File f : dir.listFiles()) { if (!f.getName().endsWith(".xmi")) continue; System.out.println(f.getName());
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/utils/ArgUtils.java // public class ArgUtils { // // // public static String getID(String s) { // String[] tmp = s.split("/"); // return tmp[tmp.length-1].replace(".xmi","").replace(".bin", ""); // } // // // public static String getID(File f) { // return getID(f.getName()); // } // // // public static boolean isClaim(Sentence s, JCas cas) { // return selectOverlapping(Claim.class, s, cas).size()>0 || selectOverlapping(MajorClaim.class, s, cas).size()>0; // } // // // public static boolean isPremise(Sentence s, JCas cas) { // return selectOverlapping(Premise.class, s, cas).size()>0; // } // // // public static <T extends TOP> List<T> selectOverlapping(Class<T> type,Annotation annotation, JCas jCas) { // Collection<T> allAnnotations = JCasUtil.select(jCas, type); // // List<T> result = new ArrayList<T>(); // // for (T a : allAnnotations) { // if ((a instanceof Annotation) && (doOverlap(annotation, (Annotation) a))) { // result.add(a); // } // } // // return result; // } // // // public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { // return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); // } // // // public static JCas readCas(File f) throws ResourceInitializationException, SAXException, IOException, CASException { // CAS loadedCas = CasCreationUtils.createCas(TypeSystemDescriptionFactory.createTypeSystemDescription(), null, null); // FileInputStream in = new FileInputStream(f); // XmiCasDeserializer.deserialize(in, loadedCas); // IOUtils.closeQuietly(in); // return loadedCas.getJCas(); // } // // public static void writeFile(String fileName, String content) throws Exception { // BufferedWriter br = new BufferedWriter(new FileWriter(new File(fileName))); // br.write(content); // br.close(); // } // // // } // Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/statistics/ClaimSentenceDist.java import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.utils.ArgUtils; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import java.io.File; import java.text.MessageFormat; import java.util.Collection; /* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.statistics; public class ClaimSentenceDist { private static final String path = "/Users/zemes/Desktop/NLP/Papers/TACL2016/data/prep3/VG"; public static void main(String[] args) throws Exception { File dir = new File(path); double numDocs = 0.0; double numSentences = 0.0; double numTokens = 0.0; double sentClaims = 0.0; double sentPremises = 0.0; for (File f : dir.listFiles()) { if (!f.getName().endsWith(".xmi")) continue; System.out.println(f.getName());
JCas cas = ArgUtils.readCas(f);
UKPLab/emnlp2017-claim-identification
src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/features/syntactic/PunctuationSequenceUFE.java
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/features/syntactic/utils/PunctuationSequenceMetaCollector.java // public class PunctuationSequenceMetaCollector extends FreqDistBasedMetaCollector { // // public static final String PARAM_PUNCTUATION_SEQUENCE_FD_FILE = "punctSequenceFdFile"; // @ConfigurationParameter(name = PARAM_PUNCTUATION_SEQUENCE_FD_FILE, mandatory = true) // private File punctSequenceFdFile; // // @Override // public void initialize(UimaContext context) throws ResourceInitializationException { // super.initialize(context); // } // // @Override // public void process(JCas jcas) throws AnalysisEngineProcessException { // Collection<Sentence> sentences = JCasUtil.select(jcas, Sentence.class); // for (Sentence sentence : sentences) { // String sequences = createPunctuationSequence(sentence.getCoveredText()); // fd.addSample(sequences, 1); // } // } // // @Override // public Map<String, String> getParameterKeyPairs() { // Map<String, String> mapping = new HashMap<String, String>(); // mapping.put(PunctuationSequenceUFE.PARAM_PUNCTUATION_SEQUENCE_FD_FILE, PARAM_PUNCTUATION_SEQUENCE_FD_FILE); // return mapping; // } // // @Override // protected File getFreqDistFile() { // return punctSequenceFdFile; // } // // public static String createPunctuationSequence(String text){ // // normalize quotes // String normalized = text.replaceAll("'","\""); // normalized = normalized.replaceAll("`", "\""); // normalized = normalized.replaceAll("´", "\""); // // Matcher punctPattern = Pattern.compile("\\p{Punct}").matcher(normalized); // StringBuilder pattern = new StringBuilder(); // // while (punctPattern.find()) { // pattern.append(normalized.charAt(punctPattern.start())); // } // return pattern.toString(); // } // }
import org.apache.uima.resource.ResourceSpecifier; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.features.syntactic.utils.PunctuationSequenceMetaCollector; import de.tudarmstadt.ukp.dkpro.core.api.frequency.util.FrequencyDistribution; import de.tudarmstadt.ukp.dkpro.tc.api.exception.TextClassificationException; import de.tudarmstadt.ukp.dkpro.tc.api.features.ClassificationUnitFeatureExtractor; import de.tudarmstadt.ukp.dkpro.tc.api.features.Feature; import de.tudarmstadt.ukp.dkpro.tc.api.features.FeatureExtractorResource_ImplBase; import de.tudarmstadt.ukp.dkpro.tc.api.features.meta.MetaCollector; import de.tudarmstadt.ukp.dkpro.tc.api.features.meta.MetaDependent; import de.tudarmstadt.ukp.dkpro.tc.api.type.TextClassificationUnit; import org.apache.uima.fit.descriptor.ConfigurationParameter; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException;
@Override public boolean initialize(ResourceSpecifier aSpecifier, Map<String, Object> aAdditionalParams) throws ResourceInitializationException { if (!super.initialize(aSpecifier, aAdditionalParams)) { return false; } FrequencyDistribution<String> trainingFD; try { trainingFD = new FrequencyDistribution<String>(); trainingFD.load(new File(punctSequenceFdFile)); } catch (Exception e) { throw new ResourceInitializationException(e); } topKPunctuationSequences = new FrequencyDistribution<String>(); for (String sample : trainingFD.getKeys()) { topKPunctuationSequences.addSample(sample, trainingFD.getCount(sample)); } getLogger().info("Loaded " + topKPunctuationSequences.getKeys().size() + " punctuation sequences."); return true; } @Override public List<Feature> extract(JCas view, TextClassificationUnit classificationUnit) throws TextClassificationException { String text = classificationUnit.getCoveredText(); List<Feature> features = new ArrayList<Feature>();
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/features/syntactic/utils/PunctuationSequenceMetaCollector.java // public class PunctuationSequenceMetaCollector extends FreqDistBasedMetaCollector { // // public static final String PARAM_PUNCTUATION_SEQUENCE_FD_FILE = "punctSequenceFdFile"; // @ConfigurationParameter(name = PARAM_PUNCTUATION_SEQUENCE_FD_FILE, mandatory = true) // private File punctSequenceFdFile; // // @Override // public void initialize(UimaContext context) throws ResourceInitializationException { // super.initialize(context); // } // // @Override // public void process(JCas jcas) throws AnalysisEngineProcessException { // Collection<Sentence> sentences = JCasUtil.select(jcas, Sentence.class); // for (Sentence sentence : sentences) { // String sequences = createPunctuationSequence(sentence.getCoveredText()); // fd.addSample(sequences, 1); // } // } // // @Override // public Map<String, String> getParameterKeyPairs() { // Map<String, String> mapping = new HashMap<String, String>(); // mapping.put(PunctuationSequenceUFE.PARAM_PUNCTUATION_SEQUENCE_FD_FILE, PARAM_PUNCTUATION_SEQUENCE_FD_FILE); // return mapping; // } // // @Override // protected File getFreqDistFile() { // return punctSequenceFdFile; // } // // public static String createPunctuationSequence(String text){ // // normalize quotes // String normalized = text.replaceAll("'","\""); // normalized = normalized.replaceAll("`", "\""); // normalized = normalized.replaceAll("´", "\""); // // Matcher punctPattern = Pattern.compile("\\p{Punct}").matcher(normalized); // StringBuilder pattern = new StringBuilder(); // // while (punctPattern.find()) { // pattern.append(normalized.charAt(punctPattern.start())); // } // return pattern.toString(); // } // } // Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/features/syntactic/PunctuationSequenceUFE.java import org.apache.uima.resource.ResourceSpecifier; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.features.syntactic.utils.PunctuationSequenceMetaCollector; import de.tudarmstadt.ukp.dkpro.core.api.frequency.util.FrequencyDistribution; import de.tudarmstadt.ukp.dkpro.tc.api.exception.TextClassificationException; import de.tudarmstadt.ukp.dkpro.tc.api.features.ClassificationUnitFeatureExtractor; import de.tudarmstadt.ukp.dkpro.tc.api.features.Feature; import de.tudarmstadt.ukp.dkpro.tc.api.features.FeatureExtractorResource_ImplBase; import de.tudarmstadt.ukp.dkpro.tc.api.features.meta.MetaCollector; import de.tudarmstadt.ukp.dkpro.tc.api.features.meta.MetaDependent; import de.tudarmstadt.ukp.dkpro.tc.api.type.TextClassificationUnit; import org.apache.uima.fit.descriptor.ConfigurationParameter; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; @Override public boolean initialize(ResourceSpecifier aSpecifier, Map<String, Object> aAdditionalParams) throws ResourceInitializationException { if (!super.initialize(aSpecifier, aAdditionalParams)) { return false; } FrequencyDistribution<String> trainingFD; try { trainingFD = new FrequencyDistribution<String>(); trainingFD.load(new File(punctSequenceFdFile)); } catch (Exception e) { throw new ResourceInitializationException(e); } topKPunctuationSequences = new FrequencyDistribution<String>(); for (String sample : trainingFD.getKeys()) { topKPunctuationSequences.addSample(sample, trainingFD.getCount(sample)); } getLogger().info("Loaded " + topKPunctuationSequences.getKeys().size() + " punctuation sequences."); return true; } @Override public List<Feature> extract(JCas view, TextClassificationUnit classificationUnit) throws TextClassificationException { String text = classificationUnit.getCoveredText(); List<Feature> features = new ArrayList<Feature>();
String unitSequence = PunctuationSequenceMetaCollector.createPunctuationSequence(text);
UKPLab/emnlp2017-claim-identification
src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/features/syntactic/utils/PunctuationSequenceMetaCollector.java
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/features/syntactic/PunctuationSequenceUFE.java // public class PunctuationSequenceUFE extends FeatureExtractorResource_ImplBase implements ClassificationUnitFeatureExtractor, MetaDependent { // // public static final String FN_PUNCTUATION_SEQUENCE_PREFIX = "PunctSeq_"; // // public static final String PARAM_PUNCTUATION_SEQUENCE_FD_FILE = "punctSequenceFdFile"; // @ConfigurationParameter(name = PARAM_PUNCTUATION_SEQUENCE_FD_FILE, mandatory = true) // private String punctSequenceFdFile; // // public FrequencyDistribution<String> topKPunctuationSequences; // // @Override // public boolean initialize(ResourceSpecifier aSpecifier, Map<String, Object> aAdditionalParams) throws ResourceInitializationException { // if (!super.initialize(aSpecifier, aAdditionalParams)) { // return false; // } // // FrequencyDistribution<String> trainingFD; // try { // trainingFD = new FrequencyDistribution<String>(); // trainingFD.load(new File(punctSequenceFdFile)); // } catch (Exception e) { // throw new ResourceInitializationException(e); // } // // topKPunctuationSequences = new FrequencyDistribution<String>(); // // for (String sample : trainingFD.getKeys()) { // topKPunctuationSequences.addSample(sample, trainingFD.getCount(sample)); // } // // getLogger().info("Loaded " + topKPunctuationSequences.getKeys().size() + " punctuation sequences."); // return true; // } // // @Override // public List<Feature> extract(JCas view, TextClassificationUnit classificationUnit) // throws TextClassificationException { // // String text = classificationUnit.getCoveredText(); // List<Feature> features = new ArrayList<Feature>(); // String unitSequence = PunctuationSequenceMetaCollector.createPunctuationSequence(text); // // for (String seq : topKPunctuationSequences.getKeys()) { // if (unitSequence.equals(seq)) features.add(new Feature(FN_PUNCTUATION_SEQUENCE_PREFIX + seq, true)); // else features.add(new Feature(FN_PUNCTUATION_SEQUENCE_PREFIX + seq, false)); // } // return features; // } // // @Override // public List<Class<? extends MetaCollector>> getMetaCollectorClasses() { // List<Class<? extends MetaCollector>> metaCollectorClasses = new ArrayList<Class<? extends MetaCollector>>(); // metaCollectorClasses.add(PunctuationSequenceMetaCollector.class); // return metaCollectorClasses; // } // }
import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.features.syntactic.PunctuationSequenceUFE; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import de.tudarmstadt.ukp.dkpro.tc.features.ngram.meta.FreqDistBasedMetaCollector; import org.apache.uima.UimaContext; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.fit.descriptor.ConfigurationParameter; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; import java.io.File; import java.util.Collection;
/* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.features.syntactic.utils; public class PunctuationSequenceMetaCollector extends FreqDistBasedMetaCollector { public static final String PARAM_PUNCTUATION_SEQUENCE_FD_FILE = "punctSequenceFdFile"; @ConfigurationParameter(name = PARAM_PUNCTUATION_SEQUENCE_FD_FILE, mandatory = true) private File punctSequenceFdFile; @Override public void initialize(UimaContext context) throws ResourceInitializationException { super.initialize(context); } @Override public void process(JCas jcas) throws AnalysisEngineProcessException { Collection<Sentence> sentences = JCasUtil.select(jcas, Sentence.class); for (Sentence sentence : sentences) { String sequences = createPunctuationSequence(sentence.getCoveredText()); fd.addSample(sequences, 1); } } @Override public Map<String, String> getParameterKeyPairs() { Map<String, String> mapping = new HashMap<String, String>();
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/features/syntactic/PunctuationSequenceUFE.java // public class PunctuationSequenceUFE extends FeatureExtractorResource_ImplBase implements ClassificationUnitFeatureExtractor, MetaDependent { // // public static final String FN_PUNCTUATION_SEQUENCE_PREFIX = "PunctSeq_"; // // public static final String PARAM_PUNCTUATION_SEQUENCE_FD_FILE = "punctSequenceFdFile"; // @ConfigurationParameter(name = PARAM_PUNCTUATION_SEQUENCE_FD_FILE, mandatory = true) // private String punctSequenceFdFile; // // public FrequencyDistribution<String> topKPunctuationSequences; // // @Override // public boolean initialize(ResourceSpecifier aSpecifier, Map<String, Object> aAdditionalParams) throws ResourceInitializationException { // if (!super.initialize(aSpecifier, aAdditionalParams)) { // return false; // } // // FrequencyDistribution<String> trainingFD; // try { // trainingFD = new FrequencyDistribution<String>(); // trainingFD.load(new File(punctSequenceFdFile)); // } catch (Exception e) { // throw new ResourceInitializationException(e); // } // // topKPunctuationSequences = new FrequencyDistribution<String>(); // // for (String sample : trainingFD.getKeys()) { // topKPunctuationSequences.addSample(sample, trainingFD.getCount(sample)); // } // // getLogger().info("Loaded " + topKPunctuationSequences.getKeys().size() + " punctuation sequences."); // return true; // } // // @Override // public List<Feature> extract(JCas view, TextClassificationUnit classificationUnit) // throws TextClassificationException { // // String text = classificationUnit.getCoveredText(); // List<Feature> features = new ArrayList<Feature>(); // String unitSequence = PunctuationSequenceMetaCollector.createPunctuationSequence(text); // // for (String seq : topKPunctuationSequences.getKeys()) { // if (unitSequence.equals(seq)) features.add(new Feature(FN_PUNCTUATION_SEQUENCE_PREFIX + seq, true)); // else features.add(new Feature(FN_PUNCTUATION_SEQUENCE_PREFIX + seq, false)); // } // return features; // } // // @Override // public List<Class<? extends MetaCollector>> getMetaCollectorClasses() { // List<Class<? extends MetaCollector>> metaCollectorClasses = new ArrayList<Class<? extends MetaCollector>>(); // metaCollectorClasses.add(PunctuationSequenceMetaCollector.class); // return metaCollectorClasses; // } // } // Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/features/syntactic/utils/PunctuationSequenceMetaCollector.java import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.features.syntactic.PunctuationSequenceUFE; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import de.tudarmstadt.ukp.dkpro.tc.features.ngram.meta.FreqDistBasedMetaCollector; import org.apache.uima.UimaContext; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.fit.descriptor.ConfigurationParameter; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; import java.io.File; import java.util.Collection; /* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.features.syntactic.utils; public class PunctuationSequenceMetaCollector extends FreqDistBasedMetaCollector { public static final String PARAM_PUNCTUATION_SEQUENCE_FD_FILE = "punctSequenceFdFile"; @ConfigurationParameter(name = PARAM_PUNCTUATION_SEQUENCE_FD_FILE, mandatory = true) private File punctSequenceFdFile; @Override public void initialize(UimaContext context) throws ResourceInitializationException { super.initialize(context); } @Override public void process(JCas jcas) throws AnalysisEngineProcessException { Collection<Sentence> sentences = JCasUtil.select(jcas, Sentence.class); for (Sentence sentence : sentences) { String sequences = createPunctuationSequence(sentence.getCoveredText()); fd.addSample(sequences, 1); } } @Override public Map<String, String> getParameterKeyPairs() { Map<String, String> mapping = new HashMap<String, String>();
mapping.put(PunctuationSequenceUFE.PARAM_PUNCTUATION_SEQUENCE_FD_FILE, PARAM_PUNCTUATION_SEQUENCE_FD_FILE);
UKPLab/emnlp2017-claim-identification
src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/features/structural/FirstComponentInParagraph.java
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/features/FeatureUtils.java // public class FeatureUtils { // // /** // * Returns a covering paragraph of an argument component // * @param classificationUnit // * @return // */ // public static Paragraph getCoveringParagraph(Annotation classificationUnit) { // Collection<Paragraph> sentences = JCasUtil.selectCovering(Paragraph.class, classificationUnit); // if (sentences.size()!=1) return null; // else return sentences.iterator().next(); // } // // /** // * Returns a covering sentence of an argument component // * @param classificationUnit // * @return // */ // public static Sentence getCoveringSentence(Annotation classificationUnit) { // Collection<Sentence> sentences = JCasUtil.selectCovering(Sentence.class, classificationUnit); // if (sentences.size()!=1) return null; // else return sentences.iterator().next(); // } // // /** // * Selects annotations with desired type ({@code type} parameter) that overlap the given // * {@code annotation}, such that at least a part of the selected annotations // * {@link #doOverlap(org.apache.uima.jcas.tcas.Annotation, org.apache.uima.jcas.tcas.Annotation)} // * with the given {@code annotation}. // * See {@code JCasUtil2Test.testSelectOverlapping()} for details. // * // * @param type desired type // * @param annotation current annotation for which the overlapping annotations are being selected // * @param jCas the JCas // * @return collection of overlapping annotations // */ // public static <T extends TOP> List<T> selectOverlapping(Class<T> type,Annotation annotation, JCas jCas) { // Collection<T> allAnnotations = JCasUtil.select(jCas, type); // // List<T> result = new ArrayList<T>(); // // for (T a : allAnnotations) { // if ((a instanceof Annotation) && (doOverlap(annotation, (Annotation) a))) { // result.add(a); // } // } // // return result; // } // // // // /** // * Returns whether the given annotations have a non-empty overlap. // * <p/> // * <p> // * Note that this method is symmetric. Two annotations overlap // * if they have at least one character position in common. // * Annotations that merely touch at the begin or end are not // * overlapping. // * <p/> // * <ul> // * <li>anno1[0,1], anno2[1,2] => no overlap</li> // * <li>anno1[0,2], anno2[1,2] => overlap</li> // * <li>anno1[0,2], anno2[0,2] => overlap (same span)</li> // * </ul> // * </p> // * // * @param anno1 first annotation // * @param anno2 second annotation // * @return whether the annotations overlap // */ // public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { // return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); // } // }
import java.util.Collection; import java.util.List; import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.features.FeatureUtils; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import de.tudarmstadt.ukp.dkpro.tc.api.exception.TextClassificationException; import de.tudarmstadt.ukp.dkpro.tc.api.features.ClassificationUnitFeatureExtractor; import de.tudarmstadt.ukp.dkpro.tc.api.features.Feature; import de.tudarmstadt.ukp.dkpro.tc.api.features.FeatureExtractorResource_ImplBase; import de.tudarmstadt.ukp.dkpro.tc.api.type.TextClassificationUnit; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import java.util.ArrayList;
/* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.features.structural; /** * * @author Christian Stab */ public class FirstComponentInParagraph extends FeatureExtractorResource_ImplBase implements ClassificationUnitFeatureExtractor { public static final String FN_FIRST_COMPONENT_IN_PARAGRAPH = "FirstComponentInParagraph"; public List<Feature> extract(JCas jcas, TextClassificationUnit classificationUnit) throws TextClassificationException { List<Feature> featList = new ArrayList<Feature>();
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/features/FeatureUtils.java // public class FeatureUtils { // // /** // * Returns a covering paragraph of an argument component // * @param classificationUnit // * @return // */ // public static Paragraph getCoveringParagraph(Annotation classificationUnit) { // Collection<Paragraph> sentences = JCasUtil.selectCovering(Paragraph.class, classificationUnit); // if (sentences.size()!=1) return null; // else return sentences.iterator().next(); // } // // /** // * Returns a covering sentence of an argument component // * @param classificationUnit // * @return // */ // public static Sentence getCoveringSentence(Annotation classificationUnit) { // Collection<Sentence> sentences = JCasUtil.selectCovering(Sentence.class, classificationUnit); // if (sentences.size()!=1) return null; // else return sentences.iterator().next(); // } // // /** // * Selects annotations with desired type ({@code type} parameter) that overlap the given // * {@code annotation}, such that at least a part of the selected annotations // * {@link #doOverlap(org.apache.uima.jcas.tcas.Annotation, org.apache.uima.jcas.tcas.Annotation)} // * with the given {@code annotation}. // * See {@code JCasUtil2Test.testSelectOverlapping()} for details. // * // * @param type desired type // * @param annotation current annotation for which the overlapping annotations are being selected // * @param jCas the JCas // * @return collection of overlapping annotations // */ // public static <T extends TOP> List<T> selectOverlapping(Class<T> type,Annotation annotation, JCas jCas) { // Collection<T> allAnnotations = JCasUtil.select(jCas, type); // // List<T> result = new ArrayList<T>(); // // for (T a : allAnnotations) { // if ((a instanceof Annotation) && (doOverlap(annotation, (Annotation) a))) { // result.add(a); // } // } // // return result; // } // // // // /** // * Returns whether the given annotations have a non-empty overlap. // * <p/> // * <p> // * Note that this method is symmetric. Two annotations overlap // * if they have at least one character position in common. // * Annotations that merely touch at the begin or end are not // * overlapping. // * <p/> // * <ul> // * <li>anno1[0,1], anno2[1,2] => no overlap</li> // * <li>anno1[0,2], anno2[1,2] => overlap</li> // * <li>anno1[0,2], anno2[0,2] => overlap (same span)</li> // * </ul> // * </p> // * // * @param anno1 first annotation // * @param anno2 second annotation // * @return whether the annotations overlap // */ // public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { // return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); // } // } // Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/features/structural/FirstComponentInParagraph.java import java.util.Collection; import java.util.List; import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.features.FeatureUtils; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import de.tudarmstadt.ukp.dkpro.tc.api.exception.TextClassificationException; import de.tudarmstadt.ukp.dkpro.tc.api.features.ClassificationUnitFeatureExtractor; import de.tudarmstadt.ukp.dkpro.tc.api.features.Feature; import de.tudarmstadt.ukp.dkpro.tc.api.features.FeatureExtractorResource_ImplBase; import de.tudarmstadt.ukp.dkpro.tc.api.type.TextClassificationUnit; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import java.util.ArrayList; /* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.features.structural; /** * * @author Christian Stab */ public class FirstComponentInParagraph extends FeatureExtractorResource_ImplBase implements ClassificationUnitFeatureExtractor { public static final String FN_FIRST_COMPONENT_IN_PARAGRAPH = "FirstComponentInParagraph"; public List<Feature> extract(JCas jcas, TextClassificationUnit classificationUnit) throws TextClassificationException { List<Feature> featList = new ArrayList<Feature>();
Paragraph para = FeatureUtils.getCoveringParagraph(classificationUnit);
UKPLab/emnlp2017-claim-identification
src/main/java/de/tudarmstadt/ukp/dkpro/tc/core/io/CustomFoldDimensionBundle.java
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/utils/ArgUtils.java // public class ArgUtils { // // // public static String getID(String s) { // String[] tmp = s.split("/"); // return tmp[tmp.length-1].replace(".xmi","").replace(".bin", ""); // } // // // public static String getID(File f) { // return getID(f.getName()); // } // // // public static boolean isClaim(Sentence s, JCas cas) { // return selectOverlapping(Claim.class, s, cas).size()>0 || selectOverlapping(MajorClaim.class, s, cas).size()>0; // } // // // public static boolean isPremise(Sentence s, JCas cas) { // return selectOverlapping(Premise.class, s, cas).size()>0; // } // // // public static <T extends TOP> List<T> selectOverlapping(Class<T> type,Annotation annotation, JCas jCas) { // Collection<T> allAnnotations = JCasUtil.select(jCas, type); // // List<T> result = new ArrayList<T>(); // // for (T a : allAnnotations) { // if ((a instanceof Annotation) && (doOverlap(annotation, (Annotation) a))) { // result.add(a); // } // } // // return result; // } // // // public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { // return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); // } // // // public static JCas readCas(File f) throws ResourceInitializationException, SAXException, IOException, CASException { // CAS loadedCas = CasCreationUtils.createCas(TypeSystemDescriptionFactory.createTypeSystemDescription(), null, null); // FileInputStream in = new FileInputStream(f); // XmiCasDeserializer.deserialize(in, loadedCas); // IOUtils.closeQuietly(in); // return loadedCas.getJCas(); // } // // public static void writeFile(String fileName, String content) throws Exception { // BufferedWriter br = new BufferedWriter(new FileWriter(new File(fileName))); // br.write(content); // br.close(); // } // // // }
import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.utils.ArgUtils; import de.tudarmstadt.ukp.dkpro.lab.task.Dimension; import de.tudarmstadt.ukp.dkpro.lab.task.impl.DynamicDimension; import de.tudarmstadt.ukp.dkpro.lab.task.impl.FoldDimensionBundle; import java.io.BufferedReader; import java.io.FileReader; import java.util.*;
/* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.dkpro.tc.core.io; public class CustomFoldDimensionBundle<T> extends FoldDimensionBundle<T> { private Dimension<T> foldedDimension; private List<T>[] test; private List<T>[] train; private int validationBucket = -1; private String foldFile; private boolean useDevSet = false; public CustomFoldDimensionBundle(String aName, Dimension<T> aFoldedDimension, String aFoldFile, boolean useDevSet) { super(aName, aFoldedDimension, 5); foldedDimension = aFoldedDimension; foldFile = aFoldFile; this.useDevSet = useDevSet; } @SuppressWarnings("unchecked") private void init() { // get mapping from file names to ids HashMap<String, T> idToPath = new HashMap<String, T>(); while (foldedDimension.hasNext()) { T path = foldedDimension.next(); //String currentID = getEssayIDFromPath((String)path).replace("_0","");
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/utils/ArgUtils.java // public class ArgUtils { // // // public static String getID(String s) { // String[] tmp = s.split("/"); // return tmp[tmp.length-1].replace(".xmi","").replace(".bin", ""); // } // // // public static String getID(File f) { // return getID(f.getName()); // } // // // public static boolean isClaim(Sentence s, JCas cas) { // return selectOverlapping(Claim.class, s, cas).size()>0 || selectOverlapping(MajorClaim.class, s, cas).size()>0; // } // // // public static boolean isPremise(Sentence s, JCas cas) { // return selectOverlapping(Premise.class, s, cas).size()>0; // } // // // public static <T extends TOP> List<T> selectOverlapping(Class<T> type,Annotation annotation, JCas jCas) { // Collection<T> allAnnotations = JCasUtil.select(jCas, type); // // List<T> result = new ArrayList<T>(); // // for (T a : allAnnotations) { // if ((a instanceof Annotation) && (doOverlap(annotation, (Annotation) a))) { // result.add(a); // } // } // // return result; // } // // // public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { // return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); // } // // // public static JCas readCas(File f) throws ResourceInitializationException, SAXException, IOException, CASException { // CAS loadedCas = CasCreationUtils.createCas(TypeSystemDescriptionFactory.createTypeSystemDescription(), null, null); // FileInputStream in = new FileInputStream(f); // XmiCasDeserializer.deserialize(in, loadedCas); // IOUtils.closeQuietly(in); // return loadedCas.getJCas(); // } // // public static void writeFile(String fileName, String content) throws Exception { // BufferedWriter br = new BufferedWriter(new FileWriter(new File(fileName))); // br.write(content); // br.close(); // } // // // } // Path: src/main/java/de/tudarmstadt/ukp/dkpro/tc/core/io/CustomFoldDimensionBundle.java import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.utils.ArgUtils; import de.tudarmstadt.ukp.dkpro.lab.task.Dimension; import de.tudarmstadt.ukp.dkpro.lab.task.impl.DynamicDimension; import de.tudarmstadt.ukp.dkpro.lab.task.impl.FoldDimensionBundle; import java.io.BufferedReader; import java.io.FileReader; import java.util.*; /* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.dkpro.tc.core.io; public class CustomFoldDimensionBundle<T> extends FoldDimensionBundle<T> { private Dimension<T> foldedDimension; private List<T>[] test; private List<T>[] train; private int validationBucket = -1; private String foldFile; private boolean useDevSet = false; public CustomFoldDimensionBundle(String aName, Dimension<T> aFoldedDimension, String aFoldFile, boolean useDevSet) { super(aName, aFoldedDimension, 5); foldedDimension = aFoldedDimension; foldFile = aFoldFile; this.useDevSet = useDevSet; } @SuppressWarnings("unchecked") private void init() { // get mapping from file names to ids HashMap<String, T> idToPath = new HashMap<String, T>(); while (foldedDimension.hasNext()) { T path = foldedDimension.next(); //String currentID = getEssayIDFromPath((String)path).replace("_0","");
String currentID = ArgUtils.getID((String)path);
UKPLab/emnlp2017-claim-identification
src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/reader/SentenceClaimOutcomeMultiplier.java
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/utils/ArgUtils.java // public class ArgUtils { // // // public static String getID(String s) { // String[] tmp = s.split("/"); // return tmp[tmp.length-1].replace(".xmi","").replace(".bin", ""); // } // // // public static String getID(File f) { // return getID(f.getName()); // } // // // public static boolean isClaim(Sentence s, JCas cas) { // return selectOverlapping(Claim.class, s, cas).size()>0 || selectOverlapping(MajorClaim.class, s, cas).size()>0; // } // // // public static boolean isPremise(Sentence s, JCas cas) { // return selectOverlapping(Premise.class, s, cas).size()>0; // } // // // public static <T extends TOP> List<T> selectOverlapping(Class<T> type,Annotation annotation, JCas jCas) { // Collection<T> allAnnotations = JCasUtil.select(jCas, type); // // List<T> result = new ArrayList<T>(); // // for (T a : allAnnotations) { // if ((a instanceof Annotation) && (doOverlap(annotation, (Annotation) a))) { // result.add(a); // } // } // // return result; // } // // // public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { // return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); // } // // // public static JCas readCas(File f) throws ResourceInitializationException, SAXException, IOException, CASException { // CAS loadedCas = CasCreationUtils.createCas(TypeSystemDescriptionFactory.createTypeSystemDescription(), null, null); // FileInputStream in = new FileInputStream(f); // XmiCasDeserializer.deserialize(in, loadedCas); // IOUtils.closeQuietly(in); // return loadedCas.getJCas(); // } // // public static void writeFile(String fileName, String content) throws Exception { // BufferedWriter br = new BufferedWriter(new FileWriter(new File(fileName))); // br.write(content); // br.close(); // } // // // }
import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.utils.ArgUtils; import de.tudarmstadt.ukp.dkpro.core.api.metadata.type.DocumentMetaData; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import de.tudarmstadt.ukp.dkpro.core.io.xmi.XmiReader; import de.tudarmstadt.ukp.dkpro.core.io.xmi.XmiWriter; import de.tudarmstadt.ukp.dkpro.tc.api.type.TextClassificationOutcome; import de.tudarmstadt.ukp.dkpro.tc.api.type.TextClassificationUnit; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.cas.AbstractCas; import org.apache.uima.cas.CAS; import org.apache.uima.cas.CASException; import org.apache.uima.cas.text.AnnotationFS; import org.apache.uima.fit.component.JCasMultiplier_ImplBase; import org.apache.uima.fit.factory.AnalysisEngineFactory; import org.apache.uima.fit.factory.CollectionReaderFactory; import org.apache.uima.fit.pipeline.SimplePipeline; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import org.apache.uima.util.CasCopier; import java.io.File; import java.util.Collection; import java.util.Iterator;
catch (CASException e) { throw new AnalysisEngineProcessException("Exception while creating JCas", null, e); } // Set new ids and URIs for copied cases. // The counting variable keeps track of how many new CAS objects are created from the // original CAS, a CAS relative counter. // NOTE: As it may cause confusion: If in sequence classification several or all CAS // contains only a single sequence this counter would be zero in all cases - this is not a // bug, but a cosmetic flaw DocumentMetaData.get(copyJCas).setDocumentId( DocumentMetaData.get(jCas).getDocumentId() + "_" + subCASCounter); DocumentMetaData.get(copyJCas).setDocumentUri( DocumentMetaData.get(jCas).getDocumentUri() + "_" + subCASCounter); // focus annotation AnnotationFS focusUnit = this.iterator.next(); Sentence s = (Sentence) focusUnit; // set unit TextClassificationUnit unit = new TextClassificationUnit(copyJCas, s.getBegin(), s.getEnd()); unit.setId(unitCounter); unitCounter++; subCASCounter++; // and outcome TextClassificationOutcome outcome = new TextClassificationOutcome(copyJCas, s.getBegin(), s.getEnd());
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/utils/ArgUtils.java // public class ArgUtils { // // // public static String getID(String s) { // String[] tmp = s.split("/"); // return tmp[tmp.length-1].replace(".xmi","").replace(".bin", ""); // } // // // public static String getID(File f) { // return getID(f.getName()); // } // // // public static boolean isClaim(Sentence s, JCas cas) { // return selectOverlapping(Claim.class, s, cas).size()>0 || selectOverlapping(MajorClaim.class, s, cas).size()>0; // } // // // public static boolean isPremise(Sentence s, JCas cas) { // return selectOverlapping(Premise.class, s, cas).size()>0; // } // // // public static <T extends TOP> List<T> selectOverlapping(Class<T> type,Annotation annotation, JCas jCas) { // Collection<T> allAnnotations = JCasUtil.select(jCas, type); // // List<T> result = new ArrayList<T>(); // // for (T a : allAnnotations) { // if ((a instanceof Annotation) && (doOverlap(annotation, (Annotation) a))) { // result.add(a); // } // } // // return result; // } // // // public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { // return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); // } // // // public static JCas readCas(File f) throws ResourceInitializationException, SAXException, IOException, CASException { // CAS loadedCas = CasCreationUtils.createCas(TypeSystemDescriptionFactory.createTypeSystemDescription(), null, null); // FileInputStream in = new FileInputStream(f); // XmiCasDeserializer.deserialize(in, loadedCas); // IOUtils.closeQuietly(in); // return loadedCas.getJCas(); // } // // public static void writeFile(String fileName, String content) throws Exception { // BufferedWriter br = new BufferedWriter(new FileWriter(new File(fileName))); // br.write(content); // br.close(); // } // // // } // Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/reader/SentenceClaimOutcomeMultiplier.java import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.utils.ArgUtils; import de.tudarmstadt.ukp.dkpro.core.api.metadata.type.DocumentMetaData; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import de.tudarmstadt.ukp.dkpro.core.io.xmi.XmiReader; import de.tudarmstadt.ukp.dkpro.core.io.xmi.XmiWriter; import de.tudarmstadt.ukp.dkpro.tc.api.type.TextClassificationOutcome; import de.tudarmstadt.ukp.dkpro.tc.api.type.TextClassificationUnit; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.cas.AbstractCas; import org.apache.uima.cas.CAS; import org.apache.uima.cas.CASException; import org.apache.uima.cas.text.AnnotationFS; import org.apache.uima.fit.component.JCasMultiplier_ImplBase; import org.apache.uima.fit.factory.AnalysisEngineFactory; import org.apache.uima.fit.factory.CollectionReaderFactory; import org.apache.uima.fit.pipeline.SimplePipeline; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import org.apache.uima.util.CasCopier; import java.io.File; import java.util.Collection; import java.util.Iterator; catch (CASException e) { throw new AnalysisEngineProcessException("Exception while creating JCas", null, e); } // Set new ids and URIs for copied cases. // The counting variable keeps track of how many new CAS objects are created from the // original CAS, a CAS relative counter. // NOTE: As it may cause confusion: If in sequence classification several or all CAS // contains only a single sequence this counter would be zero in all cases - this is not a // bug, but a cosmetic flaw DocumentMetaData.get(copyJCas).setDocumentId( DocumentMetaData.get(jCas).getDocumentId() + "_" + subCASCounter); DocumentMetaData.get(copyJCas).setDocumentUri( DocumentMetaData.get(jCas).getDocumentUri() + "_" + subCASCounter); // focus annotation AnnotationFS focusUnit = this.iterator.next(); Sentence s = (Sentence) focusUnit; // set unit TextClassificationUnit unit = new TextClassificationUnit(copyJCas, s.getBegin(), s.getEnd()); unit.setId(unitCounter); unitCounter++; subCASCounter++; // and outcome TextClassificationOutcome outcome = new TextClassificationOutcome(copyJCas, s.getBegin(), s.getEnd());
if (ArgUtils.isClaim(s, copyJCas)) {
UKPLab/emnlp2017-claim-identification
src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/statistics/ClaimExamplesExplorer.java
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/utils/ArgUtils.java // public class ArgUtils { // // // public static String getID(String s) { // String[] tmp = s.split("/"); // return tmp[tmp.length-1].replace(".xmi","").replace(".bin", ""); // } // // // public static String getID(File f) { // return getID(f.getName()); // } // // // public static boolean isClaim(Sentence s, JCas cas) { // return selectOverlapping(Claim.class, s, cas).size()>0 || selectOverlapping(MajorClaim.class, s, cas).size()>0; // } // // // public static boolean isPremise(Sentence s, JCas cas) { // return selectOverlapping(Premise.class, s, cas).size()>0; // } // // // public static <T extends TOP> List<T> selectOverlapping(Class<T> type,Annotation annotation, JCas jCas) { // Collection<T> allAnnotations = JCasUtil.select(jCas, type); // // List<T> result = new ArrayList<T>(); // // for (T a : allAnnotations) { // if ((a instanceof Annotation) && (doOverlap(annotation, (Annotation) a))) { // result.add(a); // } // } // // return result; // } // // // public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { // return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); // } // // // public static JCas readCas(File f) throws ResourceInitializationException, SAXException, IOException, CASException { // CAS loadedCas = CasCreationUtils.createCas(TypeSystemDescriptionFactory.createTypeSystemDescription(), null, null); // FileInputStream in = new FileInputStream(f); // XmiCasDeserializer.deserialize(in, loadedCas); // IOUtils.closeQuietly(in); // return loadedCas.getJCas(); // } // // public static void writeFile(String fileName, String content) throws Exception { // BufferedWriter br = new BufferedWriter(new FileWriter(new File(fileName))); // br.write(content); // br.close(); // } // // // }
import org.apache.uima.jcas.JCas; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.*; import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.utils.ArgUtils; import de.tudarmstadt.ukp.dkpro.argumentation.io.writer.ArgumentDumpWriter; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import de.tudarmstadt.ukp.dkpro.core.io.xmi.XmiReader; import org.apache.commons.io.FileUtils; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.fit.component.JCasConsumer_ImplBase; import org.apache.uima.fit.descriptor.ConfigurationParameter; import org.apache.uima.fit.factory.AnalysisEngineFactory; import org.apache.uima.fit.factory.CollectionReaderFactory; import org.apache.uima.fit.pipeline.SimplePipeline; import org.apache.uima.fit.util.JCasUtil;
/* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.statistics; /** * @author Ivan Habernal */ public class ClaimExamplesExplorer extends JCasConsumer_ImplBase { public static final String PARAM_RANDOM_CLAIMS_COUNT = "randomClaimsCount"; @ConfigurationParameter(name = PARAM_RANDOM_CLAIMS_COUNT, defaultValue = "50") int randomClaimsCount; public static final String PARAM_OUTPUT_FILE = "outputFile"; @ConfigurationParameter(name = PARAM_OUTPUT_FILE) File outputFile; /** * Random for reproducibility */ Random random = new Random(1234); SortedSet<String> allClaims = new TreeSet<>(); @Override public void process(JCas aJCas) throws AnalysisEngineProcessException { for (Sentence sentence : JCasUtil.select(aJCas, Sentence.class)) {
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/utils/ArgUtils.java // public class ArgUtils { // // // public static String getID(String s) { // String[] tmp = s.split("/"); // return tmp[tmp.length-1].replace(".xmi","").replace(".bin", ""); // } // // // public static String getID(File f) { // return getID(f.getName()); // } // // // public static boolean isClaim(Sentence s, JCas cas) { // return selectOverlapping(Claim.class, s, cas).size()>0 || selectOverlapping(MajorClaim.class, s, cas).size()>0; // } // // // public static boolean isPremise(Sentence s, JCas cas) { // return selectOverlapping(Premise.class, s, cas).size()>0; // } // // // public static <T extends TOP> List<T> selectOverlapping(Class<T> type,Annotation annotation, JCas jCas) { // Collection<T> allAnnotations = JCasUtil.select(jCas, type); // // List<T> result = new ArrayList<T>(); // // for (T a : allAnnotations) { // if ((a instanceof Annotation) && (doOverlap(annotation, (Annotation) a))) { // result.add(a); // } // } // // return result; // } // // // public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { // return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); // } // // // public static JCas readCas(File f) throws ResourceInitializationException, SAXException, IOException, CASException { // CAS loadedCas = CasCreationUtils.createCas(TypeSystemDescriptionFactory.createTypeSystemDescription(), null, null); // FileInputStream in = new FileInputStream(f); // XmiCasDeserializer.deserialize(in, loadedCas); // IOUtils.closeQuietly(in); // return loadedCas.getJCas(); // } // // public static void writeFile(String fileName, String content) throws Exception { // BufferedWriter br = new BufferedWriter(new FileWriter(new File(fileName))); // br.write(content); // br.close(); // } // // // } // Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/statistics/ClaimExamplesExplorer.java import org.apache.uima.jcas.JCas; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.*; import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.utils.ArgUtils; import de.tudarmstadt.ukp.dkpro.argumentation.io.writer.ArgumentDumpWriter; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import de.tudarmstadt.ukp.dkpro.core.io.xmi.XmiReader; import org.apache.commons.io.FileUtils; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.fit.component.JCasConsumer_ImplBase; import org.apache.uima.fit.descriptor.ConfigurationParameter; import org.apache.uima.fit.factory.AnalysisEngineFactory; import org.apache.uima.fit.factory.CollectionReaderFactory; import org.apache.uima.fit.pipeline.SimplePipeline; import org.apache.uima.fit.util.JCasUtil; /* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.statistics; /** * @author Ivan Habernal */ public class ClaimExamplesExplorer extends JCasConsumer_ImplBase { public static final String PARAM_RANDOM_CLAIMS_COUNT = "randomClaimsCount"; @ConfigurationParameter(name = PARAM_RANDOM_CLAIMS_COUNT, defaultValue = "50") int randomClaimsCount; public static final String PARAM_OUTPUT_FILE = "outputFile"; @ConfigurationParameter(name = PARAM_OUTPUT_FILE) File outputFile; /** * Random for reproducibility */ Random random = new Random(1234); SortedSet<String> allClaims = new TreeSet<>(); @Override public void process(JCas aJCas) throws AnalysisEngineProcessException { for (Sentence sentence : JCasUtil.select(aJCas, Sentence.class)) {
if (ArgUtils.isClaim(sentence, aJCas)) {
UKPLab/emnlp2017-claim-identification
src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/features/structural/LastComponentInParagraph.java
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/features/FeatureUtils.java // public class FeatureUtils { // // /** // * Returns a covering paragraph of an argument component // * @param classificationUnit // * @return // */ // public static Paragraph getCoveringParagraph(Annotation classificationUnit) { // Collection<Paragraph> sentences = JCasUtil.selectCovering(Paragraph.class, classificationUnit); // if (sentences.size()!=1) return null; // else return sentences.iterator().next(); // } // // /** // * Returns a covering sentence of an argument component // * @param classificationUnit // * @return // */ // public static Sentence getCoveringSentence(Annotation classificationUnit) { // Collection<Sentence> sentences = JCasUtil.selectCovering(Sentence.class, classificationUnit); // if (sentences.size()!=1) return null; // else return sentences.iterator().next(); // } // // /** // * Selects annotations with desired type ({@code type} parameter) that overlap the given // * {@code annotation}, such that at least a part of the selected annotations // * {@link #doOverlap(org.apache.uima.jcas.tcas.Annotation, org.apache.uima.jcas.tcas.Annotation)} // * with the given {@code annotation}. // * See {@code JCasUtil2Test.testSelectOverlapping()} for details. // * // * @param type desired type // * @param annotation current annotation for which the overlapping annotations are being selected // * @param jCas the JCas // * @return collection of overlapping annotations // */ // public static <T extends TOP> List<T> selectOverlapping(Class<T> type,Annotation annotation, JCas jCas) { // Collection<T> allAnnotations = JCasUtil.select(jCas, type); // // List<T> result = new ArrayList<T>(); // // for (T a : allAnnotations) { // if ((a instanceof Annotation) && (doOverlap(annotation, (Annotation) a))) { // result.add(a); // } // } // // return result; // } // // // // /** // * Returns whether the given annotations have a non-empty overlap. // * <p/> // * <p> // * Note that this method is symmetric. Two annotations overlap // * if they have at least one character position in common. // * Annotations that merely touch at the begin or end are not // * overlapping. // * <p/> // * <ul> // * <li>anno1[0,1], anno2[1,2] => no overlap</li> // * <li>anno1[0,2], anno2[1,2] => overlap</li> // * <li>anno1[0,2], anno2[0,2] => overlap (same span)</li> // * </ul> // * </p> // * // * @param anno1 first annotation // * @param anno2 second annotation // * @return whether the annotations overlap // */ // public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { // return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); // } // }
import java.util.Collection; import java.util.List; import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.features.FeatureUtils; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import de.tudarmstadt.ukp.dkpro.tc.api.exception.TextClassificationException; import de.tudarmstadt.ukp.dkpro.tc.api.features.ClassificationUnitFeatureExtractor; import de.tudarmstadt.ukp.dkpro.tc.api.features.Feature; import de.tudarmstadt.ukp.dkpro.tc.api.features.FeatureExtractorResource_ImplBase; import de.tudarmstadt.ukp.dkpro.tc.api.type.TextClassificationUnit; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import java.util.ArrayList;
/* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.features.structural; /** * * @author Christian Stab */ public class LastComponentInParagraph extends FeatureExtractorResource_ImplBase implements ClassificationUnitFeatureExtractor { public static final String FN_LAST_COMPONENT_IN_PARAGRAPH = "LastComponentInParagraph"; public List<Feature> extract(JCas jcas, TextClassificationUnit classificationUnit) throws TextClassificationException { List<Feature> featList = new ArrayList<Feature>();
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/features/FeatureUtils.java // public class FeatureUtils { // // /** // * Returns a covering paragraph of an argument component // * @param classificationUnit // * @return // */ // public static Paragraph getCoveringParagraph(Annotation classificationUnit) { // Collection<Paragraph> sentences = JCasUtil.selectCovering(Paragraph.class, classificationUnit); // if (sentences.size()!=1) return null; // else return sentences.iterator().next(); // } // // /** // * Returns a covering sentence of an argument component // * @param classificationUnit // * @return // */ // public static Sentence getCoveringSentence(Annotation classificationUnit) { // Collection<Sentence> sentences = JCasUtil.selectCovering(Sentence.class, classificationUnit); // if (sentences.size()!=1) return null; // else return sentences.iterator().next(); // } // // /** // * Selects annotations with desired type ({@code type} parameter) that overlap the given // * {@code annotation}, such that at least a part of the selected annotations // * {@link #doOverlap(org.apache.uima.jcas.tcas.Annotation, org.apache.uima.jcas.tcas.Annotation)} // * with the given {@code annotation}. // * See {@code JCasUtil2Test.testSelectOverlapping()} for details. // * // * @param type desired type // * @param annotation current annotation for which the overlapping annotations are being selected // * @param jCas the JCas // * @return collection of overlapping annotations // */ // public static <T extends TOP> List<T> selectOverlapping(Class<T> type,Annotation annotation, JCas jCas) { // Collection<T> allAnnotations = JCasUtil.select(jCas, type); // // List<T> result = new ArrayList<T>(); // // for (T a : allAnnotations) { // if ((a instanceof Annotation) && (doOverlap(annotation, (Annotation) a))) { // result.add(a); // } // } // // return result; // } // // // // /** // * Returns whether the given annotations have a non-empty overlap. // * <p/> // * <p> // * Note that this method is symmetric. Two annotations overlap // * if they have at least one character position in common. // * Annotations that merely touch at the begin or end are not // * overlapping. // * <p/> // * <ul> // * <li>anno1[0,1], anno2[1,2] => no overlap</li> // * <li>anno1[0,2], anno2[1,2] => overlap</li> // * <li>anno1[0,2], anno2[0,2] => overlap (same span)</li> // * </ul> // * </p> // * // * @param anno1 first annotation // * @param anno2 second annotation // * @return whether the annotations overlap // */ // public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { // return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); // } // } // Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/features/structural/LastComponentInParagraph.java import java.util.Collection; import java.util.List; import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.features.FeatureUtils; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import de.tudarmstadt.ukp.dkpro.tc.api.exception.TextClassificationException; import de.tudarmstadt.ukp.dkpro.tc.api.features.ClassificationUnitFeatureExtractor; import de.tudarmstadt.ukp.dkpro.tc.api.features.Feature; import de.tudarmstadt.ukp.dkpro.tc.api.features.FeatureExtractorResource_ImplBase; import de.tudarmstadt.ukp.dkpro.tc.api.type.TextClassificationUnit; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import java.util.ArrayList; /* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.features.structural; /** * * @author Christian Stab */ public class LastComponentInParagraph extends FeatureExtractorResource_ImplBase implements ClassificationUnitFeatureExtractor { public static final String FN_LAST_COMPONENT_IN_PARAGRAPH = "LastComponentInParagraph"; public List<Feature> extract(JCas jcas, TextClassificationUnit classificationUnit) throws TextClassificationException { List<Feature> featList = new ArrayList<Feature>();
Paragraph para = FeatureUtils.getCoveringParagraph(classificationUnit);
UKPLab/emnlp2017-claim-identification
src/main/java/de/tudarmstadt/ukp/dkpro/tc/ml/liblinear/LiblinearUtils.java
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/tc/ml/liblinear/LiblinearTestTask.java // public static final double EPISILON_DEFAULT = 0.01; // // Path: src/main/java/de/tudarmstadt/ukp/dkpro/tc/ml/liblinear/LiblinearTestTask.java // public static final double PARAM_C_DEFAULT = 1.0;
import de.bwaldvogel.liblinear.SolverType; import org.apache.commons.logging.LogFactory; import java.io.*; import java.util.*; import java.util.Map.Entry; import static de.tudarmstadt.ukp.dkpro.tc.ml.liblinear.LiblinearTestTask.EPISILON_DEFAULT; import static de.tudarmstadt.ukp.dkpro.tc.ml.liblinear.LiblinearTestTask.PARAM_C_DEFAULT;
break; case "11": type = SolverType.L2R_L2LOSS_SVR; break; case "12": type = SolverType.L2R_L2LOSS_SVR_DUAL; break; case "13": type = SolverType.L2R_L1LOSS_SVR_DUAL; break; default: throw new IllegalArgumentException("An unknown solver was specified [" + algo + "] which is unknown i.e. check parameter [-s] in your configuration"); } } } if (type == null) { // parameter -s was not specified in the parameters so we set a default value type = SolverType.L2R_LR; } LogFactory.getLog(LiblinearUtils.class).info("Will use solver " + type.toString() + ")"); return type; } public static double getParameterC(List<String> classificationArguments) { if (classificationArguments == null) {
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/tc/ml/liblinear/LiblinearTestTask.java // public static final double EPISILON_DEFAULT = 0.01; // // Path: src/main/java/de/tudarmstadt/ukp/dkpro/tc/ml/liblinear/LiblinearTestTask.java // public static final double PARAM_C_DEFAULT = 1.0; // Path: src/main/java/de/tudarmstadt/ukp/dkpro/tc/ml/liblinear/LiblinearUtils.java import de.bwaldvogel.liblinear.SolverType; import org.apache.commons.logging.LogFactory; import java.io.*; import java.util.*; import java.util.Map.Entry; import static de.tudarmstadt.ukp.dkpro.tc.ml.liblinear.LiblinearTestTask.EPISILON_DEFAULT; import static de.tudarmstadt.ukp.dkpro.tc.ml.liblinear.LiblinearTestTask.PARAM_C_DEFAULT; break; case "11": type = SolverType.L2R_L2LOSS_SVR; break; case "12": type = SolverType.L2R_L2LOSS_SVR_DUAL; break; case "13": type = SolverType.L2R_L1LOSS_SVR_DUAL; break; default: throw new IllegalArgumentException("An unknown solver was specified [" + algo + "] which is unknown i.e. check parameter [-s] in your configuration"); } } } if (type == null) { // parameter -s was not specified in the parameters so we set a default value type = SolverType.L2R_LR; } LogFactory.getLog(LiblinearUtils.class).info("Will use solver " + type.toString() + ")"); return type; } public static double getParameterC(List<String> classificationArguments) { if (classificationArguments == null) {
return PARAM_C_DEFAULT;
UKPLab/emnlp2017-claim-identification
src/main/java/de/tudarmstadt/ukp/dkpro/tc/ml/liblinear/LiblinearUtils.java
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/tc/ml/liblinear/LiblinearTestTask.java // public static final double EPISILON_DEFAULT = 0.01; // // Path: src/main/java/de/tudarmstadt/ukp/dkpro/tc/ml/liblinear/LiblinearTestTask.java // public static final double PARAM_C_DEFAULT = 1.0;
import de.bwaldvogel.liblinear.SolverType; import org.apache.commons.logging.LogFactory; import java.io.*; import java.util.*; import java.util.Map.Entry; import static de.tudarmstadt.ukp.dkpro.tc.ml.liblinear.LiblinearTestTask.EPISILON_DEFAULT; import static de.tudarmstadt.ukp.dkpro.tc.ml.liblinear.LiblinearTestTask.PARAM_C_DEFAULT;
for (int i = 0; i < classificationArguments.size(); i++) { String e = classificationArguments.get(i); if (e.equals("-c")) { if (i + 1 >= classificationArguments.size()) { throw new IllegalArgumentException( "Found parameter [-c] but no value was specified"); } Double value; try { value = Double.valueOf(classificationArguments.get(i + 1)); } catch (NumberFormatException ex) { throw new IllegalArgumentException( "The value of parameter -c has to be a floating point value but was [" + classificationArguments.get(i + 1) + "]", ex); } return value; } } LogFactory.getLog(LiblinearUtils.class) .info("Parameter c is set to default value [" + PARAM_C_DEFAULT + "]"); return PARAM_C_DEFAULT; } public static double getParameterEpsilon(List<String> classificationArguments) { if (classificationArguments == null) {
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/tc/ml/liblinear/LiblinearTestTask.java // public static final double EPISILON_DEFAULT = 0.01; // // Path: src/main/java/de/tudarmstadt/ukp/dkpro/tc/ml/liblinear/LiblinearTestTask.java // public static final double PARAM_C_DEFAULT = 1.0; // Path: src/main/java/de/tudarmstadt/ukp/dkpro/tc/ml/liblinear/LiblinearUtils.java import de.bwaldvogel.liblinear.SolverType; import org.apache.commons.logging.LogFactory; import java.io.*; import java.util.*; import java.util.Map.Entry; import static de.tudarmstadt.ukp.dkpro.tc.ml.liblinear.LiblinearTestTask.EPISILON_DEFAULT; import static de.tudarmstadt.ukp.dkpro.tc.ml.liblinear.LiblinearTestTask.PARAM_C_DEFAULT; for (int i = 0; i < classificationArguments.size(); i++) { String e = classificationArguments.get(i); if (e.equals("-c")) { if (i + 1 >= classificationArguments.size()) { throw new IllegalArgumentException( "Found parameter [-c] but no value was specified"); } Double value; try { value = Double.valueOf(classificationArguments.get(i + 1)); } catch (NumberFormatException ex) { throw new IllegalArgumentException( "The value of parameter -c has to be a floating point value but was [" + classificationArguments.get(i + 1) + "]", ex); } return value; } } LogFactory.getLog(LiblinearUtils.class) .info("Parameter c is set to default value [" + PARAM_C_DEFAULT + "]"); return PARAM_C_DEFAULT; } public static double getParameterEpsilon(List<String> classificationArguments) { if (classificationArguments == null) {
return EPISILON_DEFAULT;
UKPLab/emnlp2017-claim-identification
src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/features/syntactic/DependencyTriples.java
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/features/syntactic/utils/DependencyTriplesMC.java // public class DependencyTriplesMC extends FreqDistBasedMetaCollector { // // // public static final String DEPENDENCIES_FD_KEY = "depTripleFdFile.ser"; // // @ConfigurationParameter(name = DependencyTriples.PARAM_DEPENDENCY_TRIPLE_FD_FILE, mandatory = true) // // private File depTripleFdFile; // // // public static final String PARAM_DEPENDENCY_TRIPLE_FD_FILE = "depTripleFdFile"; // @ConfigurationParameter(name = PARAM_DEPENDENCY_TRIPLE_FD_FILE, mandatory = true) // private File depTripleFdFile; // // @Override // public void initialize(UimaContext context) throws ResourceInitializationException { // super.initialize(context); // // } // // // @Override // public void process(JCas jcas) throws AnalysisEngineProcessException { // FrequencyDistribution<String> foundDependencies = new FrequencyDistribution<String>(); // // Collection<Dependency> dependencies = JCasUtil.select(jcas, Dependency.class); // // for (Dependency dep : dependencies) { // // // lemma with type // String dependency = dep.getDependencyType()+ ":" + dep.getGovernor().getLemma().getValue()+"_"+dep.getDependent().getLemma().getValue(); // // foundDependencies.addSample(dependency, foundDependencies.getCount(dependency)+1); // } // // for (String ngram : foundDependencies.getKeys()) { // fd.addSample(ngram, foundDependencies.getCount(ngram)); // } // } // // @Override // public Map<String, String> getParameterKeyPairs() { // Map<String, String> mapping = new HashMap<String, String>(); // mapping.put(DependencyTriples.PARAM_DEPENDENCY_TRIPLE_FD_FILE, PARAM_DEPENDENCY_TRIPLE_FD_FILE); // return mapping; // } // // @Override // protected File getFreqDistFile() { // return depTripleFdFile; // } // }
import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; import org.apache.uima.resource.ResourceSpecifier; import java.io.File; import java.util.*; import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.features.syntactic.utils.DependencyTriplesMC; import de.tudarmstadt.ukp.dkpro.core.api.frequency.util.FrequencyDistribution; import de.tudarmstadt.ukp.dkpro.core.api.syntax.type.dependency.Dependency; import de.tudarmstadt.ukp.dkpro.tc.api.exception.TextClassificationException; import de.tudarmstadt.ukp.dkpro.tc.api.features.ClassificationUnitFeatureExtractor; import de.tudarmstadt.ukp.dkpro.tc.api.features.Feature; import de.tudarmstadt.ukp.dkpro.tc.api.features.FeatureExtractorResource_ImplBase; import de.tudarmstadt.ukp.dkpro.tc.api.features.meta.MetaCollector; import de.tudarmstadt.ukp.dkpro.tc.api.features.meta.MetaDependent; import de.tudarmstadt.ukp.dkpro.tc.api.type.TextClassificationUnit; import org.apache.uima.fit.descriptor.ConfigurationParameter; import org.apache.uima.fit.util.JCasUtil;
trainingFD = new FrequencyDistribution<String>(); trainingFD.load(new File(depTripleFdFile)); } catch (Exception e) { throw new ResourceInitializationException(e); } topKDeps = new FrequencyDistribution<String>(); if (numberOfDependencyTriples==-1) { // consider all samples for (String sample : trainingFD.getKeys()) { topKDeps.addSample(sample, trainingFD.getCount(sample)); } } else { // consider a given number of samples List<String> topK = trainingFD.getMostFrequentSamples(numberOfDependencyTriples); for (String sample : topK) { topKDeps.addSample(sample, trainingFD.getCount(sample)); } } getLogger().info("Loaded " + topKDeps.getKeys().size() + " dependencies for feature extraction"); return true; } public List<Class<? extends MetaCollector>> getMetaCollectorClasses() { List<Class<? extends MetaCollector>> metaCollectorClasses = new ArrayList<Class<? extends MetaCollector>>();
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/features/syntactic/utils/DependencyTriplesMC.java // public class DependencyTriplesMC extends FreqDistBasedMetaCollector { // // // public static final String DEPENDENCIES_FD_KEY = "depTripleFdFile.ser"; // // @ConfigurationParameter(name = DependencyTriples.PARAM_DEPENDENCY_TRIPLE_FD_FILE, mandatory = true) // // private File depTripleFdFile; // // // public static final String PARAM_DEPENDENCY_TRIPLE_FD_FILE = "depTripleFdFile"; // @ConfigurationParameter(name = PARAM_DEPENDENCY_TRIPLE_FD_FILE, mandatory = true) // private File depTripleFdFile; // // @Override // public void initialize(UimaContext context) throws ResourceInitializationException { // super.initialize(context); // // } // // // @Override // public void process(JCas jcas) throws AnalysisEngineProcessException { // FrequencyDistribution<String> foundDependencies = new FrequencyDistribution<String>(); // // Collection<Dependency> dependencies = JCasUtil.select(jcas, Dependency.class); // // for (Dependency dep : dependencies) { // // // lemma with type // String dependency = dep.getDependencyType()+ ":" + dep.getGovernor().getLemma().getValue()+"_"+dep.getDependent().getLemma().getValue(); // // foundDependencies.addSample(dependency, foundDependencies.getCount(dependency)+1); // } // // for (String ngram : foundDependencies.getKeys()) { // fd.addSample(ngram, foundDependencies.getCount(ngram)); // } // } // // @Override // public Map<String, String> getParameterKeyPairs() { // Map<String, String> mapping = new HashMap<String, String>(); // mapping.put(DependencyTriples.PARAM_DEPENDENCY_TRIPLE_FD_FILE, PARAM_DEPENDENCY_TRIPLE_FD_FILE); // return mapping; // } // // @Override // protected File getFreqDistFile() { // return depTripleFdFile; // } // } // Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/features/syntactic/DependencyTriples.java import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; import org.apache.uima.resource.ResourceSpecifier; import java.io.File; import java.util.*; import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.features.syntactic.utils.DependencyTriplesMC; import de.tudarmstadt.ukp.dkpro.core.api.frequency.util.FrequencyDistribution; import de.tudarmstadt.ukp.dkpro.core.api.syntax.type.dependency.Dependency; import de.tudarmstadt.ukp.dkpro.tc.api.exception.TextClassificationException; import de.tudarmstadt.ukp.dkpro.tc.api.features.ClassificationUnitFeatureExtractor; import de.tudarmstadt.ukp.dkpro.tc.api.features.Feature; import de.tudarmstadt.ukp.dkpro.tc.api.features.FeatureExtractorResource_ImplBase; import de.tudarmstadt.ukp.dkpro.tc.api.features.meta.MetaCollector; import de.tudarmstadt.ukp.dkpro.tc.api.features.meta.MetaDependent; import de.tudarmstadt.ukp.dkpro.tc.api.type.TextClassificationUnit; import org.apache.uima.fit.descriptor.ConfigurationParameter; import org.apache.uima.fit.util.JCasUtil; trainingFD = new FrequencyDistribution<String>(); trainingFD.load(new File(depTripleFdFile)); } catch (Exception e) { throw new ResourceInitializationException(e); } topKDeps = new FrequencyDistribution<String>(); if (numberOfDependencyTriples==-1) { // consider all samples for (String sample : trainingFD.getKeys()) { topKDeps.addSample(sample, trainingFD.getCount(sample)); } } else { // consider a given number of samples List<String> topK = trainingFD.getMostFrequentSamples(numberOfDependencyTriples); for (String sample : topK) { topKDeps.addSample(sample, trainingFD.getCount(sample)); } } getLogger().info("Loaded " + topKDeps.getKeys().size() + " dependencies for feature extraction"); return true; } public List<Class<? extends MetaCollector>> getMetaCollectorClasses() { List<Class<? extends MetaCollector>> metaCollectorClasses = new ArrayList<Class<? extends MetaCollector>>();
metaCollectorClasses.add(DependencyTriplesMC.class);
UKPLab/emnlp2017-claim-identification
src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/io/SentenceOutput.java
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/utils/ArgUtils.java // public class ArgUtils { // // // public static String getID(String s) { // String[] tmp = s.split("/"); // return tmp[tmp.length-1].replace(".xmi","").replace(".bin", ""); // } // // // public static String getID(File f) { // return getID(f.getName()); // } // // // public static boolean isClaim(Sentence s, JCas cas) { // return selectOverlapping(Claim.class, s, cas).size()>0 || selectOverlapping(MajorClaim.class, s, cas).size()>0; // } // // // public static boolean isPremise(Sentence s, JCas cas) { // return selectOverlapping(Premise.class, s, cas).size()>0; // } // // // public static <T extends TOP> List<T> selectOverlapping(Class<T> type,Annotation annotation, JCas jCas) { // Collection<T> allAnnotations = JCasUtil.select(jCas, type); // // List<T> result = new ArrayList<T>(); // // for (T a : allAnnotations) { // if ((a instanceof Annotation) && (doOverlap(annotation, (Annotation) a))) { // result.add(a); // } // } // // return result; // } // // // public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { // return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); // } // // // public static JCas readCas(File f) throws ResourceInitializationException, SAXException, IOException, CASException { // CAS loadedCas = CasCreationUtils.createCas(TypeSystemDescriptionFactory.createTypeSystemDescription(), null, null); // FileInputStream in = new FileInputStream(f); // XmiCasDeserializer.deserialize(in, loadedCas); // IOUtils.closeQuietly(in); // return loadedCas.getJCas(); // } // // public static void writeFile(String fileName, String content) throws Exception { // BufferedWriter br = new BufferedWriter(new FileWriter(new File(fileName))); // br.write(content); // br.close(); // } // // // }
import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.utils.ArgUtils; import de.tudarmstadt.ukp.dkpro.core.api.metadata.type.DocumentMetaData; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Collection;
/* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.dkpro.argumentation.io; public class SentenceOutput { private static final String path = "/Users/zemes/Desktop/NLP/Papers/TACL2016/data/prep3/WTP"; private static final String output = "/Users/zemes/Desktop/NLP/Papers/TACL2016/data/prep3/WTP.tsv"; public static void main(String[] args) throws Exception { File dir = new File(path); double numSentences = 0.0; StringBuilder sb = new StringBuilder(); for (File f : dir.listFiles()) { if (!f.getName().endsWith(".xmi")) continue; //System.out.println(f.getName());
// Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/crossdomainclaims/utils/ArgUtils.java // public class ArgUtils { // // // public static String getID(String s) { // String[] tmp = s.split("/"); // return tmp[tmp.length-1].replace(".xmi","").replace(".bin", ""); // } // // // public static String getID(File f) { // return getID(f.getName()); // } // // // public static boolean isClaim(Sentence s, JCas cas) { // return selectOverlapping(Claim.class, s, cas).size()>0 || selectOverlapping(MajorClaim.class, s, cas).size()>0; // } // // // public static boolean isPremise(Sentence s, JCas cas) { // return selectOverlapping(Premise.class, s, cas).size()>0; // } // // // public static <T extends TOP> List<T> selectOverlapping(Class<T> type,Annotation annotation, JCas jCas) { // Collection<T> allAnnotations = JCasUtil.select(jCas, type); // // List<T> result = new ArrayList<T>(); // // for (T a : allAnnotations) { // if ((a instanceof Annotation) && (doOverlap(annotation, (Annotation) a))) { // result.add(a); // } // } // // return result; // } // // // public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { // return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); // } // // // public static JCas readCas(File f) throws ResourceInitializationException, SAXException, IOException, CASException { // CAS loadedCas = CasCreationUtils.createCas(TypeSystemDescriptionFactory.createTypeSystemDescription(), null, null); // FileInputStream in = new FileInputStream(f); // XmiCasDeserializer.deserialize(in, loadedCas); // IOUtils.closeQuietly(in); // return loadedCas.getJCas(); // } // // public static void writeFile(String fileName, String content) throws Exception { // BufferedWriter br = new BufferedWriter(new FileWriter(new File(fileName))); // br.write(content); // br.close(); // } // // // } // Path: src/main/java/de/tudarmstadt/ukp/dkpro/argumentation/io/SentenceOutput.java import de.tudarmstadt.ukp.dkpro.argumentation.crossdomainclaims.utils.ArgUtils; import de.tudarmstadt.ukp.dkpro.core.api.metadata.type.DocumentMetaData; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Collection; /* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.dkpro.argumentation.io; public class SentenceOutput { private static final String path = "/Users/zemes/Desktop/NLP/Papers/TACL2016/data/prep3/WTP"; private static final String output = "/Users/zemes/Desktop/NLP/Papers/TACL2016/data/prep3/WTP.tsv"; public static void main(String[] args) throws Exception { File dir = new File(path); double numSentences = 0.0; StringBuilder sb = new StringBuilder(); for (File f : dir.listFiles()) { if (!f.getName().endsWith(".xmi")) continue; //System.out.println(f.getName());
JCas cas = ArgUtils.readCas(f);
lukas-krecan/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/GenericNodeBuilder.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Boolean> toBoolList(boolean[] source) { // List<Boolean> result = new ArrayList<>(source.length); // for (boolean value : source) { // result.add(value); // } // return result; // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Double> toDoubleList(double[] source) { // return Arrays.stream(source).boxed().collect(toList()); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Integer> toIntList(int[] source) { // return Arrays.stream(source).boxed().collect(toList()); // }
import org.jetbrains.annotations.NotNull; import java.math.BigDecimal; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toBoolList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toDoubleList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toIntList;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; class GenericNodeBuilder implements NodeBuilder { private static final GenericNodeBuilder INSTANCE = new GenericNodeBuilder(); static Node wrapDeserializedObject(Object object) { return INSTANCE.newNode(object); } @Override @SuppressWarnings("unchecked") public Node newNode(Object object) { if (object == null) { return new NullNode(); } else if (object instanceof Map) { return new ObjectNode((Map<String, Object>) object, this); } else if (object instanceof Number) { return new NumberNode((Number) object); } else if (object instanceof String) { return new StringNode((String) object); } else if (object instanceof Boolean) { return new BooleanNode((Boolean) object); } else if (object instanceof Object[]) { return new ArrayNode(Arrays.asList((Object[]) object), this); } else if (object instanceof int[]) {
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Boolean> toBoolList(boolean[] source) { // List<Boolean> result = new ArrayList<>(source.length); // for (boolean value : source) { // result.add(value); // } // return result; // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Double> toDoubleList(double[] source) { // return Arrays.stream(source).boxed().collect(toList()); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Integer> toIntList(int[] source) { // return Arrays.stream(source).boxed().collect(toList()); // } // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/GenericNodeBuilder.java import org.jetbrains.annotations.NotNull; import java.math.BigDecimal; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toBoolList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toDoubleList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toIntList; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; class GenericNodeBuilder implements NodeBuilder { private static final GenericNodeBuilder INSTANCE = new GenericNodeBuilder(); static Node wrapDeserializedObject(Object object) { return INSTANCE.newNode(object); } @Override @SuppressWarnings("unchecked") public Node newNode(Object object) { if (object == null) { return new NullNode(); } else if (object instanceof Map) { return new ObjectNode((Map<String, Object>) object, this); } else if (object instanceof Number) { return new NumberNode((Number) object); } else if (object instanceof String) { return new StringNode((String) object); } else if (object instanceof Boolean) { return new BooleanNode((Boolean) object); } else if (object instanceof Object[]) { return new ArrayNode(Arrays.asList((Object[]) object), this); } else if (object instanceof int[]) {
return new ArrayNode(toIntList((int[]) object), this);
lukas-krecan/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/GenericNodeBuilder.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Boolean> toBoolList(boolean[] source) { // List<Boolean> result = new ArrayList<>(source.length); // for (boolean value : source) { // result.add(value); // } // return result; // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Double> toDoubleList(double[] source) { // return Arrays.stream(source).boxed().collect(toList()); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Integer> toIntList(int[] source) { // return Arrays.stream(source).boxed().collect(toList()); // }
import org.jetbrains.annotations.NotNull; import java.math.BigDecimal; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toBoolList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toDoubleList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toIntList;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; class GenericNodeBuilder implements NodeBuilder { private static final GenericNodeBuilder INSTANCE = new GenericNodeBuilder(); static Node wrapDeserializedObject(Object object) { return INSTANCE.newNode(object); } @Override @SuppressWarnings("unchecked") public Node newNode(Object object) { if (object == null) { return new NullNode(); } else if (object instanceof Map) { return new ObjectNode((Map<String, Object>) object, this); } else if (object instanceof Number) { return new NumberNode((Number) object); } else if (object instanceof String) { return new StringNode((String) object); } else if (object instanceof Boolean) { return new BooleanNode((Boolean) object); } else if (object instanceof Object[]) { return new ArrayNode(Arrays.asList((Object[]) object), this); } else if (object instanceof int[]) { return new ArrayNode(toIntList((int[]) object), this); } else if (object instanceof double[]) {
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Boolean> toBoolList(boolean[] source) { // List<Boolean> result = new ArrayList<>(source.length); // for (boolean value : source) { // result.add(value); // } // return result; // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Double> toDoubleList(double[] source) { // return Arrays.stream(source).boxed().collect(toList()); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Integer> toIntList(int[] source) { // return Arrays.stream(source).boxed().collect(toList()); // } // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/GenericNodeBuilder.java import org.jetbrains.annotations.NotNull; import java.math.BigDecimal; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toBoolList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toDoubleList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toIntList; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; class GenericNodeBuilder implements NodeBuilder { private static final GenericNodeBuilder INSTANCE = new GenericNodeBuilder(); static Node wrapDeserializedObject(Object object) { return INSTANCE.newNode(object); } @Override @SuppressWarnings("unchecked") public Node newNode(Object object) { if (object == null) { return new NullNode(); } else if (object instanceof Map) { return new ObjectNode((Map<String, Object>) object, this); } else if (object instanceof Number) { return new NumberNode((Number) object); } else if (object instanceof String) { return new StringNode((String) object); } else if (object instanceof Boolean) { return new BooleanNode((Boolean) object); } else if (object instanceof Object[]) { return new ArrayNode(Arrays.asList((Object[]) object), this); } else if (object instanceof int[]) { return new ArrayNode(toIntList((int[]) object), this); } else if (object instanceof double[]) {
return new ArrayNode(toDoubleList((double[]) object), this);
lukas-krecan/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/GenericNodeBuilder.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Boolean> toBoolList(boolean[] source) { // List<Boolean> result = new ArrayList<>(source.length); // for (boolean value : source) { // result.add(value); // } // return result; // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Double> toDoubleList(double[] source) { // return Arrays.stream(source).boxed().collect(toList()); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Integer> toIntList(int[] source) { // return Arrays.stream(source).boxed().collect(toList()); // }
import org.jetbrains.annotations.NotNull; import java.math.BigDecimal; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toBoolList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toDoubleList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toIntList;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; class GenericNodeBuilder implements NodeBuilder { private static final GenericNodeBuilder INSTANCE = new GenericNodeBuilder(); static Node wrapDeserializedObject(Object object) { return INSTANCE.newNode(object); } @Override @SuppressWarnings("unchecked") public Node newNode(Object object) { if (object == null) { return new NullNode(); } else if (object instanceof Map) { return new ObjectNode((Map<String, Object>) object, this); } else if (object instanceof Number) { return new NumberNode((Number) object); } else if (object instanceof String) { return new StringNode((String) object); } else if (object instanceof Boolean) { return new BooleanNode((Boolean) object); } else if (object instanceof Object[]) { return new ArrayNode(Arrays.asList((Object[]) object), this); } else if (object instanceof int[]) { return new ArrayNode(toIntList((int[]) object), this); } else if (object instanceof double[]) { return new ArrayNode(toDoubleList((double[]) object), this); } else if (object instanceof boolean[]) {
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Boolean> toBoolList(boolean[] source) { // List<Boolean> result = new ArrayList<>(source.length); // for (boolean value : source) { // result.add(value); // } // return result; // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Double> toDoubleList(double[] source) { // return Arrays.stream(source).boxed().collect(toList()); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Integer> toIntList(int[] source) { // return Arrays.stream(source).boxed().collect(toList()); // } // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/GenericNodeBuilder.java import org.jetbrains.annotations.NotNull; import java.math.BigDecimal; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toBoolList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toDoubleList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toIntList; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; class GenericNodeBuilder implements NodeBuilder { private static final GenericNodeBuilder INSTANCE = new GenericNodeBuilder(); static Node wrapDeserializedObject(Object object) { return INSTANCE.newNode(object); } @Override @SuppressWarnings("unchecked") public Node newNode(Object object) { if (object == null) { return new NullNode(); } else if (object instanceof Map) { return new ObjectNode((Map<String, Object>) object, this); } else if (object instanceof Number) { return new NumberNode((Number) object); } else if (object instanceof String) { return new StringNode((String) object); } else if (object instanceof Boolean) { return new BooleanNode((Boolean) object); } else if (object instanceof Object[]) { return new ArrayNode(Arrays.asList((Object[]) object), this); } else if (object instanceof int[]) { return new ArrayNode(toIntList((int[]) object), this); } else if (object instanceof double[]) { return new ArrayNode(toDoubleList((double[]) object), this); } else if (object instanceof boolean[]) {
return new ArrayNode(toBoolList((boolean[]) object), this);
lukas-krecan/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Converter.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ClassUtils.java // static boolean isClassPresent(String className) { // try { // ClassUtils.class.getClassLoader().loadClass(className); // return true; // } catch (Throwable e) { // return false; // } // }
import java.util.ArrayList; import java.util.List; import static net.javacrumbs.jsonunit.core.internal.ClassUtils.isClassPresent;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; /** * Converts object to Node using {@link net.javacrumbs.jsonunit.core.internal.NodeFactory}. */ class Converter { static final String LIBRARIES_PROPERTY_NAME = "json-unit.libraries"; private final List<NodeFactory> factories; private static final boolean jackson2Present =
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ClassUtils.java // static boolean isClassPresent(String className) { // try { // ClassUtils.class.getClassLoader().loadClass(className); // return true; // } catch (Throwable e) { // return false; // } // } // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Converter.java import java.util.ArrayList; import java.util.List; import static net.javacrumbs.jsonunit.core.internal.ClassUtils.isClassPresent; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; /** * Converts object to Node using {@link net.javacrumbs.jsonunit.core.internal.NodeFactory}. */ class Converter { static final String LIBRARIES_PROPERTY_NAME = "json-unit.libraries"; private final List<NodeFactory> factories; private static final boolean jackson2Present =
isClassPresent("com.fasterxml.jackson.databind.ObjectMapper") &&
lukas-krecan/JsonUnit
json-unit-json-path/src/test/java/net/javacrumbs/jsonunit/jsonpath/InternalJsonPathUtilsTest.java
// Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/InternalJsonPathUtils.java // static String fromBracketNotation(String path) { // return path // .replace("['", ".") // .replace("']", ""); // }
import org.junit.jupiter.api.Test; import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.fromBracketNotation; import static org.assertj.core.api.Assertions.assertThat;
package net.javacrumbs.jsonunit.jsonpath; class InternalJsonPathUtilsTest { @Test void shouldConvertFromBracketNotation() {
// Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/InternalJsonPathUtils.java // static String fromBracketNotation(String path) { // return path // .replace("['", ".") // .replace("']", ""); // } // Path: json-unit-json-path/src/test/java/net/javacrumbs/jsonunit/jsonpath/InternalJsonPathUtilsTest.java import org.junit.jupiter.api.Test; import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.fromBracketNotation; import static org.assertj.core.api.Assertions.assertThat; package net.javacrumbs.jsonunit.jsonpath; class InternalJsonPathUtilsTest { @Test void shouldConvertFromBracketNotation() {
assertThat(fromBracketNotation("$['tool']['jsonpath'][2]")).isEqualTo("$.tool.jsonpath[2]");
lukas-krecan/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/MoshiNodeFactory.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static void closeQuietly(final Reader resourceReader) { // if (resourceReader != null) { // try { // resourceReader.close(); // } catch (IOException ignored) { // } // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static Reader toReader(String string) { // return new JsonStringReader(string); // }
import com.squareup.moshi.JsonAdapter; import com.squareup.moshi.Moshi; import java.io.IOException; import java.io.Reader; import java.math.BigDecimal; import java.math.RoundingMode; import static net.javacrumbs.jsonunit.core.internal.Utils.closeQuietly; import static net.javacrumbs.jsonunit.core.internal.Utils.toReader;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; /** * Deserializes node using Moshi */ class MoshiNodeFactory extends AbstractNodeFactory { private static final Moshi moshi = new Moshi.Builder().build(); private static final NodeBuilder moshiNodeBuilder = new MoshiNodeBuilder(); @Override protected Node doConvertValue(Object source) { return newNode(source); } @Override protected Node nullNode() { return newNode(null); } @Override protected Node readValue(String source, String label, boolean lenient) { try { JsonAdapter<Object> adapter = moshi.adapter(Object.class); if (lenient) { adapter = adapter.lenient(); } return newNode(adapter.fromJson(source)); } catch (IOException e) {
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static void closeQuietly(final Reader resourceReader) { // if (resourceReader != null) { // try { // resourceReader.close(); // } catch (IOException ignored) { // } // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static Reader toReader(String string) { // return new JsonStringReader(string); // } // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/MoshiNodeFactory.java import com.squareup.moshi.JsonAdapter; import com.squareup.moshi.Moshi; import java.io.IOException; import java.io.Reader; import java.math.BigDecimal; import java.math.RoundingMode; import static net.javacrumbs.jsonunit.core.internal.Utils.closeQuietly; import static net.javacrumbs.jsonunit.core.internal.Utils.toReader; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; /** * Deserializes node using Moshi */ class MoshiNodeFactory extends AbstractNodeFactory { private static final Moshi moshi = new Moshi.Builder().build(); private static final NodeBuilder moshiNodeBuilder = new MoshiNodeBuilder(); @Override protected Node doConvertValue(Object source) { return newNode(source); } @Override protected Node nullNode() { return newNode(null); } @Override protected Node readValue(String source, String label, boolean lenient) { try { JsonAdapter<Object> adapter = moshi.adapter(Object.class); if (lenient) { adapter = adapter.lenient(); } return newNode(adapter.fromJson(source)); } catch (IOException e) {
throw newParseException(label, toReader(source), e);
lukas-krecan/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/MoshiNodeFactory.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static void closeQuietly(final Reader resourceReader) { // if (resourceReader != null) { // try { // resourceReader.close(); // } catch (IOException ignored) { // } // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static Reader toReader(String string) { // return new JsonStringReader(string); // }
import com.squareup.moshi.JsonAdapter; import com.squareup.moshi.Moshi; import java.io.IOException; import java.io.Reader; import java.math.BigDecimal; import java.math.RoundingMode; import static net.javacrumbs.jsonunit.core.internal.Utils.closeQuietly; import static net.javacrumbs.jsonunit.core.internal.Utils.toReader;
@Override protected Node doConvertValue(Object source) { return newNode(source); } @Override protected Node nullNode() { return newNode(null); } @Override protected Node readValue(String source, String label, boolean lenient) { try { JsonAdapter<Object> adapter = moshi.adapter(Object.class); if (lenient) { adapter = adapter.lenient(); } return newNode(adapter.fromJson(source)); } catch (IOException e) { throw newParseException(label, toReader(source), e); } } @Override protected Node readValue(Reader value, String label, boolean lenient) { try { return readValue(Utils.readAsString(value), label, lenient); } catch (IOException e) { throw new IllegalArgumentException("Can not parse " + label + " value.", e); } finally {
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static void closeQuietly(final Reader resourceReader) { // if (resourceReader != null) { // try { // resourceReader.close(); // } catch (IOException ignored) { // } // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static Reader toReader(String string) { // return new JsonStringReader(string); // } // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/MoshiNodeFactory.java import com.squareup.moshi.JsonAdapter; import com.squareup.moshi.Moshi; import java.io.IOException; import java.io.Reader; import java.math.BigDecimal; import java.math.RoundingMode; import static net.javacrumbs.jsonunit.core.internal.Utils.closeQuietly; import static net.javacrumbs.jsonunit.core.internal.Utils.toReader; @Override protected Node doConvertValue(Object source) { return newNode(source); } @Override protected Node nullNode() { return newNode(null); } @Override protected Node readValue(String source, String label, boolean lenient) { try { JsonAdapter<Object> adapter = moshi.adapter(Object.class); if (lenient) { adapter = adapter.lenient(); } return newNode(adapter.fromJson(source)); } catch (IOException e) { throw newParseException(label, toReader(source), e); } } @Override protected Node readValue(Reader value, String label, boolean lenient) { try { return readValue(Utils.readAsString(value), label, lenient); } catch (IOException e) { throw new IllegalArgumentException("Can not parse " + label + " value.", e); } finally {
closeQuietly(value);
lukas-krecan/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Jackson2NodeFactory.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/providers/Jackson2ObjectMapperProvider.java // public interface Jackson2ObjectMapperProvider { // /** // * Provides ObjectMapper // * @param lenient Lenient parsing is used for parsing the expected JSON value // * @return customized ObjectMapper. // */ // ObjectMapper getObjectMapper(boolean lenient); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static void closeQuietly(final Reader resourceReader) { // if (resourceReader != null) { // try { // resourceReader.close(); // } catch (IOException ignored) { // } // } // }
import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.NullNode; import net.javacrumbs.jsonunit.providers.Jackson2ObjectMapperProvider; import java.io.IOException; import java.io.Reader; import java.math.BigDecimal; import java.util.Iterator; import java.util.Map; import java.util.ServiceLoader; import static net.javacrumbs.jsonunit.core.internal.Utils.closeQuietly;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; /** * Deserializes node using Jackson 2 */ class Jackson2NodeFactory extends AbstractNodeFactory { private final ServiceLoader<Jackson2ObjectMapperProvider> serviceLoader = ServiceLoader.load(Jackson2ObjectMapperProvider.class); @Override protected Node doConvertValue(Object source) { if (source instanceof JsonNode) { return newNode((JsonNode) source); } else { return newNode(getMapper(false).convertValue(source, JsonNode.class)); } } @Override protected Node nullNode() { return newNode(NullNode.getInstance()); } @Override protected Node readValue(Reader value, String label, boolean lenient) { try { return newNode(getMapper(lenient).readTree(value)); } catch (IOException e) { throw newParseException(label, value, e); } finally {
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/providers/Jackson2ObjectMapperProvider.java // public interface Jackson2ObjectMapperProvider { // /** // * Provides ObjectMapper // * @param lenient Lenient parsing is used for parsing the expected JSON value // * @return customized ObjectMapper. // */ // ObjectMapper getObjectMapper(boolean lenient); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static void closeQuietly(final Reader resourceReader) { // if (resourceReader != null) { // try { // resourceReader.close(); // } catch (IOException ignored) { // } // } // } // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Jackson2NodeFactory.java import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.NullNode; import net.javacrumbs.jsonunit.providers.Jackson2ObjectMapperProvider; import java.io.IOException; import java.io.Reader; import java.math.BigDecimal; import java.util.Iterator; import java.util.Map; import java.util.ServiceLoader; import static net.javacrumbs.jsonunit.core.internal.Utils.closeQuietly; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; /** * Deserializes node using Jackson 2 */ class Jackson2NodeFactory extends AbstractNodeFactory { private final ServiceLoader<Jackson2ObjectMapperProvider> serviceLoader = ServiceLoader.load(Jackson2ObjectMapperProvider.class); @Override protected Node doConvertValue(Object source) { if (source instanceof JsonNode) { return newNode((JsonNode) source); } else { return newNode(getMapper(false).convertValue(source, JsonNode.class)); } } @Override protected Node nullNode() { return newNode(NullNode.getInstance()); } @Override protected Node readValue(Reader value, String label, boolean lenient) { try { return newNode(getMapper(lenient).readTree(value)); } catch (IOException e) { throw newParseException(label, value, e); } finally {
closeQuietly(value);
lukas-krecan/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ExceptionUtils.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ClassUtils.java // static boolean isClassPresent(String className) { // try { // ClassUtils.class.getClassLoader().loadClass(className); // return true; // } catch (Throwable e) { // return false; // } // }
import java.util.List; import static net.javacrumbs.jsonunit.core.internal.ClassUtils.isClassPresent;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; class ExceptionUtils { private static final String ROOT_MESSAGE = "JSON documents are different:\n"; private static final ExceptionFactory exceptionFactory
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ClassUtils.java // static boolean isClassPresent(String className) { // try { // ClassUtils.class.getClassLoader().loadClass(className); // return true; // } catch (Throwable e) { // return false; // } // } // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ExceptionUtils.java import java.util.List; import static net.javacrumbs.jsonunit.core.internal.ClassUtils.isClassPresent; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; class ExceptionUtils { private static final String ROOT_MESSAGE = "JSON documents are different:\n"; private static final ExceptionFactory exceptionFactory
= isClassPresent("org.opentest4j.AssertionFailedError") ? new Opentest4jExceptionFactory() : new BasicExceptionFactory();
lukas-krecan/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Node.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // static String prettyPrint(Map<String, Object> map) { // StringBuilder builder = new StringBuilder(); // builder.append("{"); // Iterator<Entry<String, Object>> entries = map.entrySet().stream().sorted(comparingByKey()).iterator(); // while (entries.hasNext()) { // Entry<String, Object> entry = entries.next(); // builder.append('"').append(entry.getKey()).append('"').append(":"); // appendQuoteString(entry.getValue(), builder); // if (entries.hasNext()) { // builder.append(","); // } // } // builder.append("}"); // return builder.toString(); // }
import java.math.BigDecimal; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.prettyPrint;
public Object getValue() { return null; } @Override public void ___do_not_implement_this_interface_seriously() {} @Override public String toString() { return "<missing>"; } }; interface ValueExtractor { Object getValue(Node node); } class JsonMap extends LinkedHashMap<String, Object> implements NodeWrapper { private final Node wrappedNode; JsonMap(Node node) { wrappedNode = node; Iterator<KeyValue> fields = node.fields(); while (fields.hasNext()) { KeyValue keyValue = fields.next(); put(keyValue.getKey(), keyValue.getValue().getValue()); } } @Override public String toString() {
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // static String prettyPrint(Map<String, Object> map) { // StringBuilder builder = new StringBuilder(); // builder.append("{"); // Iterator<Entry<String, Object>> entries = map.entrySet().stream().sorted(comparingByKey()).iterator(); // while (entries.hasNext()) { // Entry<String, Object> entry = entries.next(); // builder.append('"').append(entry.getKey()).append('"').append(":"); // appendQuoteString(entry.getValue(), builder); // if (entries.hasNext()) { // builder.append(","); // } // } // builder.append("}"); // return builder.toString(); // } // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Node.java import java.math.BigDecimal; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.prettyPrint; public Object getValue() { return null; } @Override public void ___do_not_implement_this_interface_seriously() {} @Override public String toString() { return "<missing>"; } }; interface ValueExtractor { Object getValue(Node node); } class JsonMap extends LinkedHashMap<String, Object> implements NodeWrapper { private final Node wrappedNode; JsonMap(Node node) { wrappedNode = node; Iterator<KeyValue> fields = node.fields(); while (fields.hasNext()) { KeyValue keyValue = fields.next(); put(keyValue.getKey(), keyValue.getValue().getValue()); } } @Override public String toString() {
return prettyPrint(this);
lukas-krecan/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonOrgNodeFactory.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/GenericNodeBuilder.java // static abstract class NodeSkeleton extends AbstractNode { // @Override // public Node element(int index) { // return MISSING_NODE; // } // // @Override // public Iterator<KeyValue> fields() { // throw new UnsupportedOperationException(); // } // // @Override // public Node get(String key) { // return MISSING_NODE; // } // // @Override // public boolean isMissingNode() { // return false; // } // // @Override // public boolean isNull() { // return false; // } // // @Override // public Iterator<Node> arrayElements() { // throw new UnsupportedOperationException(); // } // // @Override // public int size() { // throw new UnsupportedOperationException(); // } // // @Override // public String asText() { // throw new UnsupportedOperationException(); // } // // @Override // public BigDecimal decimalValue() { // throw new UnsupportedOperationException(); // } // // @Override // public Boolean asBoolean() { // throw new UnsupportedOperationException(); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static void closeQuietly(final Reader resourceReader) { // if (resourceReader != null) { // try { // resourceReader.close(); // } catch (IOException ignored) { // } // } // }
import net.javacrumbs.jsonunit.core.internal.GenericNodeBuilder.NodeSkeleton; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import java.io.Reader; import java.util.Collection; import java.util.Iterator; import java.util.Map; import static net.javacrumbs.jsonunit.core.internal.Utils.closeQuietly;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; /** * Deserializes node using org.json.JSONObject */ class JsonOrgNodeFactory extends AbstractNodeFactory { @Override protected Node doConvertValue(Object source) { return newNode(source); } @Override protected Node nullNode() { return newNode(null); } @Override protected Node readValue(Reader value, String label, boolean lenient) { try { return newNode(new JSONTokener(value).nextValue()); } catch (JSONException e) { throw newParseException(label, value, e); } finally {
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/GenericNodeBuilder.java // static abstract class NodeSkeleton extends AbstractNode { // @Override // public Node element(int index) { // return MISSING_NODE; // } // // @Override // public Iterator<KeyValue> fields() { // throw new UnsupportedOperationException(); // } // // @Override // public Node get(String key) { // return MISSING_NODE; // } // // @Override // public boolean isMissingNode() { // return false; // } // // @Override // public boolean isNull() { // return false; // } // // @Override // public Iterator<Node> arrayElements() { // throw new UnsupportedOperationException(); // } // // @Override // public int size() { // throw new UnsupportedOperationException(); // } // // @Override // public String asText() { // throw new UnsupportedOperationException(); // } // // @Override // public BigDecimal decimalValue() { // throw new UnsupportedOperationException(); // } // // @Override // public Boolean asBoolean() { // throw new UnsupportedOperationException(); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static void closeQuietly(final Reader resourceReader) { // if (resourceReader != null) { // try { // resourceReader.close(); // } catch (IOException ignored) { // } // } // } // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonOrgNodeFactory.java import net.javacrumbs.jsonunit.core.internal.GenericNodeBuilder.NodeSkeleton; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import java.io.Reader; import java.util.Collection; import java.util.Iterator; import java.util.Map; import static net.javacrumbs.jsonunit.core.internal.Utils.closeQuietly; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; /** * Deserializes node using org.json.JSONObject */ class JsonOrgNodeFactory extends AbstractNodeFactory { @Override protected Node doConvertValue(Object source) { return newNode(source); } @Override protected Node nullNode() { return newNode(null); } @Override protected Node readValue(Reader value, String label, boolean lenient) { try { return newNode(new JSONTokener(value).nextValue()); } catch (JSONException e) { throw newParseException(label, value, e); } finally {
closeQuietly(value);
lukas-krecan/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonOrgNodeFactory.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/GenericNodeBuilder.java // static abstract class NodeSkeleton extends AbstractNode { // @Override // public Node element(int index) { // return MISSING_NODE; // } // // @Override // public Iterator<KeyValue> fields() { // throw new UnsupportedOperationException(); // } // // @Override // public Node get(String key) { // return MISSING_NODE; // } // // @Override // public boolean isMissingNode() { // return false; // } // // @Override // public boolean isNull() { // return false; // } // // @Override // public Iterator<Node> arrayElements() { // throw new UnsupportedOperationException(); // } // // @Override // public int size() { // throw new UnsupportedOperationException(); // } // // @Override // public String asText() { // throw new UnsupportedOperationException(); // } // // @Override // public BigDecimal decimalValue() { // throw new UnsupportedOperationException(); // } // // @Override // public Boolean asBoolean() { // throw new UnsupportedOperationException(); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static void closeQuietly(final Reader resourceReader) { // if (resourceReader != null) { // try { // resourceReader.close(); // } catch (IOException ignored) { // } // } // }
import net.javacrumbs.jsonunit.core.internal.GenericNodeBuilder.NodeSkeleton; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import java.io.Reader; import java.util.Collection; import java.util.Iterator; import java.util.Map; import static net.javacrumbs.jsonunit.core.internal.Utils.closeQuietly;
} } private static Node newNode(Object object) { if (object instanceof JSONObject) { return new JSONObjectNode((JSONObject) object); } else if (object instanceof Number) { return new GenericNodeBuilder.NumberNode((Number) object); } else if (object instanceof String) { return new GenericNodeBuilder.StringNode((String) object); } else if (object instanceof Boolean) { return new GenericNodeBuilder.BooleanNode((Boolean) object); } else if (object instanceof JSONArray) { return new JSONArrayNode((JSONArray) object); } else if (JSONObject.NULL.equals(object)) { return new GenericNodeBuilder.NullNode(); } else if (object instanceof Map) { return new JSONObjectNode(new JSONObject((Map<?, ?>) object)); } else if (object instanceof Collection || object.getClass().isArray()) { return new JSONArrayNode((JSONArray) JSONObject.wrap(object)); } else { throw new IllegalArgumentException("Unsupported type " + object.getClass()); } } @Override public boolean isPreferredFor(Object source) { return source instanceof JSONObject || source instanceof JSONArray; }
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/GenericNodeBuilder.java // static abstract class NodeSkeleton extends AbstractNode { // @Override // public Node element(int index) { // return MISSING_NODE; // } // // @Override // public Iterator<KeyValue> fields() { // throw new UnsupportedOperationException(); // } // // @Override // public Node get(String key) { // return MISSING_NODE; // } // // @Override // public boolean isMissingNode() { // return false; // } // // @Override // public boolean isNull() { // return false; // } // // @Override // public Iterator<Node> arrayElements() { // throw new UnsupportedOperationException(); // } // // @Override // public int size() { // throw new UnsupportedOperationException(); // } // // @Override // public String asText() { // throw new UnsupportedOperationException(); // } // // @Override // public BigDecimal decimalValue() { // throw new UnsupportedOperationException(); // } // // @Override // public Boolean asBoolean() { // throw new UnsupportedOperationException(); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static void closeQuietly(final Reader resourceReader) { // if (resourceReader != null) { // try { // resourceReader.close(); // } catch (IOException ignored) { // } // } // } // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonOrgNodeFactory.java import net.javacrumbs.jsonunit.core.internal.GenericNodeBuilder.NodeSkeleton; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import java.io.Reader; import java.util.Collection; import java.util.Iterator; import java.util.Map; import static net.javacrumbs.jsonunit.core.internal.Utils.closeQuietly; } } private static Node newNode(Object object) { if (object instanceof JSONObject) { return new JSONObjectNode((JSONObject) object); } else if (object instanceof Number) { return new GenericNodeBuilder.NumberNode((Number) object); } else if (object instanceof String) { return new GenericNodeBuilder.StringNode((String) object); } else if (object instanceof Boolean) { return new GenericNodeBuilder.BooleanNode((Boolean) object); } else if (object instanceof JSONArray) { return new JSONArrayNode((JSONArray) object); } else if (JSONObject.NULL.equals(object)) { return new GenericNodeBuilder.NullNode(); } else if (object instanceof Map) { return new JSONObjectNode(new JSONObject((Map<?, ?>) object)); } else if (object instanceof Collection || object.getClass().isArray()) { return new JSONArrayNode((JSONArray) JSONObject.wrap(object)); } else { throw new IllegalArgumentException("Unsupported type " + object.getClass()); } } @Override public boolean isPreferredFor(Object source) { return source instanceof JSONObject || source instanceof JSONArray; }
private static final class JSONArrayNode extends NodeSkeleton {
lukas-krecan/JsonUnit
json-unit-core/src/test/java/net/javacrumbs/jsonunit/core/internal/JsonUtilsTest.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node convertToJson(Object source, String label) { // return convertToJson(source, label, false); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node getNode(Object root, String path) { // return getNode(root, Path.create(path)); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static boolean nodeAbsent(Object json, String path, Configuration configuration) { // return nodeAbsent(json, Path.create(path), configuration); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // @Deprecated // public static boolean nodeExists(Object json, String path) { // return !getNode(json, path).isMissingNode(); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // static String quoteIfNeeded(String source) { // String trimmed = source.trim(); // // if (isObject(trimmed) || isArray(trimmed) || isString(trimmed) // || isBoolean(trimmed) || isNull(trimmed) // || isNumber(trimmed)) { // return source; // } else { // return "\"" + source + "\""; // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node valueToNode(Object source) { // if (source instanceof Node) { // return (Node) source; // } else { // return converter.valueToNode(source); // } // }
import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import java.io.IOException; import java.math.BigDecimal; import static java.util.Collections.singletonMap; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.convertToJson; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.getNode; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.nodeAbsent; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.nodeExists; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.quoteIfNeeded; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.valueToNode; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.ARRAY; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.BOOLEAN; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.NULL; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.NUMBER; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.OBJECT; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.STRING; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; class JsonUtilsTest { private static final ObjectMapper mapper = new ObjectMapper(); @Test void testConvertToJson() {
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node convertToJson(Object source, String label) { // return convertToJson(source, label, false); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node getNode(Object root, String path) { // return getNode(root, Path.create(path)); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static boolean nodeAbsent(Object json, String path, Configuration configuration) { // return nodeAbsent(json, Path.create(path), configuration); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // @Deprecated // public static boolean nodeExists(Object json, String path) { // return !getNode(json, path).isMissingNode(); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // static String quoteIfNeeded(String source) { // String trimmed = source.trim(); // // if (isObject(trimmed) || isArray(trimmed) || isString(trimmed) // || isBoolean(trimmed) || isNull(trimmed) // || isNumber(trimmed)) { // return source; // } else { // return "\"" + source + "\""; // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node valueToNode(Object source) { // if (source instanceof Node) { // return (Node) source; // } else { // return converter.valueToNode(source); // } // } // Path: json-unit-core/src/test/java/net/javacrumbs/jsonunit/core/internal/JsonUtilsTest.java import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import java.io.IOException; import java.math.BigDecimal; import static java.util.Collections.singletonMap; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.convertToJson; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.getNode; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.nodeAbsent; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.nodeExists; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.quoteIfNeeded; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.valueToNode; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.ARRAY; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.BOOLEAN; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.NULL; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.NUMBER; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.OBJECT; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.STRING; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; class JsonUtilsTest { private static final ObjectMapper mapper = new ObjectMapper(); @Test void testConvertToJson() {
assertEquals(STRING, convertToJson("\"a\"", "x").getNodeType());
lukas-krecan/JsonUnit
json-unit-core/src/test/java/net/javacrumbs/jsonunit/core/internal/JsonUtilsTest.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node convertToJson(Object source, String label) { // return convertToJson(source, label, false); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node getNode(Object root, String path) { // return getNode(root, Path.create(path)); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static boolean nodeAbsent(Object json, String path, Configuration configuration) { // return nodeAbsent(json, Path.create(path), configuration); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // @Deprecated // public static boolean nodeExists(Object json, String path) { // return !getNode(json, path).isMissingNode(); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // static String quoteIfNeeded(String source) { // String trimmed = source.trim(); // // if (isObject(trimmed) || isArray(trimmed) || isString(trimmed) // || isBoolean(trimmed) || isNull(trimmed) // || isNumber(trimmed)) { // return source; // } else { // return "\"" + source + "\""; // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node valueToNode(Object source) { // if (source instanceof Node) { // return (Node) source; // } else { // return converter.valueToNode(source); // } // }
import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import java.io.IOException; import java.math.BigDecimal; import static java.util.Collections.singletonMap; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.convertToJson; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.getNode; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.nodeAbsent; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.nodeExists; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.quoteIfNeeded; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.valueToNode; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.ARRAY; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.BOOLEAN; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.NULL; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.NUMBER; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.OBJECT; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.STRING; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; class JsonUtilsTest { private static final ObjectMapper mapper = new ObjectMapper(); @Test void testConvertToJson() { assertEquals(STRING, convertToJson("\"a\"", "x").getNodeType()); assertEquals(NUMBER, convertToJson(1, "x").getNodeType()); assertEquals(NUMBER, convertToJson("1", "x").getNodeType()); assertEquals(NUMBER, convertToJson(1.0, "x").getNodeType()); assertEquals(NUMBER, convertToJson("1.0", "x").getNodeType()); assertEquals(OBJECT, convertToJson("{\"a\":1}", "x").getNodeType()); assertEquals(ARRAY, convertToJson("[1 ,2, 3]", "x").getNodeType()); assertEquals(BOOLEAN, convertToJson("true", "x").getNodeType()); assertEquals(BOOLEAN, convertToJson(true, "x").getNodeType()); assertEquals(BOOLEAN, convertToJson("false", "x").getNodeType()); assertEquals(BOOLEAN, convertToJson(false, "x").getNodeType()); assertTrue(convertToJson("null", "x").isNull()); assertTrue(convertToJson(null, "x").isNull()); } @Test void testValueToJson() {
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node convertToJson(Object source, String label) { // return convertToJson(source, label, false); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node getNode(Object root, String path) { // return getNode(root, Path.create(path)); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static boolean nodeAbsent(Object json, String path, Configuration configuration) { // return nodeAbsent(json, Path.create(path), configuration); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // @Deprecated // public static boolean nodeExists(Object json, String path) { // return !getNode(json, path).isMissingNode(); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // static String quoteIfNeeded(String source) { // String trimmed = source.trim(); // // if (isObject(trimmed) || isArray(trimmed) || isString(trimmed) // || isBoolean(trimmed) || isNull(trimmed) // || isNumber(trimmed)) { // return source; // } else { // return "\"" + source + "\""; // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node valueToNode(Object source) { // if (source instanceof Node) { // return (Node) source; // } else { // return converter.valueToNode(source); // } // } // Path: json-unit-core/src/test/java/net/javacrumbs/jsonunit/core/internal/JsonUtilsTest.java import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import java.io.IOException; import java.math.BigDecimal; import static java.util.Collections.singletonMap; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.convertToJson; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.getNode; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.nodeAbsent; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.nodeExists; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.quoteIfNeeded; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.valueToNode; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.ARRAY; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.BOOLEAN; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.NULL; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.NUMBER; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.OBJECT; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.STRING; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; class JsonUtilsTest { private static final ObjectMapper mapper = new ObjectMapper(); @Test void testConvertToJson() { assertEquals(STRING, convertToJson("\"a\"", "x").getNodeType()); assertEquals(NUMBER, convertToJson(1, "x").getNodeType()); assertEquals(NUMBER, convertToJson("1", "x").getNodeType()); assertEquals(NUMBER, convertToJson(1.0, "x").getNodeType()); assertEquals(NUMBER, convertToJson("1.0", "x").getNodeType()); assertEquals(OBJECT, convertToJson("{\"a\":1}", "x").getNodeType()); assertEquals(ARRAY, convertToJson("[1 ,2, 3]", "x").getNodeType()); assertEquals(BOOLEAN, convertToJson("true", "x").getNodeType()); assertEquals(BOOLEAN, convertToJson(true, "x").getNodeType()); assertEquals(BOOLEAN, convertToJson("false", "x").getNodeType()); assertEquals(BOOLEAN, convertToJson(false, "x").getNodeType()); assertTrue(convertToJson("null", "x").isNull()); assertTrue(convertToJson(null, "x").isNull()); } @Test void testValueToJson() {
assertEquals(STRING, valueToNode("a").getNodeType());
lukas-krecan/JsonUnit
json-unit-core/src/test/java/net/javacrumbs/jsonunit/core/internal/JsonUtilsTest.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node convertToJson(Object source, String label) { // return convertToJson(source, label, false); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node getNode(Object root, String path) { // return getNode(root, Path.create(path)); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static boolean nodeAbsent(Object json, String path, Configuration configuration) { // return nodeAbsent(json, Path.create(path), configuration); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // @Deprecated // public static boolean nodeExists(Object json, String path) { // return !getNode(json, path).isMissingNode(); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // static String quoteIfNeeded(String source) { // String trimmed = source.trim(); // // if (isObject(trimmed) || isArray(trimmed) || isString(trimmed) // || isBoolean(trimmed) || isNull(trimmed) // || isNumber(trimmed)) { // return source; // } else { // return "\"" + source + "\""; // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node valueToNode(Object source) { // if (source instanceof Node) { // return (Node) source; // } else { // return converter.valueToNode(source); // } // }
import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import java.io.IOException; import java.math.BigDecimal; import static java.util.Collections.singletonMap; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.convertToJson; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.getNode; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.nodeAbsent; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.nodeExists; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.quoteIfNeeded; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.valueToNode; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.ARRAY; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.BOOLEAN; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.NULL; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.NUMBER; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.OBJECT; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.STRING; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue;
assertEquals(NUMBER, convertToJson("1.0", "x").getNodeType()); assertEquals(OBJECT, convertToJson("{\"a\":1}", "x").getNodeType()); assertEquals(ARRAY, convertToJson("[1 ,2, 3]", "x").getNodeType()); assertEquals(BOOLEAN, convertToJson("true", "x").getNodeType()); assertEquals(BOOLEAN, convertToJson(true, "x").getNodeType()); assertEquals(BOOLEAN, convertToJson("false", "x").getNodeType()); assertEquals(BOOLEAN, convertToJson(false, "x").getNodeType()); assertTrue(convertToJson("null", "x").isNull()); assertTrue(convertToJson(null, "x").isNull()); } @Test void testValueToJson() { assertEquals(STRING, valueToNode("a").getNodeType()); assertEquals(NUMBER, valueToNode(BigDecimal.valueOf(1)).getNodeType()); assertEquals(STRING, valueToNode("1").getNodeType()); assertEquals(NUMBER, valueToNode(1.0).getNodeType()); assertEquals(STRING, valueToNode("1.0").getNodeType()); assertEquals(OBJECT, valueToNode(singletonMap("a", 1)).getNodeType()); assertEquals(ARRAY, valueToNode(new int[]{1 ,2, 3}).getNodeType()); assertEquals(STRING, valueToNode("true").getNodeType()); assertEquals(BOOLEAN, valueToNode(true).getNodeType()); assertEquals(STRING, valueToNode("false").getNodeType()); assertEquals(BOOLEAN, valueToNode(false).getNodeType()); assertEquals(STRING, valueToNode("null").getNodeType()); assertEquals(NULL, valueToNode(null).getNodeType()); } @Test void testQuoteIfNeeded() {
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node convertToJson(Object source, String label) { // return convertToJson(source, label, false); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node getNode(Object root, String path) { // return getNode(root, Path.create(path)); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static boolean nodeAbsent(Object json, String path, Configuration configuration) { // return nodeAbsent(json, Path.create(path), configuration); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // @Deprecated // public static boolean nodeExists(Object json, String path) { // return !getNode(json, path).isMissingNode(); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // static String quoteIfNeeded(String source) { // String trimmed = source.trim(); // // if (isObject(trimmed) || isArray(trimmed) || isString(trimmed) // || isBoolean(trimmed) || isNull(trimmed) // || isNumber(trimmed)) { // return source; // } else { // return "\"" + source + "\""; // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node valueToNode(Object source) { // if (source instanceof Node) { // return (Node) source; // } else { // return converter.valueToNode(source); // } // } // Path: json-unit-core/src/test/java/net/javacrumbs/jsonunit/core/internal/JsonUtilsTest.java import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import java.io.IOException; import java.math.BigDecimal; import static java.util.Collections.singletonMap; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.convertToJson; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.getNode; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.nodeAbsent; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.nodeExists; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.quoteIfNeeded; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.valueToNode; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.ARRAY; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.BOOLEAN; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.NULL; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.NUMBER; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.OBJECT; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.STRING; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; assertEquals(NUMBER, convertToJson("1.0", "x").getNodeType()); assertEquals(OBJECT, convertToJson("{\"a\":1}", "x").getNodeType()); assertEquals(ARRAY, convertToJson("[1 ,2, 3]", "x").getNodeType()); assertEquals(BOOLEAN, convertToJson("true", "x").getNodeType()); assertEquals(BOOLEAN, convertToJson(true, "x").getNodeType()); assertEquals(BOOLEAN, convertToJson("false", "x").getNodeType()); assertEquals(BOOLEAN, convertToJson(false, "x").getNodeType()); assertTrue(convertToJson("null", "x").isNull()); assertTrue(convertToJson(null, "x").isNull()); } @Test void testValueToJson() { assertEquals(STRING, valueToNode("a").getNodeType()); assertEquals(NUMBER, valueToNode(BigDecimal.valueOf(1)).getNodeType()); assertEquals(STRING, valueToNode("1").getNodeType()); assertEquals(NUMBER, valueToNode(1.0).getNodeType()); assertEquals(STRING, valueToNode("1.0").getNodeType()); assertEquals(OBJECT, valueToNode(singletonMap("a", 1)).getNodeType()); assertEquals(ARRAY, valueToNode(new int[]{1 ,2, 3}).getNodeType()); assertEquals(STRING, valueToNode("true").getNodeType()); assertEquals(BOOLEAN, valueToNode(true).getNodeType()); assertEquals(STRING, valueToNode("false").getNodeType()); assertEquals(BOOLEAN, valueToNode(false).getNodeType()); assertEquals(STRING, valueToNode("null").getNodeType()); assertEquals(NULL, valueToNode(null).getNodeType()); } @Test void testQuoteIfNeeded() {
assertEquals("1", quoteIfNeeded("1"));
lukas-krecan/JsonUnit
json-unit-core/src/test/java/net/javacrumbs/jsonunit/core/internal/JsonUtilsTest.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node convertToJson(Object source, String label) { // return convertToJson(source, label, false); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node getNode(Object root, String path) { // return getNode(root, Path.create(path)); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static boolean nodeAbsent(Object json, String path, Configuration configuration) { // return nodeAbsent(json, Path.create(path), configuration); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // @Deprecated // public static boolean nodeExists(Object json, String path) { // return !getNode(json, path).isMissingNode(); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // static String quoteIfNeeded(String source) { // String trimmed = source.trim(); // // if (isObject(trimmed) || isArray(trimmed) || isString(trimmed) // || isBoolean(trimmed) || isNull(trimmed) // || isNumber(trimmed)) { // return source; // } else { // return "\"" + source + "\""; // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node valueToNode(Object source) { // if (source instanceof Node) { // return (Node) source; // } else { // return converter.valueToNode(source); // } // }
import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import java.io.IOException; import java.math.BigDecimal; import static java.util.Collections.singletonMap; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.convertToJson; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.getNode; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.nodeAbsent; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.nodeExists; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.quoteIfNeeded; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.valueToNode; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.ARRAY; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.BOOLEAN; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.NULL; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.NUMBER; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.OBJECT; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.STRING; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue;
assertEquals(NUMBER, valueToNode(1.0).getNodeType()); assertEquals(STRING, valueToNode("1.0").getNodeType()); assertEquals(OBJECT, valueToNode(singletonMap("a", 1)).getNodeType()); assertEquals(ARRAY, valueToNode(new int[]{1 ,2, 3}).getNodeType()); assertEquals(STRING, valueToNode("true").getNodeType()); assertEquals(BOOLEAN, valueToNode(true).getNodeType()); assertEquals(STRING, valueToNode("false").getNodeType()); assertEquals(BOOLEAN, valueToNode(false).getNodeType()); assertEquals(STRING, valueToNode("null").getNodeType()); assertEquals(NULL, valueToNode(null).getNodeType()); } @Test void testQuoteIfNeeded() { assertEquals("1", quoteIfNeeded("1")); assertEquals("1.1", quoteIfNeeded("1.1")); assertEquals("{\"a\":1}", quoteIfNeeded("{\"a\":1}")); assertEquals("[1 ,2, 3]", quoteIfNeeded("[1 ,2, 3]")); assertEquals("true", quoteIfNeeded("true")); assertEquals("false", quoteIfNeeded("false")); assertEquals("null", quoteIfNeeded("null")); assertEquals("\"a\"", quoteIfNeeded("a")); assertEquals("\"a b\"", quoteIfNeeded("a b")); assertEquals("\"123 b\"", quoteIfNeeded("123 b")); } @Test void testGetStartNodeRoot() throws IOException {
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node convertToJson(Object source, String label) { // return convertToJson(source, label, false); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node getNode(Object root, String path) { // return getNode(root, Path.create(path)); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static boolean nodeAbsent(Object json, String path, Configuration configuration) { // return nodeAbsent(json, Path.create(path), configuration); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // @Deprecated // public static boolean nodeExists(Object json, String path) { // return !getNode(json, path).isMissingNode(); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // static String quoteIfNeeded(String source) { // String trimmed = source.trim(); // // if (isObject(trimmed) || isArray(trimmed) || isString(trimmed) // || isBoolean(trimmed) || isNull(trimmed) // || isNumber(trimmed)) { // return source; // } else { // return "\"" + source + "\""; // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node valueToNode(Object source) { // if (source instanceof Node) { // return (Node) source; // } else { // return converter.valueToNode(source); // } // } // Path: json-unit-core/src/test/java/net/javacrumbs/jsonunit/core/internal/JsonUtilsTest.java import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import java.io.IOException; import java.math.BigDecimal; import static java.util.Collections.singletonMap; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.convertToJson; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.getNode; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.nodeAbsent; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.nodeExists; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.quoteIfNeeded; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.valueToNode; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.ARRAY; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.BOOLEAN; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.NULL; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.NUMBER; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.OBJECT; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.STRING; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; assertEquals(NUMBER, valueToNode(1.0).getNodeType()); assertEquals(STRING, valueToNode("1.0").getNodeType()); assertEquals(OBJECT, valueToNode(singletonMap("a", 1)).getNodeType()); assertEquals(ARRAY, valueToNode(new int[]{1 ,2, 3}).getNodeType()); assertEquals(STRING, valueToNode("true").getNodeType()); assertEquals(BOOLEAN, valueToNode(true).getNodeType()); assertEquals(STRING, valueToNode("false").getNodeType()); assertEquals(BOOLEAN, valueToNode(false).getNodeType()); assertEquals(STRING, valueToNode("null").getNodeType()); assertEquals(NULL, valueToNode(null).getNodeType()); } @Test void testQuoteIfNeeded() { assertEquals("1", quoteIfNeeded("1")); assertEquals("1.1", quoteIfNeeded("1.1")); assertEquals("{\"a\":1}", quoteIfNeeded("{\"a\":1}")); assertEquals("[1 ,2, 3]", quoteIfNeeded("[1 ,2, 3]")); assertEquals("true", quoteIfNeeded("true")); assertEquals("false", quoteIfNeeded("false")); assertEquals("null", quoteIfNeeded("null")); assertEquals("\"a\"", quoteIfNeeded("a")); assertEquals("\"a b\"", quoteIfNeeded("a b")); assertEquals("\"123 b\"", quoteIfNeeded("123 b")); } @Test void testGetStartNodeRoot() throws IOException {
Node startNode = getNode(mapper.readTree("{\"test\":{\"value\":1}}"), "");
lukas-krecan/JsonUnit
json-unit-core/src/test/java/net/javacrumbs/jsonunit/core/internal/JsonUtilsTest.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node convertToJson(Object source, String label) { // return convertToJson(source, label, false); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node getNode(Object root, String path) { // return getNode(root, Path.create(path)); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static boolean nodeAbsent(Object json, String path, Configuration configuration) { // return nodeAbsent(json, Path.create(path), configuration); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // @Deprecated // public static boolean nodeExists(Object json, String path) { // return !getNode(json, path).isMissingNode(); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // static String quoteIfNeeded(String source) { // String trimmed = source.trim(); // // if (isObject(trimmed) || isArray(trimmed) || isString(trimmed) // || isBoolean(trimmed) || isNull(trimmed) // || isNumber(trimmed)) { // return source; // } else { // return "\"" + source + "\""; // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node valueToNode(Object source) { // if (source instanceof Node) { // return (Node) source; // } else { // return converter.valueToNode(source); // } // }
import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import java.io.IOException; import java.math.BigDecimal; import static java.util.Collections.singletonMap; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.convertToJson; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.getNode; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.nodeAbsent; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.nodeExists; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.quoteIfNeeded; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.valueToNode; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.ARRAY; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.BOOLEAN; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.NULL; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.NUMBER; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.OBJECT; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.STRING; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue;
} @Test void testGetStartNodeArraysRootComplex() throws IOException { Node startNode = getNode(mapper.readTree("[{\"values\":[1,2]}, {\"values\":[3,4]}]"), "[1].values[1]"); assertEquals(4, startNode.decimalValue().intValue()); } @Test void testGetStartNodeArraysConvoluted() throws IOException { Node startNode = getNode(mapper.readTree("{\"test\":[{\"values\":[1,2]}, {\"values\":[3,4]}]}"), "test.[1].values.[1]"); assertEquals(4, startNode.decimalValue().intValue()); } @Test void testGetStartNodeArraysRoot() throws IOException { Node startNode = getNode(mapper.readTree("[1,2]"), "[0]"); assertEquals(1, startNode.decimalValue().intValue()); } @Test void testGetStartNodeNonexisting() throws IOException { Node startNode = getNode(mapper.readTree("{\"test\":{\"value\":1}}"), "test.bogus"); assertEquals(true, startNode.isMissingNode()); } @Test @SuppressWarnings("deprecation") void testNodeExists() { String json = "{\"test\":{\"value\":1}}";
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node convertToJson(Object source, String label) { // return convertToJson(source, label, false); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node getNode(Object root, String path) { // return getNode(root, Path.create(path)); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static boolean nodeAbsent(Object json, String path, Configuration configuration) { // return nodeAbsent(json, Path.create(path), configuration); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // @Deprecated // public static boolean nodeExists(Object json, String path) { // return !getNode(json, path).isMissingNode(); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // static String quoteIfNeeded(String source) { // String trimmed = source.trim(); // // if (isObject(trimmed) || isArray(trimmed) || isString(trimmed) // || isBoolean(trimmed) || isNull(trimmed) // || isNumber(trimmed)) { // return source; // } else { // return "\"" + source + "\""; // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node valueToNode(Object source) { // if (source instanceof Node) { // return (Node) source; // } else { // return converter.valueToNode(source); // } // } // Path: json-unit-core/src/test/java/net/javacrumbs/jsonunit/core/internal/JsonUtilsTest.java import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import java.io.IOException; import java.math.BigDecimal; import static java.util.Collections.singletonMap; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.convertToJson; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.getNode; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.nodeAbsent; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.nodeExists; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.quoteIfNeeded; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.valueToNode; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.ARRAY; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.BOOLEAN; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.NULL; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.NUMBER; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.OBJECT; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.STRING; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; } @Test void testGetStartNodeArraysRootComplex() throws IOException { Node startNode = getNode(mapper.readTree("[{\"values\":[1,2]}, {\"values\":[3,4]}]"), "[1].values[1]"); assertEquals(4, startNode.decimalValue().intValue()); } @Test void testGetStartNodeArraysConvoluted() throws IOException { Node startNode = getNode(mapper.readTree("{\"test\":[{\"values\":[1,2]}, {\"values\":[3,4]}]}"), "test.[1].values.[1]"); assertEquals(4, startNode.decimalValue().intValue()); } @Test void testGetStartNodeArraysRoot() throws IOException { Node startNode = getNode(mapper.readTree("[1,2]"), "[0]"); assertEquals(1, startNode.decimalValue().intValue()); } @Test void testGetStartNodeNonexisting() throws IOException { Node startNode = getNode(mapper.readTree("{\"test\":{\"value\":1}}"), "test.bogus"); assertEquals(true, startNode.isMissingNode()); } @Test @SuppressWarnings("deprecation") void testNodeExists() { String json = "{\"test\":{\"value\":1}}";
assertTrue(nodeExists(json, "test"));
lukas-krecan/JsonUnit
json-unit-core/src/test/java/net/javacrumbs/jsonunit/core/internal/JsonUtilsTest.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node convertToJson(Object source, String label) { // return convertToJson(source, label, false); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node getNode(Object root, String path) { // return getNode(root, Path.create(path)); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static boolean nodeAbsent(Object json, String path, Configuration configuration) { // return nodeAbsent(json, Path.create(path), configuration); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // @Deprecated // public static boolean nodeExists(Object json, String path) { // return !getNode(json, path).isMissingNode(); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // static String quoteIfNeeded(String source) { // String trimmed = source.trim(); // // if (isObject(trimmed) || isArray(trimmed) || isString(trimmed) // || isBoolean(trimmed) || isNull(trimmed) // || isNumber(trimmed)) { // return source; // } else { // return "\"" + source + "\""; // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node valueToNode(Object source) { // if (source instanceof Node) { // return (Node) source; // } else { // return converter.valueToNode(source); // } // }
import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import java.io.IOException; import java.math.BigDecimal; import static java.util.Collections.singletonMap; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.convertToJson; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.getNode; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.nodeAbsent; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.nodeExists; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.quoteIfNeeded; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.valueToNode; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.ARRAY; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.BOOLEAN; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.NULL; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.NUMBER; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.OBJECT; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.STRING; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue;
void testGetStartNodeArraysConvoluted() throws IOException { Node startNode = getNode(mapper.readTree("{\"test\":[{\"values\":[1,2]}, {\"values\":[3,4]}]}"), "test.[1].values.[1]"); assertEquals(4, startNode.decimalValue().intValue()); } @Test void testGetStartNodeArraysRoot() throws IOException { Node startNode = getNode(mapper.readTree("[1,2]"), "[0]"); assertEquals(1, startNode.decimalValue().intValue()); } @Test void testGetStartNodeNonexisting() throws IOException { Node startNode = getNode(mapper.readTree("{\"test\":{\"value\":1}}"), "test.bogus"); assertEquals(true, startNode.isMissingNode()); } @Test @SuppressWarnings("deprecation") void testNodeExists() { String json = "{\"test\":{\"value\":1}}"; assertTrue(nodeExists(json, "test")); assertTrue(nodeExists(json, "test.value")); assertFalse(nodeExists(json, "test.nonsense")); assertFalse(nodeExists(json, "root")); } @Test void testNodeAbsent() { String json = "{\"test\":{\"value\":1, \"value2\": null}}";
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node convertToJson(Object source, String label) { // return convertToJson(source, label, false); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node getNode(Object root, String path) { // return getNode(root, Path.create(path)); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static boolean nodeAbsent(Object json, String path, Configuration configuration) { // return nodeAbsent(json, Path.create(path), configuration); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // @Deprecated // public static boolean nodeExists(Object json, String path) { // return !getNode(json, path).isMissingNode(); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // static String quoteIfNeeded(String source) { // String trimmed = source.trim(); // // if (isObject(trimmed) || isArray(trimmed) || isString(trimmed) // || isBoolean(trimmed) || isNull(trimmed) // || isNumber(trimmed)) { // return source; // } else { // return "\"" + source + "\""; // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node valueToNode(Object source) { // if (source instanceof Node) { // return (Node) source; // } else { // return converter.valueToNode(source); // } // } // Path: json-unit-core/src/test/java/net/javacrumbs/jsonunit/core/internal/JsonUtilsTest.java import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import java.io.IOException; import java.math.BigDecimal; import static java.util.Collections.singletonMap; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.convertToJson; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.getNode; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.nodeAbsent; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.nodeExists; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.quoteIfNeeded; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.valueToNode; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.ARRAY; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.BOOLEAN; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.NULL; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.NUMBER; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.OBJECT; import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.STRING; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; void testGetStartNodeArraysConvoluted() throws IOException { Node startNode = getNode(mapper.readTree("{\"test\":[{\"values\":[1,2]}, {\"values\":[3,4]}]}"), "test.[1].values.[1]"); assertEquals(4, startNode.decimalValue().intValue()); } @Test void testGetStartNodeArraysRoot() throws IOException { Node startNode = getNode(mapper.readTree("[1,2]"), "[0]"); assertEquals(1, startNode.decimalValue().intValue()); } @Test void testGetStartNodeNonexisting() throws IOException { Node startNode = getNode(mapper.readTree("{\"test\":{\"value\":1}}"), "test.bogus"); assertEquals(true, startNode.isMissingNode()); } @Test @SuppressWarnings("deprecation") void testNodeExists() { String json = "{\"test\":{\"value\":1}}"; assertTrue(nodeExists(json, "test")); assertTrue(nodeExists(json, "test.value")); assertFalse(nodeExists(json, "test.nonsense")); assertFalse(nodeExists(json, "root")); } @Test void testNodeAbsent() { String json = "{\"test\":{\"value\":1, \"value2\": null}}";
assertFalse(nodeAbsent(json, Path.create("test"), false));
lukas-krecan/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/GsonNodeFactory.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static void closeQuietly(final Reader resourceReader) { // if (resourceReader != null) { // try { // resourceReader.close(); // } catch (IOException ignored) { // } // } // }
import static net.javacrumbs.jsonunit.core.internal.Utils.closeQuietly; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonIOException; import com.google.gson.JsonNull; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSyntaxException; import java.io.Reader; import java.math.BigDecimal; import java.util.Iterator; import java.util.Map;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; /** * Deserializes node using Gson */ class GsonNodeFactory extends AbstractNodeFactory { private final Gson gson = new Gson(); @Override protected Node doConvertValue(Object source) { if (source instanceof JsonElement) { return newNode((JsonElement) source); } else { return newNode(gson.toJsonTree(source)); } } @Override protected Node nullNode() { return newNode(JsonNull.INSTANCE); } @Override protected Node readValue(Reader value, String label, boolean lenient) { // GSON is always lenient :-( try { return newNode(JsonParser.parseReader(value)); } catch (JsonIOException | JsonSyntaxException e) { throw newParseException(label, value, e); } finally {
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static void closeQuietly(final Reader resourceReader) { // if (resourceReader != null) { // try { // resourceReader.close(); // } catch (IOException ignored) { // } // } // } // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/GsonNodeFactory.java import static net.javacrumbs.jsonunit.core.internal.Utils.closeQuietly; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonIOException; import com.google.gson.JsonNull; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSyntaxException; import java.io.Reader; import java.math.BigDecimal; import java.util.Iterator; import java.util.Map; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; /** * Deserializes node using Gson */ class GsonNodeFactory extends AbstractNodeFactory { private final Gson gson = new Gson(); @Override protected Node doConvertValue(Object source) { if (source instanceof JsonElement) { return newNode((JsonElement) source); } else { return newNode(gson.toJsonTree(source)); } } @Override protected Node nullNode() { return newNode(JsonNull.INSTANCE); } @Override protected Node readValue(Reader value, String label, boolean lenient) { // GSON is always lenient :-( try { return newNode(JsonParser.parseReader(value)); } catch (JsonIOException | JsonSyntaxException e) { throw newParseException(label, value, e); } finally {
closeQuietly(value);
lukas-krecan/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/AbstractNodeFactory.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static class JsonStringReader extends StringReader { // private final String string; // // public JsonStringReader(@NotNull String s) { // super(s); // this.string = s; // } // // public String getString() { // return string; // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static void closeQuietly(final Reader resourceReader) { // if (resourceReader != null) { // try { // resourceReader.close(); // } catch (IOException ignored) { // } // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static Reader toReader(String string) { // return new JsonStringReader(string); // }
import net.javacrumbs.jsonunit.core.internal.Utils.JsonStringReader; import org.jetbrains.annotations.NotNull; import java.io.Reader; import java.math.BigDecimal; import static net.javacrumbs.jsonunit.core.internal.Utils.closeQuietly; import static net.javacrumbs.jsonunit.core.internal.Utils.toReader;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; /** * Common superclass for node factories */ abstract class AbstractNodeFactory implements NodeFactory { @Override public Node convertToNode(Object source, String label, boolean lenient) { if (source == null) { return nullNode(); } else if (source instanceof Node) { return (Node) source; } else if (source instanceof String && ((String) source).trim().length() > 0) { return readValue((String) source, label, lenient); } else if (source instanceof Reader) { try { return readValue((Reader) source, label, lenient); } finally {
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static class JsonStringReader extends StringReader { // private final String string; // // public JsonStringReader(@NotNull String s) { // super(s); // this.string = s; // } // // public String getString() { // return string; // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static void closeQuietly(final Reader resourceReader) { // if (resourceReader != null) { // try { // resourceReader.close(); // } catch (IOException ignored) { // } // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static Reader toReader(String string) { // return new JsonStringReader(string); // } // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/AbstractNodeFactory.java import net.javacrumbs.jsonunit.core.internal.Utils.JsonStringReader; import org.jetbrains.annotations.NotNull; import java.io.Reader; import java.math.BigDecimal; import static net.javacrumbs.jsonunit.core.internal.Utils.closeQuietly; import static net.javacrumbs.jsonunit.core.internal.Utils.toReader; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; /** * Common superclass for node factories */ abstract class AbstractNodeFactory implements NodeFactory { @Override public Node convertToNode(Object source, String label, boolean lenient) { if (source == null) { return nullNode(); } else if (source instanceof Node) { return (Node) source; } else if (source instanceof String && ((String) source).trim().length() > 0) { return readValue((String) source, label, lenient); } else if (source instanceof Reader) { try { return readValue((Reader) source, label, lenient); } finally {
closeQuietly((Reader) source);
lukas-krecan/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/AbstractNodeFactory.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static class JsonStringReader extends StringReader { // private final String string; // // public JsonStringReader(@NotNull String s) { // super(s); // this.string = s; // } // // public String getString() { // return string; // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static void closeQuietly(final Reader resourceReader) { // if (resourceReader != null) { // try { // resourceReader.close(); // } catch (IOException ignored) { // } // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static Reader toReader(String string) { // return new JsonStringReader(string); // }
import net.javacrumbs.jsonunit.core.internal.Utils.JsonStringReader; import org.jetbrains.annotations.NotNull; import java.io.Reader; import java.math.BigDecimal; import static net.javacrumbs.jsonunit.core.internal.Utils.closeQuietly; import static net.javacrumbs.jsonunit.core.internal.Utils.toReader;
try { return readValue((Reader) source, label, lenient); } finally { closeQuietly((Reader) source); } } else { return convertValue(source); } } @Override public Node valueToNode(Object source) { if (source == null) { return nullNode(); } else { return convertValue(source); } } final Node convertValue(Object source) { if (source instanceof BigDecimal) { return new GenericNodeBuilder.NumberNode((Number) source); } else { return doConvertValue(source); } } @NotNull protected IllegalArgumentException newParseException(String label, Reader value, Exception e) {
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static class JsonStringReader extends StringReader { // private final String string; // // public JsonStringReader(@NotNull String s) { // super(s); // this.string = s; // } // // public String getString() { // return string; // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static void closeQuietly(final Reader resourceReader) { // if (resourceReader != null) { // try { // resourceReader.close(); // } catch (IOException ignored) { // } // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static Reader toReader(String string) { // return new JsonStringReader(string); // } // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/AbstractNodeFactory.java import net.javacrumbs.jsonunit.core.internal.Utils.JsonStringReader; import org.jetbrains.annotations.NotNull; import java.io.Reader; import java.math.BigDecimal; import static net.javacrumbs.jsonunit.core.internal.Utils.closeQuietly; import static net.javacrumbs.jsonunit.core.internal.Utils.toReader; try { return readValue((Reader) source, label, lenient); } finally { closeQuietly((Reader) source); } } else { return convertValue(source); } } @Override public Node valueToNode(Object source) { if (source == null) { return nullNode(); } else { return convertValue(source); } } final Node convertValue(Object source) { if (source instanceof BigDecimal) { return new GenericNodeBuilder.NumberNode((Number) source); } else { return doConvertValue(source); } } @NotNull protected IllegalArgumentException newParseException(String label, Reader value, Exception e) {
if (value instanceof JsonStringReader) {
lukas-krecan/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/AbstractNodeFactory.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static class JsonStringReader extends StringReader { // private final String string; // // public JsonStringReader(@NotNull String s) { // super(s); // this.string = s; // } // // public String getString() { // return string; // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static void closeQuietly(final Reader resourceReader) { // if (resourceReader != null) { // try { // resourceReader.close(); // } catch (IOException ignored) { // } // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static Reader toReader(String string) { // return new JsonStringReader(string); // }
import net.javacrumbs.jsonunit.core.internal.Utils.JsonStringReader; import org.jetbrains.annotations.NotNull; import java.io.Reader; import java.math.BigDecimal; import static net.javacrumbs.jsonunit.core.internal.Utils.closeQuietly; import static net.javacrumbs.jsonunit.core.internal.Utils.toReader;
return nullNode(); } else { return convertValue(source); } } final Node convertValue(Object source) { if (source instanceof BigDecimal) { return new GenericNodeBuilder.NumberNode((Number) source); } else { return doConvertValue(source); } } @NotNull protected IllegalArgumentException newParseException(String label, Reader value, Exception e) { if (value instanceof JsonStringReader) { return new IllegalArgumentException("Can not parse " + label + " value: '" + ((JsonStringReader) value).getString() + "'", e); } else { return new IllegalArgumentException("Can not parse " + label + " value.", e); } } protected abstract Node doConvertValue(Object source); protected abstract Node readValue(Reader reader, String label, boolean lenient); Node readValue(String source, String label, boolean lenient) {
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static class JsonStringReader extends StringReader { // private final String string; // // public JsonStringReader(@NotNull String s) { // super(s); // this.string = s; // } // // public String getString() { // return string; // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static void closeQuietly(final Reader resourceReader) { // if (resourceReader != null) { // try { // resourceReader.close(); // } catch (IOException ignored) { // } // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static Reader toReader(String string) { // return new JsonStringReader(string); // } // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/AbstractNodeFactory.java import net.javacrumbs.jsonunit.core.internal.Utils.JsonStringReader; import org.jetbrains.annotations.NotNull; import java.io.Reader; import java.math.BigDecimal; import static net.javacrumbs.jsonunit.core.internal.Utils.closeQuietly; import static net.javacrumbs.jsonunit.core.internal.Utils.toReader; return nullNode(); } else { return convertValue(source); } } final Node convertValue(Object source) { if (source instanceof BigDecimal) { return new GenericNodeBuilder.NumberNode((Number) source); } else { return doConvertValue(source); } } @NotNull protected IllegalArgumentException newParseException(String label, Reader value, Exception e) { if (value instanceof JsonStringReader) { return new IllegalArgumentException("Can not parse " + label + " value: '" + ((JsonStringReader) value).getString() + "'", e); } else { return new IllegalArgumentException("Can not parse " + label + " value.", e); } } protected abstract Node doConvertValue(Object source); protected abstract Node readValue(Reader reader, String label, boolean lenient); Node readValue(String source, String label, boolean lenient) {
return readValue(toReader(source), label, lenient);
lukas-krecan/JsonUnit
json-unit-spring/src/test/java/net/javacrumbs/jsonunit/spring/testit/ClientTest.java
// Path: json-unit-spring/src/main/java/net/javacrumbs/jsonunit/spring/JsonUnitRequestMatchers.java // @NotNull // public static JsonUnitRequestMatchers json() { // return new JsonUnitRequestMatchers(Path.root(), Configuration.empty()); // }
import org.junit.jupiter.api.Test; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestTemplate; import static net.javacrumbs.jsonunit.spring.JsonUnitRequestMatchers.json; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
/** * Copyright 2009-2019 the original author or authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.spring.testit; class ClientTest { private static final String URI = "/sample"; private final RestTemplate restTemplate = new RestTemplate(); private final MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate); private final String jsonResponse = "{\"response\": \"€\"}";
// Path: json-unit-spring/src/main/java/net/javacrumbs/jsonunit/spring/JsonUnitRequestMatchers.java // @NotNull // public static JsonUnitRequestMatchers json() { // return new JsonUnitRequestMatchers(Path.root(), Configuration.empty()); // } // Path: json-unit-spring/src/test/java/net/javacrumbs/jsonunit/spring/testit/ClientTest.java import org.junit.jupiter.api.Test; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestTemplate; import static net.javacrumbs.jsonunit.spring.JsonUnitRequestMatchers.json; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; /** * Copyright 2009-2019 the original author or authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.spring.testit; class ClientTest { private static final String URI = "/sample"; private final RestTemplate restTemplate = new RestTemplate(); private final MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate); private final String jsonResponse = "{\"response\": \"€\"}";
private final String json = "{\"test\": 1}";
lukas-krecan/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/PathOptionMatcher.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/Option.java // public enum Option { // /** // * Treats null nodes in actual value as absent. In other words // * if you expect {"test":{"a":1}} this {"test":{"a":1, "b": null}} will pass the test. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, exact path to such nodes should be passed, // * which is test.b in the example above. // */ // TREATING_NULL_AS_ABSENT, // // /** // * When comparing arrays, ignores array order. In other words, treats arrays as sets. // */ // IGNORING_ARRAY_ORDER, // // /** // * Ignores extra fields in the actual value. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, path to the nodes with such fields should be passed. // */ // IGNORING_EXTRA_FIELDS, // // // /** // * Passes even if array in compared document has more items than expected. // * Items are taken from the beginning of the expected array unless IGNORING_ARRAY_ORDER is specified. // */ // IGNORING_EXTRA_ARRAY_ITEMS, // // /** // * Compares only structures. Completely ignores both values and types. // * Is too lenient, ignores types, prefer {@link Option#IGNORING_VALUES} instead. // * // * @deprecated Use IGNORING_VALUES option instead // */ // @Deprecated // COMPARING_ONLY_STRUCTURE, // // /** // * Ignores values but fails if value types are different. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, path to the node with ignored value should be passed. // */ // IGNORING_VALUES // }
import net.javacrumbs.jsonunit.core.Option; import java.util.Collection; import java.util.stream.Stream;
package net.javacrumbs.jsonunit.core.internal; class PathOptionMatcher { private final PathMatcher pathMatcher;
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/Option.java // public enum Option { // /** // * Treats null nodes in actual value as absent. In other words // * if you expect {"test":{"a":1}} this {"test":{"a":1, "b": null}} will pass the test. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, exact path to such nodes should be passed, // * which is test.b in the example above. // */ // TREATING_NULL_AS_ABSENT, // // /** // * When comparing arrays, ignores array order. In other words, treats arrays as sets. // */ // IGNORING_ARRAY_ORDER, // // /** // * Ignores extra fields in the actual value. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, path to the nodes with such fields should be passed. // */ // IGNORING_EXTRA_FIELDS, // // // /** // * Passes even if array in compared document has more items than expected. // * Items are taken from the beginning of the expected array unless IGNORING_ARRAY_ORDER is specified. // */ // IGNORING_EXTRA_ARRAY_ITEMS, // // /** // * Compares only structures. Completely ignores both values and types. // * Is too lenient, ignores types, prefer {@link Option#IGNORING_VALUES} instead. // * // * @deprecated Use IGNORING_VALUES option instead // */ // @Deprecated // COMPARING_ONLY_STRUCTURE, // // /** // * Ignores values but fails if value types are different. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, path to the node with ignored value should be passed. // */ // IGNORING_VALUES // } // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/PathOptionMatcher.java import net.javacrumbs.jsonunit.core.Option; import java.util.Collection; import java.util.stream.Stream; package net.javacrumbs.jsonunit.core.internal; class PathOptionMatcher { private final PathMatcher pathMatcher;
private final Option option;
lukas-krecan/JsonUnit
tests/test-jackson2-config/src/test/java/net/javacrumbs/jsonunit/test/jackson2config/Jackson2ConfigTest.java
// Path: json-unit/src/main/java/net/javacrumbs/jsonunit/JsonAssert.java // public static void assertJsonEquals(Object expected, Object actual) { // assertJsonEquals(expected, actual, configuration); // } // // Path: json-unit-assertj/src/main/java/net/javacrumbs/jsonunit/assertj/JsonAssertions.java // @NotNull // public static ConfigurableJsonAssert assertThatJson(@Nullable Object actual) { // return new ConfigurableJsonAssert(actual, Configuration.empty()); // }
import org.junit.jupiter.api.Test; import java.time.Instant; import static net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals; import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.test.jackson2config; class Jackson2ConfigTest { @Test void testSerializeTime() {
// Path: json-unit/src/main/java/net/javacrumbs/jsonunit/JsonAssert.java // public static void assertJsonEquals(Object expected, Object actual) { // assertJsonEquals(expected, actual, configuration); // } // // Path: json-unit-assertj/src/main/java/net/javacrumbs/jsonunit/assertj/JsonAssertions.java // @NotNull // public static ConfigurableJsonAssert assertThatJson(@Nullable Object actual) { // return new ConfigurableJsonAssert(actual, Configuration.empty()); // } // Path: tests/test-jackson2-config/src/test/java/net/javacrumbs/jsonunit/test/jackson2config/Jackson2ConfigTest.java import org.junit.jupiter.api.Test; import java.time.Instant; import static net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals; import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.test.jackson2config; class Jackson2ConfigTest { @Test void testSerializeTime() {
assertThatJson(new Bean()).isEqualTo("{time:'2019-01-11T18:12:00Z'}");
lukas-krecan/JsonUnit
tests/test-jackson2-config/src/test/java/net/javacrumbs/jsonunit/test/jackson2config/Jackson2ConfigTest.java
// Path: json-unit/src/main/java/net/javacrumbs/jsonunit/JsonAssert.java // public static void assertJsonEquals(Object expected, Object actual) { // assertJsonEquals(expected, actual, configuration); // } // // Path: json-unit-assertj/src/main/java/net/javacrumbs/jsonunit/assertj/JsonAssertions.java // @NotNull // public static ConfigurableJsonAssert assertThatJson(@Nullable Object actual) { // return new ConfigurableJsonAssert(actual, Configuration.empty()); // }
import org.junit.jupiter.api.Test; import java.time.Instant; import static net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals; import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.test.jackson2config; class Jackson2ConfigTest { @Test void testSerializeTime() { assertThatJson(new Bean()).isEqualTo("{time:'2019-01-11T18:12:00Z'}"); } @Test void testSerializeTime2() { assertThatJson(new Bean()).isEqualTo(new Bean()); } @Test void assertSame() { String s = "{ \"a\": 0.0 }";
// Path: json-unit/src/main/java/net/javacrumbs/jsonunit/JsonAssert.java // public static void assertJsonEquals(Object expected, Object actual) { // assertJsonEquals(expected, actual, configuration); // } // // Path: json-unit-assertj/src/main/java/net/javacrumbs/jsonunit/assertj/JsonAssertions.java // @NotNull // public static ConfigurableJsonAssert assertThatJson(@Nullable Object actual) { // return new ConfigurableJsonAssert(actual, Configuration.empty()); // } // Path: tests/test-jackson2-config/src/test/java/net/javacrumbs/jsonunit/test/jackson2config/Jackson2ConfigTest.java import org.junit.jupiter.api.Test; import java.time.Instant; import static net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals; import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.test.jackson2config; class Jackson2ConfigTest { @Test void testSerializeTime() { assertThatJson(new Bean()).isEqualTo("{time:'2019-01-11T18:12:00Z'}"); } @Test void testSerializeTime2() { assertThatJson(new Bean()).isEqualTo(new Bean()); } @Test void assertSame() { String s = "{ \"a\": 0.0 }";
assertJsonEquals(s, s);
lukas-krecan/JsonUnit
tests/test-junit4/src/test/java/net/javacrumbs/jsonunit/test/junit4/JUnit4Test.java
// Path: json-unit/src/main/java/net/javacrumbs/jsonunit/JsonAssert.java // public static void assertJsonEquals(Object expected, Object actual) { // assertJsonEquals(expected, actual, configuration); // }
import org.junit.Test; import static net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals; import static org.assertj.core.api.Assertions.assertThatThrownBy;
package net.javacrumbs.jsonunit.test.junit4; public class JUnit4Test { @Test public void testComplexErrors() {
// Path: json-unit/src/main/java/net/javacrumbs/jsonunit/JsonAssert.java // public static void assertJsonEquals(Object expected, Object actual) { // assertJsonEquals(expected, actual, configuration); // } // Path: tests/test-junit4/src/test/java/net/javacrumbs/jsonunit/test/junit4/JUnit4Test.java import org.junit.Test; import static net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals; import static org.assertj.core.api.Assertions.assertThatThrownBy; package net.javacrumbs.jsonunit.test.junit4; public class JUnit4Test { @Test public void testComplexErrors() {
assertThatThrownBy(() -> assertJsonEquals("{\n" +
lukas-krecan/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/ConfigurationWhen.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/PathOption.java // public class PathOption { // private final List<String> paths; // private final Set<Option> options; // // /** // * True if this option is included, false if excluded. // */ // private final boolean included; // // public PathOption(List<String> paths, Set<Option> options, boolean included) { // this.paths = Collections.unmodifiableList(paths); // this.options = Collections.unmodifiableSet(EnumSet.copyOf(options)); // this.included = included; // } // // public List<String> getPaths() { // return paths; // } // // public Set<Option> getOptions() { // return options; // } // // boolean isIncluded() { // return included; // } // // public PathOption withPaths(List<String> newPoPaths) { // return new PathOption(newPoPaths, options, included); // } // }
import net.javacrumbs.jsonunit.core.internal.PathOption; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.HashSet; import java.util.List; import java.util.Set;
private PathsParam(String... paths) { this.paths = Arrays.asList(paths); } List<String> getPaths() { return paths; } Configuration apply(Configuration configuration, ApplicableForPath action) { return action.applyForPaths(configuration, this); } } public interface ApplicableForPath { @NotNull Configuration applyForPaths(@NotNull Configuration configuration, @NotNull PathsParam pathsParam); } static class OptionsParam implements ApplicableForPath { private final EnumSet<Option> options; private final boolean included; private OptionsParam(boolean included, Option first, Option... next) { this.options = EnumSet.of(first, next); this.included = included; } @Override @NotNull public Configuration applyForPaths(@NotNull Configuration configuration, @NotNull PathsParam pathsParam) {
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/PathOption.java // public class PathOption { // private final List<String> paths; // private final Set<Option> options; // // /** // * True if this option is included, false if excluded. // */ // private final boolean included; // // public PathOption(List<String> paths, Set<Option> options, boolean included) { // this.paths = Collections.unmodifiableList(paths); // this.options = Collections.unmodifiableSet(EnumSet.copyOf(options)); // this.included = included; // } // // public List<String> getPaths() { // return paths; // } // // public Set<Option> getOptions() { // return options; // } // // boolean isIncluded() { // return included; // } // // public PathOption withPaths(List<String> newPoPaths) { // return new PathOption(newPoPaths, options, included); // } // } // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/ConfigurationWhen.java import net.javacrumbs.jsonunit.core.internal.PathOption; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.HashSet; import java.util.List; import java.util.Set; private PathsParam(String... paths) { this.paths = Arrays.asList(paths); } List<String> getPaths() { return paths; } Configuration apply(Configuration configuration, ApplicableForPath action) { return action.applyForPaths(configuration, this); } } public interface ApplicableForPath { @NotNull Configuration applyForPaths(@NotNull Configuration configuration, @NotNull PathsParam pathsParam); } static class OptionsParam implements ApplicableForPath { private final EnumSet<Option> options; private final boolean included; private OptionsParam(boolean included, Option first, Option... next) { this.options = EnumSet.of(first, next); this.included = included; } @Override @NotNull public Configuration applyForPaths(@NotNull Configuration configuration, @NotNull PathsParam pathsParam) {
return configuration.addPathOption(new PathOption(pathsParam.getPaths(), options, included));
lukas-krecan/JsonUnit
tests/test-no-hamcrest/src/test/java/net/javacrumbs/jsonunit/test/nohamcrest/NoHamcrestTest.java
// Path: json-unit-fluent/src/main/java/net/javacrumbs/jsonunit/fluent/JsonFluentAssert.java // public static ConfigurableJsonFluentAssert assertThatJson(Object json) { // return new ConfigurableJsonFluentAssert(convertToJson(json, ACTUAL), getPathPrefix(json)); // }
import org.junit.jupiter.api.Test; import static net.javacrumbs.jsonunit.fluent.JsonFluentAssert.assertThatJson;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.test.nohamcrest; class NoHamcrestTest { @Test void comparisonShouldWork() {
// Path: json-unit-fluent/src/main/java/net/javacrumbs/jsonunit/fluent/JsonFluentAssert.java // public static ConfigurableJsonFluentAssert assertThatJson(Object json) { // return new ConfigurableJsonFluentAssert(convertToJson(json, ACTUAL), getPathPrefix(json)); // } // Path: tests/test-no-hamcrest/src/test/java/net/javacrumbs/jsonunit/test/nohamcrest/NoHamcrestTest.java import org.junit.jupiter.api.Test; import static net.javacrumbs.jsonunit.fluent.JsonFluentAssert.assertThatJson; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.test.nohamcrest; class NoHamcrestTest { @Test void comparisonShouldWork() {
assertThatJson("{\"a\":1}").isEqualTo("{a: 1}");
lukas-krecan/JsonUnit
json-unit-core/src/test/java/net/javacrumbs/jsonunit/core/internal/ConverterTest.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ClassUtils.java // static boolean isClassPresent(String className) { // try { // ClassUtils.class.getClassLoader().loadClass(className); // return true; // } catch (Throwable e) { // return false; // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Converter.java // static final String LIBRARIES_PROPERTY_NAME = "json-unit.libraries";
import com.fasterxml.jackson.databind.node.BooleanNode; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; import static net.javacrumbs.jsonunit.core.internal.ClassUtils.isClassPresent; import static net.javacrumbs.jsonunit.core.internal.Converter.LIBRARIES_PROPERTY_NAME; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; class ConverterTest { private static final String JSON = "{\"test\":1}"; @Test void shouldFailIfNoConverterSet() { assertThatThrownBy(() -> new Converter(Collections.emptyList())).isInstanceOf(IllegalStateException.class); } @Test void shouldUseTheLastFactoryForNonPreferred() { Converter converter = new Converter(Arrays.asList(new GsonNodeFactory(), new Jackson2NodeFactory())); Node node = converter.convertToNode(JSON, "", false); assertEquals(Jackson2NodeFactory.Jackson2Node.class, node.getClass()); } @Test void shouldUsePreferredFactory() { Converter converter = new Converter(Arrays.asList(new Jackson2NodeFactory(), new GsonNodeFactory())); Node node = converter.convertToNode(BooleanNode.TRUE, "", false); assertEquals(Jackson2NodeFactory.Jackson2Node.class, node.getClass()); } @Test void shouldUseOnlyFactorySpecifiedBySystemProperty() {
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ClassUtils.java // static boolean isClassPresent(String className) { // try { // ClassUtils.class.getClassLoader().loadClass(className); // return true; // } catch (Throwable e) { // return false; // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Converter.java // static final String LIBRARIES_PROPERTY_NAME = "json-unit.libraries"; // Path: json-unit-core/src/test/java/net/javacrumbs/jsonunit/core/internal/ConverterTest.java import com.fasterxml.jackson.databind.node.BooleanNode; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; import static net.javacrumbs.jsonunit.core.internal.ClassUtils.isClassPresent; import static net.javacrumbs.jsonunit.core.internal.Converter.LIBRARIES_PROPERTY_NAME; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; class ConverterTest { private static final String JSON = "{\"test\":1}"; @Test void shouldFailIfNoConverterSet() { assertThatThrownBy(() -> new Converter(Collections.emptyList())).isInstanceOf(IllegalStateException.class); } @Test void shouldUseTheLastFactoryForNonPreferred() { Converter converter = new Converter(Arrays.asList(new GsonNodeFactory(), new Jackson2NodeFactory())); Node node = converter.convertToNode(JSON, "", false); assertEquals(Jackson2NodeFactory.Jackson2Node.class, node.getClass()); } @Test void shouldUsePreferredFactory() { Converter converter = new Converter(Arrays.asList(new Jackson2NodeFactory(), new GsonNodeFactory())); Node node = converter.convertToNode(BooleanNode.TRUE, "", false); assertEquals(Jackson2NodeFactory.Jackson2Node.class, node.getClass()); } @Test void shouldUseOnlyFactorySpecifiedBySystemProperty() {
System.setProperty(LIBRARIES_PROPERTY_NAME,"gson");
lukas-krecan/JsonUnit
json-unit-core/src/test/java/net/javacrumbs/jsonunit/core/internal/ConverterTest.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ClassUtils.java // static boolean isClassPresent(String className) { // try { // ClassUtils.class.getClassLoader().loadClass(className); // return true; // } catch (Throwable e) { // return false; // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Converter.java // static final String LIBRARIES_PROPERTY_NAME = "json-unit.libraries";
import com.fasterxml.jackson.databind.node.BooleanNode; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; import static net.javacrumbs.jsonunit.core.internal.ClassUtils.isClassPresent; import static net.javacrumbs.jsonunit.core.internal.Converter.LIBRARIES_PROPERTY_NAME; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail;
void shouldUseOnlyFactorySpecifiedBySystemProperty() { System.setProperty(LIBRARIES_PROPERTY_NAME,"gson"); Converter converter = Converter.createDefaultConverter(); assertThat(converter.getFactories()).extracting("class").containsExactly(GsonNodeFactory.class); System.setProperty(LIBRARIES_PROPERTY_NAME, ""); } @Test void shouldChangeOrderSpecifiedBySystemProperty() { System.setProperty(LIBRARIES_PROPERTY_NAME,"jackson2, gson ,json.org"); Converter converter = Converter.createDefaultConverter(); assertThat(converter.getFactories()).extracting("class").containsExactly(Jackson2NodeFactory.class, GsonNodeFactory.class, JsonOrgNodeFactory.class); System.setProperty(LIBRARIES_PROPERTY_NAME, ""); } @Test void shouldFailOnUnknownFactory() { System.setProperty(LIBRARIES_PROPERTY_NAME,"unknown"); try { Converter.createDefaultConverter(); fail("Exception expected"); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).isEqualTo("'unknown' library name not recognized."); } finally { System.setProperty(LIBRARIES_PROPERTY_NAME, ""); } } @Test void classShouldBePresent() {
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ClassUtils.java // static boolean isClassPresent(String className) { // try { // ClassUtils.class.getClassLoader().loadClass(className); // return true; // } catch (Throwable e) { // return false; // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Converter.java // static final String LIBRARIES_PROPERTY_NAME = "json-unit.libraries"; // Path: json-unit-core/src/test/java/net/javacrumbs/jsonunit/core/internal/ConverterTest.java import com.fasterxml.jackson.databind.node.BooleanNode; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; import static net.javacrumbs.jsonunit.core.internal.ClassUtils.isClassPresent; import static net.javacrumbs.jsonunit.core.internal.Converter.LIBRARIES_PROPERTY_NAME; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; void shouldUseOnlyFactorySpecifiedBySystemProperty() { System.setProperty(LIBRARIES_PROPERTY_NAME,"gson"); Converter converter = Converter.createDefaultConverter(); assertThat(converter.getFactories()).extracting("class").containsExactly(GsonNodeFactory.class); System.setProperty(LIBRARIES_PROPERTY_NAME, ""); } @Test void shouldChangeOrderSpecifiedBySystemProperty() { System.setProperty(LIBRARIES_PROPERTY_NAME,"jackson2, gson ,json.org"); Converter converter = Converter.createDefaultConverter(); assertThat(converter.getFactories()).extracting("class").containsExactly(Jackson2NodeFactory.class, GsonNodeFactory.class, JsonOrgNodeFactory.class); System.setProperty(LIBRARIES_PROPERTY_NAME, ""); } @Test void shouldFailOnUnknownFactory() { System.setProperty(LIBRARIES_PROPERTY_NAME,"unknown"); try { Converter.createDefaultConverter(); fail("Exception expected"); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).isEqualTo("'unknown' library name not recognized."); } finally { System.setProperty(LIBRARIES_PROPERTY_NAME, ""); } } @Test void classShouldBePresent() {
assertTrue(isClassPresent("java.lang.String"));
lukas-krecan/JsonUnit
tests/test-base/src/main/java/net/javacrumbs/jsonunit/test/base/RecordingDifferenceListener.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/listener/Difference.java // public interface Difference { // enum Type {EXTRA, MISSING, DIFFERENT} // // /** // * Path to the difference // */ // String getActualPath(); // // /** // * Path to the expected element (may be different than actual path if IGNORE_ARRAY_ORDER is used) // */ // String getExpectedPath(); // // /** // * Actual node serialized as Map&lt;String, Object&gt; for objects, BigDecimal for numbers, ... // */ // Object getActual(); // // // /** // * Expected node serialized as Map&lt;String, Object&gt; for objects, BigDecimal for numbers, ... // */ // Object getExpected(); // // /** // * Type of the difference // */ // Type getType(); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/listener/DifferenceContext.java // public interface DifferenceContext { // // /** // * Configuration used for comparison. // */ // Configuration getConfiguration(); // // /** // * Actual source serialized as Map&lt;String, Object&gt; for objects, BigDecimal for numbers, ... // */ // Object getActualSource(); // // // /** // * Expected source serialized as Map&lt;String, Object&gt; for objects, BigDecimal for numbers, ... // */ // Object getExpectedSource(); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/listener/DifferenceListener.java // public interface DifferenceListener { // void diff(Difference difference, DifferenceContext context); // }
import net.javacrumbs.jsonunit.core.listener.Difference; import net.javacrumbs.jsonunit.core.listener.DifferenceContext; import net.javacrumbs.jsonunit.core.listener.DifferenceListener; import java.util.ArrayList; import java.util.List;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.test.base; public class RecordingDifferenceListener implements DifferenceListener { private final List<Difference> differenceList = new ArrayList<>(); @Override
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/listener/Difference.java // public interface Difference { // enum Type {EXTRA, MISSING, DIFFERENT} // // /** // * Path to the difference // */ // String getActualPath(); // // /** // * Path to the expected element (may be different than actual path if IGNORE_ARRAY_ORDER is used) // */ // String getExpectedPath(); // // /** // * Actual node serialized as Map&lt;String, Object&gt; for objects, BigDecimal for numbers, ... // */ // Object getActual(); // // // /** // * Expected node serialized as Map&lt;String, Object&gt; for objects, BigDecimal for numbers, ... // */ // Object getExpected(); // // /** // * Type of the difference // */ // Type getType(); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/listener/DifferenceContext.java // public interface DifferenceContext { // // /** // * Configuration used for comparison. // */ // Configuration getConfiguration(); // // /** // * Actual source serialized as Map&lt;String, Object&gt; for objects, BigDecimal for numbers, ... // */ // Object getActualSource(); // // // /** // * Expected source serialized as Map&lt;String, Object&gt; for objects, BigDecimal for numbers, ... // */ // Object getExpectedSource(); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/listener/DifferenceListener.java // public interface DifferenceListener { // void diff(Difference difference, DifferenceContext context); // } // Path: tests/test-base/src/main/java/net/javacrumbs/jsonunit/test/base/RecordingDifferenceListener.java import net.javacrumbs.jsonunit.core.listener.Difference; import net.javacrumbs.jsonunit.core.listener.DifferenceContext; import net.javacrumbs.jsonunit.core.listener.DifferenceListener; import java.util.ArrayList; import java.util.List; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.test.base; public class RecordingDifferenceListener implements DifferenceListener { private final List<Difference> differenceList = new ArrayList<>(); @Override
public void diff(Difference difference, DifferenceContext context) {
lukas-krecan/JsonUnit
json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/JsonPathAdapter.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Object jsonSource(Object json, String pathPrefix) { // return jsonSource(json, pathPrefix, emptyList()); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Object missingNode() { // return Node.MISSING_NODE; // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node wrapDeserializedObject(Object source) { // return GenericNodeBuilder.wrapDeserializedObject(source); // } // // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/InternalJsonPathUtils.java // static String fromBracketNotation(String path) { // return path // .replace("['", ".") // .replace("']", ""); // } // // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/InternalJsonPathUtils.java // static <T> T readValue(com.jayway.jsonpath.Configuration conf, Object json, String path) { // if (json instanceof String) { // return using(conf).parse((String) json).read(path); // } else { // return using(conf).parse(JsonUtils.convertToJson(json, "actual").getValue()).read(path); // } // }
import com.jayway.jsonpath.EvaluationListener; import com.jayway.jsonpath.PathNotFoundException; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import static com.jayway.jsonpath.Configuration.defaultConfiguration; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.jsonSource; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.missingNode; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.wrapDeserializedObject; import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.fromBracketNotation; import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.readValue;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.jsonpath; /** * Adapts json-path to json-unit. */ public final class JsonPathAdapter { private JsonPathAdapter() { } public static Object inPath(@NotNull Object json, @NotNull String path) {
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Object jsonSource(Object json, String pathPrefix) { // return jsonSource(json, pathPrefix, emptyList()); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Object missingNode() { // return Node.MISSING_NODE; // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node wrapDeserializedObject(Object source) { // return GenericNodeBuilder.wrapDeserializedObject(source); // } // // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/InternalJsonPathUtils.java // static String fromBracketNotation(String path) { // return path // .replace("['", ".") // .replace("']", ""); // } // // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/InternalJsonPathUtils.java // static <T> T readValue(com.jayway.jsonpath.Configuration conf, Object json, String path) { // if (json instanceof String) { // return using(conf).parse((String) json).read(path); // } else { // return using(conf).parse(JsonUtils.convertToJson(json, "actual").getValue()).read(path); // } // } // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/JsonPathAdapter.java import com.jayway.jsonpath.EvaluationListener; import com.jayway.jsonpath.PathNotFoundException; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import static com.jayway.jsonpath.Configuration.defaultConfiguration; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.jsonSource; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.missingNode; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.wrapDeserializedObject; import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.fromBracketNotation; import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.readValue; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.jsonpath; /** * Adapts json-path to json-unit. */ public final class JsonPathAdapter { private JsonPathAdapter() { } public static Object inPath(@NotNull Object json, @NotNull String path) {
String normalizedPath = fromBracketNotation(path);
lukas-krecan/JsonUnit
json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/JsonPathAdapter.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Object jsonSource(Object json, String pathPrefix) { // return jsonSource(json, pathPrefix, emptyList()); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Object missingNode() { // return Node.MISSING_NODE; // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node wrapDeserializedObject(Object source) { // return GenericNodeBuilder.wrapDeserializedObject(source); // } // // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/InternalJsonPathUtils.java // static String fromBracketNotation(String path) { // return path // .replace("['", ".") // .replace("']", ""); // } // // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/InternalJsonPathUtils.java // static <T> T readValue(com.jayway.jsonpath.Configuration conf, Object json, String path) { // if (json instanceof String) { // return using(conf).parse((String) json).read(path); // } else { // return using(conf).parse(JsonUtils.convertToJson(json, "actual").getValue()).read(path); // } // }
import com.jayway.jsonpath.EvaluationListener; import com.jayway.jsonpath.PathNotFoundException; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import static com.jayway.jsonpath.Configuration.defaultConfiguration; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.jsonSource; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.missingNode; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.wrapDeserializedObject; import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.fromBracketNotation; import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.readValue;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.jsonpath; /** * Adapts json-path to json-unit. */ public final class JsonPathAdapter { private JsonPathAdapter() { } public static Object inPath(@NotNull Object json, @NotNull String path) { String normalizedPath = fromBracketNotation(path); try { MatchRecordingListener recordingListener = new MatchRecordingListener();
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Object jsonSource(Object json, String pathPrefix) { // return jsonSource(json, pathPrefix, emptyList()); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Object missingNode() { // return Node.MISSING_NODE; // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node wrapDeserializedObject(Object source) { // return GenericNodeBuilder.wrapDeserializedObject(source); // } // // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/InternalJsonPathUtils.java // static String fromBracketNotation(String path) { // return path // .replace("['", ".") // .replace("']", ""); // } // // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/InternalJsonPathUtils.java // static <T> T readValue(com.jayway.jsonpath.Configuration conf, Object json, String path) { // if (json instanceof String) { // return using(conf).parse((String) json).read(path); // } else { // return using(conf).parse(JsonUtils.convertToJson(json, "actual").getValue()).read(path); // } // } // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/JsonPathAdapter.java import com.jayway.jsonpath.EvaluationListener; import com.jayway.jsonpath.PathNotFoundException; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import static com.jayway.jsonpath.Configuration.defaultConfiguration; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.jsonSource; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.missingNode; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.wrapDeserializedObject; import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.fromBracketNotation; import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.readValue; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.jsonpath; /** * Adapts json-path to json-unit. */ public final class JsonPathAdapter { private JsonPathAdapter() { } public static Object inPath(@NotNull Object json, @NotNull String path) { String normalizedPath = fromBracketNotation(path); try { MatchRecordingListener recordingListener = new MatchRecordingListener();
Object value = readValue(defaultConfiguration().addEvaluationListeners(recordingListener), json, path);
lukas-krecan/JsonUnit
json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/JsonPathAdapter.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Object jsonSource(Object json, String pathPrefix) { // return jsonSource(json, pathPrefix, emptyList()); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Object missingNode() { // return Node.MISSING_NODE; // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node wrapDeserializedObject(Object source) { // return GenericNodeBuilder.wrapDeserializedObject(source); // } // // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/InternalJsonPathUtils.java // static String fromBracketNotation(String path) { // return path // .replace("['", ".") // .replace("']", ""); // } // // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/InternalJsonPathUtils.java // static <T> T readValue(com.jayway.jsonpath.Configuration conf, Object json, String path) { // if (json instanceof String) { // return using(conf).parse((String) json).read(path); // } else { // return using(conf).parse(JsonUtils.convertToJson(json, "actual").getValue()).read(path); // } // }
import com.jayway.jsonpath.EvaluationListener; import com.jayway.jsonpath.PathNotFoundException; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import static com.jayway.jsonpath.Configuration.defaultConfiguration; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.jsonSource; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.missingNode; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.wrapDeserializedObject; import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.fromBracketNotation; import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.readValue;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.jsonpath; /** * Adapts json-path to json-unit. */ public final class JsonPathAdapter { private JsonPathAdapter() { } public static Object inPath(@NotNull Object json, @NotNull String path) { String normalizedPath = fromBracketNotation(path); try { MatchRecordingListener recordingListener = new MatchRecordingListener(); Object value = readValue(defaultConfiguration().addEvaluationListeners(recordingListener), json, path);
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Object jsonSource(Object json, String pathPrefix) { // return jsonSource(json, pathPrefix, emptyList()); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Object missingNode() { // return Node.MISSING_NODE; // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node wrapDeserializedObject(Object source) { // return GenericNodeBuilder.wrapDeserializedObject(source); // } // // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/InternalJsonPathUtils.java // static String fromBracketNotation(String path) { // return path // .replace("['", ".") // .replace("']", ""); // } // // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/InternalJsonPathUtils.java // static <T> T readValue(com.jayway.jsonpath.Configuration conf, Object json, String path) { // if (json instanceof String) { // return using(conf).parse((String) json).read(path); // } else { // return using(conf).parse(JsonUtils.convertToJson(json, "actual").getValue()).read(path); // } // } // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/JsonPathAdapter.java import com.jayway.jsonpath.EvaluationListener; import com.jayway.jsonpath.PathNotFoundException; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import static com.jayway.jsonpath.Configuration.defaultConfiguration; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.jsonSource; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.missingNode; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.wrapDeserializedObject; import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.fromBracketNotation; import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.readValue; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.jsonpath; /** * Adapts json-path to json-unit. */ public final class JsonPathAdapter { private JsonPathAdapter() { } public static Object inPath(@NotNull Object json, @NotNull String path) { String normalizedPath = fromBracketNotation(path); try { MatchRecordingListener recordingListener = new MatchRecordingListener(); Object value = readValue(defaultConfiguration().addEvaluationListeners(recordingListener), json, path);
return jsonSource(wrapDeserializedObject(value), normalizedPath, recordingListener.getMatchingPaths());
lukas-krecan/JsonUnit
json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/JsonPathAdapter.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Object jsonSource(Object json, String pathPrefix) { // return jsonSource(json, pathPrefix, emptyList()); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Object missingNode() { // return Node.MISSING_NODE; // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node wrapDeserializedObject(Object source) { // return GenericNodeBuilder.wrapDeserializedObject(source); // } // // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/InternalJsonPathUtils.java // static String fromBracketNotation(String path) { // return path // .replace("['", ".") // .replace("']", ""); // } // // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/InternalJsonPathUtils.java // static <T> T readValue(com.jayway.jsonpath.Configuration conf, Object json, String path) { // if (json instanceof String) { // return using(conf).parse((String) json).read(path); // } else { // return using(conf).parse(JsonUtils.convertToJson(json, "actual").getValue()).read(path); // } // }
import com.jayway.jsonpath.EvaluationListener; import com.jayway.jsonpath.PathNotFoundException; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import static com.jayway.jsonpath.Configuration.defaultConfiguration; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.jsonSource; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.missingNode; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.wrapDeserializedObject; import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.fromBracketNotation; import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.readValue;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.jsonpath; /** * Adapts json-path to json-unit. */ public final class JsonPathAdapter { private JsonPathAdapter() { } public static Object inPath(@NotNull Object json, @NotNull String path) { String normalizedPath = fromBracketNotation(path); try { MatchRecordingListener recordingListener = new MatchRecordingListener(); Object value = readValue(defaultConfiguration().addEvaluationListeners(recordingListener), json, path);
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Object jsonSource(Object json, String pathPrefix) { // return jsonSource(json, pathPrefix, emptyList()); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Object missingNode() { // return Node.MISSING_NODE; // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node wrapDeserializedObject(Object source) { // return GenericNodeBuilder.wrapDeserializedObject(source); // } // // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/InternalJsonPathUtils.java // static String fromBracketNotation(String path) { // return path // .replace("['", ".") // .replace("']", ""); // } // // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/InternalJsonPathUtils.java // static <T> T readValue(com.jayway.jsonpath.Configuration conf, Object json, String path) { // if (json instanceof String) { // return using(conf).parse((String) json).read(path); // } else { // return using(conf).parse(JsonUtils.convertToJson(json, "actual").getValue()).read(path); // } // } // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/JsonPathAdapter.java import com.jayway.jsonpath.EvaluationListener; import com.jayway.jsonpath.PathNotFoundException; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import static com.jayway.jsonpath.Configuration.defaultConfiguration; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.jsonSource; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.missingNode; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.wrapDeserializedObject; import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.fromBracketNotation; import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.readValue; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.jsonpath; /** * Adapts json-path to json-unit. */ public final class JsonPathAdapter { private JsonPathAdapter() { } public static Object inPath(@NotNull Object json, @NotNull String path) { String normalizedPath = fromBracketNotation(path); try { MatchRecordingListener recordingListener = new MatchRecordingListener(); Object value = readValue(defaultConfiguration().addEvaluationListeners(recordingListener), json, path);
return jsonSource(wrapDeserializedObject(value), normalizedPath, recordingListener.getMatchingPaths());
lukas-krecan/JsonUnit
json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/JsonPathAdapter.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Object jsonSource(Object json, String pathPrefix) { // return jsonSource(json, pathPrefix, emptyList()); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Object missingNode() { // return Node.MISSING_NODE; // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node wrapDeserializedObject(Object source) { // return GenericNodeBuilder.wrapDeserializedObject(source); // } // // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/InternalJsonPathUtils.java // static String fromBracketNotation(String path) { // return path // .replace("['", ".") // .replace("']", ""); // } // // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/InternalJsonPathUtils.java // static <T> T readValue(com.jayway.jsonpath.Configuration conf, Object json, String path) { // if (json instanceof String) { // return using(conf).parse((String) json).read(path); // } else { // return using(conf).parse(JsonUtils.convertToJson(json, "actual").getValue()).read(path); // } // }
import com.jayway.jsonpath.EvaluationListener; import com.jayway.jsonpath.PathNotFoundException; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import static com.jayway.jsonpath.Configuration.defaultConfiguration; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.jsonSource; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.missingNode; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.wrapDeserializedObject; import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.fromBracketNotation; import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.readValue;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.jsonpath; /** * Adapts json-path to json-unit. */ public final class JsonPathAdapter { private JsonPathAdapter() { } public static Object inPath(@NotNull Object json, @NotNull String path) { String normalizedPath = fromBracketNotation(path); try { MatchRecordingListener recordingListener = new MatchRecordingListener(); Object value = readValue(defaultConfiguration().addEvaluationListeners(recordingListener), json, path); return jsonSource(wrapDeserializedObject(value), normalizedPath, recordingListener.getMatchingPaths()); } catch (PathNotFoundException e) {
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Object jsonSource(Object json, String pathPrefix) { // return jsonSource(json, pathPrefix, emptyList()); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Object missingNode() { // return Node.MISSING_NODE; // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java // public static Node wrapDeserializedObject(Object source) { // return GenericNodeBuilder.wrapDeserializedObject(source); // } // // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/InternalJsonPathUtils.java // static String fromBracketNotation(String path) { // return path // .replace("['", ".") // .replace("']", ""); // } // // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/InternalJsonPathUtils.java // static <T> T readValue(com.jayway.jsonpath.Configuration conf, Object json, String path) { // if (json instanceof String) { // return using(conf).parse((String) json).read(path); // } else { // return using(conf).parse(JsonUtils.convertToJson(json, "actual").getValue()).read(path); // } // } // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/JsonPathAdapter.java import com.jayway.jsonpath.EvaluationListener; import com.jayway.jsonpath.PathNotFoundException; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import static com.jayway.jsonpath.Configuration.defaultConfiguration; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.jsonSource; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.missingNode; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.wrapDeserializedObject; import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.fromBracketNotation; import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.readValue; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.jsonpath; /** * Adapts json-path to json-unit. */ public final class JsonPathAdapter { private JsonPathAdapter() { } public static Object inPath(@NotNull Object json, @NotNull String path) { String normalizedPath = fromBracketNotation(path); try { MatchRecordingListener recordingListener = new MatchRecordingListener(); Object value = readValue(defaultConfiguration().addEvaluationListeners(recordingListener), json, path); return jsonSource(wrapDeserializedObject(value), normalizedPath, recordingListener.getMatchingPaths()); } catch (PathNotFoundException e) {
return jsonSource(missingNode(), normalizedPath);
lukas-krecan/JsonUnit
json-unit-core/src/test/java/net/javacrumbs/jsonunit/core/internal/NodeFactoryTest.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static Reader toReader(String string) { // return new JsonStringReader(string); // }
import static org.junit.Assert.assertTrue; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import static java.math.BigDecimal.ONE; import static java.math.BigDecimal.valueOf; import static java.util.Arrays.asList; import static net.javacrumbs.jsonunit.core.internal.Utils.toReader; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse;
assertEquals(Node.NodeType.OBJECT, node.getNodeType()); Node root = node.get("root"); assertEquals(Node.NodeType.OBJECT, root.getNodeType()); Node a = root.get("a"); assertEquals(Node.NodeType.NUMBER, a.getNodeType()); assertEquals(ONE, a.decimalValue()); Node b = root.get("b"); assertEquals(Node.NodeType.NULL, b.getNodeType()); assertEquals(true, b.isNull()); } @Test public void shouldConvertArray() { Node node = factory.convertValue(new int[]{1, 2}); assertEquals(Node.NodeType.ARRAY, node.getNodeType()); assertEquals(ONE, node.element(0).decimalValue()); } @Test public void shouldConvertCollection() { Node node = factory.convertValue(asList(false, "two")); assertEquals(Node.NodeType.ARRAY, node.getNodeType()); assertEquals(false, node.element(0).asBoolean()); assertEquals("two", node.element(1).asText()); } private Node read(String value) {
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Utils.java // static Reader toReader(String string) { // return new JsonStringReader(string); // } // Path: json-unit-core/src/test/java/net/javacrumbs/jsonunit/core/internal/NodeFactoryTest.java import static org.junit.Assert.assertTrue; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import static java.math.BigDecimal.ONE; import static java.math.BigDecimal.valueOf; import static java.util.Arrays.asList; import static net.javacrumbs.jsonunit.core.internal.Utils.toReader; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; assertEquals(Node.NodeType.OBJECT, node.getNodeType()); Node root = node.get("root"); assertEquals(Node.NodeType.OBJECT, root.getNodeType()); Node a = root.get("a"); assertEquals(Node.NodeType.NUMBER, a.getNodeType()); assertEquals(ONE, a.decimalValue()); Node b = root.get("b"); assertEquals(Node.NodeType.NULL, b.getNodeType()); assertEquals(true, b.isNull()); } @Test public void shouldConvertArray() { Node node = factory.convertValue(new int[]{1, 2}); assertEquals(Node.NodeType.ARRAY, node.getNodeType()); assertEquals(ONE, node.element(0).decimalValue()); } @Test public void shouldConvertCollection() { Node node = factory.convertValue(asList(false, "two")); assertEquals(Node.NodeType.ARRAY, node.getNodeType()); assertEquals(false, node.element(0).asBoolean()); assertEquals("two", node.element(1).asText()); } private Node read(String value) {
return factory.readValue(toReader(value), "label", false);
lukas-krecan/JsonUnit
tests/test-json-path/src/test/java/net/javacrumbs/jsonunit/test/jsonpath/JsonPathTest.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/Option.java // public enum Option { // /** // * Treats null nodes in actual value as absent. In other words // * if you expect {"test":{"a":1}} this {"test":{"a":1, "b": null}} will pass the test. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, exact path to such nodes should be passed, // * which is test.b in the example above. // */ // TREATING_NULL_AS_ABSENT, // // /** // * When comparing arrays, ignores array order. In other words, treats arrays as sets. // */ // IGNORING_ARRAY_ORDER, // // /** // * Ignores extra fields in the actual value. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, path to the nodes with such fields should be passed. // */ // IGNORING_EXTRA_FIELDS, // // // /** // * Passes even if array in compared document has more items than expected. // * Items are taken from the beginning of the expected array unless IGNORING_ARRAY_ORDER is specified. // */ // IGNORING_EXTRA_ARRAY_ITEMS, // // /** // * Compares only structures. Completely ignores both values and types. // * Is too lenient, ignores types, prefer {@link Option#IGNORING_VALUES} instead. // * // * @deprecated Use IGNORING_VALUES option instead // */ // @Deprecated // COMPARING_ONLY_STRUCTURE, // // /** // * Ignores values but fails if value types are different. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, path to the node with ignored value should be passed. // */ // IGNORING_VALUES // } // // Path: json-unit-fluent/src/main/java/net/javacrumbs/jsonunit/fluent/JsonFluentAssert.java // public static ConfigurableJsonFluentAssert assertThatJson(Object json) { // return new ConfigurableJsonFluentAssert(convertToJson(json, ACTUAL), getPathPrefix(json)); // } // // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/JsonPathAdapter.java // public static Object inPath(@NotNull Object json, @NotNull String path) { // String normalizedPath = fromBracketNotation(path); // try { // MatchRecordingListener recordingListener = new MatchRecordingListener(); // Object value = readValue(defaultConfiguration().addEvaluationListeners(recordingListener), json, path); // return jsonSource(wrapDeserializedObject(value), normalizedPath, recordingListener.getMatchingPaths()); // } catch (PathNotFoundException e) { // return jsonSource(missingNode(), normalizedPath); // } // }
import net.javacrumbs.jsonunit.core.Option; import org.junit.jupiter.api.Test; import static net.javacrumbs.jsonunit.fluent.JsonFluentAssert.assertThatJson; import static net.javacrumbs.jsonunit.jsonpath.JsonPathAdapter.inPath; import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.test.jsonpath; class JsonPathTest { @Test void shouldBeAbleToUseSimpleValues() {
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/Option.java // public enum Option { // /** // * Treats null nodes in actual value as absent. In other words // * if you expect {"test":{"a":1}} this {"test":{"a":1, "b": null}} will pass the test. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, exact path to such nodes should be passed, // * which is test.b in the example above. // */ // TREATING_NULL_AS_ABSENT, // // /** // * When comparing arrays, ignores array order. In other words, treats arrays as sets. // */ // IGNORING_ARRAY_ORDER, // // /** // * Ignores extra fields in the actual value. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, path to the nodes with such fields should be passed. // */ // IGNORING_EXTRA_FIELDS, // // // /** // * Passes even if array in compared document has more items than expected. // * Items are taken from the beginning of the expected array unless IGNORING_ARRAY_ORDER is specified. // */ // IGNORING_EXTRA_ARRAY_ITEMS, // // /** // * Compares only structures. Completely ignores both values and types. // * Is too lenient, ignores types, prefer {@link Option#IGNORING_VALUES} instead. // * // * @deprecated Use IGNORING_VALUES option instead // */ // @Deprecated // COMPARING_ONLY_STRUCTURE, // // /** // * Ignores values but fails if value types are different. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, path to the node with ignored value should be passed. // */ // IGNORING_VALUES // } // // Path: json-unit-fluent/src/main/java/net/javacrumbs/jsonunit/fluent/JsonFluentAssert.java // public static ConfigurableJsonFluentAssert assertThatJson(Object json) { // return new ConfigurableJsonFluentAssert(convertToJson(json, ACTUAL), getPathPrefix(json)); // } // // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/JsonPathAdapter.java // public static Object inPath(@NotNull Object json, @NotNull String path) { // String normalizedPath = fromBracketNotation(path); // try { // MatchRecordingListener recordingListener = new MatchRecordingListener(); // Object value = readValue(defaultConfiguration().addEvaluationListeners(recordingListener), json, path); // return jsonSource(wrapDeserializedObject(value), normalizedPath, recordingListener.getMatchingPaths()); // } catch (PathNotFoundException e) { // return jsonSource(missingNode(), normalizedPath); // } // } // Path: tests/test-json-path/src/test/java/net/javacrumbs/jsonunit/test/jsonpath/JsonPathTest.java import net.javacrumbs.jsonunit.core.Option; import org.junit.jupiter.api.Test; import static net.javacrumbs.jsonunit.fluent.JsonFluentAssert.assertThatJson; import static net.javacrumbs.jsonunit.jsonpath.JsonPathAdapter.inPath; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.test.jsonpath; class JsonPathTest { @Test void shouldBeAbleToUseSimpleValues() {
assertThatJson(inPath(json, "$.store.book[*].author"))
lukas-krecan/JsonUnit
tests/test-json-path/src/test/java/net/javacrumbs/jsonunit/test/jsonpath/JsonPathTest.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/Option.java // public enum Option { // /** // * Treats null nodes in actual value as absent. In other words // * if you expect {"test":{"a":1}} this {"test":{"a":1, "b": null}} will pass the test. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, exact path to such nodes should be passed, // * which is test.b in the example above. // */ // TREATING_NULL_AS_ABSENT, // // /** // * When comparing arrays, ignores array order. In other words, treats arrays as sets. // */ // IGNORING_ARRAY_ORDER, // // /** // * Ignores extra fields in the actual value. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, path to the nodes with such fields should be passed. // */ // IGNORING_EXTRA_FIELDS, // // // /** // * Passes even if array in compared document has more items than expected. // * Items are taken from the beginning of the expected array unless IGNORING_ARRAY_ORDER is specified. // */ // IGNORING_EXTRA_ARRAY_ITEMS, // // /** // * Compares only structures. Completely ignores both values and types. // * Is too lenient, ignores types, prefer {@link Option#IGNORING_VALUES} instead. // * // * @deprecated Use IGNORING_VALUES option instead // */ // @Deprecated // COMPARING_ONLY_STRUCTURE, // // /** // * Ignores values but fails if value types are different. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, path to the node with ignored value should be passed. // */ // IGNORING_VALUES // } // // Path: json-unit-fluent/src/main/java/net/javacrumbs/jsonunit/fluent/JsonFluentAssert.java // public static ConfigurableJsonFluentAssert assertThatJson(Object json) { // return new ConfigurableJsonFluentAssert(convertToJson(json, ACTUAL), getPathPrefix(json)); // } // // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/JsonPathAdapter.java // public static Object inPath(@NotNull Object json, @NotNull String path) { // String normalizedPath = fromBracketNotation(path); // try { // MatchRecordingListener recordingListener = new MatchRecordingListener(); // Object value = readValue(defaultConfiguration().addEvaluationListeners(recordingListener), json, path); // return jsonSource(wrapDeserializedObject(value), normalizedPath, recordingListener.getMatchingPaths()); // } catch (PathNotFoundException e) { // return jsonSource(missingNode(), normalizedPath); // } // }
import net.javacrumbs.jsonunit.core.Option; import org.junit.jupiter.api.Test; import static net.javacrumbs.jsonunit.fluent.JsonFluentAssert.assertThatJson; import static net.javacrumbs.jsonunit.jsonpath.JsonPathAdapter.inPath; import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.test.jsonpath; class JsonPathTest { @Test void shouldBeAbleToUseSimpleValues() {
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/Option.java // public enum Option { // /** // * Treats null nodes in actual value as absent. In other words // * if you expect {"test":{"a":1}} this {"test":{"a":1, "b": null}} will pass the test. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, exact path to such nodes should be passed, // * which is test.b in the example above. // */ // TREATING_NULL_AS_ABSENT, // // /** // * When comparing arrays, ignores array order. In other words, treats arrays as sets. // */ // IGNORING_ARRAY_ORDER, // // /** // * Ignores extra fields in the actual value. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, path to the nodes with such fields should be passed. // */ // IGNORING_EXTRA_FIELDS, // // // /** // * Passes even if array in compared document has more items than expected. // * Items are taken from the beginning of the expected array unless IGNORING_ARRAY_ORDER is specified. // */ // IGNORING_EXTRA_ARRAY_ITEMS, // // /** // * Compares only structures. Completely ignores both values and types. // * Is too lenient, ignores types, prefer {@link Option#IGNORING_VALUES} instead. // * // * @deprecated Use IGNORING_VALUES option instead // */ // @Deprecated // COMPARING_ONLY_STRUCTURE, // // /** // * Ignores values but fails if value types are different. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, path to the node with ignored value should be passed. // */ // IGNORING_VALUES // } // // Path: json-unit-fluent/src/main/java/net/javacrumbs/jsonunit/fluent/JsonFluentAssert.java // public static ConfigurableJsonFluentAssert assertThatJson(Object json) { // return new ConfigurableJsonFluentAssert(convertToJson(json, ACTUAL), getPathPrefix(json)); // } // // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/JsonPathAdapter.java // public static Object inPath(@NotNull Object json, @NotNull String path) { // String normalizedPath = fromBracketNotation(path); // try { // MatchRecordingListener recordingListener = new MatchRecordingListener(); // Object value = readValue(defaultConfiguration().addEvaluationListeners(recordingListener), json, path); // return jsonSource(wrapDeserializedObject(value), normalizedPath, recordingListener.getMatchingPaths()); // } catch (PathNotFoundException e) { // return jsonSource(missingNode(), normalizedPath); // } // } // Path: tests/test-json-path/src/test/java/net/javacrumbs/jsonunit/test/jsonpath/JsonPathTest.java import net.javacrumbs.jsonunit.core.Option; import org.junit.jupiter.api.Test; import static net.javacrumbs.jsonunit.fluent.JsonFluentAssert.assertThatJson; import static net.javacrumbs.jsonunit.jsonpath.JsonPathAdapter.inPath; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.test.jsonpath; class JsonPathTest { @Test void shouldBeAbleToUseSimpleValues() {
assertThatJson(inPath(json, "$.store.book[*].author"))
lukas-krecan/JsonUnit
tests/test-json-path/src/test/java/net/javacrumbs/jsonunit/test/jsonpath/JsonPathTest.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/Option.java // public enum Option { // /** // * Treats null nodes in actual value as absent. In other words // * if you expect {"test":{"a":1}} this {"test":{"a":1, "b": null}} will pass the test. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, exact path to such nodes should be passed, // * which is test.b in the example above. // */ // TREATING_NULL_AS_ABSENT, // // /** // * When comparing arrays, ignores array order. In other words, treats arrays as sets. // */ // IGNORING_ARRAY_ORDER, // // /** // * Ignores extra fields in the actual value. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, path to the nodes with such fields should be passed. // */ // IGNORING_EXTRA_FIELDS, // // // /** // * Passes even if array in compared document has more items than expected. // * Items are taken from the beginning of the expected array unless IGNORING_ARRAY_ORDER is specified. // */ // IGNORING_EXTRA_ARRAY_ITEMS, // // /** // * Compares only structures. Completely ignores both values and types. // * Is too lenient, ignores types, prefer {@link Option#IGNORING_VALUES} instead. // * // * @deprecated Use IGNORING_VALUES option instead // */ // @Deprecated // COMPARING_ONLY_STRUCTURE, // // /** // * Ignores values but fails if value types are different. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, path to the node with ignored value should be passed. // */ // IGNORING_VALUES // } // // Path: json-unit-fluent/src/main/java/net/javacrumbs/jsonunit/fluent/JsonFluentAssert.java // public static ConfigurableJsonFluentAssert assertThatJson(Object json) { // return new ConfigurableJsonFluentAssert(convertToJson(json, ACTUAL), getPathPrefix(json)); // } // // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/JsonPathAdapter.java // public static Object inPath(@NotNull Object json, @NotNull String path) { // String normalizedPath = fromBracketNotation(path); // try { // MatchRecordingListener recordingListener = new MatchRecordingListener(); // Object value = readValue(defaultConfiguration().addEvaluationListeners(recordingListener), json, path); // return jsonSource(wrapDeserializedObject(value), normalizedPath, recordingListener.getMatchingPaths()); // } catch (PathNotFoundException e) { // return jsonSource(missingNode(), normalizedPath); // } // }
import net.javacrumbs.jsonunit.core.Option; import org.junit.jupiter.api.Test; import static net.javacrumbs.jsonunit.fluent.JsonFluentAssert.assertThatJson; import static net.javacrumbs.jsonunit.jsonpath.JsonPathAdapter.inPath; import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.test.jsonpath; class JsonPathTest { @Test void shouldBeAbleToUseSimpleValues() { assertThatJson(inPath(json, "$.store.book[*].author")) .isEqualTo("['Nigel Rees', 'Evelyn Waugh', 'Herman Melville', 'J. R. R. Tolkien']"); } @Test void shouldBeAbleToUseSimpleValuesAndIgnoreArrayOrder() { assertThatJson(inPath(json, "$.store.book[*].author"))
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/Option.java // public enum Option { // /** // * Treats null nodes in actual value as absent. In other words // * if you expect {"test":{"a":1}} this {"test":{"a":1, "b": null}} will pass the test. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, exact path to such nodes should be passed, // * which is test.b in the example above. // */ // TREATING_NULL_AS_ABSENT, // // /** // * When comparing arrays, ignores array order. In other words, treats arrays as sets. // */ // IGNORING_ARRAY_ORDER, // // /** // * Ignores extra fields in the actual value. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, path to the nodes with such fields should be passed. // */ // IGNORING_EXTRA_FIELDS, // // // /** // * Passes even if array in compared document has more items than expected. // * Items are taken from the beginning of the expected array unless IGNORING_ARRAY_ORDER is specified. // */ // IGNORING_EXTRA_ARRAY_ITEMS, // // /** // * Compares only structures. Completely ignores both values and types. // * Is too lenient, ignores types, prefer {@link Option#IGNORING_VALUES} instead. // * // * @deprecated Use IGNORING_VALUES option instead // */ // @Deprecated // COMPARING_ONLY_STRUCTURE, // // /** // * Ignores values but fails if value types are different. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, path to the node with ignored value should be passed. // */ // IGNORING_VALUES // } // // Path: json-unit-fluent/src/main/java/net/javacrumbs/jsonunit/fluent/JsonFluentAssert.java // public static ConfigurableJsonFluentAssert assertThatJson(Object json) { // return new ConfigurableJsonFluentAssert(convertToJson(json, ACTUAL), getPathPrefix(json)); // } // // Path: json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/JsonPathAdapter.java // public static Object inPath(@NotNull Object json, @NotNull String path) { // String normalizedPath = fromBracketNotation(path); // try { // MatchRecordingListener recordingListener = new MatchRecordingListener(); // Object value = readValue(defaultConfiguration().addEvaluationListeners(recordingListener), json, path); // return jsonSource(wrapDeserializedObject(value), normalizedPath, recordingListener.getMatchingPaths()); // } catch (PathNotFoundException e) { // return jsonSource(missingNode(), normalizedPath); // } // } // Path: tests/test-json-path/src/test/java/net/javacrumbs/jsonunit/test/jsonpath/JsonPathTest.java import net.javacrumbs.jsonunit.core.Option; import org.junit.jupiter.api.Test; import static net.javacrumbs.jsonunit.fluent.JsonFluentAssert.assertThatJson; import static net.javacrumbs.jsonunit.jsonpath.JsonPathAdapter.inPath; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.test.jsonpath; class JsonPathTest { @Test void shouldBeAbleToUseSimpleValues() { assertThatJson(inPath(json, "$.store.book[*].author")) .isEqualTo("['Nigel Rees', 'Evelyn Waugh', 'Herman Melville', 'J. R. R. Tolkien']"); } @Test void shouldBeAbleToUseSimpleValuesAndIgnoreArrayOrder() { assertThatJson(inPath(json, "$.store.book[*].author"))
.when(Option.IGNORING_ARRAY_ORDER)
lukas-krecan/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ExceptionFactory.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ExceptionUtils.java // static String formatDifferences(String message, Differences differences) { // return formatDifferences(message, differences.getDifferences()); // }
import org.opentest4j.AssertionFailedError; import org.opentest4j.MultipleFailuresError; import java.util.Collections; import java.util.List; import static java.util.stream.Collectors.toList; import static net.javacrumbs.jsonunit.core.internal.ExceptionUtils.formatDifferences;
package net.javacrumbs.jsonunit.core.internal; interface ExceptionFactory { AssertionError createException(String message, Differences diffs); } class BasicExceptionFactory implements ExceptionFactory { @Override public AssertionError createException(String message, Differences diffs) { return new BasicJsonAssertError(message, diffs); } private static class BasicJsonAssertError extends AssertionError { BasicJsonAssertError(String message, Differences differences) {
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ExceptionUtils.java // static String formatDifferences(String message, Differences differences) { // return formatDifferences(message, differences.getDifferences()); // } // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ExceptionFactory.java import org.opentest4j.AssertionFailedError; import org.opentest4j.MultipleFailuresError; import java.util.Collections; import java.util.List; import static java.util.stream.Collectors.toList; import static net.javacrumbs.jsonunit.core.internal.ExceptionUtils.formatDifferences; package net.javacrumbs.jsonunit.core.internal; interface ExceptionFactory { AssertionError createException(String message, Differences diffs); } class BasicExceptionFactory implements ExceptionFactory { @Override public AssertionError createException(String message, Differences diffs) { return new BasicJsonAssertError(message, diffs); } private static class BasicJsonAssertError extends AssertionError { BasicJsonAssertError(String message, Differences differences) {
super(formatDifferences(message, differences));
lukas-krecan/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/Configuration.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/ConfigurationWhen.java // public interface ApplicableForPath { // @NotNull // Configuration applyForPaths(@NotNull Configuration configuration, @NotNull PathsParam pathsParam); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/ConfigurationWhen.java // public static class PathsParam { // private final List<String> paths; // // private PathsParam(String path) { // this.paths = Collections.singletonList(path); // } // // private PathsParam(String... paths) { // this.paths = Arrays.asList(paths); // } // // List<String> getPaths() { // return paths; // } // // Configuration apply(Configuration configuration, ApplicableForPath action) { // return action.applyForPaths(configuration, this); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Options.java // public class Options { // private static final Options EMPTY_OPTIONS = new Options(EnumSet.noneOf(Option.class)); // private final EnumSet<Option> options; // // private Options(EnumSet<Option> options) { // this.options = options; // } // // public Options(Option first, Option... rest) { // this(EnumSet.of(first, rest)); // } // // public static Options empty() { // return EMPTY_OPTIONS; // } // // public boolean contains(Option option) { // return options.contains(option); // } // // public Options with(Option option, Option... otherOptions) { // EnumSet<Option> optionsWith = EnumSet.copyOf(options); // optionsWith.addAll(EnumSet.of(option, otherOptions)); // return new Options(optionsWith); // } // // // public Options without(Option option) { // EnumSet<Option> optionsWithout = EnumSet.copyOf(options); // optionsWithout.remove(option); // return new Options(optionsWithout); // } // // public Set<Option> values() { // return EnumSet.copyOf(options); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/PathOption.java // public class PathOption { // private final List<String> paths; // private final Set<Option> options; // // /** // * True if this option is included, false if excluded. // */ // private final boolean included; // // public PathOption(List<String> paths, Set<Option> options, boolean included) { // this.paths = Collections.unmodifiableList(paths); // this.options = Collections.unmodifiableSet(EnumSet.copyOf(options)); // this.included = included; // } // // public List<String> getPaths() { // return paths; // } // // public Set<Option> getOptions() { // return options; // } // // boolean isIncluded() { // return included; // } // // public PathOption withPaths(List<String> newPoPaths) { // return new PathOption(newPoPaths, options, included); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/listener/DifferenceListener.java // public interface DifferenceListener { // void diff(Difference difference, DifferenceContext context); // }
import java.util.Set; import static java.util.Arrays.asList; import net.javacrumbs.jsonunit.core.ConfigurationWhen.ApplicableForPath; import net.javacrumbs.jsonunit.core.ConfigurationWhen.PathsParam; import net.javacrumbs.jsonunit.core.internal.Options; import net.javacrumbs.jsonunit.core.internal.PathOption; import net.javacrumbs.jsonunit.core.listener.DifferenceListener; import org.hamcrest.Matcher; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core; /** * Comparison configuration. Immutable. */ public class Configuration { private static final DifferenceListener DUMMY_LISTENER = (difference, context) -> {}; private static final String DEFAULT_IGNORE_PLACEHOLDER = "${json-unit.ignore}"; private static final String ALTERNATIVE_IGNORE_PLACEHOLDER = "#{json-unit.ignore}";
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/ConfigurationWhen.java // public interface ApplicableForPath { // @NotNull // Configuration applyForPaths(@NotNull Configuration configuration, @NotNull PathsParam pathsParam); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/ConfigurationWhen.java // public static class PathsParam { // private final List<String> paths; // // private PathsParam(String path) { // this.paths = Collections.singletonList(path); // } // // private PathsParam(String... paths) { // this.paths = Arrays.asList(paths); // } // // List<String> getPaths() { // return paths; // } // // Configuration apply(Configuration configuration, ApplicableForPath action) { // return action.applyForPaths(configuration, this); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Options.java // public class Options { // private static final Options EMPTY_OPTIONS = new Options(EnumSet.noneOf(Option.class)); // private final EnumSet<Option> options; // // private Options(EnumSet<Option> options) { // this.options = options; // } // // public Options(Option first, Option... rest) { // this(EnumSet.of(first, rest)); // } // // public static Options empty() { // return EMPTY_OPTIONS; // } // // public boolean contains(Option option) { // return options.contains(option); // } // // public Options with(Option option, Option... otherOptions) { // EnumSet<Option> optionsWith = EnumSet.copyOf(options); // optionsWith.addAll(EnumSet.of(option, otherOptions)); // return new Options(optionsWith); // } // // // public Options without(Option option) { // EnumSet<Option> optionsWithout = EnumSet.copyOf(options); // optionsWithout.remove(option); // return new Options(optionsWithout); // } // // public Set<Option> values() { // return EnumSet.copyOf(options); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/PathOption.java // public class PathOption { // private final List<String> paths; // private final Set<Option> options; // // /** // * True if this option is included, false if excluded. // */ // private final boolean included; // // public PathOption(List<String> paths, Set<Option> options, boolean included) { // this.paths = Collections.unmodifiableList(paths); // this.options = Collections.unmodifiableSet(EnumSet.copyOf(options)); // this.included = included; // } // // public List<String> getPaths() { // return paths; // } // // public Set<Option> getOptions() { // return options; // } // // boolean isIncluded() { // return included; // } // // public PathOption withPaths(List<String> newPoPaths) { // return new PathOption(newPoPaths, options, included); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/listener/DifferenceListener.java // public interface DifferenceListener { // void diff(Difference difference, DifferenceContext context); // } // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/Configuration.java import java.util.Set; import static java.util.Arrays.asList; import net.javacrumbs.jsonunit.core.ConfigurationWhen.ApplicableForPath; import net.javacrumbs.jsonunit.core.ConfigurationWhen.PathsParam; import net.javacrumbs.jsonunit.core.internal.Options; import net.javacrumbs.jsonunit.core.internal.PathOption; import net.javacrumbs.jsonunit.core.listener.DifferenceListener; import org.hamcrest.Matcher; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core; /** * Comparison configuration. Immutable. */ public class Configuration { private static final DifferenceListener DUMMY_LISTENER = (difference, context) -> {}; private static final String DEFAULT_IGNORE_PLACEHOLDER = "${json-unit.ignore}"; private static final String ALTERNATIVE_IGNORE_PLACEHOLDER = "#{json-unit.ignore}";
private static final Configuration EMPTY_CONFIGURATION = new Configuration(null, Options.empty(), DEFAULT_IGNORE_PLACEHOLDER, Matchers.empty(), Collections.emptySet(), DUMMY_LISTENER, Collections.emptyList());
lukas-krecan/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/Configuration.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/ConfigurationWhen.java // public interface ApplicableForPath { // @NotNull // Configuration applyForPaths(@NotNull Configuration configuration, @NotNull PathsParam pathsParam); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/ConfigurationWhen.java // public static class PathsParam { // private final List<String> paths; // // private PathsParam(String path) { // this.paths = Collections.singletonList(path); // } // // private PathsParam(String... paths) { // this.paths = Arrays.asList(paths); // } // // List<String> getPaths() { // return paths; // } // // Configuration apply(Configuration configuration, ApplicableForPath action) { // return action.applyForPaths(configuration, this); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Options.java // public class Options { // private static final Options EMPTY_OPTIONS = new Options(EnumSet.noneOf(Option.class)); // private final EnumSet<Option> options; // // private Options(EnumSet<Option> options) { // this.options = options; // } // // public Options(Option first, Option... rest) { // this(EnumSet.of(first, rest)); // } // // public static Options empty() { // return EMPTY_OPTIONS; // } // // public boolean contains(Option option) { // return options.contains(option); // } // // public Options with(Option option, Option... otherOptions) { // EnumSet<Option> optionsWith = EnumSet.copyOf(options); // optionsWith.addAll(EnumSet.of(option, otherOptions)); // return new Options(optionsWith); // } // // // public Options without(Option option) { // EnumSet<Option> optionsWithout = EnumSet.copyOf(options); // optionsWithout.remove(option); // return new Options(optionsWithout); // } // // public Set<Option> values() { // return EnumSet.copyOf(options); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/PathOption.java // public class PathOption { // private final List<String> paths; // private final Set<Option> options; // // /** // * True if this option is included, false if excluded. // */ // private final boolean included; // // public PathOption(List<String> paths, Set<Option> options, boolean included) { // this.paths = Collections.unmodifiableList(paths); // this.options = Collections.unmodifiableSet(EnumSet.copyOf(options)); // this.included = included; // } // // public List<String> getPaths() { // return paths; // } // // public Set<Option> getOptions() { // return options; // } // // boolean isIncluded() { // return included; // } // // public PathOption withPaths(List<String> newPoPaths) { // return new PathOption(newPoPaths, options, included); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/listener/DifferenceListener.java // public interface DifferenceListener { // void diff(Difference difference, DifferenceContext context); // }
import java.util.Set; import static java.util.Arrays.asList; import net.javacrumbs.jsonunit.core.ConfigurationWhen.ApplicableForPath; import net.javacrumbs.jsonunit.core.ConfigurationWhen.PathsParam; import net.javacrumbs.jsonunit.core.internal.Options; import net.javacrumbs.jsonunit.core.internal.PathOption; import net.javacrumbs.jsonunit.core.listener.DifferenceListener; import org.hamcrest.Matcher; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List;
/** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core; /** * Comparison configuration. Immutable. */ public class Configuration { private static final DifferenceListener DUMMY_LISTENER = (difference, context) -> {}; private static final String DEFAULT_IGNORE_PLACEHOLDER = "${json-unit.ignore}"; private static final String ALTERNATIVE_IGNORE_PLACEHOLDER = "#{json-unit.ignore}"; private static final Configuration EMPTY_CONFIGURATION = new Configuration(null, Options.empty(), DEFAULT_IGNORE_PLACEHOLDER, Matchers.empty(), Collections.emptySet(), DUMMY_LISTENER, Collections.emptyList()); private final BigDecimal tolerance; private final Options options; private final String ignorePlaceholder; private final Matchers matchers;
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/ConfigurationWhen.java // public interface ApplicableForPath { // @NotNull // Configuration applyForPaths(@NotNull Configuration configuration, @NotNull PathsParam pathsParam); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/ConfigurationWhen.java // public static class PathsParam { // private final List<String> paths; // // private PathsParam(String path) { // this.paths = Collections.singletonList(path); // } // // private PathsParam(String... paths) { // this.paths = Arrays.asList(paths); // } // // List<String> getPaths() { // return paths; // } // // Configuration apply(Configuration configuration, ApplicableForPath action) { // return action.applyForPaths(configuration, this); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Options.java // public class Options { // private static final Options EMPTY_OPTIONS = new Options(EnumSet.noneOf(Option.class)); // private final EnumSet<Option> options; // // private Options(EnumSet<Option> options) { // this.options = options; // } // // public Options(Option first, Option... rest) { // this(EnumSet.of(first, rest)); // } // // public static Options empty() { // return EMPTY_OPTIONS; // } // // public boolean contains(Option option) { // return options.contains(option); // } // // public Options with(Option option, Option... otherOptions) { // EnumSet<Option> optionsWith = EnumSet.copyOf(options); // optionsWith.addAll(EnumSet.of(option, otherOptions)); // return new Options(optionsWith); // } // // // public Options without(Option option) { // EnumSet<Option> optionsWithout = EnumSet.copyOf(options); // optionsWithout.remove(option); // return new Options(optionsWithout); // } // // public Set<Option> values() { // return EnumSet.copyOf(options); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/PathOption.java // public class PathOption { // private final List<String> paths; // private final Set<Option> options; // // /** // * True if this option is included, false if excluded. // */ // private final boolean included; // // public PathOption(List<String> paths, Set<Option> options, boolean included) { // this.paths = Collections.unmodifiableList(paths); // this.options = Collections.unmodifiableSet(EnumSet.copyOf(options)); // this.included = included; // } // // public List<String> getPaths() { // return paths; // } // // public Set<Option> getOptions() { // return options; // } // // boolean isIncluded() { // return included; // } // // public PathOption withPaths(List<String> newPoPaths) { // return new PathOption(newPoPaths, options, included); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/listener/DifferenceListener.java // public interface DifferenceListener { // void diff(Difference difference, DifferenceContext context); // } // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/Configuration.java import java.util.Set; import static java.util.Arrays.asList; import net.javacrumbs.jsonunit.core.ConfigurationWhen.ApplicableForPath; import net.javacrumbs.jsonunit.core.ConfigurationWhen.PathsParam; import net.javacrumbs.jsonunit.core.internal.Options; import net.javacrumbs.jsonunit.core.internal.PathOption; import net.javacrumbs.jsonunit.core.listener.DifferenceListener; import org.hamcrest.Matcher; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; /** * Copyright 2009-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core; /** * Comparison configuration. Immutable. */ public class Configuration { private static final DifferenceListener DUMMY_LISTENER = (difference, context) -> {}; private static final String DEFAULT_IGNORE_PLACEHOLDER = "${json-unit.ignore}"; private static final String ALTERNATIVE_IGNORE_PLACEHOLDER = "#{json-unit.ignore}"; private static final Configuration EMPTY_CONFIGURATION = new Configuration(null, Options.empty(), DEFAULT_IGNORE_PLACEHOLDER, Matchers.empty(), Collections.emptySet(), DUMMY_LISTENER, Collections.emptyList()); private final BigDecimal tolerance; private final Options options; private final String ignorePlaceholder; private final Matchers matchers;
private final List<PathOption> pathOptions;
lukas-krecan/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/Configuration.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/ConfigurationWhen.java // public interface ApplicableForPath { // @NotNull // Configuration applyForPaths(@NotNull Configuration configuration, @NotNull PathsParam pathsParam); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/ConfigurationWhen.java // public static class PathsParam { // private final List<String> paths; // // private PathsParam(String path) { // this.paths = Collections.singletonList(path); // } // // private PathsParam(String... paths) { // this.paths = Arrays.asList(paths); // } // // List<String> getPaths() { // return paths; // } // // Configuration apply(Configuration configuration, ApplicableForPath action) { // return action.applyForPaths(configuration, this); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Options.java // public class Options { // private static final Options EMPTY_OPTIONS = new Options(EnumSet.noneOf(Option.class)); // private final EnumSet<Option> options; // // private Options(EnumSet<Option> options) { // this.options = options; // } // // public Options(Option first, Option... rest) { // this(EnumSet.of(first, rest)); // } // // public static Options empty() { // return EMPTY_OPTIONS; // } // // public boolean contains(Option option) { // return options.contains(option); // } // // public Options with(Option option, Option... otherOptions) { // EnumSet<Option> optionsWith = EnumSet.copyOf(options); // optionsWith.addAll(EnumSet.of(option, otherOptions)); // return new Options(optionsWith); // } // // // public Options without(Option option) { // EnumSet<Option> optionsWithout = EnumSet.copyOf(options); // optionsWithout.remove(option); // return new Options(optionsWithout); // } // // public Set<Option> values() { // return EnumSet.copyOf(options); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/PathOption.java // public class PathOption { // private final List<String> paths; // private final Set<Option> options; // // /** // * True if this option is included, false if excluded. // */ // private final boolean included; // // public PathOption(List<String> paths, Set<Option> options, boolean included) { // this.paths = Collections.unmodifiableList(paths); // this.options = Collections.unmodifiableSet(EnumSet.copyOf(options)); // this.included = included; // } // // public List<String> getPaths() { // return paths; // } // // public Set<Option> getOptions() { // return options; // } // // boolean isIncluded() { // return included; // } // // public PathOption withPaths(List<String> newPoPaths) { // return new PathOption(newPoPaths, options, included); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/listener/DifferenceListener.java // public interface DifferenceListener { // void diff(Difference difference, DifferenceContext context); // }
import java.util.Set; import static java.util.Arrays.asList; import net.javacrumbs.jsonunit.core.ConfigurationWhen.ApplicableForPath; import net.javacrumbs.jsonunit.core.ConfigurationWhen.PathsParam; import net.javacrumbs.jsonunit.core.internal.Options; import net.javacrumbs.jsonunit.core.internal.PathOption; import net.javacrumbs.jsonunit.core.listener.DifferenceListener; import org.hamcrest.Matcher; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List;
* * @param first * @param next * @return */ @NotNull public Configuration withOptions(@NotNull Option first, @NotNull Option... next) { return new Configuration(tolerance, options.with(first, next), ignorePlaceholder, matchers, pathsToBeIgnored, differenceListener, pathOptions); } /** * Sets comparison options. * * @param options * @return */ @NotNull public Configuration withOptions(@NotNull Options options) { return new Configuration(tolerance, options, ignorePlaceholder, matchers, pathsToBeIgnored, differenceListener, pathOptions); } /** * Defines general comparison options. See {@link ConfigurationWhen#path} for some examples. * * @param object an object to apply actions, e.g. {@link ConfigurationWhen#path}, {@link ConfigurationWhen#rootPath}. * @param actions actions to be applied on the object. * * @see ConfigurationWhen#path */ @NotNull
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/ConfigurationWhen.java // public interface ApplicableForPath { // @NotNull // Configuration applyForPaths(@NotNull Configuration configuration, @NotNull PathsParam pathsParam); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/ConfigurationWhen.java // public static class PathsParam { // private final List<String> paths; // // private PathsParam(String path) { // this.paths = Collections.singletonList(path); // } // // private PathsParam(String... paths) { // this.paths = Arrays.asList(paths); // } // // List<String> getPaths() { // return paths; // } // // Configuration apply(Configuration configuration, ApplicableForPath action) { // return action.applyForPaths(configuration, this); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Options.java // public class Options { // private static final Options EMPTY_OPTIONS = new Options(EnumSet.noneOf(Option.class)); // private final EnumSet<Option> options; // // private Options(EnumSet<Option> options) { // this.options = options; // } // // public Options(Option first, Option... rest) { // this(EnumSet.of(first, rest)); // } // // public static Options empty() { // return EMPTY_OPTIONS; // } // // public boolean contains(Option option) { // return options.contains(option); // } // // public Options with(Option option, Option... otherOptions) { // EnumSet<Option> optionsWith = EnumSet.copyOf(options); // optionsWith.addAll(EnumSet.of(option, otherOptions)); // return new Options(optionsWith); // } // // // public Options without(Option option) { // EnumSet<Option> optionsWithout = EnumSet.copyOf(options); // optionsWithout.remove(option); // return new Options(optionsWithout); // } // // public Set<Option> values() { // return EnumSet.copyOf(options); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/PathOption.java // public class PathOption { // private final List<String> paths; // private final Set<Option> options; // // /** // * True if this option is included, false if excluded. // */ // private final boolean included; // // public PathOption(List<String> paths, Set<Option> options, boolean included) { // this.paths = Collections.unmodifiableList(paths); // this.options = Collections.unmodifiableSet(EnumSet.copyOf(options)); // this.included = included; // } // // public List<String> getPaths() { // return paths; // } // // public Set<Option> getOptions() { // return options; // } // // boolean isIncluded() { // return included; // } // // public PathOption withPaths(List<String> newPoPaths) { // return new PathOption(newPoPaths, options, included); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/listener/DifferenceListener.java // public interface DifferenceListener { // void diff(Difference difference, DifferenceContext context); // } // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/Configuration.java import java.util.Set; import static java.util.Arrays.asList; import net.javacrumbs.jsonunit.core.ConfigurationWhen.ApplicableForPath; import net.javacrumbs.jsonunit.core.ConfigurationWhen.PathsParam; import net.javacrumbs.jsonunit.core.internal.Options; import net.javacrumbs.jsonunit.core.internal.PathOption; import net.javacrumbs.jsonunit.core.listener.DifferenceListener; import org.hamcrest.Matcher; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; * * @param first * @param next * @return */ @NotNull public Configuration withOptions(@NotNull Option first, @NotNull Option... next) { return new Configuration(tolerance, options.with(first, next), ignorePlaceholder, matchers, pathsToBeIgnored, differenceListener, pathOptions); } /** * Sets comparison options. * * @param options * @return */ @NotNull public Configuration withOptions(@NotNull Options options) { return new Configuration(tolerance, options, ignorePlaceholder, matchers, pathsToBeIgnored, differenceListener, pathOptions); } /** * Defines general comparison options. See {@link ConfigurationWhen#path} for some examples. * * @param object an object to apply actions, e.g. {@link ConfigurationWhen#path}, {@link ConfigurationWhen#rootPath}. * @param actions actions to be applied on the object. * * @see ConfigurationWhen#path */ @NotNull
public final Configuration when(@NotNull PathsParam object, @NotNull ApplicableForPath... actions) {
lukas-krecan/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/Configuration.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/ConfigurationWhen.java // public interface ApplicableForPath { // @NotNull // Configuration applyForPaths(@NotNull Configuration configuration, @NotNull PathsParam pathsParam); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/ConfigurationWhen.java // public static class PathsParam { // private final List<String> paths; // // private PathsParam(String path) { // this.paths = Collections.singletonList(path); // } // // private PathsParam(String... paths) { // this.paths = Arrays.asList(paths); // } // // List<String> getPaths() { // return paths; // } // // Configuration apply(Configuration configuration, ApplicableForPath action) { // return action.applyForPaths(configuration, this); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Options.java // public class Options { // private static final Options EMPTY_OPTIONS = new Options(EnumSet.noneOf(Option.class)); // private final EnumSet<Option> options; // // private Options(EnumSet<Option> options) { // this.options = options; // } // // public Options(Option first, Option... rest) { // this(EnumSet.of(first, rest)); // } // // public static Options empty() { // return EMPTY_OPTIONS; // } // // public boolean contains(Option option) { // return options.contains(option); // } // // public Options with(Option option, Option... otherOptions) { // EnumSet<Option> optionsWith = EnumSet.copyOf(options); // optionsWith.addAll(EnumSet.of(option, otherOptions)); // return new Options(optionsWith); // } // // // public Options without(Option option) { // EnumSet<Option> optionsWithout = EnumSet.copyOf(options); // optionsWithout.remove(option); // return new Options(optionsWithout); // } // // public Set<Option> values() { // return EnumSet.copyOf(options); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/PathOption.java // public class PathOption { // private final List<String> paths; // private final Set<Option> options; // // /** // * True if this option is included, false if excluded. // */ // private final boolean included; // // public PathOption(List<String> paths, Set<Option> options, boolean included) { // this.paths = Collections.unmodifiableList(paths); // this.options = Collections.unmodifiableSet(EnumSet.copyOf(options)); // this.included = included; // } // // public List<String> getPaths() { // return paths; // } // // public Set<Option> getOptions() { // return options; // } // // boolean isIncluded() { // return included; // } // // public PathOption withPaths(List<String> newPoPaths) { // return new PathOption(newPoPaths, options, included); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/listener/DifferenceListener.java // public interface DifferenceListener { // void diff(Difference difference, DifferenceContext context); // }
import java.util.Set; import static java.util.Arrays.asList; import net.javacrumbs.jsonunit.core.ConfigurationWhen.ApplicableForPath; import net.javacrumbs.jsonunit.core.ConfigurationWhen.PathsParam; import net.javacrumbs.jsonunit.core.internal.Options; import net.javacrumbs.jsonunit.core.internal.PathOption; import net.javacrumbs.jsonunit.core.listener.DifferenceListener; import org.hamcrest.Matcher; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List;
* * @param first * @param next * @return */ @NotNull public Configuration withOptions(@NotNull Option first, @NotNull Option... next) { return new Configuration(tolerance, options.with(first, next), ignorePlaceholder, matchers, pathsToBeIgnored, differenceListener, pathOptions); } /** * Sets comparison options. * * @param options * @return */ @NotNull public Configuration withOptions(@NotNull Options options) { return new Configuration(tolerance, options, ignorePlaceholder, matchers, pathsToBeIgnored, differenceListener, pathOptions); } /** * Defines general comparison options. See {@link ConfigurationWhen#path} for some examples. * * @param object an object to apply actions, e.g. {@link ConfigurationWhen#path}, {@link ConfigurationWhen#rootPath}. * @param actions actions to be applied on the object. * * @see ConfigurationWhen#path */ @NotNull
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/ConfigurationWhen.java // public interface ApplicableForPath { // @NotNull // Configuration applyForPaths(@NotNull Configuration configuration, @NotNull PathsParam pathsParam); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/ConfigurationWhen.java // public static class PathsParam { // private final List<String> paths; // // private PathsParam(String path) { // this.paths = Collections.singletonList(path); // } // // private PathsParam(String... paths) { // this.paths = Arrays.asList(paths); // } // // List<String> getPaths() { // return paths; // } // // Configuration apply(Configuration configuration, ApplicableForPath action) { // return action.applyForPaths(configuration, this); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/Options.java // public class Options { // private static final Options EMPTY_OPTIONS = new Options(EnumSet.noneOf(Option.class)); // private final EnumSet<Option> options; // // private Options(EnumSet<Option> options) { // this.options = options; // } // // public Options(Option first, Option... rest) { // this(EnumSet.of(first, rest)); // } // // public static Options empty() { // return EMPTY_OPTIONS; // } // // public boolean contains(Option option) { // return options.contains(option); // } // // public Options with(Option option, Option... otherOptions) { // EnumSet<Option> optionsWith = EnumSet.copyOf(options); // optionsWith.addAll(EnumSet.of(option, otherOptions)); // return new Options(optionsWith); // } // // // public Options without(Option option) { // EnumSet<Option> optionsWithout = EnumSet.copyOf(options); // optionsWithout.remove(option); // return new Options(optionsWithout); // } // // public Set<Option> values() { // return EnumSet.copyOf(options); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/PathOption.java // public class PathOption { // private final List<String> paths; // private final Set<Option> options; // // /** // * True if this option is included, false if excluded. // */ // private final boolean included; // // public PathOption(List<String> paths, Set<Option> options, boolean included) { // this.paths = Collections.unmodifiableList(paths); // this.options = Collections.unmodifiableSet(EnumSet.copyOf(options)); // this.included = included; // } // // public List<String> getPaths() { // return paths; // } // // public Set<Option> getOptions() { // return options; // } // // boolean isIncluded() { // return included; // } // // public PathOption withPaths(List<String> newPoPaths) { // return new PathOption(newPoPaths, options, included); // } // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/listener/DifferenceListener.java // public interface DifferenceListener { // void diff(Difference difference, DifferenceContext context); // } // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/Configuration.java import java.util.Set; import static java.util.Arrays.asList; import net.javacrumbs.jsonunit.core.ConfigurationWhen.ApplicableForPath; import net.javacrumbs.jsonunit.core.ConfigurationWhen.PathsParam; import net.javacrumbs.jsonunit.core.internal.Options; import net.javacrumbs.jsonunit.core.internal.PathOption; import net.javacrumbs.jsonunit.core.listener.DifferenceListener; import org.hamcrest.Matcher; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; * * @param first * @param next * @return */ @NotNull public Configuration withOptions(@NotNull Option first, @NotNull Option... next) { return new Configuration(tolerance, options.with(first, next), ignorePlaceholder, matchers, pathsToBeIgnored, differenceListener, pathOptions); } /** * Sets comparison options. * * @param options * @return */ @NotNull public Configuration withOptions(@NotNull Options options) { return new Configuration(tolerance, options, ignorePlaceholder, matchers, pathsToBeIgnored, differenceListener, pathOptions); } /** * Defines general comparison options. See {@link ConfigurationWhen#path} for some examples. * * @param object an object to apply actions, e.g. {@link ConfigurationWhen#path}, {@link ConfigurationWhen#rootPath}. * @param actions actions to be applied on the object. * * @see ConfigurationWhen#path */ @NotNull
public final Configuration when(@NotNull PathsParam object, @NotNull ApplicableForPath... actions) {
lukas-krecan/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/PathOption.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/Option.java // public enum Option { // /** // * Treats null nodes in actual value as absent. In other words // * if you expect {"test":{"a":1}} this {"test":{"a":1, "b": null}} will pass the test. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, exact path to such nodes should be passed, // * which is test.b in the example above. // */ // TREATING_NULL_AS_ABSENT, // // /** // * When comparing arrays, ignores array order. In other words, treats arrays as sets. // */ // IGNORING_ARRAY_ORDER, // // /** // * Ignores extra fields in the actual value. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, path to the nodes with such fields should be passed. // */ // IGNORING_EXTRA_FIELDS, // // // /** // * Passes even if array in compared document has more items than expected. // * Items are taken from the beginning of the expected array unless IGNORING_ARRAY_ORDER is specified. // */ // IGNORING_EXTRA_ARRAY_ITEMS, // // /** // * Compares only structures. Completely ignores both values and types. // * Is too lenient, ignores types, prefer {@link Option#IGNORING_VALUES} instead. // * // * @deprecated Use IGNORING_VALUES option instead // */ // @Deprecated // COMPARING_ONLY_STRUCTURE, // // /** // * Ignores values but fails if value types are different. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, path to the node with ignored value should be passed. // */ // IGNORING_VALUES // }
import net.javacrumbs.jsonunit.core.Option; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Set;
package net.javacrumbs.jsonunit.core.internal; public class PathOption { private final List<String> paths;
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/Option.java // public enum Option { // /** // * Treats null nodes in actual value as absent. In other words // * if you expect {"test":{"a":1}} this {"test":{"a":1, "b": null}} will pass the test. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, exact path to such nodes should be passed, // * which is test.b in the example above. // */ // TREATING_NULL_AS_ABSENT, // // /** // * When comparing arrays, ignores array order. In other words, treats arrays as sets. // */ // IGNORING_ARRAY_ORDER, // // /** // * Ignores extra fields in the actual value. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, path to the nodes with such fields should be passed. // */ // IGNORING_EXTRA_FIELDS, // // // /** // * Passes even if array in compared document has more items than expected. // * Items are taken from the beginning of the expected array unless IGNORING_ARRAY_ORDER is specified. // */ // IGNORING_EXTRA_ARRAY_ITEMS, // // /** // * Compares only structures. Completely ignores both values and types. // * Is too lenient, ignores types, prefer {@link Option#IGNORING_VALUES} instead. // * // * @deprecated Use IGNORING_VALUES option instead // */ // @Deprecated // COMPARING_ONLY_STRUCTURE, // // /** // * Ignores values but fails if value types are different. // * When using within {@link ConfigurationWhen#then(Option, Option...)}, path to the node with ignored value should be passed. // */ // IGNORING_VALUES // } // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/PathOption.java import net.javacrumbs.jsonunit.core.Option; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Set; package net.javacrumbs.jsonunit.core.internal; public class PathOption { private final List<String> paths;
private final Set<Option> options;
lukas-krecan/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JohnzonNodeFactory.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Boolean> toBoolList(boolean[] source) { // List<Boolean> result = new ArrayList<>(source.length); // for (boolean value : source) { // result.add(value); // } // return result; // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Double> toDoubleList(double[] source) { // return Arrays.stream(source).boxed().collect(toList()); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Integer> toIntList(int[] source) { // return Arrays.stream(source).boxed().collect(toList()); // }
import org.apache.johnzon.core.JsonLongImpl; import org.apache.johnzon.mapper.Mapper; import org.apache.johnzon.mapper.MapperBuilder; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonNumber; import javax.json.JsonObject; import javax.json.JsonReader; import javax.json.JsonString; import javax.json.JsonValue; import javax.json.stream.JsonParsingException; import java.io.Reader; import java.math.BigDecimal; import java.util.Iterator; import java.util.Map; import static java.util.Arrays.asList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toBoolList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toDoubleList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toIntList;
/** * Copyright 2009-2019 the original author or authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; public class JohnzonNodeFactory extends AbstractNodeFactory { private final Mapper mapper = new MapperBuilder().build(); @Override protected Node doConvertValue(Object source) { if (source instanceof JsonValue) { return newNode((JsonValue) source); } else if (source instanceof int[]) { // Johnzon can't convert arrays but it support lists
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Boolean> toBoolList(boolean[] source) { // List<Boolean> result = new ArrayList<>(source.length); // for (boolean value : source) { // result.add(value); // } // return result; // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Double> toDoubleList(double[] source) { // return Arrays.stream(source).boxed().collect(toList()); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Integer> toIntList(int[] source) { // return Arrays.stream(source).boxed().collect(toList()); // } // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JohnzonNodeFactory.java import org.apache.johnzon.core.JsonLongImpl; import org.apache.johnzon.mapper.Mapper; import org.apache.johnzon.mapper.MapperBuilder; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonNumber; import javax.json.JsonObject; import javax.json.JsonReader; import javax.json.JsonString; import javax.json.JsonValue; import javax.json.stream.JsonParsingException; import java.io.Reader; import java.math.BigDecimal; import java.util.Iterator; import java.util.Map; import static java.util.Arrays.asList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toBoolList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toDoubleList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toIntList; /** * Copyright 2009-2019 the original author or authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; public class JohnzonNodeFactory extends AbstractNodeFactory { private final Mapper mapper = new MapperBuilder().build(); @Override protected Node doConvertValue(Object source) { if (source instanceof JsonValue) { return newNode((JsonValue) source); } else if (source instanceof int[]) { // Johnzon can't convert arrays but it support lists
return newNode(mapper.toStructure(toIntList((int[]) source)));
lukas-krecan/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JohnzonNodeFactory.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Boolean> toBoolList(boolean[] source) { // List<Boolean> result = new ArrayList<>(source.length); // for (boolean value : source) { // result.add(value); // } // return result; // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Double> toDoubleList(double[] source) { // return Arrays.stream(source).boxed().collect(toList()); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Integer> toIntList(int[] source) { // return Arrays.stream(source).boxed().collect(toList()); // }
import org.apache.johnzon.core.JsonLongImpl; import org.apache.johnzon.mapper.Mapper; import org.apache.johnzon.mapper.MapperBuilder; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonNumber; import javax.json.JsonObject; import javax.json.JsonReader; import javax.json.JsonString; import javax.json.JsonValue; import javax.json.stream.JsonParsingException; import java.io.Reader; import java.math.BigDecimal; import java.util.Iterator; import java.util.Map; import static java.util.Arrays.asList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toBoolList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toDoubleList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toIntList;
/** * Copyright 2009-2019 the original author or authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; public class JohnzonNodeFactory extends AbstractNodeFactory { private final Mapper mapper = new MapperBuilder().build(); @Override protected Node doConvertValue(Object source) { if (source instanceof JsonValue) { return newNode((JsonValue) source); } else if (source instanceof int[]) { // Johnzon can't convert arrays but it support lists return newNode(mapper.toStructure(toIntList((int[]) source))); } else if (source instanceof double[]) { // Johnzon can't convert arrays but it support lists
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Boolean> toBoolList(boolean[] source) { // List<Boolean> result = new ArrayList<>(source.length); // for (boolean value : source) { // result.add(value); // } // return result; // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Double> toDoubleList(double[] source) { // return Arrays.stream(source).boxed().collect(toList()); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Integer> toIntList(int[] source) { // return Arrays.stream(source).boxed().collect(toList()); // } // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JohnzonNodeFactory.java import org.apache.johnzon.core.JsonLongImpl; import org.apache.johnzon.mapper.Mapper; import org.apache.johnzon.mapper.MapperBuilder; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonNumber; import javax.json.JsonObject; import javax.json.JsonReader; import javax.json.JsonString; import javax.json.JsonValue; import javax.json.stream.JsonParsingException; import java.io.Reader; import java.math.BigDecimal; import java.util.Iterator; import java.util.Map; import static java.util.Arrays.asList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toBoolList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toDoubleList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toIntList; /** * Copyright 2009-2019 the original author or authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; public class JohnzonNodeFactory extends AbstractNodeFactory { private final Mapper mapper = new MapperBuilder().build(); @Override protected Node doConvertValue(Object source) { if (source instanceof JsonValue) { return newNode((JsonValue) source); } else if (source instanceof int[]) { // Johnzon can't convert arrays but it support lists return newNode(mapper.toStructure(toIntList((int[]) source))); } else if (source instanceof double[]) { // Johnzon can't convert arrays but it support lists
return newNode(mapper.toStructure(toDoubleList((double[]) source)));
lukas-krecan/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JohnzonNodeFactory.java
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Boolean> toBoolList(boolean[] source) { // List<Boolean> result = new ArrayList<>(source.length); // for (boolean value : source) { // result.add(value); // } // return result; // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Double> toDoubleList(double[] source) { // return Arrays.stream(source).boxed().collect(toList()); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Integer> toIntList(int[] source) { // return Arrays.stream(source).boxed().collect(toList()); // }
import org.apache.johnzon.core.JsonLongImpl; import org.apache.johnzon.mapper.Mapper; import org.apache.johnzon.mapper.MapperBuilder; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonNumber; import javax.json.JsonObject; import javax.json.JsonReader; import javax.json.JsonString; import javax.json.JsonValue; import javax.json.stream.JsonParsingException; import java.io.Reader; import java.math.BigDecimal; import java.util.Iterator; import java.util.Map; import static java.util.Arrays.asList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toBoolList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toDoubleList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toIntList;
/** * Copyright 2009-2019 the original author or authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; public class JohnzonNodeFactory extends AbstractNodeFactory { private final Mapper mapper = new MapperBuilder().build(); @Override protected Node doConvertValue(Object source) { if (source instanceof JsonValue) { return newNode((JsonValue) source); } else if (source instanceof int[]) { // Johnzon can't convert arrays but it support lists return newNode(mapper.toStructure(toIntList((int[]) source))); } else if (source instanceof double[]) { // Johnzon can't convert arrays but it support lists return newNode(mapper.toStructure(toDoubleList((double[]) source))); } else if (source instanceof boolean[]) { // Johnzon can't convert arrays but it support lists
// Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Boolean> toBoolList(boolean[] source) { // List<Boolean> result = new ArrayList<>(source.length); // for (boolean value : source) { // result.add(value); // } // return result; // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Double> toDoubleList(double[] source) { // return Arrays.stream(source).boxed().collect(toList()); // } // // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/ArrayUtils.java // static List<Integer> toIntList(int[] source) { // return Arrays.stream(source).boxed().collect(toList()); // } // Path: json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JohnzonNodeFactory.java import org.apache.johnzon.core.JsonLongImpl; import org.apache.johnzon.mapper.Mapper; import org.apache.johnzon.mapper.MapperBuilder; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonNumber; import javax.json.JsonObject; import javax.json.JsonReader; import javax.json.JsonString; import javax.json.JsonValue; import javax.json.stream.JsonParsingException; import java.io.Reader; import java.math.BigDecimal; import java.util.Iterator; import java.util.Map; import static java.util.Arrays.asList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toBoolList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toDoubleList; import static net.javacrumbs.jsonunit.core.internal.ArrayUtils.toIntList; /** * Copyright 2009-2019 the original author or authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.jsonunit.core.internal; public class JohnzonNodeFactory extends AbstractNodeFactory { private final Mapper mapper = new MapperBuilder().build(); @Override protected Node doConvertValue(Object source) { if (source instanceof JsonValue) { return newNode((JsonValue) source); } else if (source instanceof int[]) { // Johnzon can't convert arrays but it support lists return newNode(mapper.toStructure(toIntList((int[]) source))); } else if (source instanceof double[]) { // Johnzon can't convert arrays but it support lists return newNode(mapper.toStructure(toDoubleList((double[]) source))); } else if (source instanceof boolean[]) { // Johnzon can't convert arrays but it support lists
return newNode(mapper.toStructure(toBoolList((boolean[]) source)));
TheTemportalist/CountryGamer_PlantsVsZombies
java/com/countrygamer/pvz/client/block/tile/RenderGravestone.java
// Path: java/com/countrygamer/pvz/block/tile/TileEntityGravestone.java // public class TileEntityGravestone extends TileEntity { // public int facing = -1; // public int type = 0; // public ResourceLocation[] typeTexture = { Resources.gravestone, // Resources.gravestoneReg, Resources.gravestoneFootball, // Resources.gravestoneFlag, Resources.gravestoneCone, // Resources.gravestoneBucket }; // // private double spawnDelay = 120.0D; // private int maxNearbyEntities = 10; // // public void updateEntity() { // double spawnDelay = this.spawnDelay; // // if (!getWorldObj().isRemote) { // if (spawnDelay > 0.0D) { // spawnDelay -= 1.0D; // return; // } // // if (this.facing == -1) { // this.facing = 0; // System.out.println("facing was -1"); // } // // Entity entity = new EntityZombie(getWorldObj()); // // List<?> entList = getWorldObj().getEntitiesWithinAABB( // entity.getClass(), // AxisAlignedBB.getAABBPool() // .getAABB(this.xCoord - 3.0D, this.yCoord, // this.zCoord - 3.0D, this.xCoord + 3.0D, // this.yCoord, this.zCoord + 3.0D)); // // int j = entList.size(); // if (j >= this.maxNearbyEntities) { // return; // } // Util.checkUnder(getWorldObj(), this.xCoord, this.yCoord, // this.zCoord, 4); // System.out.println("Spawn wave"); // // Util.spawnRandZombie(this.worldObj, this.xCoord, this.yCoord, // this.zCoord, this.facing, this.type); // // spawnDelay = this.spawnDelay; // } // super.updateEntity(); // } // // public void readFromNBT(NBTTagCompound par1NBTTagCompound) { // super.readFromNBT(par1NBTTagCompound); // // this.facing = par1NBTTagCompound.getShort("Facing"); // this.facing = par1NBTTagCompound.getShort("Type"); // } // // public void writeToNBT(NBTTagCompound par1NBTTagCompound) { // super.writeToNBT(par1NBTTagCompound); // par1NBTTagCompound.setShort("Facing", (short) this.facing); // par1NBTTagCompound.setShort("Type", (short) this.type); // NBTTagList nbttaglist = new NBTTagList(); // } // }
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.tileentity.TileEntity; import org.lwjgl.opengl.GL11; import com.countrygamer.pvz.block.tile.TileEntityGravestone; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly;
package com.countrygamer.pvz.client.block.tile; public class RenderGravestone extends TileEntitySpecialRenderer { private ModelGravestone aModel; public RenderGravestone() { this.aModel = new ModelGravestone(); } @SideOnly(Side.CLIENT)
// Path: java/com/countrygamer/pvz/block/tile/TileEntityGravestone.java // public class TileEntityGravestone extends TileEntity { // public int facing = -1; // public int type = 0; // public ResourceLocation[] typeTexture = { Resources.gravestone, // Resources.gravestoneReg, Resources.gravestoneFootball, // Resources.gravestoneFlag, Resources.gravestoneCone, // Resources.gravestoneBucket }; // // private double spawnDelay = 120.0D; // private int maxNearbyEntities = 10; // // public void updateEntity() { // double spawnDelay = this.spawnDelay; // // if (!getWorldObj().isRemote) { // if (spawnDelay > 0.0D) { // spawnDelay -= 1.0D; // return; // } // // if (this.facing == -1) { // this.facing = 0; // System.out.println("facing was -1"); // } // // Entity entity = new EntityZombie(getWorldObj()); // // List<?> entList = getWorldObj().getEntitiesWithinAABB( // entity.getClass(), // AxisAlignedBB.getAABBPool() // .getAABB(this.xCoord - 3.0D, this.yCoord, // this.zCoord - 3.0D, this.xCoord + 3.0D, // this.yCoord, this.zCoord + 3.0D)); // // int j = entList.size(); // if (j >= this.maxNearbyEntities) { // return; // } // Util.checkUnder(getWorldObj(), this.xCoord, this.yCoord, // this.zCoord, 4); // System.out.println("Spawn wave"); // // Util.spawnRandZombie(this.worldObj, this.xCoord, this.yCoord, // this.zCoord, this.facing, this.type); // // spawnDelay = this.spawnDelay; // } // super.updateEntity(); // } // // public void readFromNBT(NBTTagCompound par1NBTTagCompound) { // super.readFromNBT(par1NBTTagCompound); // // this.facing = par1NBTTagCompound.getShort("Facing"); // this.facing = par1NBTTagCompound.getShort("Type"); // } // // public void writeToNBT(NBTTagCompound par1NBTTagCompound) { // super.writeToNBT(par1NBTTagCompound); // par1NBTTagCompound.setShort("Facing", (short) this.facing); // par1NBTTagCompound.setShort("Type", (short) this.type); // NBTTagList nbttaglist = new NBTTagList(); // } // } // Path: java/com/countrygamer/pvz/client/block/tile/RenderGravestone.java import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.tileentity.TileEntity; import org.lwjgl.opengl.GL11; import com.countrygamer.pvz.block.tile.TileEntityGravestone; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; package com.countrygamer.pvz.client.block.tile; public class RenderGravestone extends TileEntitySpecialRenderer { private ModelGravestone aModel; public RenderGravestone() { this.aModel = new ModelGravestone(); } @SideOnly(Side.CLIENT)
public void renderAModelAt(TileEntityGravestone tileEnt, double x, double y, double z, float f) {
TheTemportalist/CountryGamer_PlantsVsZombies
java/com/countrygamer/pvz/entities/mobs/plants/EntityShroomShooterBase.java
// Path: java/com/countrygamer/pvz/entities/projectiles/EntityShroomPod.java // public class EntityShroomPod extends EntityPodBase // { // public EntityShroomPod(World world) // { // super(world); // } // public EntityShroomPod(World world, EntityLivingBase entLiv) { // super(world, entLiv); // } // public EntityShroomPod(World world, double par2, double par4, double par6) { // super(world, par2, par4, par6); // } // // public void setDamage() // { // this.damage = (byte)(this.damage / 4); // this.toDamage = true; // if (!this.worldObj.isDaytime()) // this.damage = (byte)(this.damage * 2); // } // // public void damageType(MovingObjectPosition movObjPos) // { // movObjPos.entityHit.attackEntityFrom(DamageSource.causeThrownDamage(this, getThrower()), this.damage); // } // }
import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.IRangedAttackMob; import net.minecraft.entity.ai.EntityAIArrowAttack; import net.minecraft.entity.ai.EntityAILookIdle; import net.minecraft.entity.ai.EntityAINearestAttackableTarget; import net.minecraft.entity.ai.EntityAIWatchClosest; import net.minecraft.entity.monster.IMob; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.projectile.EntityThrowable; import net.minecraft.item.ItemStack; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import com.countrygamer.pvz.entities.projectiles.EntityShroomPod;
} public void attackEntityWithRangedAttack(EntityLivingBase entitylivingbase, float f) { if (entitySelect(this.worldObj) != null) { EntityThrowable ent = entitySelect(this.worldObj); double toX = entitylivingbase.posX - this.posX; float percentToMouth = 0.5F; double toY = entitylivingbase.posY + this.height * percentToMouth - 1.0D - ent.posY; double toZ = entitylivingbase.posZ - this.posZ; float f1 = MathHelper.sqrt_double(toX * toX + toZ * toZ) * 0.2F; ent.setThrowableHeading(toX, toY + f1, toZ, 1.6F, 12.0F); playSound("random.bow", 1.0F, 1.0F / (getRNG().nextFloat() * 0.4F + 0.8F)); this.worldObj.spawnEntityInWorld(ent); } } public void ai() { this.tasks.addTask(1, new EntityAIArrowAttack(this, 0.25D, 20, 10.0F)); this.targetTasks.addTask(1, new EntityAINearestAttackableTarget(this, EntityLiving.class, 0, true, false, IMob.mobSelector)); this.tasks.addTask(9, new EntityAIWatchClosest(this, EntityPlayer.class, 6.0F)); this.tasks.addTask(10, new EntityAILookIdle(this)); } public EntityThrowable entitySelect(World world) { EntityThrowable ent; if (!this.worldObj.isDaytime())
// Path: java/com/countrygamer/pvz/entities/projectiles/EntityShroomPod.java // public class EntityShroomPod extends EntityPodBase // { // public EntityShroomPod(World world) // { // super(world); // } // public EntityShroomPod(World world, EntityLivingBase entLiv) { // super(world, entLiv); // } // public EntityShroomPod(World world, double par2, double par4, double par6) { // super(world, par2, par4, par6); // } // // public void setDamage() // { // this.damage = (byte)(this.damage / 4); // this.toDamage = true; // if (!this.worldObj.isDaytime()) // this.damage = (byte)(this.damage * 2); // } // // public void damageType(MovingObjectPosition movObjPos) // { // movObjPos.entityHit.attackEntityFrom(DamageSource.causeThrownDamage(this, getThrower()), this.damage); // } // } // Path: java/com/countrygamer/pvz/entities/mobs/plants/EntityShroomShooterBase.java import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.IRangedAttackMob; import net.minecraft.entity.ai.EntityAIArrowAttack; import net.minecraft.entity.ai.EntityAILookIdle; import net.minecraft.entity.ai.EntityAINearestAttackableTarget; import net.minecraft.entity.ai.EntityAIWatchClosest; import net.minecraft.entity.monster.IMob; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.projectile.EntityThrowable; import net.minecraft.item.ItemStack; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import com.countrygamer.pvz.entities.projectiles.EntityShroomPod; } public void attackEntityWithRangedAttack(EntityLivingBase entitylivingbase, float f) { if (entitySelect(this.worldObj) != null) { EntityThrowable ent = entitySelect(this.worldObj); double toX = entitylivingbase.posX - this.posX; float percentToMouth = 0.5F; double toY = entitylivingbase.posY + this.height * percentToMouth - 1.0D - ent.posY; double toZ = entitylivingbase.posZ - this.posZ; float f1 = MathHelper.sqrt_double(toX * toX + toZ * toZ) * 0.2F; ent.setThrowableHeading(toX, toY + f1, toZ, 1.6F, 12.0F); playSound("random.bow", 1.0F, 1.0F / (getRNG().nextFloat() * 0.4F + 0.8F)); this.worldObj.spawnEntityInWorld(ent); } } public void ai() { this.tasks.addTask(1, new EntityAIArrowAttack(this, 0.25D, 20, 10.0F)); this.targetTasks.addTask(1, new EntityAINearestAttackableTarget(this, EntityLiving.class, 0, true, false, IMob.mobSelector)); this.tasks.addTask(9, new EntityAIWatchClosest(this, EntityPlayer.class, 6.0F)); this.tasks.addTask(10, new EntityAILookIdle(this)); } public EntityThrowable entitySelect(World world) { EntityThrowable ent; if (!this.worldObj.isDaytime())
ent = new EntityShroomPod(world, this);
TheTemportalist/CountryGamer_PlantsVsZombies
java/com/countrygamer/pvz/client/render/RenderWalnut.java
// Path: java/com/countrygamer/pvz/entities/mobs/plants/EntityWalnut.java // public class EntityWalnut extends EntityPlantBase { // public EntityWalnut(World par1World) { // super(par1World, new ItemStack(PvZ.sunlight, 1, 0)); // } // // protected void applyEntityAttributes() { // super.applyEntityAttributes(); // setMaxHealth(PvZ.basePlantHealth * 16); // getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue( // this.baseHealth); // } // // public void onEntityUpdate() { // super.onEntityUpdate(); // // int r = 10; // List<?> rEntities = this.worldObj.getEntitiesWithinAABB( // EntityLivingBase.class, AxisAlignedBB.getBoundingBox(this.posX // - r, this.posY, this.posZ - r, this.posX + r, // this.posY + 1.0D, this.posZ + r)); // // ArrayList<EntityLivingBase> otherMob = new ArrayList<EntityLivingBase>(); // for (int i = 0; i < rEntities.size(); i++) { // EntityLivingBase ent = (EntityLivingBase) rEntities.get(i); // if ((ent.getCreatureAttribute() == PvZ.plantAttribute) // || ((ent instanceof EntityPlayer))) { // rEntities.remove(ent); // otherMob.add(ent); // } else { // if ((((EntityCreature) ent).getEntityToAttack() instanceof EntityWalnut)) // continue; // } // } // } // } // // Path: java/com/countrygamer/pvz/lib/Resources.java // public class Resources { // public static final ResourceLocation chlorophyllBowl = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/bowlfilled.png"); // // public static final ResourceLocation gravestone = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone.png"); // // public static final ResourceLocation gravestoneReg = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Reg.png"); // // public static final ResourceLocation gravestoneFootball = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/blocks/Gravestone_Football.png"); // // public static final ResourceLocation gravestoneFlag = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Flag.png"); // // public static final ResourceLocation gravestoneCone = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Cone.png"); // // public static final ResourceLocation gravestoneBucket = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Bucket.png"); // // public static final ResourceLocation greenhouse = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/greenhouse.png"); // // public static final ResourceLocation sunflowerMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/sunflower.png"); // // public static final ResourceLocation peaShooterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/peashooter.png"); // // public static final ResourceLocation snowPeaMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/snowpea.png"); // // public static final ResourceLocation repeaterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/repeater.png"); // // public static final ResourceLocation threePeaterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/threepeater.png"); // // public static final ResourceLocation sunShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/sun_shroom_0.png"); // // public static final ResourceLocation sunShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/sun_shroom_1.png"); // // public static final ResourceLocation puffShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/puff_shroom_0.png"); // // public static final ResourceLocation puffShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/puff_shroom_1.png"); // // public static final ResourceLocation scaredyShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/basicNight/scaredy_shroom_0.png"); // // public static final ResourceLocation scaredyShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/basicNight/scaredy_shroom_1.png"); // // public static final ResourceLocation fumeShroomMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/fume_shroom_0.png"); // // public static final ResourceLocation moonShroomMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/moonShroom.png"); // // public static final ResourceLocation antiCreeperMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/special/creeperrepeater.png"); // // public static final ResourceLocation walnutMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/special/walnut.png"); // }
import net.minecraft.client.model.ModelBase; import net.minecraft.client.renderer.entity.RenderLiving; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import net.minecraft.util.ResourceLocation; import com.countrygamer.pvz.entities.mobs.plants.EntityWalnut; import com.countrygamer.pvz.lib.Resources; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly;
package com.countrygamer.pvz.client.render; @SideOnly(Side.CLIENT) public class RenderWalnut extends RenderLiving { protected ModelWalnut model; @SideOnly(Side.CLIENT) public RenderWalnut(ModelBase par1ModelBase, float par2) { super(par1ModelBase, par2); this.model = ((ModelWalnut)this.mainModel); } @SideOnly(Side.CLIENT)
// Path: java/com/countrygamer/pvz/entities/mobs/plants/EntityWalnut.java // public class EntityWalnut extends EntityPlantBase { // public EntityWalnut(World par1World) { // super(par1World, new ItemStack(PvZ.sunlight, 1, 0)); // } // // protected void applyEntityAttributes() { // super.applyEntityAttributes(); // setMaxHealth(PvZ.basePlantHealth * 16); // getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue( // this.baseHealth); // } // // public void onEntityUpdate() { // super.onEntityUpdate(); // // int r = 10; // List<?> rEntities = this.worldObj.getEntitiesWithinAABB( // EntityLivingBase.class, AxisAlignedBB.getBoundingBox(this.posX // - r, this.posY, this.posZ - r, this.posX + r, // this.posY + 1.0D, this.posZ + r)); // // ArrayList<EntityLivingBase> otherMob = new ArrayList<EntityLivingBase>(); // for (int i = 0; i < rEntities.size(); i++) { // EntityLivingBase ent = (EntityLivingBase) rEntities.get(i); // if ((ent.getCreatureAttribute() == PvZ.plantAttribute) // || ((ent instanceof EntityPlayer))) { // rEntities.remove(ent); // otherMob.add(ent); // } else { // if ((((EntityCreature) ent).getEntityToAttack() instanceof EntityWalnut)) // continue; // } // } // } // } // // Path: java/com/countrygamer/pvz/lib/Resources.java // public class Resources { // public static final ResourceLocation chlorophyllBowl = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/bowlfilled.png"); // // public static final ResourceLocation gravestone = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone.png"); // // public static final ResourceLocation gravestoneReg = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Reg.png"); // // public static final ResourceLocation gravestoneFootball = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/blocks/Gravestone_Football.png"); // // public static final ResourceLocation gravestoneFlag = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Flag.png"); // // public static final ResourceLocation gravestoneCone = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Cone.png"); // // public static final ResourceLocation gravestoneBucket = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Bucket.png"); // // public static final ResourceLocation greenhouse = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/greenhouse.png"); // // public static final ResourceLocation sunflowerMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/sunflower.png"); // // public static final ResourceLocation peaShooterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/peashooter.png"); // // public static final ResourceLocation snowPeaMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/snowpea.png"); // // public static final ResourceLocation repeaterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/repeater.png"); // // public static final ResourceLocation threePeaterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/threepeater.png"); // // public static final ResourceLocation sunShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/sun_shroom_0.png"); // // public static final ResourceLocation sunShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/sun_shroom_1.png"); // // public static final ResourceLocation puffShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/puff_shroom_0.png"); // // public static final ResourceLocation puffShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/puff_shroom_1.png"); // // public static final ResourceLocation scaredyShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/basicNight/scaredy_shroom_0.png"); // // public static final ResourceLocation scaredyShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/basicNight/scaredy_shroom_1.png"); // // public static final ResourceLocation fumeShroomMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/fume_shroom_0.png"); // // public static final ResourceLocation moonShroomMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/moonShroom.png"); // // public static final ResourceLocation antiCreeperMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/special/creeperrepeater.png"); // // public static final ResourceLocation walnutMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/special/walnut.png"); // } // Path: java/com/countrygamer/pvz/client/render/RenderWalnut.java import net.minecraft.client.model.ModelBase; import net.minecraft.client.renderer.entity.RenderLiving; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import net.minecraft.util.ResourceLocation; import com.countrygamer.pvz.entities.mobs.plants.EntityWalnut; import com.countrygamer.pvz.lib.Resources; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; package com.countrygamer.pvz.client.render; @SideOnly(Side.CLIENT) public class RenderWalnut extends RenderLiving { protected ModelWalnut model; @SideOnly(Side.CLIENT) public RenderWalnut(ModelBase par1ModelBase, float par2) { super(par1ModelBase, par2); this.model = ((ModelWalnut)this.mainModel); } @SideOnly(Side.CLIENT)
public void renderWalnut(EntityWalnut entity, double par2, double par4, double par6, float par8, float par9) {
TheTemportalist/CountryGamer_PlantsVsZombies
java/com/countrygamer/pvz/client/gui/GuiGuide.java
// Path: java/com/countrygamer/pvz/items/ItemGuideBook.java // public class ItemGuideBook extends ItemBase { // public ItemGuideBook(String modid, String name) { // super(modid, name); // } // // public ItemStack onItemRightClick(ItemStack itemStack, World world, // EntityPlayer player) { // if (world.isRemote) { // player.openGui(PvZ.instance, 3, world, (int) player.posX, // (int) player.posY, (int) player.posZ); // } // // return itemStack; // } // } // // Path: java/com/countrygamer/pvz/lib/Reference.java // public class Reference { // /* Mod constants */ // public static final String MOD_ID = "pvz"; // public static final String BASE_TEX = Reference.MOD_ID + ":"; // public static final String MOD_NAME = "Plants Vz Zombies"; // public static final String VERSION = "4.0.0"; // public static final String MC_VERSION = "1.7.2"; // public static final String CHANNEL_NAME = MOD_ID; // public static final String SERVER_PROXY_CLASS = "com.countrygamer." // + MOD_ID + ".proxy.ServerProxy"; // public static final String CLIENT_PROXY_CLASS = "com.countrygamer." // + MOD_ID + ".proxy.ClientProxy"; // }
import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; import com.countrygamer.core.Base.client.gui.GuiButtonArrow; import com.countrygamer.core.Base.client.gui.GuiButtonArrow.ButtonType; import com.countrygamer.pvz.items.ItemGuideBook; import com.countrygamer.pvz.lib.Reference;
package com.countrygamer.pvz.client.gui; public class GuiGuide extends GuiScreen { private static final ResourceLocation book = new ResourceLocation(
// Path: java/com/countrygamer/pvz/items/ItemGuideBook.java // public class ItemGuideBook extends ItemBase { // public ItemGuideBook(String modid, String name) { // super(modid, name); // } // // public ItemStack onItemRightClick(ItemStack itemStack, World world, // EntityPlayer player) { // if (world.isRemote) { // player.openGui(PvZ.instance, 3, world, (int) player.posX, // (int) player.posY, (int) player.posZ); // } // // return itemStack; // } // } // // Path: java/com/countrygamer/pvz/lib/Reference.java // public class Reference { // /* Mod constants */ // public static final String MOD_ID = "pvz"; // public static final String BASE_TEX = Reference.MOD_ID + ":"; // public static final String MOD_NAME = "Plants Vz Zombies"; // public static final String VERSION = "4.0.0"; // public static final String MC_VERSION = "1.7.2"; // public static final String CHANNEL_NAME = MOD_ID; // public static final String SERVER_PROXY_CLASS = "com.countrygamer." // + MOD_ID + ".proxy.ServerProxy"; // public static final String CLIENT_PROXY_CLASS = "com.countrygamer." // + MOD_ID + ".proxy.ClientProxy"; // } // Path: java/com/countrygamer/pvz/client/gui/GuiGuide.java import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; import com.countrygamer.core.Base.client.gui.GuiButtonArrow; import com.countrygamer.core.Base.client.gui.GuiButtonArrow.ButtonType; import com.countrygamer.pvz.items.ItemGuideBook; import com.countrygamer.pvz.lib.Reference; package com.countrygamer.pvz.client.gui; public class GuiGuide extends GuiScreen { private static final ResourceLocation book = new ResourceLocation(
Reference.MOD_ID, "textures/gui/book1.png");
TheTemportalist/CountryGamer_PlantsVsZombies
java/com/countrygamer/pvz/client/gui/GuiGuide.java
// Path: java/com/countrygamer/pvz/items/ItemGuideBook.java // public class ItemGuideBook extends ItemBase { // public ItemGuideBook(String modid, String name) { // super(modid, name); // } // // public ItemStack onItemRightClick(ItemStack itemStack, World world, // EntityPlayer player) { // if (world.isRemote) { // player.openGui(PvZ.instance, 3, world, (int) player.posX, // (int) player.posY, (int) player.posZ); // } // // return itemStack; // } // } // // Path: java/com/countrygamer/pvz/lib/Reference.java // public class Reference { // /* Mod constants */ // public static final String MOD_ID = "pvz"; // public static final String BASE_TEX = Reference.MOD_ID + ":"; // public static final String MOD_NAME = "Plants Vz Zombies"; // public static final String VERSION = "4.0.0"; // public static final String MC_VERSION = "1.7.2"; // public static final String CHANNEL_NAME = MOD_ID; // public static final String SERVER_PROXY_CLASS = "com.countrygamer." // + MOD_ID + ".proxy.ServerProxy"; // public static final String CLIENT_PROXY_CLASS = "com.countrygamer." // + MOD_ID + ".proxy.ClientProxy"; // }
import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; import com.countrygamer.core.Base.client.gui.GuiButtonArrow; import com.countrygamer.core.Base.client.gui.GuiButtonArrow.ButtonType; import com.countrygamer.pvz.items.ItemGuideBook; import com.countrygamer.pvz.lib.Reference;
package com.countrygamer.pvz.client.gui; public class GuiGuide extends GuiScreen { private static final ResourceLocation book = new ResourceLocation( Reference.MOD_ID, "textures/gui/book1.png"); private int bookImageWidth = 256; private int bookImageHeight = 256; private int page = 0; private int totalPage = 20; private GuiButtonArrow nextRecipeButtonIndex; private GuiButtonArrow previousRecipeButtonIndex; private GuiButton a; private GuiButton b; private GuiButton c; private GuiButton d; private GuiButton e; private GuiButton f;
// Path: java/com/countrygamer/pvz/items/ItemGuideBook.java // public class ItemGuideBook extends ItemBase { // public ItemGuideBook(String modid, String name) { // super(modid, name); // } // // public ItemStack onItemRightClick(ItemStack itemStack, World world, // EntityPlayer player) { // if (world.isRemote) { // player.openGui(PvZ.instance, 3, world, (int) player.posX, // (int) player.posY, (int) player.posZ); // } // // return itemStack; // } // } // // Path: java/com/countrygamer/pvz/lib/Reference.java // public class Reference { // /* Mod constants */ // public static final String MOD_ID = "pvz"; // public static final String BASE_TEX = Reference.MOD_ID + ":"; // public static final String MOD_NAME = "Plants Vz Zombies"; // public static final String VERSION = "4.0.0"; // public static final String MC_VERSION = "1.7.2"; // public static final String CHANNEL_NAME = MOD_ID; // public static final String SERVER_PROXY_CLASS = "com.countrygamer." // + MOD_ID + ".proxy.ServerProxy"; // public static final String CLIENT_PROXY_CLASS = "com.countrygamer." // + MOD_ID + ".proxy.ClientProxy"; // } // Path: java/com/countrygamer/pvz/client/gui/GuiGuide.java import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; import com.countrygamer.core.Base.client.gui.GuiButtonArrow; import com.countrygamer.core.Base.client.gui.GuiButtonArrow.ButtonType; import com.countrygamer.pvz.items.ItemGuideBook; import com.countrygamer.pvz.lib.Reference; package com.countrygamer.pvz.client.gui; public class GuiGuide extends GuiScreen { private static final ResourceLocation book = new ResourceLocation( Reference.MOD_ID, "textures/gui/book1.png"); private int bookImageWidth = 256; private int bookImageHeight = 256; private int page = 0; private int totalPage = 20; private GuiButtonArrow nextRecipeButtonIndex; private GuiButtonArrow previousRecipeButtonIndex; private GuiButton a; private GuiButton b; private GuiButton c; private GuiButton d; private GuiButton e; private GuiButton f;
public ItemGuideBook itemBook;
TheTemportalist/CountryGamer_PlantsVsZombies
java/com/countrygamer/pvz/block/BlockChlorophyllBowl.java
// Path: java/com/countrygamer/pvz/block/tile/TileEntityChlorophyllBowl.java // public class TileEntityChlorophyllBowl extends TileEntityInventoryBase { // // public int delayControl = 1200 * PvZ.sunlightTimer; // public int delay = this.delayControl; // // public int sunlightHeld = 0; // // public TileEntityChlorophyllBowl() { // super("Chlorophyll Bowl", 36, 64); // } // // public void sunlightControl() { // World world = this.worldObj; // int x = this.xCoord; // int y = this.yCoord; // int z = this.zCoord; // // if (!world.isRemote) // if (Util.dayCheck(world)) { // for (int i = 0; i <= 36; i++) { // ItemStack slot = getStackInSlot(i); // // if (slot != null) { // if (slot.getItem() == PvZ.sunlight) { // ItemBase stackItem = (ItemBase) slot.getItem(); // if (slot.stackSize < stackItem.getMaxStackSize()) { // slot.stackSize += 1; // break; // } // } // } else { // ItemStack givenSunlight = new ItemStack(PvZ.sunlight, // 1, 0); // // setInventorySlotContents(i, givenSunlight); // break; // } // // } // // } else if (!Util.dayCheck(world)) { // for (int i = 0; i <= 36; i++) { // ItemStack slot = getStackInSlot(i); // // if (slot != null) { // if (slot.getItem() == PvZ.moonlight) { // ItemBase stackItem = (ItemBase) slot.getItem(); // if (slot.stackSize < stackItem.getMaxStackSize()) { // slot.stackSize += 1; // break; // } // } // } else { // ItemStack givenSunlight = new ItemStack(PvZ.moonlight, // 1, 0); // // setInventorySlotContents(i, givenSunlight); // break; // } // } // } // } // // public void updateEntity() { // if (this.delay > 0) { // this.delay -= 1; // // return; // } // this.delay = this.delayControl; // // sunlightControl(); // // } // // }
import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import com.countrygamer.core.Base.common.block.BlockContainerBase; import com.countrygamer.pvz.block.tile.TileEntityChlorophyllBowl;
package com.countrygamer.pvz.block; public class BlockChlorophyllBowl extends BlockContainerBase { Random random = new Random(); public BlockChlorophyllBowl(Material mat, String modid, String name, Class<? extends TileEntity> tileEntityClass) { super(mat, modid, name, tileEntityClass); setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.5F, 1.0F); } public int getRenderType() { return -1; } public boolean isOpaqueCube() { return false; } public boolean renderAsNormalBlock() { return false; } public void onNeighborBlockChange(World par1World, int par2, int par3, int par4, Block par5) { super.onNeighborBlockChange(par1World, par2, par3, par4, par5);
// Path: java/com/countrygamer/pvz/block/tile/TileEntityChlorophyllBowl.java // public class TileEntityChlorophyllBowl extends TileEntityInventoryBase { // // public int delayControl = 1200 * PvZ.sunlightTimer; // public int delay = this.delayControl; // // public int sunlightHeld = 0; // // public TileEntityChlorophyllBowl() { // super("Chlorophyll Bowl", 36, 64); // } // // public void sunlightControl() { // World world = this.worldObj; // int x = this.xCoord; // int y = this.yCoord; // int z = this.zCoord; // // if (!world.isRemote) // if (Util.dayCheck(world)) { // for (int i = 0; i <= 36; i++) { // ItemStack slot = getStackInSlot(i); // // if (slot != null) { // if (slot.getItem() == PvZ.sunlight) { // ItemBase stackItem = (ItemBase) slot.getItem(); // if (slot.stackSize < stackItem.getMaxStackSize()) { // slot.stackSize += 1; // break; // } // } // } else { // ItemStack givenSunlight = new ItemStack(PvZ.sunlight, // 1, 0); // // setInventorySlotContents(i, givenSunlight); // break; // } // // } // // } else if (!Util.dayCheck(world)) { // for (int i = 0; i <= 36; i++) { // ItemStack slot = getStackInSlot(i); // // if (slot != null) { // if (slot.getItem() == PvZ.moonlight) { // ItemBase stackItem = (ItemBase) slot.getItem(); // if (slot.stackSize < stackItem.getMaxStackSize()) { // slot.stackSize += 1; // break; // } // } // } else { // ItemStack givenSunlight = new ItemStack(PvZ.moonlight, // 1, 0); // // setInventorySlotContents(i, givenSunlight); // break; // } // } // } // } // // public void updateEntity() { // if (this.delay > 0) { // this.delay -= 1; // // return; // } // this.delay = this.delayControl; // // sunlightControl(); // // } // // } // Path: java/com/countrygamer/pvz/block/BlockChlorophyllBowl.java import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import com.countrygamer.core.Base.common.block.BlockContainerBase; import com.countrygamer.pvz.block.tile.TileEntityChlorophyllBowl; package com.countrygamer.pvz.block; public class BlockChlorophyllBowl extends BlockContainerBase { Random random = new Random(); public BlockChlorophyllBowl(Material mat, String modid, String name, Class<? extends TileEntity> tileEntityClass) { super(mat, modid, name, tileEntityClass); setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.5F, 1.0F); } public int getRenderType() { return -1; } public boolean isOpaqueCube() { return false; } public boolean renderAsNormalBlock() { return false; } public void onNeighborBlockChange(World par1World, int par2, int par3, int par4, Block par5) { super.onNeighborBlockChange(par1World, par2, par3, par4, par5);
TileEntityChlorophyllBowl tileentitychest = (TileEntityChlorophyllBowl) par1World
TheTemportalist/CountryGamer_PlantsVsZombies
java/com/countrygamer/pvz/client/render/RenderPuffShroom.java
// Path: java/com/countrygamer/pvz/entities/mobs/plants/EntityPuffShroom.java // public class EntityPuffShroom extends EntityShroomShooterBase { // public EntityPuffShroom(World world) { // super(world, new ItemStack(PvZ.nightPlants, 1, 0)); // } // // protected void applyEntityAttributes() { // super.applyEntityAttributes(); // setMaxHealth(PvZ.basePlantHealth / 2); // getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue( // this.baseHealth); // } // // public void dropFewItems(boolean par1, int par2) { // dropItem(PvZ.shroomPod, 1); // } // // public void onUpdate() { // super.onUpdate(); // int lightBright = this.worldObj.getBlockLightValue((int) this.posX, // (int) this.posY, (int) this.posZ); // // if ((this.worldObj != null) // && (!this.worldObj.isRemote) // && (((this.worldObj.getWorldTime() < 0L) || (this.worldObj // .getWorldTime() > 12000L)) || ((this.worldObj // .getWorldTime() >= 12000L) && (this.worldObj // .getWorldTime() <= 23999L)))) // ; // } // } // // Path: java/com/countrygamer/pvz/lib/Resources.java // public class Resources { // public static final ResourceLocation chlorophyllBowl = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/bowlfilled.png"); // // public static final ResourceLocation gravestone = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone.png"); // // public static final ResourceLocation gravestoneReg = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Reg.png"); // // public static final ResourceLocation gravestoneFootball = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/blocks/Gravestone_Football.png"); // // public static final ResourceLocation gravestoneFlag = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Flag.png"); // // public static final ResourceLocation gravestoneCone = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Cone.png"); // // public static final ResourceLocation gravestoneBucket = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Bucket.png"); // // public static final ResourceLocation greenhouse = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/greenhouse.png"); // // public static final ResourceLocation sunflowerMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/sunflower.png"); // // public static final ResourceLocation peaShooterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/peashooter.png"); // // public static final ResourceLocation snowPeaMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/snowpea.png"); // // public static final ResourceLocation repeaterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/repeater.png"); // // public static final ResourceLocation threePeaterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/threepeater.png"); // // public static final ResourceLocation sunShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/sun_shroom_0.png"); // // public static final ResourceLocation sunShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/sun_shroom_1.png"); // // public static final ResourceLocation puffShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/puff_shroom_0.png"); // // public static final ResourceLocation puffShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/puff_shroom_1.png"); // // public static final ResourceLocation scaredyShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/basicNight/scaredy_shroom_0.png"); // // public static final ResourceLocation scaredyShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/basicNight/scaredy_shroom_1.png"); // // public static final ResourceLocation fumeShroomMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/fume_shroom_0.png"); // // public static final ResourceLocation moonShroomMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/moonShroom.png"); // // public static final ResourceLocation antiCreeperMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/special/creeperrepeater.png"); // // public static final ResourceLocation walnutMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/special/walnut.png"); // }
import net.minecraft.client.model.ModelBase; import net.minecraft.client.renderer.entity.RenderLiving; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import net.minecraft.util.ResourceLocation; import com.countrygamer.pvz.entities.mobs.plants.EntityPuffShroom; import com.countrygamer.pvz.lib.Resources; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly;
package com.countrygamer.pvz.client.render; @SideOnly(Side.CLIENT) public class RenderPuffShroom extends RenderLiving { protected ModelPuffShroom model;
// Path: java/com/countrygamer/pvz/entities/mobs/plants/EntityPuffShroom.java // public class EntityPuffShroom extends EntityShroomShooterBase { // public EntityPuffShroom(World world) { // super(world, new ItemStack(PvZ.nightPlants, 1, 0)); // } // // protected void applyEntityAttributes() { // super.applyEntityAttributes(); // setMaxHealth(PvZ.basePlantHealth / 2); // getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue( // this.baseHealth); // } // // public void dropFewItems(boolean par1, int par2) { // dropItem(PvZ.shroomPod, 1); // } // // public void onUpdate() { // super.onUpdate(); // int lightBright = this.worldObj.getBlockLightValue((int) this.posX, // (int) this.posY, (int) this.posZ); // // if ((this.worldObj != null) // && (!this.worldObj.isRemote) // && (((this.worldObj.getWorldTime() < 0L) || (this.worldObj // .getWorldTime() > 12000L)) || ((this.worldObj // .getWorldTime() >= 12000L) && (this.worldObj // .getWorldTime() <= 23999L)))) // ; // } // } // // Path: java/com/countrygamer/pvz/lib/Resources.java // public class Resources { // public static final ResourceLocation chlorophyllBowl = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/bowlfilled.png"); // // public static final ResourceLocation gravestone = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone.png"); // // public static final ResourceLocation gravestoneReg = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Reg.png"); // // public static final ResourceLocation gravestoneFootball = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/blocks/Gravestone_Football.png"); // // public static final ResourceLocation gravestoneFlag = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Flag.png"); // // public static final ResourceLocation gravestoneCone = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Cone.png"); // // public static final ResourceLocation gravestoneBucket = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Bucket.png"); // // public static final ResourceLocation greenhouse = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/greenhouse.png"); // // public static final ResourceLocation sunflowerMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/sunflower.png"); // // public static final ResourceLocation peaShooterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/peashooter.png"); // // public static final ResourceLocation snowPeaMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/snowpea.png"); // // public static final ResourceLocation repeaterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/repeater.png"); // // public static final ResourceLocation threePeaterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/threepeater.png"); // // public static final ResourceLocation sunShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/sun_shroom_0.png"); // // public static final ResourceLocation sunShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/sun_shroom_1.png"); // // public static final ResourceLocation puffShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/puff_shroom_0.png"); // // public static final ResourceLocation puffShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/puff_shroom_1.png"); // // public static final ResourceLocation scaredyShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/basicNight/scaredy_shroom_0.png"); // // public static final ResourceLocation scaredyShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/basicNight/scaredy_shroom_1.png"); // // public static final ResourceLocation fumeShroomMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/fume_shroom_0.png"); // // public static final ResourceLocation moonShroomMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/moonShroom.png"); // // public static final ResourceLocation antiCreeperMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/special/creeperrepeater.png"); // // public static final ResourceLocation walnutMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/special/walnut.png"); // } // Path: java/com/countrygamer/pvz/client/render/RenderPuffShroom.java import net.minecraft.client.model.ModelBase; import net.minecraft.client.renderer.entity.RenderLiving; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import net.minecraft.util.ResourceLocation; import com.countrygamer.pvz.entities.mobs.plants.EntityPuffShroom; import com.countrygamer.pvz.lib.Resources; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; package com.countrygamer.pvz.client.render; @SideOnly(Side.CLIENT) public class RenderPuffShroom extends RenderLiving { protected ModelPuffShroom model;
private static ResourceLocation field_110887_f = Resources.puffShroomMob_0;
TheTemportalist/CountryGamer_PlantsVsZombies
java/com/countrygamer/pvz/client/render/RenderPuffShroom.java
// Path: java/com/countrygamer/pvz/entities/mobs/plants/EntityPuffShroom.java // public class EntityPuffShroom extends EntityShroomShooterBase { // public EntityPuffShroom(World world) { // super(world, new ItemStack(PvZ.nightPlants, 1, 0)); // } // // protected void applyEntityAttributes() { // super.applyEntityAttributes(); // setMaxHealth(PvZ.basePlantHealth / 2); // getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue( // this.baseHealth); // } // // public void dropFewItems(boolean par1, int par2) { // dropItem(PvZ.shroomPod, 1); // } // // public void onUpdate() { // super.onUpdate(); // int lightBright = this.worldObj.getBlockLightValue((int) this.posX, // (int) this.posY, (int) this.posZ); // // if ((this.worldObj != null) // && (!this.worldObj.isRemote) // && (((this.worldObj.getWorldTime() < 0L) || (this.worldObj // .getWorldTime() > 12000L)) || ((this.worldObj // .getWorldTime() >= 12000L) && (this.worldObj // .getWorldTime() <= 23999L)))) // ; // } // } // // Path: java/com/countrygamer/pvz/lib/Resources.java // public class Resources { // public static final ResourceLocation chlorophyllBowl = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/bowlfilled.png"); // // public static final ResourceLocation gravestone = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone.png"); // // public static final ResourceLocation gravestoneReg = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Reg.png"); // // public static final ResourceLocation gravestoneFootball = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/blocks/Gravestone_Football.png"); // // public static final ResourceLocation gravestoneFlag = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Flag.png"); // // public static final ResourceLocation gravestoneCone = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Cone.png"); // // public static final ResourceLocation gravestoneBucket = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Bucket.png"); // // public static final ResourceLocation greenhouse = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/greenhouse.png"); // // public static final ResourceLocation sunflowerMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/sunflower.png"); // // public static final ResourceLocation peaShooterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/peashooter.png"); // // public static final ResourceLocation snowPeaMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/snowpea.png"); // // public static final ResourceLocation repeaterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/repeater.png"); // // public static final ResourceLocation threePeaterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/threepeater.png"); // // public static final ResourceLocation sunShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/sun_shroom_0.png"); // // public static final ResourceLocation sunShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/sun_shroom_1.png"); // // public static final ResourceLocation puffShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/puff_shroom_0.png"); // // public static final ResourceLocation puffShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/puff_shroom_1.png"); // // public static final ResourceLocation scaredyShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/basicNight/scaredy_shroom_0.png"); // // public static final ResourceLocation scaredyShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/basicNight/scaredy_shroom_1.png"); // // public static final ResourceLocation fumeShroomMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/fume_shroom_0.png"); // // public static final ResourceLocation moonShroomMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/moonShroom.png"); // // public static final ResourceLocation antiCreeperMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/special/creeperrepeater.png"); // // public static final ResourceLocation walnutMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/special/walnut.png"); // }
import net.minecraft.client.model.ModelBase; import net.minecraft.client.renderer.entity.RenderLiving; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import net.minecraft.util.ResourceLocation; import com.countrygamer.pvz.entities.mobs.plants.EntityPuffShroom; import com.countrygamer.pvz.lib.Resources; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly;
package com.countrygamer.pvz.client.render; @SideOnly(Side.CLIENT) public class RenderPuffShroom extends RenderLiving { protected ModelPuffShroom model; private static ResourceLocation field_110887_f = Resources.puffShroomMob_0; @SideOnly(Side.CLIENT) public RenderPuffShroom(ModelBase par1ModelBase, float par2) { super(par1ModelBase, par2); this.model = ((ModelPuffShroom)this.mainModel); } @SideOnly(Side.CLIENT)
// Path: java/com/countrygamer/pvz/entities/mobs/plants/EntityPuffShroom.java // public class EntityPuffShroom extends EntityShroomShooterBase { // public EntityPuffShroom(World world) { // super(world, new ItemStack(PvZ.nightPlants, 1, 0)); // } // // protected void applyEntityAttributes() { // super.applyEntityAttributes(); // setMaxHealth(PvZ.basePlantHealth / 2); // getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue( // this.baseHealth); // } // // public void dropFewItems(boolean par1, int par2) { // dropItem(PvZ.shroomPod, 1); // } // // public void onUpdate() { // super.onUpdate(); // int lightBright = this.worldObj.getBlockLightValue((int) this.posX, // (int) this.posY, (int) this.posZ); // // if ((this.worldObj != null) // && (!this.worldObj.isRemote) // && (((this.worldObj.getWorldTime() < 0L) || (this.worldObj // .getWorldTime() > 12000L)) || ((this.worldObj // .getWorldTime() >= 12000L) && (this.worldObj // .getWorldTime() <= 23999L)))) // ; // } // } // // Path: java/com/countrygamer/pvz/lib/Resources.java // public class Resources { // public static final ResourceLocation chlorophyllBowl = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/bowlfilled.png"); // // public static final ResourceLocation gravestone = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone.png"); // // public static final ResourceLocation gravestoneReg = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Reg.png"); // // public static final ResourceLocation gravestoneFootball = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/blocks/Gravestone_Football.png"); // // public static final ResourceLocation gravestoneFlag = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Flag.png"); // // public static final ResourceLocation gravestoneCone = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Cone.png"); // // public static final ResourceLocation gravestoneBucket = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Bucket.png"); // // public static final ResourceLocation greenhouse = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/greenhouse.png"); // // public static final ResourceLocation sunflowerMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/sunflower.png"); // // public static final ResourceLocation peaShooterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/peashooter.png"); // // public static final ResourceLocation snowPeaMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/snowpea.png"); // // public static final ResourceLocation repeaterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/repeater.png"); // // public static final ResourceLocation threePeaterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/threepeater.png"); // // public static final ResourceLocation sunShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/sun_shroom_0.png"); // // public static final ResourceLocation sunShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/sun_shroom_1.png"); // // public static final ResourceLocation puffShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/puff_shroom_0.png"); // // public static final ResourceLocation puffShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/puff_shroom_1.png"); // // public static final ResourceLocation scaredyShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/basicNight/scaredy_shroom_0.png"); // // public static final ResourceLocation scaredyShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/basicNight/scaredy_shroom_1.png"); // // public static final ResourceLocation fumeShroomMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/fume_shroom_0.png"); // // public static final ResourceLocation moonShroomMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/moonShroom.png"); // // public static final ResourceLocation antiCreeperMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/special/creeperrepeater.png"); // // public static final ResourceLocation walnutMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/special/walnut.png"); // } // Path: java/com/countrygamer/pvz/client/render/RenderPuffShroom.java import net.minecraft.client.model.ModelBase; import net.minecraft.client.renderer.entity.RenderLiving; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import net.minecraft.util.ResourceLocation; import com.countrygamer.pvz.entities.mobs.plants.EntityPuffShroom; import com.countrygamer.pvz.lib.Resources; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; package com.countrygamer.pvz.client.render; @SideOnly(Side.CLIENT) public class RenderPuffShroom extends RenderLiving { protected ModelPuffShroom model; private static ResourceLocation field_110887_f = Resources.puffShroomMob_0; @SideOnly(Side.CLIENT) public RenderPuffShroom(ModelBase par1ModelBase, float par2) { super(par1ModelBase, par2); this.model = ((ModelPuffShroom)this.mainModel); } @SideOnly(Side.CLIENT)
public void renderPuffShroom(EntityPuffShroom entity, double par2, double par4, double par6, float par8, float par9) {
TheTemportalist/CountryGamer_PlantsVsZombies
java/com/countrygamer/pvz/client/render/RenderScaredyShroom.java
// Path: java/com/countrygamer/pvz/entities/mobs/plants/EntityScaredyShroom.java // public class EntityScaredyShroom extends EntityShroomShooterBase { // public EntityScaredyShroom(World world) { // super(world, new ItemStack(PvZ.nightPlants, 1, 1)); // } // // public void dropFewItems(boolean par1, int par2) { // dropItem(PvZ.shroomPod, 2); // } // } // // Path: java/com/countrygamer/pvz/lib/Resources.java // public class Resources { // public static final ResourceLocation chlorophyllBowl = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/bowlfilled.png"); // // public static final ResourceLocation gravestone = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone.png"); // // public static final ResourceLocation gravestoneReg = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Reg.png"); // // public static final ResourceLocation gravestoneFootball = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/blocks/Gravestone_Football.png"); // // public static final ResourceLocation gravestoneFlag = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Flag.png"); // // public static final ResourceLocation gravestoneCone = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Cone.png"); // // public static final ResourceLocation gravestoneBucket = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Bucket.png"); // // public static final ResourceLocation greenhouse = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/greenhouse.png"); // // public static final ResourceLocation sunflowerMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/sunflower.png"); // // public static final ResourceLocation peaShooterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/peashooter.png"); // // public static final ResourceLocation snowPeaMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/snowpea.png"); // // public static final ResourceLocation repeaterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/repeater.png"); // // public static final ResourceLocation threePeaterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/threepeater.png"); // // public static final ResourceLocation sunShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/sun_shroom_0.png"); // // public static final ResourceLocation sunShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/sun_shroom_1.png"); // // public static final ResourceLocation puffShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/puff_shroom_0.png"); // // public static final ResourceLocation puffShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/puff_shroom_1.png"); // // public static final ResourceLocation scaredyShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/basicNight/scaredy_shroom_0.png"); // // public static final ResourceLocation scaredyShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/basicNight/scaredy_shroom_1.png"); // // public static final ResourceLocation fumeShroomMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/fume_shroom_0.png"); // // public static final ResourceLocation moonShroomMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/moonShroom.png"); // // public static final ResourceLocation antiCreeperMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/special/creeperrepeater.png"); // // public static final ResourceLocation walnutMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/special/walnut.png"); // }
import net.minecraft.client.model.ModelBase; import net.minecraft.client.renderer.entity.RenderLiving; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import net.minecraft.util.ResourceLocation; import com.countrygamer.pvz.entities.mobs.plants.EntityScaredyShroom; import com.countrygamer.pvz.lib.Resources; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly;
package com.countrygamer.pvz.client.render; @SideOnly(Side.CLIENT) public class RenderScaredyShroom extends RenderLiving { protected ModelScaredyShroom model; @SideOnly(Side.CLIENT) public RenderScaredyShroom(ModelBase par1ModelBase, float par2) { super(par1ModelBase, par2); this.model = ((ModelScaredyShroom)this.mainModel); } @SideOnly(Side.CLIENT)
// Path: java/com/countrygamer/pvz/entities/mobs/plants/EntityScaredyShroom.java // public class EntityScaredyShroom extends EntityShroomShooterBase { // public EntityScaredyShroom(World world) { // super(world, new ItemStack(PvZ.nightPlants, 1, 1)); // } // // public void dropFewItems(boolean par1, int par2) { // dropItem(PvZ.shroomPod, 2); // } // } // // Path: java/com/countrygamer/pvz/lib/Resources.java // public class Resources { // public static final ResourceLocation chlorophyllBowl = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/bowlfilled.png"); // // public static final ResourceLocation gravestone = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone.png"); // // public static final ResourceLocation gravestoneReg = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Reg.png"); // // public static final ResourceLocation gravestoneFootball = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/blocks/Gravestone_Football.png"); // // public static final ResourceLocation gravestoneFlag = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Flag.png"); // // public static final ResourceLocation gravestoneCone = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Cone.png"); // // public static final ResourceLocation gravestoneBucket = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Bucket.png"); // // public static final ResourceLocation greenhouse = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/greenhouse.png"); // // public static final ResourceLocation sunflowerMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/sunflower.png"); // // public static final ResourceLocation peaShooterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/peashooter.png"); // // public static final ResourceLocation snowPeaMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/snowpea.png"); // // public static final ResourceLocation repeaterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/repeater.png"); // // public static final ResourceLocation threePeaterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/threepeater.png"); // // public static final ResourceLocation sunShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/sun_shroom_0.png"); // // public static final ResourceLocation sunShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/sun_shroom_1.png"); // // public static final ResourceLocation puffShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/puff_shroom_0.png"); // // public static final ResourceLocation puffShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/puff_shroom_1.png"); // // public static final ResourceLocation scaredyShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/basicNight/scaredy_shroom_0.png"); // // public static final ResourceLocation scaredyShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/basicNight/scaredy_shroom_1.png"); // // public static final ResourceLocation fumeShroomMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/fume_shroom_0.png"); // // public static final ResourceLocation moonShroomMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/moonShroom.png"); // // public static final ResourceLocation antiCreeperMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/special/creeperrepeater.png"); // // public static final ResourceLocation walnutMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/special/walnut.png"); // } // Path: java/com/countrygamer/pvz/client/render/RenderScaredyShroom.java import net.minecraft.client.model.ModelBase; import net.minecraft.client.renderer.entity.RenderLiving; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import net.minecraft.util.ResourceLocation; import com.countrygamer.pvz.entities.mobs.plants.EntityScaredyShroom; import com.countrygamer.pvz.lib.Resources; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; package com.countrygamer.pvz.client.render; @SideOnly(Side.CLIENT) public class RenderScaredyShroom extends RenderLiving { protected ModelScaredyShroom model; @SideOnly(Side.CLIENT) public RenderScaredyShroom(ModelBase par1ModelBase, float par2) { super(par1ModelBase, par2); this.model = ((ModelScaredyShroom)this.mainModel); } @SideOnly(Side.CLIENT)
public void renderScaredyShroom(EntityScaredyShroom entity, double par2, double par4, double par6, float par8, float par9) {
TheTemportalist/CountryGamer_PlantsVsZombies
java/com/countrygamer/pvz/client/render/RenderScaredyShroom.java
// Path: java/com/countrygamer/pvz/entities/mobs/plants/EntityScaredyShroom.java // public class EntityScaredyShroom extends EntityShroomShooterBase { // public EntityScaredyShroom(World world) { // super(world, new ItemStack(PvZ.nightPlants, 1, 1)); // } // // public void dropFewItems(boolean par1, int par2) { // dropItem(PvZ.shroomPod, 2); // } // } // // Path: java/com/countrygamer/pvz/lib/Resources.java // public class Resources { // public static final ResourceLocation chlorophyllBowl = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/bowlfilled.png"); // // public static final ResourceLocation gravestone = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone.png"); // // public static final ResourceLocation gravestoneReg = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Reg.png"); // // public static final ResourceLocation gravestoneFootball = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/blocks/Gravestone_Football.png"); // // public static final ResourceLocation gravestoneFlag = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Flag.png"); // // public static final ResourceLocation gravestoneCone = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Cone.png"); // // public static final ResourceLocation gravestoneBucket = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Bucket.png"); // // public static final ResourceLocation greenhouse = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/greenhouse.png"); // // public static final ResourceLocation sunflowerMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/sunflower.png"); // // public static final ResourceLocation peaShooterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/peashooter.png"); // // public static final ResourceLocation snowPeaMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/snowpea.png"); // // public static final ResourceLocation repeaterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/repeater.png"); // // public static final ResourceLocation threePeaterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/threepeater.png"); // // public static final ResourceLocation sunShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/sun_shroom_0.png"); // // public static final ResourceLocation sunShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/sun_shroom_1.png"); // // public static final ResourceLocation puffShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/puff_shroom_0.png"); // // public static final ResourceLocation puffShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/puff_shroom_1.png"); // // public static final ResourceLocation scaredyShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/basicNight/scaredy_shroom_0.png"); // // public static final ResourceLocation scaredyShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/basicNight/scaredy_shroom_1.png"); // // public static final ResourceLocation fumeShroomMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/fume_shroom_0.png"); // // public static final ResourceLocation moonShroomMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/moonShroom.png"); // // public static final ResourceLocation antiCreeperMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/special/creeperrepeater.png"); // // public static final ResourceLocation walnutMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/special/walnut.png"); // }
import net.minecraft.client.model.ModelBase; import net.minecraft.client.renderer.entity.RenderLiving; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import net.minecraft.util.ResourceLocation; import com.countrygamer.pvz.entities.mobs.plants.EntityScaredyShroom; import com.countrygamer.pvz.lib.Resources; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly;
package com.countrygamer.pvz.client.render; @SideOnly(Side.CLIENT) public class RenderScaredyShroom extends RenderLiving { protected ModelScaredyShroom model; @SideOnly(Side.CLIENT) public RenderScaredyShroom(ModelBase par1ModelBase, float par2) { super(par1ModelBase, par2); this.model = ((ModelScaredyShroom)this.mainModel); } @SideOnly(Side.CLIENT) public void renderScaredyShroom(EntityScaredyShroom entity, double par2, double par4, double par6, float par8, float par9) { super.doRender(entity, par2, par4, par6, par8, par9); } @SideOnly(Side.CLIENT) public void doRenderLiving(EntityLiving par1EntityLiving, double par2, double par4, double par6, float par8, float par9) { renderScaredyShroom((EntityScaredyShroom)par1EntityLiving, par2, par4, par6, par8, par9); } @SideOnly(Side.CLIENT) public void doRender(Entity par1Entity, double par2, double par4, double par6, float par8, float par9) { renderScaredyShroom((EntityScaredyShroom)par1Entity, par2, par4, par6, par8, par9); } protected ResourceLocation getEntityTexture(Entity entity) {
// Path: java/com/countrygamer/pvz/entities/mobs/plants/EntityScaredyShroom.java // public class EntityScaredyShroom extends EntityShroomShooterBase { // public EntityScaredyShroom(World world) { // super(world, new ItemStack(PvZ.nightPlants, 1, 1)); // } // // public void dropFewItems(boolean par1, int par2) { // dropItem(PvZ.shroomPod, 2); // } // } // // Path: java/com/countrygamer/pvz/lib/Resources.java // public class Resources { // public static final ResourceLocation chlorophyllBowl = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/bowlfilled.png"); // // public static final ResourceLocation gravestone = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone.png"); // // public static final ResourceLocation gravestoneReg = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Reg.png"); // // public static final ResourceLocation gravestoneFootball = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/blocks/Gravestone_Football.png"); // // public static final ResourceLocation gravestoneFlag = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Flag.png"); // // public static final ResourceLocation gravestoneCone = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Cone.png"); // // public static final ResourceLocation gravestoneBucket = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Bucket.png"); // // public static final ResourceLocation greenhouse = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/greenhouse.png"); // // public static final ResourceLocation sunflowerMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/sunflower.png"); // // public static final ResourceLocation peaShooterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/peashooter.png"); // // public static final ResourceLocation snowPeaMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/snowpea.png"); // // public static final ResourceLocation repeaterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/repeater.png"); // // public static final ResourceLocation threePeaterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/threepeater.png"); // // public static final ResourceLocation sunShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/sun_shroom_0.png"); // // public static final ResourceLocation sunShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/sun_shroom_1.png"); // // public static final ResourceLocation puffShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/puff_shroom_0.png"); // // public static final ResourceLocation puffShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/puff_shroom_1.png"); // // public static final ResourceLocation scaredyShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/basicNight/scaredy_shroom_0.png"); // // public static final ResourceLocation scaredyShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/basicNight/scaredy_shroom_1.png"); // // public static final ResourceLocation fumeShroomMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/fume_shroom_0.png"); // // public static final ResourceLocation moonShroomMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/moonShroom.png"); // // public static final ResourceLocation antiCreeperMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/special/creeperrepeater.png"); // // public static final ResourceLocation walnutMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/special/walnut.png"); // } // Path: java/com/countrygamer/pvz/client/render/RenderScaredyShroom.java import net.minecraft.client.model.ModelBase; import net.minecraft.client.renderer.entity.RenderLiving; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import net.minecraft.util.ResourceLocation; import com.countrygamer.pvz.entities.mobs.plants.EntityScaredyShroom; import com.countrygamer.pvz.lib.Resources; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; package com.countrygamer.pvz.client.render; @SideOnly(Side.CLIENT) public class RenderScaredyShroom extends RenderLiving { protected ModelScaredyShroom model; @SideOnly(Side.CLIENT) public RenderScaredyShroom(ModelBase par1ModelBase, float par2) { super(par1ModelBase, par2); this.model = ((ModelScaredyShroom)this.mainModel); } @SideOnly(Side.CLIENT) public void renderScaredyShroom(EntityScaredyShroom entity, double par2, double par4, double par6, float par8, float par9) { super.doRender(entity, par2, par4, par6, par8, par9); } @SideOnly(Side.CLIENT) public void doRenderLiving(EntityLiving par1EntityLiving, double par2, double par4, double par6, float par8, float par9) { renderScaredyShroom((EntityScaredyShroom)par1EntityLiving, par2, par4, par6, par8, par9); } @SideOnly(Side.CLIENT) public void doRender(Entity par1Entity, double par2, double par4, double par6, float par8, float par9) { renderScaredyShroom((EntityScaredyShroom)par1Entity, par2, par4, par6, par8, par9); } protected ResourceLocation getEntityTexture(Entity entity) {
return Resources.scaredyShroomMob_0;
TheTemportalist/CountryGamer_PlantsVsZombies
java/com/countrygamer/pvz/entities/mobs/plants/EntityShroomBase.java
// Path: java/com/countrygamer/pvz/lib/Resources.java // public class Resources { // public static final ResourceLocation chlorophyllBowl = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/bowlfilled.png"); // // public static final ResourceLocation gravestone = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone.png"); // // public static final ResourceLocation gravestoneReg = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Reg.png"); // // public static final ResourceLocation gravestoneFootball = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/blocks/Gravestone_Football.png"); // // public static final ResourceLocation gravestoneFlag = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Flag.png"); // // public static final ResourceLocation gravestoneCone = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Cone.png"); // // public static final ResourceLocation gravestoneBucket = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Bucket.png"); // // public static final ResourceLocation greenhouse = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/greenhouse.png"); // // public static final ResourceLocation sunflowerMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/sunflower.png"); // // public static final ResourceLocation peaShooterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/peashooter.png"); // // public static final ResourceLocation snowPeaMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/snowpea.png"); // // public static final ResourceLocation repeaterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/repeater.png"); // // public static final ResourceLocation threePeaterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/threepeater.png"); // // public static final ResourceLocation sunShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/sun_shroom_0.png"); // // public static final ResourceLocation sunShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/sun_shroom_1.png"); // // public static final ResourceLocation puffShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/puff_shroom_0.png"); // // public static final ResourceLocation puffShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/puff_shroom_1.png"); // // public static final ResourceLocation scaredyShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/basicNight/scaredy_shroom_0.png"); // // public static final ResourceLocation scaredyShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/basicNight/scaredy_shroom_1.png"); // // public static final ResourceLocation fumeShroomMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/fume_shroom_0.png"); // // public static final ResourceLocation moonShroomMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/moonShroom.png"); // // public static final ResourceLocation antiCreeperMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/special/creeperrepeater.png"); // // public static final ResourceLocation walnutMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/special/walnut.png"); // }
import net.minecraft.entity.ai.EntityAILookIdle; import net.minecraft.entity.ai.EntityAIWatchClosest; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import com.countrygamer.pvz.lib.Resources;
package com.countrygamer.pvz.entities.mobs.plants; public class EntityShroomBase extends EntityPlantBase { public ResourceLocation rl_0; public ResourceLocation rl_1;
// Path: java/com/countrygamer/pvz/lib/Resources.java // public class Resources { // public static final ResourceLocation chlorophyllBowl = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/bowlfilled.png"); // // public static final ResourceLocation gravestone = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone.png"); // // public static final ResourceLocation gravestoneReg = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Reg.png"); // // public static final ResourceLocation gravestoneFootball = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/blocks/Gravestone_Football.png"); // // public static final ResourceLocation gravestoneFlag = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Flag.png"); // // public static final ResourceLocation gravestoneCone = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Cone.png"); // // public static final ResourceLocation gravestoneBucket = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/Gravestone_Bucket.png"); // // public static final ResourceLocation greenhouse = new ResourceLocation( // Reference.MOD_ID, "textures/entities/blocks/greenhouse.png"); // // public static final ResourceLocation sunflowerMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/sunflower.png"); // // public static final ResourceLocation peaShooterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/peashooter.png"); // // public static final ResourceLocation snowPeaMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/snowpea.png"); // // public static final ResourceLocation repeaterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/repeater.png"); // // public static final ResourceLocation threePeaterMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicDay/threepeater.png"); // // public static final ResourceLocation sunShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/sun_shroom_0.png"); // // public static final ResourceLocation sunShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/sun_shroom_1.png"); // // public static final ResourceLocation puffShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/puff_shroom_0.png"); // // public static final ResourceLocation puffShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/puff_shroom_1.png"); // // public static final ResourceLocation scaredyShroomMob_0 = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/basicNight/scaredy_shroom_0.png"); // // public static final ResourceLocation scaredyShroomMob_1 = new ResourceLocation( // Reference.MOD_ID, // "textures/entities/basicNight/scaredy_shroom_1.png"); // // public static final ResourceLocation fumeShroomMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/fume_shroom_0.png"); // // public static final ResourceLocation moonShroomMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/basicNight/moonShroom.png"); // // public static final ResourceLocation antiCreeperMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/special/creeperrepeater.png"); // // public static final ResourceLocation walnutMob = new ResourceLocation( // Reference.MOD_ID, "textures/entities/special/walnut.png"); // } // Path: java/com/countrygamer/pvz/entities/mobs/plants/EntityShroomBase.java import net.minecraft.entity.ai.EntityAILookIdle; import net.minecraft.entity.ai.EntityAIWatchClosest; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import com.countrygamer.pvz.lib.Resources; package com.countrygamer.pvz.entities.mobs.plants; public class EntityShroomBase extends EntityPlantBase { public ResourceLocation rl_0; public ResourceLocation rl_1;
public ResourceLocation renderRL = Resources.puffShroomMob_0;
TheTemportalist/CountryGamer_PlantsVsZombies
java/com/countrygamer/pvz/ParticleEffects.java
// Path: java/com/countrygamer/pvz/entities/projectiles/EntityPodPop.java // public class EntityPodPop extends EntityFX // { // float reddustParticleScale; // // public EntityPodPop(World par1World, double par2, double par4, double par6, float par8, float par9, float par10) // { // this(par1World, par2, par4, par6, 1.0F, par8, par9, par10); // } // // public EntityPodPop(World par1World, double par2, double par4, double par6, float par8, float par9, float par10, float par11) // { // super(par1World, par2, par4, par6, 0.0D, 0.0D, 0.0D); // this.motionX *= 0.1000000014901161D; // this.motionY *= 0.1000000014901161D; // this.motionZ *= 0.1000000014901161D; // // if (par9 == 0.0F) // { // par9 = 1.0F; // } // // float var12 = (float)Math.random() * 0.4F + 0.6F; // this.particleRed = 0.0F; // this.particleGreen = 10.0F; // this.particleBlue = 0.0F; // this.particleScale *= 0.75F; // this.particleScale *= par8; // this.reddustParticleScale = this.particleScale; // this.particleMaxAge = (int)(8.0D / (Math.random() * 0.8D + 0.2D)); // this.particleMaxAge = (int)(this.particleMaxAge * par8); // this.noClip = false; // } // // public void renderParticle(Tessellator par1Tessellator, float par2, float par3, float par4, float par5, float par6, float par7) // { // float var8 = (this.particleAge + par2) / this.particleMaxAge * 32.0F; // // if (var8 < 0.0F) // { // var8 = 0.0F; // } // // if (var8 > 1.0F) // { // var8 = 1.0F; // } // // this.particleScale = (this.reddustParticleScale * var8); // super.renderParticle(par1Tessellator, par2, par3, par4, par5, par6, par7); // } // // public void onUpdate() // { // this.prevPosX = this.posX; // this.prevPosY = this.posY; // this.prevPosZ = this.posZ; // // if (this.particleAge++ >= this.particleMaxAge) // { // setDead(); // } // // setParticleTextureIndex(7 - this.particleAge * 8 / this.particleMaxAge); // moveEntity(this.motionX, this.motionY, this.motionZ); // // if (this.posY == this.prevPosY) // { // this.motionX *= 1.1D; // this.motionZ *= 1.1D; // } // // this.motionX *= 0.9599999785423279D; // this.motionY *= 0.9599999785423279D; // this.motionZ *= 0.9599999785423279D; // // if (this.onGround) // { // this.motionX *= 0.699999988079071D; // this.motionZ *= 0.699999988079071D; // } // } // }
import net.minecraft.client.Minecraft; import net.minecraft.client.particle.EntityFX; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.world.World; import com.countrygamer.pvz.entities.projectiles.EntityPodPop; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly;
private static TextureManager renderEngine = mc.renderEngine; public static EntityFX spawnParticle(String particleName, double par2, double par4, double par6, double par8, double par10, double par12) { if ((mc != null) && (mc.renderViewEntity != null) && (mc.effectRenderer != null)) { int var14 = mc.gameSettings.particleSetting; if ((var14 == 1) && (theWorld.rand.nextInt(3) == 0)) { var14 = 2; } double var15 = mc.renderViewEntity.posX - par2; double var17 = mc.renderViewEntity.posY - par4; double var19 = mc.renderViewEntity.posZ - par6; EntityFX var21 = null; double var22 = 16.0D; if (var15 * var15 + var17 * var17 + var19 * var19 > var22 * var22) { return null; } if (var14 > 1) { return null; } if (particleName.equals("pod-pop")) {
// Path: java/com/countrygamer/pvz/entities/projectiles/EntityPodPop.java // public class EntityPodPop extends EntityFX // { // float reddustParticleScale; // // public EntityPodPop(World par1World, double par2, double par4, double par6, float par8, float par9, float par10) // { // this(par1World, par2, par4, par6, 1.0F, par8, par9, par10); // } // // public EntityPodPop(World par1World, double par2, double par4, double par6, float par8, float par9, float par10, float par11) // { // super(par1World, par2, par4, par6, 0.0D, 0.0D, 0.0D); // this.motionX *= 0.1000000014901161D; // this.motionY *= 0.1000000014901161D; // this.motionZ *= 0.1000000014901161D; // // if (par9 == 0.0F) // { // par9 = 1.0F; // } // // float var12 = (float)Math.random() * 0.4F + 0.6F; // this.particleRed = 0.0F; // this.particleGreen = 10.0F; // this.particleBlue = 0.0F; // this.particleScale *= 0.75F; // this.particleScale *= par8; // this.reddustParticleScale = this.particleScale; // this.particleMaxAge = (int)(8.0D / (Math.random() * 0.8D + 0.2D)); // this.particleMaxAge = (int)(this.particleMaxAge * par8); // this.noClip = false; // } // // public void renderParticle(Tessellator par1Tessellator, float par2, float par3, float par4, float par5, float par6, float par7) // { // float var8 = (this.particleAge + par2) / this.particleMaxAge * 32.0F; // // if (var8 < 0.0F) // { // var8 = 0.0F; // } // // if (var8 > 1.0F) // { // var8 = 1.0F; // } // // this.particleScale = (this.reddustParticleScale * var8); // super.renderParticle(par1Tessellator, par2, par3, par4, par5, par6, par7); // } // // public void onUpdate() // { // this.prevPosX = this.posX; // this.prevPosY = this.posY; // this.prevPosZ = this.posZ; // // if (this.particleAge++ >= this.particleMaxAge) // { // setDead(); // } // // setParticleTextureIndex(7 - this.particleAge * 8 / this.particleMaxAge); // moveEntity(this.motionX, this.motionY, this.motionZ); // // if (this.posY == this.prevPosY) // { // this.motionX *= 1.1D; // this.motionZ *= 1.1D; // } // // this.motionX *= 0.9599999785423279D; // this.motionY *= 0.9599999785423279D; // this.motionZ *= 0.9599999785423279D; // // if (this.onGround) // { // this.motionX *= 0.699999988079071D; // this.motionZ *= 0.699999988079071D; // } // } // } // Path: java/com/countrygamer/pvz/ParticleEffects.java import net.minecraft.client.Minecraft; import net.minecraft.client.particle.EntityFX; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.world.World; import com.countrygamer.pvz.entities.projectiles.EntityPodPop; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; private static TextureManager renderEngine = mc.renderEngine; public static EntityFX spawnParticle(String particleName, double par2, double par4, double par6, double par8, double par10, double par12) { if ((mc != null) && (mc.renderViewEntity != null) && (mc.effectRenderer != null)) { int var14 = mc.gameSettings.particleSetting; if ((var14 == 1) && (theWorld.rand.nextInt(3) == 0)) { var14 = 2; } double var15 = mc.renderViewEntity.posX - par2; double var17 = mc.renderViewEntity.posY - par4; double var19 = mc.renderViewEntity.posZ - par6; EntityFX var21 = null; double var22 = 16.0D; if (var15 * var15 + var17 * var17 + var19 * var19 > var22 * var22) { return null; } if (var14 > 1) { return null; } if (particleName.equals("pod-pop")) {
var21 = new EntityPodPop(theWorld, par2, par4, par6, (float)par8, (float)par10, (float)par12);
bmatthews68/inmemdb-maven-plugin
src/main/java/com/btmatthews/maven/plugins/inmemdb/ldr/AbstractLoader.java
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Loader.java // public interface Loader { // // /** // * The message key for the error reported when a source file cannot be read. // */ // String CANNOT_READ_SOURCE_FILE = "cannot_read_source_file"; // // /** // * The message key for the error reported when a source file cannot be processed. // */ // String ERROR_PROCESSING_SOURCE_FILE = "error_processing_source_file"; // // /** // * Determine whether or not the data or script can be loaded or executed. // * // * @param logger Used to report errors and raise exceptions. // * @param source The source file containing the data or script. // * @return <ul> // * <li><code>true</code> if the data or script can be loaded or executed.</li> // * <li><code>false</code>if the data or script cannot be loaded or executed.</li> // * </ul> // */ // boolean isSupported(Logger logger, Source source); // // /** // * Load data into or execute a script against the in-memory database. // * // * @param logger Used to report errors and raise exceptions. // * @param database The in-memory database. // * @param source The source file containing the data or script. // */ // void load(Logger logger, Database database, Source source); // } // // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Source.java // public interface Source { // // /** // * Get the source file that contains the DDL/DML script or DBUnit data set. // * // * @return The source file. // */ // String getSourceFile(); // // /** // * Determine if the table names in the source file are fully qualified. // * // * @return <ul> // * <li>{@link Boolean#TRUE} if the table names are fully qualified.</li> // * <li>{@link Boolean#FALSE} if the table names are not fully qualified.</li> // * </ul> // */ // Boolean getQualifiedTableNames(); // }
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.Locale; import com.btmatthews.maven.plugins.inmemdb.Loader; import com.btmatthews.maven.plugins.inmemdb.Source; import com.btmatthews.utils.monitor.Logger;
/* * Copyright 2011-2012 Brian Matthews * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmatthews.maven.plugins.inmemdb.ldr; /** * Abstract base class for loaders that implements the {@link * Loader#isSupported(com.btmatthews.utils.monitor.Logger, com.btmatthews.maven.plugins.inmemdb.Source)} method. * * @author <a href="mailto:brian@btmathews.com">Brian Matthews</a> * @version 1.0.0 */ public abstract class AbstractLoader implements Loader { /** * The prefix used to denote that a resource should be loaded from the classpath * rather than the file system. */ protected static final String CLASSPATH_PREFIX = "classpath:"; /** * The length of the classpath: prefix. */ protected static final int CLASSPATH_PREFIX_LENGTH = 10; /** * The message key for the error reported when an error occurs validating a * file. */ protected static final String CANNOT_VALIDATE_FILE = "cannot_validate_file"; /** * Get the extension of the files that the loader will support. * * @return The file extension. */ protected abstract String getExtension(); /** * Check the contents of the file to see if it is valid for this loader. * * @param logger Used to report errors and raise exceptions. * @param source The source data or script. * @return <ul> * <li><code>true</code> if the content is valid.</li> * <li><code>false</code> if the content is invalid.</li> * </ul> */
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Loader.java // public interface Loader { // // /** // * The message key for the error reported when a source file cannot be read. // */ // String CANNOT_READ_SOURCE_FILE = "cannot_read_source_file"; // // /** // * The message key for the error reported when a source file cannot be processed. // */ // String ERROR_PROCESSING_SOURCE_FILE = "error_processing_source_file"; // // /** // * Determine whether or not the data or script can be loaded or executed. // * // * @param logger Used to report errors and raise exceptions. // * @param source The source file containing the data or script. // * @return <ul> // * <li><code>true</code> if the data or script can be loaded or executed.</li> // * <li><code>false</code>if the data or script cannot be loaded or executed.</li> // * </ul> // */ // boolean isSupported(Logger logger, Source source); // // /** // * Load data into or execute a script against the in-memory database. // * // * @param logger Used to report errors and raise exceptions. // * @param database The in-memory database. // * @param source The source file containing the data or script. // */ // void load(Logger logger, Database database, Source source); // } // // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Source.java // public interface Source { // // /** // * Get the source file that contains the DDL/DML script or DBUnit data set. // * // * @return The source file. // */ // String getSourceFile(); // // /** // * Determine if the table names in the source file are fully qualified. // * // * @return <ul> // * <li>{@link Boolean#TRUE} if the table names are fully qualified.</li> // * <li>{@link Boolean#FALSE} if the table names are not fully qualified.</li> // * </ul> // */ // Boolean getQualifiedTableNames(); // } // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/ldr/AbstractLoader.java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.Locale; import com.btmatthews.maven.plugins.inmemdb.Loader; import com.btmatthews.maven.plugins.inmemdb.Source; import com.btmatthews.utils.monitor.Logger; /* * Copyright 2011-2012 Brian Matthews * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmatthews.maven.plugins.inmemdb.ldr; /** * Abstract base class for loaders that implements the {@link * Loader#isSupported(com.btmatthews.utils.monitor.Logger, com.btmatthews.maven.plugins.inmemdb.Source)} method. * * @author <a href="mailto:brian@btmathews.com">Brian Matthews</a> * @version 1.0.0 */ public abstract class AbstractLoader implements Loader { /** * The prefix used to denote that a resource should be loaded from the classpath * rather than the file system. */ protected static final String CLASSPATH_PREFIX = "classpath:"; /** * The length of the classpath: prefix. */ protected static final int CLASSPATH_PREFIX_LENGTH = 10; /** * The message key for the error reported when an error occurs validating a * file. */ protected static final String CANNOT_VALIDATE_FILE = "cannot_validate_file"; /** * Get the extension of the files that the loader will support. * * @return The file extension. */ protected abstract String getExtension(); /** * Check the contents of the file to see if it is valid for this loader. * * @param logger Used to report errors and raise exceptions. * @param source The source data or script. * @return <ul> * <li><code>true</code> if the content is valid.</li> * <li><code>false</code> if the content is invalid.</li> * </ul> */
protected boolean hasValidContent(final Logger logger, final Source source) {
bmatthews68/inmemdb-maven-plugin
src/test/java/com/btmatthews/maven/plugins/inmemdb/test/TestH2Database.java
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/db/h2/H2Database.java // public final class H2Database extends AbstractSQLDatabase { // // /** // * The connection protocol for in-memory H2 databases. // */ // private static final String PROTOCOL = "h2:tcp://localhost:{0,number,#}/mem:"; // /** // * Default port H2 listens on, can be altered via setting port property // */ // private static final int DEFAULT_PORT = 9092; // /** // * The loaders that are supported for loading data or executing scripts. // */ // private static final Loader[] LOADERS = new Loader[]{ // new DBUnitXMLLoader(), new DBUnitFlatXMLLoader(), // new DBUnitCSVLoader(), new DBUnitXLSLoader(), new SQLLoader()}; // /** // * The H2 TCP server. // */ // private TcpServer service; // // /** // * The default constructor initializes the default database port. // */ // public H2Database() { // super(DEFAULT_PORT); // } // // /** // * Get the database connection protocol. // * // * @return Always returns {@link H2Database#PROTOCOL}. // */ // protected String getUrlProtocol() { // return MessageFormat.format(PROTOCOL, getPort()); // } // // /** // * Get the data source that describes the connection to the in-memory H2 // * database. // * // * @return Returns {@code dataSource} which was initialised by the // * constructor. // */ // @Override // public DataSource getDataSource() { // final Map<String, String> attributes = new HashMap<String, String>(); // attributes.put("DB_CLOSE_DELAY", "-1"); // final JdbcDataSource dataSource = new JdbcDataSource(); // dataSource.setURL(getUrl(attributes)); // dataSource.setUser(getUsername()); // dataSource.setPassword(getPassword()); // return dataSource; // } // // /** // * Get the loaders that are supported for loading data or executing scripts. // * // * @return Returns {@link #LOADERS}. // */ // @Override // public Loader[] getLoaders() { // return LOADERS; // } // // /** // * Start the in-memory H2 database. // * // * @param logger Used to report errors and raise exceptions. // */ // @Override // public void start(final Logger logger) { // // logger.logInfo("Starting embedded H2 database"); // // try { // service = new TcpServer(); // service.init("-tcpDaemon", "-tcpPort", Integer.toString(getPort())); // service.start(); // } catch (final SQLException exception) { // final String message = MessageUtil.getMessage(ERROR_STARTING_SERVER, getDatabaseName()); // logger.logError(message, exception); // return; // } // // final Thread serviceListenerThread = new Thread(new Runnable() { // @Override // public void run() { // service.listen(); // } // }); // serviceListenerThread.setDaemon(true); // serviceListenerThread.start(); // // logger.logInfo("Embedded H2 database has started"); // } // // /** // * Shutdown the in-memory H2 database by opening a connection and issuing // * the SHUTDOWN command. // * // * @param logger Used to report errors and raise exceptions. // */ // public void stop(final Logger logger) { // // logger.logInfo("Stopping embedded H2 database"); // // if (service != null) { // service.stop(); // } // // logger.logInfo("Stopped embedded H2 database"); // } // // @Override // public boolean isStarted(final Logger logger) { // return service != null && service.isRunning(true); // } // // @Override // public boolean isStopped(final Logger logger) { // return !service.isRunning(false); // } // }
import com.btmatthews.maven.plugins.inmemdb.db.h2.H2Database; import com.btmatthews.utils.monitor.Server;
/* * Copyright 2011-2012 Brian Matthews * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmatthews.maven.plugins.inmemdb.test; /** * Unit test the H2 database server. * * @author <a href="mailto:brian@btmatthews.com">Brian Matthews</a> * @since 1.2.0 */ public class TestH2Database extends AbstractTestDatabase { /** * Create the {@link H2Database} server test fixture. * * @return The {@link H2Database} server test fixture. */ @Override protected Server createDatabaseServer() {
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/db/h2/H2Database.java // public final class H2Database extends AbstractSQLDatabase { // // /** // * The connection protocol for in-memory H2 databases. // */ // private static final String PROTOCOL = "h2:tcp://localhost:{0,number,#}/mem:"; // /** // * Default port H2 listens on, can be altered via setting port property // */ // private static final int DEFAULT_PORT = 9092; // /** // * The loaders that are supported for loading data or executing scripts. // */ // private static final Loader[] LOADERS = new Loader[]{ // new DBUnitXMLLoader(), new DBUnitFlatXMLLoader(), // new DBUnitCSVLoader(), new DBUnitXLSLoader(), new SQLLoader()}; // /** // * The H2 TCP server. // */ // private TcpServer service; // // /** // * The default constructor initializes the default database port. // */ // public H2Database() { // super(DEFAULT_PORT); // } // // /** // * Get the database connection protocol. // * // * @return Always returns {@link H2Database#PROTOCOL}. // */ // protected String getUrlProtocol() { // return MessageFormat.format(PROTOCOL, getPort()); // } // // /** // * Get the data source that describes the connection to the in-memory H2 // * database. // * // * @return Returns {@code dataSource} which was initialised by the // * constructor. // */ // @Override // public DataSource getDataSource() { // final Map<String, String> attributes = new HashMap<String, String>(); // attributes.put("DB_CLOSE_DELAY", "-1"); // final JdbcDataSource dataSource = new JdbcDataSource(); // dataSource.setURL(getUrl(attributes)); // dataSource.setUser(getUsername()); // dataSource.setPassword(getPassword()); // return dataSource; // } // // /** // * Get the loaders that are supported for loading data or executing scripts. // * // * @return Returns {@link #LOADERS}. // */ // @Override // public Loader[] getLoaders() { // return LOADERS; // } // // /** // * Start the in-memory H2 database. // * // * @param logger Used to report errors and raise exceptions. // */ // @Override // public void start(final Logger logger) { // // logger.logInfo("Starting embedded H2 database"); // // try { // service = new TcpServer(); // service.init("-tcpDaemon", "-tcpPort", Integer.toString(getPort())); // service.start(); // } catch (final SQLException exception) { // final String message = MessageUtil.getMessage(ERROR_STARTING_SERVER, getDatabaseName()); // logger.logError(message, exception); // return; // } // // final Thread serviceListenerThread = new Thread(new Runnable() { // @Override // public void run() { // service.listen(); // } // }); // serviceListenerThread.setDaemon(true); // serviceListenerThread.start(); // // logger.logInfo("Embedded H2 database has started"); // } // // /** // * Shutdown the in-memory H2 database by opening a connection and issuing // * the SHUTDOWN command. // * // * @param logger Used to report errors and raise exceptions. // */ // public void stop(final Logger logger) { // // logger.logInfo("Stopping embedded H2 database"); // // if (service != null) { // service.stop(); // } // // logger.logInfo("Stopped embedded H2 database"); // } // // @Override // public boolean isStarted(final Logger logger) { // return service != null && service.isRunning(true); // } // // @Override // public boolean isStopped(final Logger logger) { // return !service.isRunning(false); // } // } // Path: src/test/java/com/btmatthews/maven/plugins/inmemdb/test/TestH2Database.java import com.btmatthews.maven.plugins.inmemdb.db.h2.H2Database; import com.btmatthews.utils.monitor.Server; /* * Copyright 2011-2012 Brian Matthews * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmatthews.maven.plugins.inmemdb.test; /** * Unit test the H2 database server. * * @author <a href="mailto:brian@btmatthews.com">Brian Matthews</a> * @since 1.2.0 */ public class TestH2Database extends AbstractTestDatabase { /** * Create the {@link H2Database} server test fixture. * * @return The {@link H2Database} server test fixture. */ @Override protected Server createDatabaseServer() {
return new H2Database();
bmatthews68/inmemdb-maven-plugin
src/test/java/com/btmatthews/maven/plugins/inmemdb/test/AbstractTestDatabase.java
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Database.java // public interface Database { // // /** // * Find the loader that supports the source file and use it to load the data // * into or execute the script against the database. // * // * @param logger Used to report errors and raise exceptions. // * @param source The source file containing data or script. // */ // void load(Logger logger, Source source); // } // // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/mojo/DataSet.java // public final class DataSet extends AbstractSource { // // /** // * Indicates whether or not the data set contains qualified table names. // */ // private Boolean qualifiedTableNames; // // /** // * The default constructor. // * // * @see AbstractSource#AbstractSource() // */ // public DataSet() { // } // // /** // * Construct a source object that describes DBUnit data set. // * // * @param file The source file that contains the DDL/DML script or DBUnit // * data set. // * @param flag <ul> // * <li>{@link Boolean#TRUE} if the are qualified with the schema // * name.</li> // * <li>{@link Boolean#FALSE} if the are not qualified with the // * schema name.</li> // * </ul> // * @see AbstractSource#AbstractSource(String) // */ // public DataSet(final String file, final Boolean flag) { // super(file); // this.qualifiedTableNames = flag; // } // // /** // * Determine if the DBUnit data set contains qualified or unqualified table // * names. // * // * @return <ul> // * <li>{@link Boolean#TRUE} if the are qualified with the schema // * name.</li> // * <li>{@link Boolean#FALSE} if the are not qualified with the // * schema name.</li> // * </ul> // * @see com.btmatthews.maven.plugins.inmemdb.Source#getQualifiedTableNames() // */ // public Boolean getQualifiedTableNames() { // return this.qualifiedTableNames; // } // // /** // * Indicate whether or not the DBUnit data set contains qualified or // * unqualified table names. // * // * @param flag <ul> // * <li>{@link Boolean#TRUE} if the are qualified with the schema // * name.</li> // * <li>{@link Boolean#FALSE} if the are not qualified with the // * schema name.</li> // * </ul> // */ // public void setQualifiedTableNames(final Boolean flag) { // this.qualifiedTableNames = flag; // } // // @Override // public String toString() { // return "DataSet[" + getSourceFile() + "]"; // } // } // // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/mojo/Script.java // public final class Script extends AbstractSource { // // /** // * The default constructor. // */ // public Script() { // } // // /** // * Construct a source object that describes a DDL/DML script or DBUnit data // * set. // * // * @param file The source file that contains the DDL/DML script or DBUnit // * data set. // */ // public Script(final String file) { // super(file); // } // // /** // * Indicates that the script source descriptor does not distinguish between // * qualified and unqualified table names by returning <code>null</code>. // * // * @return Always returns <code>null</code>. // */ // public Boolean getQualifiedTableNames() { // return null; // } // // @Override // public String toString() { // return "Script[" + getSourceFile() + "]"; // } // }
import static org.mockito.MockitoAnnotations.initMocks; import com.btmatthews.maven.plugins.inmemdb.Database; import com.btmatthews.maven.plugins.inmemdb.mojo.DataSet; import com.btmatthews.maven.plugins.inmemdb.mojo.Script; import com.btmatthews.utils.monitor.Logger; import com.btmatthews.utils.monitor.Server; import org.apache.maven.plugin.MojoFailureException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mock;
/* * Copyright 2011-2012 Brian Matthews * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmatthews.maven.plugins.inmemdb.test; /** * Created with IntelliJ IDEA. * User: Brian * Date: 29/11/12 * Time: 19:53 * To change this template use File | Settings | File Templates. */ public abstract class AbstractTestDatabase { /** * Mock for the logger. */ @Mock private Logger logger; /** * The main test fixture. */ private Server database; /** * Concrete class should override this method to create the main test fixture. * * @return The main test fixture. */ protected abstract Server createDatabaseServer(); /** * Prepare for test case execute by creating, configuring and starting the main test fixture. */ @Before public void setUp() { initMocks(this); database = createDatabaseServer(); database.configure("database", "test", logger); database.configure("username", "sa", logger); database.configure("password", "", logger); database.start(logger); } /** * Clean up after test case execution by stopping the main test fixture. */ @After public void tearDown() { database.stop(logger); } /** * Verify that the database server starts and stops cleanly. */ @Test public void testStartStop() { } /** * Verify that a valid DDL/DML script can be loaded. */ @Test public void testLoadScript() {
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Database.java // public interface Database { // // /** // * Find the loader that supports the source file and use it to load the data // * into or execute the script against the database. // * // * @param logger Used to report errors and raise exceptions. // * @param source The source file containing data or script. // */ // void load(Logger logger, Source source); // } // // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/mojo/DataSet.java // public final class DataSet extends AbstractSource { // // /** // * Indicates whether or not the data set contains qualified table names. // */ // private Boolean qualifiedTableNames; // // /** // * The default constructor. // * // * @see AbstractSource#AbstractSource() // */ // public DataSet() { // } // // /** // * Construct a source object that describes DBUnit data set. // * // * @param file The source file that contains the DDL/DML script or DBUnit // * data set. // * @param flag <ul> // * <li>{@link Boolean#TRUE} if the are qualified with the schema // * name.</li> // * <li>{@link Boolean#FALSE} if the are not qualified with the // * schema name.</li> // * </ul> // * @see AbstractSource#AbstractSource(String) // */ // public DataSet(final String file, final Boolean flag) { // super(file); // this.qualifiedTableNames = flag; // } // // /** // * Determine if the DBUnit data set contains qualified or unqualified table // * names. // * // * @return <ul> // * <li>{@link Boolean#TRUE} if the are qualified with the schema // * name.</li> // * <li>{@link Boolean#FALSE} if the are not qualified with the // * schema name.</li> // * </ul> // * @see com.btmatthews.maven.plugins.inmemdb.Source#getQualifiedTableNames() // */ // public Boolean getQualifiedTableNames() { // return this.qualifiedTableNames; // } // // /** // * Indicate whether or not the DBUnit data set contains qualified or // * unqualified table names. // * // * @param flag <ul> // * <li>{@link Boolean#TRUE} if the are qualified with the schema // * name.</li> // * <li>{@link Boolean#FALSE} if the are not qualified with the // * schema name.</li> // * </ul> // */ // public void setQualifiedTableNames(final Boolean flag) { // this.qualifiedTableNames = flag; // } // // @Override // public String toString() { // return "DataSet[" + getSourceFile() + "]"; // } // } // // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/mojo/Script.java // public final class Script extends AbstractSource { // // /** // * The default constructor. // */ // public Script() { // } // // /** // * Construct a source object that describes a DDL/DML script or DBUnit data // * set. // * // * @param file The source file that contains the DDL/DML script or DBUnit // * data set. // */ // public Script(final String file) { // super(file); // } // // /** // * Indicates that the script source descriptor does not distinguish between // * qualified and unqualified table names by returning <code>null</code>. // * // * @return Always returns <code>null</code>. // */ // public Boolean getQualifiedTableNames() { // return null; // } // // @Override // public String toString() { // return "Script[" + getSourceFile() + "]"; // } // } // Path: src/test/java/com/btmatthews/maven/plugins/inmemdb/test/AbstractTestDatabase.java import static org.mockito.MockitoAnnotations.initMocks; import com.btmatthews.maven.plugins.inmemdb.Database; import com.btmatthews.maven.plugins.inmemdb.mojo.DataSet; import com.btmatthews.maven.plugins.inmemdb.mojo.Script; import com.btmatthews.utils.monitor.Logger; import com.btmatthews.utils.monitor.Server; import org.apache.maven.plugin.MojoFailureException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; /* * Copyright 2011-2012 Brian Matthews * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmatthews.maven.plugins.inmemdb.test; /** * Created with IntelliJ IDEA. * User: Brian * Date: 29/11/12 * Time: 19:53 * To change this template use File | Settings | File Templates. */ public abstract class AbstractTestDatabase { /** * Mock for the logger. */ @Mock private Logger logger; /** * The main test fixture. */ private Server database; /** * Concrete class should override this method to create the main test fixture. * * @return The main test fixture. */ protected abstract Server createDatabaseServer(); /** * Prepare for test case execute by creating, configuring and starting the main test fixture. */ @Before public void setUp() { initMocks(this); database = createDatabaseServer(); database.configure("database", "test", logger); database.configure("username", "sa", logger); database.configure("password", "", logger); database.start(logger); } /** * Clean up after test case execution by stopping the main test fixture. */ @After public void tearDown() { database.stop(logger); } /** * Verify that the database server starts and stops cleanly. */ @Test public void testStartStop() { } /** * Verify that a valid DDL/DML script can be loaded. */ @Test public void testLoadScript() {
final Script source = new Script();
bmatthews68/inmemdb-maven-plugin
src/test/java/com/btmatthews/maven/plugins/inmemdb/test/AbstractTestDatabase.java
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Database.java // public interface Database { // // /** // * Find the loader that supports the source file and use it to load the data // * into or execute the script against the database. // * // * @param logger Used to report errors and raise exceptions. // * @param source The source file containing data or script. // */ // void load(Logger logger, Source source); // } // // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/mojo/DataSet.java // public final class DataSet extends AbstractSource { // // /** // * Indicates whether or not the data set contains qualified table names. // */ // private Boolean qualifiedTableNames; // // /** // * The default constructor. // * // * @see AbstractSource#AbstractSource() // */ // public DataSet() { // } // // /** // * Construct a source object that describes DBUnit data set. // * // * @param file The source file that contains the DDL/DML script or DBUnit // * data set. // * @param flag <ul> // * <li>{@link Boolean#TRUE} if the are qualified with the schema // * name.</li> // * <li>{@link Boolean#FALSE} if the are not qualified with the // * schema name.</li> // * </ul> // * @see AbstractSource#AbstractSource(String) // */ // public DataSet(final String file, final Boolean flag) { // super(file); // this.qualifiedTableNames = flag; // } // // /** // * Determine if the DBUnit data set contains qualified or unqualified table // * names. // * // * @return <ul> // * <li>{@link Boolean#TRUE} if the are qualified with the schema // * name.</li> // * <li>{@link Boolean#FALSE} if the are not qualified with the // * schema name.</li> // * </ul> // * @see com.btmatthews.maven.plugins.inmemdb.Source#getQualifiedTableNames() // */ // public Boolean getQualifiedTableNames() { // return this.qualifiedTableNames; // } // // /** // * Indicate whether or not the DBUnit data set contains qualified or // * unqualified table names. // * // * @param flag <ul> // * <li>{@link Boolean#TRUE} if the are qualified with the schema // * name.</li> // * <li>{@link Boolean#FALSE} if the are not qualified with the // * schema name.</li> // * </ul> // */ // public void setQualifiedTableNames(final Boolean flag) { // this.qualifiedTableNames = flag; // } // // @Override // public String toString() { // return "DataSet[" + getSourceFile() + "]"; // } // } // // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/mojo/Script.java // public final class Script extends AbstractSource { // // /** // * The default constructor. // */ // public Script() { // } // // /** // * Construct a source object that describes a DDL/DML script or DBUnit data // * set. // * // * @param file The source file that contains the DDL/DML script or DBUnit // * data set. // */ // public Script(final String file) { // super(file); // } // // /** // * Indicates that the script source descriptor does not distinguish between // * qualified and unqualified table names by returning <code>null</code>. // * // * @return Always returns <code>null</code>. // */ // public Boolean getQualifiedTableNames() { // return null; // } // // @Override // public String toString() { // return "Script[" + getSourceFile() + "]"; // } // }
import static org.mockito.MockitoAnnotations.initMocks; import com.btmatthews.maven.plugins.inmemdb.Database; import com.btmatthews.maven.plugins.inmemdb.mojo.DataSet; import com.btmatthews.maven.plugins.inmemdb.mojo.Script; import com.btmatthews.utils.monitor.Logger; import com.btmatthews.utils.monitor.Server; import org.apache.maven.plugin.MojoFailureException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mock;
/* * Copyright 2011-2012 Brian Matthews * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmatthews.maven.plugins.inmemdb.test; /** * Created with IntelliJ IDEA. * User: Brian * Date: 29/11/12 * Time: 19:53 * To change this template use File | Settings | File Templates. */ public abstract class AbstractTestDatabase { /** * Mock for the logger. */ @Mock private Logger logger; /** * The main test fixture. */ private Server database; /** * Concrete class should override this method to create the main test fixture. * * @return The main test fixture. */ protected abstract Server createDatabaseServer(); /** * Prepare for test case execute by creating, configuring and starting the main test fixture. */ @Before public void setUp() { initMocks(this); database = createDatabaseServer(); database.configure("database", "test", logger); database.configure("username", "sa", logger); database.configure("password", "", logger); database.start(logger); } /** * Clean up after test case execution by stopping the main test fixture. */ @After public void tearDown() { database.stop(logger); } /** * Verify that the database server starts and stops cleanly. */ @Test public void testStartStop() { } /** * Verify that a valid DDL/DML script can be loaded. */ @Test public void testLoadScript() { final Script source = new Script(); source.setSourceFile("src/test/resources/create_database.sql");
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Database.java // public interface Database { // // /** // * Find the loader that supports the source file and use it to load the data // * into or execute the script against the database. // * // * @param logger Used to report errors and raise exceptions. // * @param source The source file containing data or script. // */ // void load(Logger logger, Source source); // } // // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/mojo/DataSet.java // public final class DataSet extends AbstractSource { // // /** // * Indicates whether or not the data set contains qualified table names. // */ // private Boolean qualifiedTableNames; // // /** // * The default constructor. // * // * @see AbstractSource#AbstractSource() // */ // public DataSet() { // } // // /** // * Construct a source object that describes DBUnit data set. // * // * @param file The source file that contains the DDL/DML script or DBUnit // * data set. // * @param flag <ul> // * <li>{@link Boolean#TRUE} if the are qualified with the schema // * name.</li> // * <li>{@link Boolean#FALSE} if the are not qualified with the // * schema name.</li> // * </ul> // * @see AbstractSource#AbstractSource(String) // */ // public DataSet(final String file, final Boolean flag) { // super(file); // this.qualifiedTableNames = flag; // } // // /** // * Determine if the DBUnit data set contains qualified or unqualified table // * names. // * // * @return <ul> // * <li>{@link Boolean#TRUE} if the are qualified with the schema // * name.</li> // * <li>{@link Boolean#FALSE} if the are not qualified with the // * schema name.</li> // * </ul> // * @see com.btmatthews.maven.plugins.inmemdb.Source#getQualifiedTableNames() // */ // public Boolean getQualifiedTableNames() { // return this.qualifiedTableNames; // } // // /** // * Indicate whether or not the DBUnit data set contains qualified or // * unqualified table names. // * // * @param flag <ul> // * <li>{@link Boolean#TRUE} if the are qualified with the schema // * name.</li> // * <li>{@link Boolean#FALSE} if the are not qualified with the // * schema name.</li> // * </ul> // */ // public void setQualifiedTableNames(final Boolean flag) { // this.qualifiedTableNames = flag; // } // // @Override // public String toString() { // return "DataSet[" + getSourceFile() + "]"; // } // } // // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/mojo/Script.java // public final class Script extends AbstractSource { // // /** // * The default constructor. // */ // public Script() { // } // // /** // * Construct a source object that describes a DDL/DML script or DBUnit data // * set. // * // * @param file The source file that contains the DDL/DML script or DBUnit // * data set. // */ // public Script(final String file) { // super(file); // } // // /** // * Indicates that the script source descriptor does not distinguish between // * qualified and unqualified table names by returning <code>null</code>. // * // * @return Always returns <code>null</code>. // */ // public Boolean getQualifiedTableNames() { // return null; // } // // @Override // public String toString() { // return "Script[" + getSourceFile() + "]"; // } // } // Path: src/test/java/com/btmatthews/maven/plugins/inmemdb/test/AbstractTestDatabase.java import static org.mockito.MockitoAnnotations.initMocks; import com.btmatthews.maven.plugins.inmemdb.Database; import com.btmatthews.maven.plugins.inmemdb.mojo.DataSet; import com.btmatthews.maven.plugins.inmemdb.mojo.Script; import com.btmatthews.utils.monitor.Logger; import com.btmatthews.utils.monitor.Server; import org.apache.maven.plugin.MojoFailureException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; /* * Copyright 2011-2012 Brian Matthews * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmatthews.maven.plugins.inmemdb.test; /** * Created with IntelliJ IDEA. * User: Brian * Date: 29/11/12 * Time: 19:53 * To change this template use File | Settings | File Templates. */ public abstract class AbstractTestDatabase { /** * Mock for the logger. */ @Mock private Logger logger; /** * The main test fixture. */ private Server database; /** * Concrete class should override this method to create the main test fixture. * * @return The main test fixture. */ protected abstract Server createDatabaseServer(); /** * Prepare for test case execute by creating, configuring and starting the main test fixture. */ @Before public void setUp() { initMocks(this); database = createDatabaseServer(); database.configure("database", "test", logger); database.configure("username", "sa", logger); database.configure("password", "", logger); database.start(logger); } /** * Clean up after test case execution by stopping the main test fixture. */ @After public void tearDown() { database.stop(logger); } /** * Verify that the database server starts and stops cleanly. */ @Test public void testStartStop() { } /** * Verify that a valid DDL/DML script can be loaded. */ @Test public void testLoadScript() { final Script source = new Script(); source.setSourceFile("src/test/resources/create_database.sql");
((Database)database).load(logger, source);
bmatthews68/inmemdb-maven-plugin
src/test/java/com/btmatthews/maven/plugins/inmemdb/test/AbstractTestDatabase.java
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Database.java // public interface Database { // // /** // * Find the loader that supports the source file and use it to load the data // * into or execute the script against the database. // * // * @param logger Used to report errors and raise exceptions. // * @param source The source file containing data or script. // */ // void load(Logger logger, Source source); // } // // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/mojo/DataSet.java // public final class DataSet extends AbstractSource { // // /** // * Indicates whether or not the data set contains qualified table names. // */ // private Boolean qualifiedTableNames; // // /** // * The default constructor. // * // * @see AbstractSource#AbstractSource() // */ // public DataSet() { // } // // /** // * Construct a source object that describes DBUnit data set. // * // * @param file The source file that contains the DDL/DML script or DBUnit // * data set. // * @param flag <ul> // * <li>{@link Boolean#TRUE} if the are qualified with the schema // * name.</li> // * <li>{@link Boolean#FALSE} if the are not qualified with the // * schema name.</li> // * </ul> // * @see AbstractSource#AbstractSource(String) // */ // public DataSet(final String file, final Boolean flag) { // super(file); // this.qualifiedTableNames = flag; // } // // /** // * Determine if the DBUnit data set contains qualified or unqualified table // * names. // * // * @return <ul> // * <li>{@link Boolean#TRUE} if the are qualified with the schema // * name.</li> // * <li>{@link Boolean#FALSE} if the are not qualified with the // * schema name.</li> // * </ul> // * @see com.btmatthews.maven.plugins.inmemdb.Source#getQualifiedTableNames() // */ // public Boolean getQualifiedTableNames() { // return this.qualifiedTableNames; // } // // /** // * Indicate whether or not the DBUnit data set contains qualified or // * unqualified table names. // * // * @param flag <ul> // * <li>{@link Boolean#TRUE} if the are qualified with the schema // * name.</li> // * <li>{@link Boolean#FALSE} if the are not qualified with the // * schema name.</li> // * </ul> // */ // public void setQualifiedTableNames(final Boolean flag) { // this.qualifiedTableNames = flag; // } // // @Override // public String toString() { // return "DataSet[" + getSourceFile() + "]"; // } // } // // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/mojo/Script.java // public final class Script extends AbstractSource { // // /** // * The default constructor. // */ // public Script() { // } // // /** // * Construct a source object that describes a DDL/DML script or DBUnit data // * set. // * // * @param file The source file that contains the DDL/DML script or DBUnit // * data set. // */ // public Script(final String file) { // super(file); // } // // /** // * Indicates that the script source descriptor does not distinguish between // * qualified and unqualified table names by returning <code>null</code>. // * // * @return Always returns <code>null</code>. // */ // public Boolean getQualifiedTableNames() { // return null; // } // // @Override // public String toString() { // return "Script[" + getSourceFile() + "]"; // } // }
import static org.mockito.MockitoAnnotations.initMocks; import com.btmatthews.maven.plugins.inmemdb.Database; import com.btmatthews.maven.plugins.inmemdb.mojo.DataSet; import com.btmatthews.maven.plugins.inmemdb.mojo.Script; import com.btmatthews.utils.monitor.Logger; import com.btmatthews.utils.monitor.Server; import org.apache.maven.plugin.MojoFailureException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mock;
} /** * Verify than an exception is thrown when {@code null} is passed as * the source file. */ @Test public void testLoadNull() throws MojoFailureException { ((Database)database).load(logger, null); } /** * Verify than an exception is thrown when the source file is actually a * directory. */ @Test public void testLoadDirectory() throws MojoFailureException { final Script source = new Script(); source.setSourceFile("src/test/resources"); ((Database)database).load(logger, source); } /** * Verify that a valid DBUnit XML data set can be loaded. */ @Test public void testLoadDBUnitXML() { final Script script = new Script(); script.setSourceFile("src/test/resources/create_database.sql"); ((Database)database).load(logger, script);
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Database.java // public interface Database { // // /** // * Find the loader that supports the source file and use it to load the data // * into or execute the script against the database. // * // * @param logger Used to report errors and raise exceptions. // * @param source The source file containing data or script. // */ // void load(Logger logger, Source source); // } // // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/mojo/DataSet.java // public final class DataSet extends AbstractSource { // // /** // * Indicates whether or not the data set contains qualified table names. // */ // private Boolean qualifiedTableNames; // // /** // * The default constructor. // * // * @see AbstractSource#AbstractSource() // */ // public DataSet() { // } // // /** // * Construct a source object that describes DBUnit data set. // * // * @param file The source file that contains the DDL/DML script or DBUnit // * data set. // * @param flag <ul> // * <li>{@link Boolean#TRUE} if the are qualified with the schema // * name.</li> // * <li>{@link Boolean#FALSE} if the are not qualified with the // * schema name.</li> // * </ul> // * @see AbstractSource#AbstractSource(String) // */ // public DataSet(final String file, final Boolean flag) { // super(file); // this.qualifiedTableNames = flag; // } // // /** // * Determine if the DBUnit data set contains qualified or unqualified table // * names. // * // * @return <ul> // * <li>{@link Boolean#TRUE} if the are qualified with the schema // * name.</li> // * <li>{@link Boolean#FALSE} if the are not qualified with the // * schema name.</li> // * </ul> // * @see com.btmatthews.maven.plugins.inmemdb.Source#getQualifiedTableNames() // */ // public Boolean getQualifiedTableNames() { // return this.qualifiedTableNames; // } // // /** // * Indicate whether or not the DBUnit data set contains qualified or // * unqualified table names. // * // * @param flag <ul> // * <li>{@link Boolean#TRUE} if the are qualified with the schema // * name.</li> // * <li>{@link Boolean#FALSE} if the are not qualified with the // * schema name.</li> // * </ul> // */ // public void setQualifiedTableNames(final Boolean flag) { // this.qualifiedTableNames = flag; // } // // @Override // public String toString() { // return "DataSet[" + getSourceFile() + "]"; // } // } // // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/mojo/Script.java // public final class Script extends AbstractSource { // // /** // * The default constructor. // */ // public Script() { // } // // /** // * Construct a source object that describes a DDL/DML script or DBUnit data // * set. // * // * @param file The source file that contains the DDL/DML script or DBUnit // * data set. // */ // public Script(final String file) { // super(file); // } // // /** // * Indicates that the script source descriptor does not distinguish between // * qualified and unqualified table names by returning <code>null</code>. // * // * @return Always returns <code>null</code>. // */ // public Boolean getQualifiedTableNames() { // return null; // } // // @Override // public String toString() { // return "Script[" + getSourceFile() + "]"; // } // } // Path: src/test/java/com/btmatthews/maven/plugins/inmemdb/test/AbstractTestDatabase.java import static org.mockito.MockitoAnnotations.initMocks; import com.btmatthews.maven.plugins.inmemdb.Database; import com.btmatthews.maven.plugins.inmemdb.mojo.DataSet; import com.btmatthews.maven.plugins.inmemdb.mojo.Script; import com.btmatthews.utils.monitor.Logger; import com.btmatthews.utils.monitor.Server; import org.apache.maven.plugin.MojoFailureException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; } /** * Verify than an exception is thrown when {@code null} is passed as * the source file. */ @Test public void testLoadNull() throws MojoFailureException { ((Database)database).load(logger, null); } /** * Verify than an exception is thrown when the source file is actually a * directory. */ @Test public void testLoadDirectory() throws MojoFailureException { final Script source = new Script(); source.setSourceFile("src/test/resources"); ((Database)database).load(logger, source); } /** * Verify that a valid DBUnit XML data set can be loaded. */ @Test public void testLoadDBUnitXML() { final Script script = new Script(); script.setSourceFile("src/test/resources/create_database.sql"); ((Database)database).load(logger, script);
final DataSet source = new DataSet();
bmatthews68/inmemdb-maven-plugin
src/main/java/com/btmatthews/maven/plugins/inmemdb/ldr/dbunit/DBUnitXLSLoader.java
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Source.java // public interface Source { // // /** // * Get the source file that contains the DDL/DML script or DBUnit data set. // * // * @return The source file. // */ // String getSourceFile(); // // /** // * Determine if the table names in the source file are fully qualified. // * // * @return <ul> // * <li>{@link Boolean#TRUE} if the table names are fully qualified.</li> // * <li>{@link Boolean#FALSE} if the table names are not fully qualified.</li> // * </ul> // */ // Boolean getQualifiedTableNames(); // }
import java.io.File; import java.io.IOException; import java.io.InputStream; import com.btmatthews.maven.plugins.inmemdb.Source; import org.dbunit.dataset.DataSetException; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.excel.XlsDataSet;
/* * Copyright 2011-2012 Brian Matthews * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmatthews.maven.plugins.inmemdb.ldr.dbunit; /** * Loader that loads data from a DBUnit Excel data set. * * @author <a href="brian@btmatthews.com">Brian Matthews</a> * @version 1.0.0 */ public final class DBUnitXLSLoader extends AbstractDBUnitLoader { /** * The file extension for DBUnit Excel data set files. */ private static final String EXT = ".xls"; /** * Get the file extension for DBUnit Excel data set files. * * @return {@link #EXT} */ @Override protected String getExtension() { return EXT; } /** * Load a DBUnit Excel data set. * * @param source The source file containing the DBUnit Excel data set. * @return The DBUnit Excel data set. * @throws DataSetException If there was an error loading the DBUnit Excel data set. * @throws IOException If there was an error reading the DBUnit Excel data set from the file. */ @Override
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Source.java // public interface Source { // // /** // * Get the source file that contains the DDL/DML script or DBUnit data set. // * // * @return The source file. // */ // String getSourceFile(); // // /** // * Determine if the table names in the source file are fully qualified. // * // * @return <ul> // * <li>{@link Boolean#TRUE} if the table names are fully qualified.</li> // * <li>{@link Boolean#FALSE} if the table names are not fully qualified.</li> // * </ul> // */ // Boolean getQualifiedTableNames(); // } // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/ldr/dbunit/DBUnitXLSLoader.java import java.io.File; import java.io.IOException; import java.io.InputStream; import com.btmatthews.maven.plugins.inmemdb.Source; import org.dbunit.dataset.DataSetException; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.excel.XlsDataSet; /* * Copyright 2011-2012 Brian Matthews * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmatthews.maven.plugins.inmemdb.ldr.dbunit; /** * Loader that loads data from a DBUnit Excel data set. * * @author <a href="brian@btmatthews.com">Brian Matthews</a> * @version 1.0.0 */ public final class DBUnitXLSLoader extends AbstractDBUnitLoader { /** * The file extension for DBUnit Excel data set files. */ private static final String EXT = ".xls"; /** * Get the file extension for DBUnit Excel data set files. * * @return {@link #EXT} */ @Override protected String getExtension() { return EXT; } /** * Load a DBUnit Excel data set. * * @param source The source file containing the DBUnit Excel data set. * @return The DBUnit Excel data set. * @throws DataSetException If there was an error loading the DBUnit Excel data set. * @throws IOException If there was an error reading the DBUnit Excel data set from the file. */ @Override
protected IDataSet loadDataSet(final Source source) throws DataSetException,
bmatthews68/inmemdb-maven-plugin
src/main/java/com/btmatthews/maven/plugins/inmemdb/mojo/RunMojo.java
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Database.java // public interface Database { // // /** // * Find the loader that supports the source file and use it to load the data // * into or execute the script against the database. // * // * @param logger Used to report errors and raise exceptions. // * @param source The source file containing data or script. // */ // void load(Logger logger, Source source); // } // // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Source.java // public interface Source { // // /** // * Get the source file that contains the DDL/DML script or DBUnit data set. // * // * @return The source file. // */ // String getSourceFile(); // // /** // * Determine if the table names in the source file are fully qualified. // * // * @return <ul> // * <li>{@link Boolean#TRUE} if the table names are fully qualified.</li> // * <li>{@link Boolean#FALSE} if the table names are not fully qualified.</li> // * </ul> // */ // Boolean getQualifiedTableNames(); // }
import com.btmatthews.maven.plugins.inmemdb.Database; import com.btmatthews.maven.plugins.inmemdb.Source; import com.btmatthews.utils.monitor.Logger; import com.btmatthews.utils.monitor.Server; import com.btmatthews.utils.monitor.mojo.AbstractRunMojo; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import java.util.HashMap; import java.util.List; import java.util.Map;
/* * Copyright 2011-2012 Brian Matthews * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmatthews.maven.plugins.inmemdb.mojo; /** * This plug-in Mojo starts an In Memory Database. * * @author <a href="mailto:brian@btmatthews.com">Brian Matthews</a> * @version 1.2.0 */ @Mojo(name = "run", defaultPhase = LifecyclePhase.PRE_INTEGRATION_TEST) public final class RunMojo extends AbstractRunMojo { /** * The source files used to populate the database. */ @Parameter
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Database.java // public interface Database { // // /** // * Find the loader that supports the source file and use it to load the data // * into or execute the script against the database. // * // * @param logger Used to report errors and raise exceptions. // * @param source The source file containing data or script. // */ // void load(Logger logger, Source source); // } // // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Source.java // public interface Source { // // /** // * Get the source file that contains the DDL/DML script or DBUnit data set. // * // * @return The source file. // */ // String getSourceFile(); // // /** // * Determine if the table names in the source file are fully qualified. // * // * @return <ul> // * <li>{@link Boolean#TRUE} if the table names are fully qualified.</li> // * <li>{@link Boolean#FALSE} if the table names are not fully qualified.</li> // * </ul> // */ // Boolean getQualifiedTableNames(); // } // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/mojo/RunMojo.java import com.btmatthews.maven.plugins.inmemdb.Database; import com.btmatthews.maven.plugins.inmemdb.Source; import com.btmatthews.utils.monitor.Logger; import com.btmatthews.utils.monitor.Server; import com.btmatthews.utils.monitor.mojo.AbstractRunMojo; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import java.util.HashMap; import java.util.List; import java.util.Map; /* * Copyright 2011-2012 Brian Matthews * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmatthews.maven.plugins.inmemdb.mojo; /** * This plug-in Mojo starts an In Memory Database. * * @author <a href="mailto:brian@btmatthews.com">Brian Matthews</a> * @version 1.2.0 */ @Mojo(name = "run", defaultPhase = LifecyclePhase.PRE_INTEGRATION_TEST) public final class RunMojo extends AbstractRunMojo { /** * The source files used to populate the database. */ @Parameter
private List<? extends Source> sources;
bmatthews68/inmemdb-maven-plugin
src/main/java/com/btmatthews/maven/plugins/inmemdb/mojo/RunMojo.java
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Database.java // public interface Database { // // /** // * Find the loader that supports the source file and use it to load the data // * into or execute the script against the database. // * // * @param logger Used to report errors and raise exceptions. // * @param source The source file containing data or script. // */ // void load(Logger logger, Source source); // } // // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Source.java // public interface Source { // // /** // * Get the source file that contains the DDL/DML script or DBUnit data set. // * // * @return The source file. // */ // String getSourceFile(); // // /** // * Determine if the table names in the source file are fully qualified. // * // * @return <ul> // * <li>{@link Boolean#TRUE} if the table names are fully qualified.</li> // * <li>{@link Boolean#FALSE} if the table names are not fully qualified.</li> // * </ul> // */ // Boolean getQualifiedTableNames(); // }
import com.btmatthews.maven.plugins.inmemdb.Database; import com.btmatthews.maven.plugins.inmemdb.Source; import com.btmatthews.utils.monitor.Logger; import com.btmatthews.utils.monitor.Server; import com.btmatthews.utils.monitor.mojo.AbstractRunMojo; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import java.util.HashMap; import java.util.List; import java.util.Map;
if (port != null) { config.put("port", port); } if (password == null) { config.put("password", ""); } else { config.put("password", password); } if (attributes != null) { config.put("attributes", attributes); } return config; } /** * This callback is invoked after the server has started and is used load the scripts * and datasets that will initialise the database. * * @param server The database server. * @param logger Used to log information and error messages. */ @Override public void started(final Server server, final Logger logger) { logger.logInfo("Server has been started"); if (sources != null) { logger.logInfo("Executing initialization scripts and loading data sets"); for (final Source source : sources) { logger.logInfo("Loading " + source.toString());
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Database.java // public interface Database { // // /** // * Find the loader that supports the source file and use it to load the data // * into or execute the script against the database. // * // * @param logger Used to report errors and raise exceptions. // * @param source The source file containing data or script. // */ // void load(Logger logger, Source source); // } // // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Source.java // public interface Source { // // /** // * Get the source file that contains the DDL/DML script or DBUnit data set. // * // * @return The source file. // */ // String getSourceFile(); // // /** // * Determine if the table names in the source file are fully qualified. // * // * @return <ul> // * <li>{@link Boolean#TRUE} if the table names are fully qualified.</li> // * <li>{@link Boolean#FALSE} if the table names are not fully qualified.</li> // * </ul> // */ // Boolean getQualifiedTableNames(); // } // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/mojo/RunMojo.java import com.btmatthews.maven.plugins.inmemdb.Database; import com.btmatthews.maven.plugins.inmemdb.Source; import com.btmatthews.utils.monitor.Logger; import com.btmatthews.utils.monitor.Server; import com.btmatthews.utils.monitor.mojo.AbstractRunMojo; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import java.util.HashMap; import java.util.List; import java.util.Map; if (port != null) { config.put("port", port); } if (password == null) { config.put("password", ""); } else { config.put("password", password); } if (attributes != null) { config.put("attributes", attributes); } return config; } /** * This callback is invoked after the server has started and is used load the scripts * and datasets that will initialise the database. * * @param server The database server. * @param logger Used to log information and error messages. */ @Override public void started(final Server server, final Logger logger) { logger.logInfo("Server has been started"); if (sources != null) { logger.logInfo("Executing initialization scripts and loading data sets"); for (final Source source : sources) { logger.logInfo("Loading " + source.toString());
((Database) server).load(this, source);
bmatthews68/inmemdb-maven-plugin
src/main/java/com/btmatthews/maven/plugins/inmemdb/ldr/dbunit/DBUnitCSVLoader.java
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Source.java // public interface Source { // // /** // * Get the source file that contains the DDL/DML script or DBUnit data set. // * // * @return The source file. // */ // String getSourceFile(); // // /** // * Determine if the table names in the source file are fully qualified. // * // * @return <ul> // * <li>{@link Boolean#TRUE} if the table names are fully qualified.</li> // * <li>{@link Boolean#FALSE} if the table names are not fully qualified.</li> // * </ul> // */ // Boolean getQualifiedTableNames(); // }
import org.dbunit.dataset.datatype.DataType; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.List; import com.btmatthews.maven.plugins.inmemdb.Source; import org.dbunit.dataset.CachedDataSet; import org.dbunit.dataset.Column; import org.dbunit.dataset.DataSetException; import org.dbunit.dataset.DefaultTableMetaData; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.ITableMetaData; import org.dbunit.dataset.csv.CsvDataSetWriter; import org.dbunit.dataset.csv.CsvParser; import org.dbunit.dataset.csv.CsvParserImpl;
/* * Copyright 2011-2012 Brian Matthews * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmatthews.maven.plugins.inmemdb.ldr.dbunit; /** * Loader that loads data from a DBUnit CSV data set. * * @author <a href="brian@btmatthews.com">Brian Matthews</a> * @version 1.0.0 */ public final class DBUnitCSVLoader extends AbstractDBUnitLoader { /** * The file extension for DBUnit CSV data set files. */ private static final String EXT = ".csv"; /** * Get the file extension for DBUnit CSV data set files. * * @return {@link #EXT} */ @Override protected String getExtension() { return EXT; } /** * Load a DBUnit CSV data set. This implementation was lifted from * {@link org.dbunit.dataset.csv.CsvProducer#produceFromFile(java.io.File)}. * * @param source The source file containing the DBUnit CSV data set. * @return The DBUnit CSV data set. * @throws DataSetException If there was an error loading the DBUnit CSV data set. * @throws IOException If there was an error reading the DBUnit CSV data set from the file. */ @SuppressWarnings("rawtypes") @Override
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Source.java // public interface Source { // // /** // * Get the source file that contains the DDL/DML script or DBUnit data set. // * // * @return The source file. // */ // String getSourceFile(); // // /** // * Determine if the table names in the source file are fully qualified. // * // * @return <ul> // * <li>{@link Boolean#TRUE} if the table names are fully qualified.</li> // * <li>{@link Boolean#FALSE} if the table names are not fully qualified.</li> // * </ul> // */ // Boolean getQualifiedTableNames(); // } // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/ldr/dbunit/DBUnitCSVLoader.java import org.dbunit.dataset.datatype.DataType; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.List; import com.btmatthews.maven.plugins.inmemdb.Source; import org.dbunit.dataset.CachedDataSet; import org.dbunit.dataset.Column; import org.dbunit.dataset.DataSetException; import org.dbunit.dataset.DefaultTableMetaData; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.ITableMetaData; import org.dbunit.dataset.csv.CsvDataSetWriter; import org.dbunit.dataset.csv.CsvParser; import org.dbunit.dataset.csv.CsvParserImpl; /* * Copyright 2011-2012 Brian Matthews * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmatthews.maven.plugins.inmemdb.ldr.dbunit; /** * Loader that loads data from a DBUnit CSV data set. * * @author <a href="brian@btmatthews.com">Brian Matthews</a> * @version 1.0.0 */ public final class DBUnitCSVLoader extends AbstractDBUnitLoader { /** * The file extension for DBUnit CSV data set files. */ private static final String EXT = ".csv"; /** * Get the file extension for DBUnit CSV data set files. * * @return {@link #EXT} */ @Override protected String getExtension() { return EXT; } /** * Load a DBUnit CSV data set. This implementation was lifted from * {@link org.dbunit.dataset.csv.CsvProducer#produceFromFile(java.io.File)}. * * @param source The source file containing the DBUnit CSV data set. * @return The DBUnit CSV data set. * @throws DataSetException If there was an error loading the DBUnit CSV data set. * @throws IOException If there was an error reading the DBUnit CSV data set from the file. */ @SuppressWarnings("rawtypes") @Override
protected IDataSet loadDataSet(final Source source) throws DataSetException,
bmatthews68/inmemdb-maven-plugin
src/main/java/com/btmatthews/maven/plugins/inmemdb/ldr/dbunit/DBUnitFlatXMLLoader.java
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Source.java // public interface Source { // // /** // * Get the source file that contains the DDL/DML script or DBUnit data set. // * // * @return The source file. // */ // String getSourceFile(); // // /** // * Determine if the table names in the source file are fully qualified. // * // * @return <ul> // * <li>{@link Boolean#TRUE} if the table names are fully qualified.</li> // * <li>{@link Boolean#FALSE} if the table names are not fully qualified.</li> // * </ul> // */ // Boolean getQualifiedTableNames(); // }
import java.io.File; import java.io.IOException; import java.net.URL; import com.btmatthews.maven.plugins.inmemdb.Source; import org.dbunit.dataset.DataSetException; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
/* * Copyright 2011-2012 Brian Matthews * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmatthews.maven.plugins.inmemdb.ldr.dbunit; /** * Loader that loads data from a DBUnit XML data set. * * @author <a href="brian@btmatthews.com">Brian Matthews</a> * @version 1.0.0 */ public final class DBUnitFlatXMLLoader extends AbstractDBUnitLoader { /** * The file extension for DBUnit Flat XML data set files. */ private static final String EXT = ".xml"; /** * Get the file extension for DBUnit Flat XML data set files. * * @return {@link #EXT} */ @Override protected String getExtension() { return EXT; } /** * Load a DBUnit Flat XML data set. * * @param source The source file containing the DBUnit Flat XML data set. * @return The DBUnit Flat XML data set. * @throws DataSetException If there was an error loading the DBUnit Flat XML data set. * @throws IOException If there was an error reading the DBUnit Flat XML data set from the file. */ @Override
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Source.java // public interface Source { // // /** // * Get the source file that contains the DDL/DML script or DBUnit data set. // * // * @return The source file. // */ // String getSourceFile(); // // /** // * Determine if the table names in the source file are fully qualified. // * // * @return <ul> // * <li>{@link Boolean#TRUE} if the table names are fully qualified.</li> // * <li>{@link Boolean#FALSE} if the table names are not fully qualified.</li> // * </ul> // */ // Boolean getQualifiedTableNames(); // } // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/ldr/dbunit/DBUnitFlatXMLLoader.java import java.io.File; import java.io.IOException; import java.net.URL; import com.btmatthews.maven.plugins.inmemdb.Source; import org.dbunit.dataset.DataSetException; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; /* * Copyright 2011-2012 Brian Matthews * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmatthews.maven.plugins.inmemdb.ldr.dbunit; /** * Loader that loads data from a DBUnit XML data set. * * @author <a href="brian@btmatthews.com">Brian Matthews</a> * @version 1.0.0 */ public final class DBUnitFlatXMLLoader extends AbstractDBUnitLoader { /** * The file extension for DBUnit Flat XML data set files. */ private static final String EXT = ".xml"; /** * Get the file extension for DBUnit Flat XML data set files. * * @return {@link #EXT} */ @Override protected String getExtension() { return EXT; } /** * Load a DBUnit Flat XML data set. * * @param source The source file containing the DBUnit Flat XML data set. * @return The DBUnit Flat XML data set. * @throws DataSetException If there was an error loading the DBUnit Flat XML data set. * @throws IOException If there was an error reading the DBUnit Flat XML data set from the file. */ @Override
protected IDataSet loadDataSet(final Source source) throws DataSetException,
bmatthews68/inmemdb-maven-plugin
src/test/java/com/btmatthews/maven/plugins/inmemdb/test/TestDatabaseFactory.java
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/db/derby/DerbyDatabaseFactory.java // public final class DerbyDatabaseFactory implements ServerFactory { // // /** // * Get the name of the server created by this server factory. // * // * @return Always returns {@code derby}. // */ // @Override // public String getServerName() { // return "derby"; // } // // /** // * Create the server instance. // * // * @return A {@link DerbyDatabase} instance. // */ // @Override // public Server createServer() { // return new DerbyDatabase(); // } // } // // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/db/h2/H2DatabaseFactory.java // public final class H2DatabaseFactory implements ServerFactory { // // /** // * Get the name of the server created by this server factory. // * // * @return Always returns {@code h2}. // */ // @Override // public String getServerName() { // return "h2"; // } // // /** // * Create the server instance. // * // * @return A {@link H2Database} instance. // */ // @Override // public Server createServer() { // return new H2Database(); // } // } // // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/db/hsqldb/HSQLDBDatabaseFactory.java // public final class HSQLDBDatabaseFactory implements ServerFactory { // // /** // * Get the name of the server created by this server factory. // * // * @return Always returns {@code hsqldb}. // */ // @Override // public String getServerName() { // return "hsqldb"; // } // // /** // * Create the server instance. // * // * @return A {@link HSQLDBDatabase} instance. // */ // @Override // public Server createServer() { // return new HSQLDBDatabase(); // } // }
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.MockitoAnnotations.initMocks; import com.btmatthews.maven.plugins.inmemdb.db.derby.DerbyDatabaseFactory; import com.btmatthews.maven.plugins.inmemdb.db.h2.H2DatabaseFactory; import com.btmatthews.maven.plugins.inmemdb.db.hsqldb.HSQLDBDatabaseFactory; import com.btmatthews.utils.monitor.Logger; import com.btmatthews.utils.monitor.ServerFactory; import com.btmatthews.utils.monitor.ServerFactoryLocator; import org.junit.Before; import org.junit.Test; import org.mockito.Mock;
/* * Copyright 2011-2012 Brian Matthews * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmatthews.maven.plugins.inmemdb.test; /** * Unit test the server factory configuration. * * @author <a href="mailto:brian@btmatthews.com">Brian Matthews</a> * @version 1.0.0 */ public final class TestDatabaseFactory { /** * Mock for the logger. */ @Mock private Logger logger; /** * Used to locate the {@link ServerFactory} for the database server. */ private ServerFactoryLocator locator; /** * Create the server locator factory test fixture. */ @Before public void setUp() { initMocks(this); locator = ServerFactoryLocator.getInstance(logger); } /** * Verify that the server factory locator returns {@code null} when {@code null} is passed as the * database type. */ @Test public void testNullType() { final ServerFactory factory = locator.getFactory(null); assertNull(factory); } /** * Verify that the server factory locator returns a {@link DerbyDatabaseFactory} when * &quot;derby&quot; is passed as the database type. */ @Test public void testDerbyType() { final ServerFactory factory = locator.getFactory("derby"); assertNotNull(factory);
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/db/derby/DerbyDatabaseFactory.java // public final class DerbyDatabaseFactory implements ServerFactory { // // /** // * Get the name of the server created by this server factory. // * // * @return Always returns {@code derby}. // */ // @Override // public String getServerName() { // return "derby"; // } // // /** // * Create the server instance. // * // * @return A {@link DerbyDatabase} instance. // */ // @Override // public Server createServer() { // return new DerbyDatabase(); // } // } // // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/db/h2/H2DatabaseFactory.java // public final class H2DatabaseFactory implements ServerFactory { // // /** // * Get the name of the server created by this server factory. // * // * @return Always returns {@code h2}. // */ // @Override // public String getServerName() { // return "h2"; // } // // /** // * Create the server instance. // * // * @return A {@link H2Database} instance. // */ // @Override // public Server createServer() { // return new H2Database(); // } // } // // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/db/hsqldb/HSQLDBDatabaseFactory.java // public final class HSQLDBDatabaseFactory implements ServerFactory { // // /** // * Get the name of the server created by this server factory. // * // * @return Always returns {@code hsqldb}. // */ // @Override // public String getServerName() { // return "hsqldb"; // } // // /** // * Create the server instance. // * // * @return A {@link HSQLDBDatabase} instance. // */ // @Override // public Server createServer() { // return new HSQLDBDatabase(); // } // } // Path: src/test/java/com/btmatthews/maven/plugins/inmemdb/test/TestDatabaseFactory.java import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.MockitoAnnotations.initMocks; import com.btmatthews.maven.plugins.inmemdb.db.derby.DerbyDatabaseFactory; import com.btmatthews.maven.plugins.inmemdb.db.h2.H2DatabaseFactory; import com.btmatthews.maven.plugins.inmemdb.db.hsqldb.HSQLDBDatabaseFactory; import com.btmatthews.utils.monitor.Logger; import com.btmatthews.utils.monitor.ServerFactory; import com.btmatthews.utils.monitor.ServerFactoryLocator; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; /* * Copyright 2011-2012 Brian Matthews * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmatthews.maven.plugins.inmemdb.test; /** * Unit test the server factory configuration. * * @author <a href="mailto:brian@btmatthews.com">Brian Matthews</a> * @version 1.0.0 */ public final class TestDatabaseFactory { /** * Mock for the logger. */ @Mock private Logger logger; /** * Used to locate the {@link ServerFactory} for the database server. */ private ServerFactoryLocator locator; /** * Create the server locator factory test fixture. */ @Before public void setUp() { initMocks(this); locator = ServerFactoryLocator.getInstance(logger); } /** * Verify that the server factory locator returns {@code null} when {@code null} is passed as the * database type. */ @Test public void testNullType() { final ServerFactory factory = locator.getFactory(null); assertNull(factory); } /** * Verify that the server factory locator returns a {@link DerbyDatabaseFactory} when * &quot;derby&quot; is passed as the database type. */ @Test public void testDerbyType() { final ServerFactory factory = locator.getFactory("derby"); assertNotNull(factory);
assertTrue(factory instanceof DerbyDatabaseFactory);