file_id
stringlengths
4
10
content
stringlengths
91
42.8k
repo
stringlengths
7
108
path
stringlengths
7
251
token_length
int64
34
8.19k
original_comment
stringlengths
11
11.5k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
prompt
stringlengths
34
42.8k
198515_0
package sets; // Voorbeeld 0805 HashSet import java.util.*; public class DemoHashSet { public static void main( String args[] ) { HashSet<String> groep1, groep2, doorsnede, vereniging, verschil1, verschil2, symVerschil; groep1 = new HashSet<String>(); groep2 = new HashSet<String>(); groep1.add( "A" ); groep1.add( "B" ); groep1.add( "C" ); groep1.add( "D" ); groep1.add( "E" ); groep2.add( "W" ); groep2.add( "X" ); groep2.add( "Y" ); groep2.add( "Z" ); groep2.add( "C" ); groep2.add( "D" ); // intersect in SQL en Python doorsnede = new HashSet<String>( groep1 ); doorsnede.retainAll( groep2 ); // Union in SQL en Python vereniging = new HashSet<String>( groep1 ); vereniging.addAll( groep2 ); // minus in SQL, difference in Python verschil1 = new HashSet<String>( groep1 ); verschil1.removeAll( groep2 ); verschil2 = new HashSet<String>( groep2 ); verschil2.removeAll( groep1 ); System.out.println( "groep1: " + groep1 ); System.out.println( "groep2: " + groep2 ); System.out.println( "doorsnede: " + doorsnede ); System.out.println( "vereniging: " + vereniging ); System.out.println( "groep1 - groep2: " + verschil1 ); System.out.println( "groep2 - groep1: " + verschil2 ); } }
hanbioinformatica/owe6a
Week5_HMset/src/sets/DemoHashSet.java
464
// Voorbeeld 0805 HashSet
line_comment
nl
package sets; // Voorbeeld 0805<SUF> import java.util.*; public class DemoHashSet { public static void main( String args[] ) { HashSet<String> groep1, groep2, doorsnede, vereniging, verschil1, verschil2, symVerschil; groep1 = new HashSet<String>(); groep2 = new HashSet<String>(); groep1.add( "A" ); groep1.add( "B" ); groep1.add( "C" ); groep1.add( "D" ); groep1.add( "E" ); groep2.add( "W" ); groep2.add( "X" ); groep2.add( "Y" ); groep2.add( "Z" ); groep2.add( "C" ); groep2.add( "D" ); // intersect in SQL en Python doorsnede = new HashSet<String>( groep1 ); doorsnede.retainAll( groep2 ); // Union in SQL en Python vereniging = new HashSet<String>( groep1 ); vereniging.addAll( groep2 ); // minus in SQL, difference in Python verschil1 = new HashSet<String>( groep1 ); verschil1.removeAll( groep2 ); verschil2 = new HashSet<String>( groep2 ); verschil2.removeAll( groep1 ); System.out.println( "groep1: " + groep1 ); System.out.println( "groep2: " + groep2 ); System.out.println( "doorsnede: " + doorsnede ); System.out.println( "vereniging: " + vereniging ); System.out.println( "groep1 - groep2: " + verschil1 ); System.out.println( "groep2 - groep1: " + verschil2 ); } }
198521_0
package Databases; import java.sql.*; import java.util.*; import javax.sql.*; /* * klasse om een database connectie te maken * @author Reshad Farid * voorbeeld connectie zie onderstaand. */ public class MysqlConnect{ public Connection connectToAndQueryDatabase(String database, String username, String password) throws SQLException { Connection con = null; try { con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/" + database, username, password); } catch (SQLException e) { e.printStackTrace(); } return con; } }
reshadf/Java
DeBasis/src/Databases/MysqlConnect.java
175
/* * klasse om een database connectie te maken * @author Reshad Farid * voorbeeld connectie zie onderstaand. */
block_comment
nl
package Databases; import java.sql.*; import java.util.*; import javax.sql.*; /* * klasse om een<SUF>*/ public class MysqlConnect{ public Connection connectToAndQueryDatabase(String database, String username, String password) throws SQLException { Connection con = null; try { con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/" + database, username, password); } catch (SQLException e) { e.printStackTrace(); } return con; } }
198532_0
package nl.topicus.cobra.web.components.shortcut; /** * Doordeze interface aanteroepen is het mogelijk een toetsencombinatie te binden aan een * component. Deze toetsencombinaties zijn gedefineerd in KeyActionEnum.java. * <p> * Mogelijke componenten zijn: textfield, links en buttons. * <p> * <b>Let wel op:</b> werkt niet met butons die een popupgenereren</br> omdat de return * waarde wordt genegeerd. * </p> * <p> * <b>Voorbeeld:</b></br> page.registerShortcut(get("submit"), KeyActionEnum.OPSLAAN); * </p> * * @author Nick Henzen */ public interface ShortcutEnabledComponent { public void registerShortcuts(ShortcutRegister register); }
topicusonderwijs/tribe-krd-opensource
cobra/webcomponents/src/main/java/nl/topicus/cobra/web/components/shortcut/ShortcutEnabledComponent.java
195
/** * Doordeze interface aanteroepen is het mogelijk een toetsencombinatie te binden aan een * component. Deze toetsencombinaties zijn gedefineerd in KeyActionEnum.java. * <p> * Mogelijke componenten zijn: textfield, links en buttons. * <p> * <b>Let wel op:</b> werkt niet met butons die een popupgenereren</br> omdat de return * waarde wordt genegeerd. * </p> * <p> * <b>Voorbeeld:</b></br> page.registerShortcut(get("submit"), KeyActionEnum.OPSLAAN); * </p> * * @author Nick Henzen */
block_comment
nl
package nl.topicus.cobra.web.components.shortcut; /** * Doordeze interface aanteroepen<SUF>*/ public interface ShortcutEnabledComponent { public void registerShortcuts(ShortcutRegister register); }
198540_0
package Stack; /** * Voorbeeld van http://math.hws.edu/javanotes/c9/s3.html * */ public class StackOfInts { /** * An object of type Node holds one of the items in the linked list * that represents the stack. */ private static class Node { int item; Node next; } private Node top; // Pointer to the Node that is at the top of // of the stack. If top == null, then the // stack is empty. /** * Add N to the top of the stack. */ public void push( int N ) { Node newTop; // A Node to hold the new item. newTop = new Node(); newTop.item = N; // Store N in the new Node. newTop.next = top; // The new Node points to the old top. top = newTop; // The new item is now on top. } /** * Remove the top item from the stack, and return it. * Throws an IllegalStateException if the stack is empty when * this method is called. */ public int pop() { if ( top == null ) throw new IllegalStateException("Can't pop from an empty stack."); int topItem = top.item; // The item that is being popped. top = top.next; // The previous second item is now on top. return topItem; } /** * Returns true if the stack is empty. Returns false * if there are one or more items on the stack. */ public boolean isEmpty() { return (top == null); } } // end class StackOfInts
hanbioinformatica/owe6a
Week3_LinkedList/src/Stack/StackOfInts.java
434
/** * Voorbeeld van http://math.hws.edu/javanotes/c9/s3.html * */
block_comment
nl
package Stack; /** * Voorbeeld van http://math.hws.edu/javanotes/c9/s3.html<SUF>*/ public class StackOfInts { /** * An object of type Node holds one of the items in the linked list * that represents the stack. */ private static class Node { int item; Node next; } private Node top; // Pointer to the Node that is at the top of // of the stack. If top == null, then the // stack is empty. /** * Add N to the top of the stack. */ public void push( int N ) { Node newTop; // A Node to hold the new item. newTop = new Node(); newTop.item = N; // Store N in the new Node. newTop.next = top; // The new Node points to the old top. top = newTop; // The new item is now on top. } /** * Remove the top item from the stack, and return it. * Throws an IllegalStateException if the stack is empty when * this method is called. */ public int pop() { if ( top == null ) throw new IllegalStateException("Can't pop from an empty stack."); int topItem = top.item; // The item that is being popped. top = top.next; // The previous second item is now on top. return topItem; } /** * Returns true if the stack is empty. Returns false * if there are one or more items on the stack. */ public boolean isEmpty() { return (top == null); } } // end class StackOfInts
198541_1
package eu.kyotoproject.main; import eu.kyotoproject.kaf.*; import eu.kyotoproject.util.Resources; import org.apache.tools.bzip2.CBZip2InputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.zip.GZIPInputStream; /** * Created with IntelliJ IDEA. * User: piek * Date: 1/29/13 * Time: 3:20 PM * To change this template use File | Settings | File Templates. */ public class KafPredicateMatrixTagger { static final String layer = "terms"; static final String name = "vua-predicate-matrix-tagger"; static final String version = "1.0"; static public void main (String[] args) { Resources resources = new Resources(); // String pathToKafFile = "/Tools/ontotagger-v1.0/naf-example/spinoza-voorbeeld-ukb.xml"; // String pathToKafFile = "/Users/piek/Desktop/NWR/NWR-SRL/wikinews-nl/files/14369_Airbus_offers_funding_to_search_for_black_boxes_from_Air_France_disaster.ukb.kaf"; String pathToKafFile = ""; //pathToKafFile = "/Tools/nwr-dutch-pipeline/vua-ontotagger-v1.0/nl.demo.naf"; // pathToKafFile = "/Users/piek/Desktop/NWR/NWR-SRL/wikinews-nl/files/14369_Airbus_offers_funding_to_search_for_black_boxes_from_Air_France_disaster.ukb.kaf"; String pathToMatrixFile = ""; //pathToMatrixFile = "/Tools/nwr-dutch-pipeline/vua-ontotagger-v1.0/resources/PredicateMatrix.v1.3.txt.role.odwn"; String pathToGrammaticalVerbsFile = ""; //pathToGrammaticalVerbsFile = "/Tools/ontotagger-v1.0/resources/grammaticals/Grammatical-words.nl"; String pathToFrameNetLex = ""; String pmVersion = ""; pmVersion = "1.1"; boolean ili = false; String pos = ""; String prefix = ""; String key = ""; //key = "odwn-eq"; String format = "naf"; String[] selectedMappings = null; for (int i = 0; i < args.length; i++) { String arg = args[i]; if ((arg.equalsIgnoreCase("--kaf-file")) && (args.length>(i+1))) { pathToKafFile = args[i+1]; } else if ((arg.equalsIgnoreCase("--naf-file")) && (args.length>(i+1))) { pathToKafFile = args[i+1]; } else if ((arg.equalsIgnoreCase("--pos")) && (args.length>(i+1))) { pos = args[i+1]; } else if ((arg.equalsIgnoreCase("--predicate-matrix")) && (args.length>(i+1))) { pathToMatrixFile = args[i+1]; } else if ((arg.equalsIgnoreCase("--fn-lexicon")) && (args.length>(i+1))) { pathToFrameNetLex = args[i+1]; } else if ((arg.equalsIgnoreCase("--fn-lexicon-pos")) && (args.length>(i+1))) { pathToFrameNetLex = args[i+1]; resources.frameNetLuReader.KEEPPOSTAG = true; } else if ((arg.equalsIgnoreCase("--grammatical-words")) && (args.length>(i+1))) { pathToGrammaticalVerbsFile = args[i+1]; } else if ((arg.equalsIgnoreCase("--version")) && (args.length>(i+1))) { pmVersion = args[i+1]; } else if ((arg.equalsIgnoreCase("--key")) && (args.length>(i+1))) { key = args[i+1]; } else if ((arg.equalsIgnoreCase("--ignore-prefix")) && (args.length>(i+1))) { prefix = args[i+1]; } else if ((arg.equalsIgnoreCase("--mappings")) && (args.length>(i+1))) { selectedMappings = args[i+1].split(";"); } else if ((arg.equalsIgnoreCase("--ili"))) { ili = true; } } if (!pathToMatrixFile.isEmpty()) { if (ili) { resources.processMatrixFileWithWordnetILI(pathToMatrixFile); } else if (!key.isEmpty()) { resources.processMatrixFile(pathToMatrixFile, key, prefix); // System.out.println("resources = " + resources.wordNetPredicateMap.size()); } else { resources.processMatrixFileWithWordnetLemma(pathToMatrixFile); } } if (!pathToFrameNetLex.isEmpty()) { resources.frameNetLuReader.parseFile(pathToFrameNetLex); } if (!pathToGrammaticalVerbsFile.isEmpty()) { resources.processGrammaticalWordsFile(pathToGrammaticalVerbsFile); } String strBeginDate = eu.kyotoproject.util.DateUtil.createTimestamp(); String strEndDate = null; KafSaxParser kafSaxParser = new KafSaxParser(); if (pathToKafFile.isEmpty()) { kafSaxParser.parseFile(System.in); } else { if (pathToKafFile.toLowerCase().endsWith(".gz")) { try { InputStream fileStream = new FileInputStream(pathToKafFile); InputStream gzipStream = new GZIPInputStream(fileStream); kafSaxParser.parseFile(gzipStream); } catch (IOException e) { e.printStackTrace(); } } else if (pathToKafFile.toLowerCase().endsWith(".bz2")) { try { InputStream fileStream = new FileInputStream(pathToKafFile); InputStream gzipStream = new CBZip2InputStream(fileStream); kafSaxParser.parseFile(gzipStream); } catch (IOException e) { e.printStackTrace(); } } else { kafSaxParser.parseFile(pathToKafFile); } } processKafFileWordnetNetSynsets(kafSaxParser, pmVersion, resources, selectedMappings); strEndDate = eu.kyotoproject.util.DateUtil.createTimestamp(); String host = ""; try { host = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { e.printStackTrace(); } LP lp = new LP(name,version, strBeginDate, strBeginDate, strEndDate, host); kafSaxParser.getKafMetaData().addLayer(layer, lp); if (format.equalsIgnoreCase("naf")) { kafSaxParser.writeNafToStream(System.out); /* try { OutputStream fos = new FileOutputStream("/Tools/ontotagger-v1.0/naf-example/89007714_06.ont.srl.naf"); kafSaxParser.writeNafToStream(fos); fos.close(); } catch (IOException e) { e.printStackTrace(); }*/ } else if (format.equalsIgnoreCase("kaf")) { kafSaxParser.writeKafToStream(System.out); } } static public void processKafFileVerbNet (KafSaxParser kafSaxParser, String pathToKafFile, Resources resources, String pmVersion, String pos, String [] selectedMappings) { kafSaxParser.parseFile(pathToKafFile); for (int i = 0; i < kafSaxParser.getKafTerms().size(); i++) { KafTerm kafTerm = kafSaxParser.getKafTerms().get(i); if ((pos.isEmpty() || (kafTerm.getPos().toLowerCase().startsWith(pos))) && !kafTerm.getLemma().isEmpty() && (resources.verbNetPredicateMap.containsKey(kafTerm.getLemma()))) { ArrayList<ArrayList<String>> mappings = resources.verbNetPredicateMap.get(kafTerm.getLemma()); for (int j = 0; j < mappings.size(); j++) { ArrayList<String> mapping = mappings.get(j); KafSense kafSense = new KafSense(); kafSense.setResource(pmVersion); kafSense.setSensecode(mapping.get(0));//// we assume that the first mapping represents the sensCode for (int k = 0; k < mapping.size(); k++) { String s = mapping.get(k); if (checkMappings(selectedMappings, s)) { String resource = s.substring(0, 2); KafSense child = new KafSense(); child.setResource(resource); child.setSensecode(s); kafSense.addChildren(child); } } kafTerm.addSenseTag(kafSense); } } } } static public void processKafFileWordnetNetSenseKeys (KafSaxParser kafSaxParser, String pathToKafFile, Resources resources, String pmVersion, String pos, String[] selectedMappings) { kafSaxParser.parseFile(pathToKafFile); for (int i = 0; i < kafSaxParser.getKafTerms().size(); i++) { KafTerm kafTerm = kafSaxParser.getKafTerms().get(i); if ((pos.isEmpty() || (kafTerm.getPos().toLowerCase().startsWith(pos))) && !kafTerm.getLemma().isEmpty() && (resources.wordNetLemmaSenseMap.containsKey(kafTerm.getLemma()))) { ArrayList<String> senses = resources.wordNetLemmaSenseMap.get(kafTerm.getLemma()); for (int j = 0; j < senses.size(); j++) { String senseKey = senses.get(j); KafSense kafSense = new KafSense(); kafSense.setResource(pmVersion); kafSense.setSensecode(senseKey); if (resources.wordNetPredicateMap.containsKey(senseKey)) { ArrayList<ArrayList<String>> mappings = resources.wordNetPredicateMap.get(senseKey); KafSense mChild = new KafSense (); for (int m = 0; m < mappings.size(); m++) { ArrayList<String> mapping = mappings.get(m); for (int k = 1; k < mapping.size(); k++) { String s = mapping.get(k); if (checkMappings(selectedMappings, s)) { String resource = s.substring(0, 2); KafSense child = new KafSense(); child.setResource(resource); child.setSensecode(s); mChild.addChildren(child); } } } kafSense.addChildren(mChild); } kafTerm.addSenseTag(kafSense); } } } } static public void processKafFileWordnetNetLemmas (KafSaxParser kafSaxParser, String pathToKafFile, Resources resources, String pmVersion, String pos, String[] selectedMappings) { kafSaxParser.parseFile(pathToKafFile); for (int i = 0; i < kafSaxParser.getKafTerms().size(); i++) { KafTerm kafTerm = kafSaxParser.getKafTerms().get(i); if ((pos.isEmpty() || (kafTerm.getPos().toLowerCase().startsWith(pos))) && !kafTerm.getLemma().isEmpty() && (resources.wordNetLemmaSenseMap.containsKey(kafTerm.getLemma()))) { ArrayList<String> senses = resources.wordNetLemmaSenseMap.get(kafTerm.getLemma()); for (int j = 0; j < senses.size(); j++) { String synsetId = senses.get(j); KafSense kafSense = new KafSense(); kafSense.setResource(pmVersion); kafSense.setSensecode(synsetId); boolean matchingSense = false; for (int k = 0; k < kafTerm.getSenseTags().size(); k++) { KafSense givenKafSense = kafTerm.getSenseTags().get(k); if (givenKafSense.getSensecode().equals(synsetId)) { kafSense = givenKafSense; matchingSense = true; break; } } if (resources.wordNetPredicateMap.containsKey(synsetId)) { ArrayList<ArrayList<String>> mappings = resources.wordNetPredicateMap.get(synsetId); KafSense mChild = new KafSense (); for (int m = 0; m < mappings.size(); m++) { ArrayList<String> mapping = mappings.get(m); for (int k = 1; k < mapping.size(); k++) { String s = mapping.get(k); if (checkMappings(selectedMappings, s)) { String resource = s.substring(0, 2); KafSense child = new KafSense(); child.setResource(resource); child.setSensecode(s); mChild.addChildren(child); } } } kafSense.addChildren(mChild); } if (!matchingSense) { kafTerm.addSenseTag(kafSense); } } } } } static boolean checkMappings (String[] mappings, String m) { if (mappings==null) { return true; } for (int l = 0; l < mappings.length; l++) { String selectedMapping = mappings[l]; if (m.equalsIgnoreCase(selectedMapping)) { return true; } else if (m.startsWith(selectedMapping)) { return true; } } return false; } static public void processKafFileWordnetNetSynsets (KafSaxParser kafSaxParser, String pmVersion, Resources resources, String[] selectedMappings) { for (int i = 0; i < kafSaxParser.getKafTerms().size(); i++) { KafTerm kafTerm = kafSaxParser.getKafTerms().get(i); if (resources.grammaticalWords.contains(kafTerm.getLemma())) { KafSense child = new KafSense(); child.setSensecode("grammatical"); kafTerm.addSenseTag(child); } else { boolean TAGGED = false; for (int j = 0; j < kafTerm.getSenseTags().size(); j++) { KafSense kafSense = kafTerm.getSenseTags().get(j); if (!TAGGED) TAGGED = mappSense(resources, kafSense, pmVersion, selectedMappings); } for (int j = 0; j < kafTerm.getComponents().size(); j++) { TermComponent termComponent = kafTerm.getComponents().get(j); for (int k = 0; k < termComponent.getSenseTags().size(); k++) { KafSense kafSense = termComponent.getSenseTags().get(k); if (!TAGGED) TAGGED = mappSense(resources, kafSense, pmVersion, selectedMappings); } } if (!TAGGED && resources.frameNetLuReader.lexicalUnitFrameMap!=null) { String lemma = kafTerm.getLemma(); if (resources.frameNetLuReader.KEEPPOSTAG) { if (kafTerm.getPos().toLowerCase().startsWith("n")) { lemma += ".n"; } else if (kafTerm.getPos().toLowerCase().startsWith("v")) { lemma += ".v"; } else if (kafTerm.getPos().toLowerCase().startsWith("g")) { lemma += ".a"; } } if (resources.frameNetLuReader.lexicalUnitFrameMap.containsKey(lemma)) { ArrayList<String> frames = resources.frameNetLuReader.lexicalUnitFrameMap.get(lemma); //System.out.println("frames = " + frames.toString()); if (frames.size()>0) { KafSense mChild = new KafSense(); mChild.setResource("fn-lexicon"); mChild.setSensecode(pmVersion); for (int j = 0; j < frames.size(); j++) { String frame = frames.get(j); KafSense child = new KafSense(); child.setResource("FrameNet"); child.setSensecode(frame); mChild.addChildren(child); } kafTerm.addSenseTag(mChild); } } } } } } static public void processKafFileCorefWordnetNetSynsets (KafSaxParser kafSaxParser, String pmVersion, Resources resources, String[] selectedMappings) { for (int i = 0; i < kafSaxParser.kafCorefenceArrayList.size(); i++) { KafCoreferenceSet kafCoreferenceSet = kafSaxParser.kafCorefenceArrayList.get(i); for (int j = 0; j < kafCoreferenceSet.getExternalReferences().size(); j++) { KafSense kafSense = kafCoreferenceSet.getExternalReferences().get(j); mappSense(resources, kafSense, pmVersion, selectedMappings); } } } static public void processExtendCorefForWordnetNetSynsets (KafSaxParser kafSaxParser, String pmVersion, Resources resources, String[] selectedMappings) { for (int i = 0; i < kafSaxParser.kafCorefenceArrayList.size(); i++) { KafCoreferenceSet kafCoreferenceSet = kafSaxParser.kafCorefenceArrayList.get(i); ArrayList<KafSense> concepts = new ArrayList<KafSense>(); for (int j = 0; j < kafCoreferenceSet.getExternalReferences().size(); j++) { KafSense kafSense = kafCoreferenceSet.getExternalReferences().get(j); ArrayList<KafSense> myconcepts = addSense(resources, kafSense, pmVersion, selectedMappings); for (int k = 0; k < myconcepts.size(); k++) { KafSense sense = myconcepts.get(k); boolean match = false; for (int l = 0; l < concepts.size(); l++) { KafSense kafSense1 = concepts.get(l); if (sense.getSensecode().equals(kafSense1.getSensecode())) { match = true; break; } } if (!match) concepts.add(sense); } } for (int j = 0; j < concepts.size(); j++) { KafSense kafSense = concepts.get(j); kafCoreferenceSet.addExternalReferences(kafSense); } } } static boolean mappSense (Resources resources, KafSense givenKafSense, String pmVersion, String[] selectedMappings) { boolean TAGGED = false; String senseCode = givenKafSense.getSensecode(); //System.out.println("senseCode = " + senseCode); if (!resources.wordNetPredicateMap.containsKey(givenKafSense.getSensecode())) { if (senseCode.startsWith("nld-")) { int idx = senseCode.indexOf("_"); //nld-21-d_v-3939-v if (idx>-1) { senseCode = senseCode.substring(idx-1); //d_v-3939-v } } } if (resources.wordNetPredicateMap.containsKey(senseCode)) { ArrayList<String> matchedSenseCode = new ArrayList<String>(); ArrayList<ArrayList<String>> mappings = resources.wordNetPredicateMap.get(senseCode); for (int m = 0; m < mappings.size(); m++) { boolean match = false; KafSense mChild = new KafSense (); mChild.setResource("predicate-matrix"); mChild.setSensecode(pmVersion); ArrayList<String> mapping = mappings.get(m); for (int k = 1; k < mapping.size(); k++) { String s = mapping.get(k); //System.out.println("s = " + s); if (checkMappings(selectedMappings, s)) { int idx = s.indexOf(":"); String resource = ""; if (idx > -1) { resource = s.substring(0, idx); } KafSense child = new KafSense(); child.setResource(resource); child.setSensecode(s); if (!matchedSenseCode.contains(s)) { match = true; matchedSenseCode.add(s); mChild.addChildren(child); } } } if (match) { // System.out.println("givenKafSense = " + givenKafSense.getSensecode()); givenKafSense.addChildren(mChild); TAGGED = true; } } } else { // System.out.println("cannot find senseCode = " + senseCode); } return TAGGED; } static ArrayList<KafSense> addSense (Resources resources, KafSense givenKafSense, String pmVersion, String[] selectedMappings) { ArrayList<KafSense> concepts = new ArrayList<KafSense>(); String senseCode = givenKafSense.getSensecode(); if (!resources.wordNetPredicateMap.containsKey(givenKafSense.getSensecode())) { if (senseCode.startsWith("nld-")) { int idx = senseCode.indexOf("_"); //nld-21-d_v-3939-v if (idx>-1) { senseCode = senseCode.substring(idx-1); //d_v-3939-v } } } if (resources.wordNetPredicateMap.containsKey(senseCode)) { ArrayList<String> coveredMappings = new ArrayList<String>(); ArrayList<ArrayList<String>> mappings = resources.wordNetPredicateMap.get(senseCode); for (int m = 0; m < mappings.size(); m++) { ArrayList<String> mapping = mappings.get(m); for (int k = 1; k < mapping.size(); k++) { String s = mapping.get(k); int idx = s.indexOf(":"); String resource = s; String value = s; if (idx > -1) { resource = s.substring(0, idx); value = s.substring(idx+1); } if (checkMappings(selectedMappings, resource) && !coveredMappings.contains(resource)) { coveredMappings.add(resource); /// prevent multiple fields that share prefix, take first KafSense child = new KafSense(); child.setResource(resource); child.setSensecode(value); concepts.add(child); } } } } else { // System.out.println("cannot find senseCode = " + senseCode); } return concepts; } }
cltl/OntoTagger
src/main/java/eu/kyotoproject/main/KafPredicateMatrixTagger.java
5,793
// String pathToKafFile = "/Tools/ontotagger-v1.0/naf-example/spinoza-voorbeeld-ukb.xml";
line_comment
nl
package eu.kyotoproject.main; import eu.kyotoproject.kaf.*; import eu.kyotoproject.util.Resources; import org.apache.tools.bzip2.CBZip2InputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.zip.GZIPInputStream; /** * Created with IntelliJ IDEA. * User: piek * Date: 1/29/13 * Time: 3:20 PM * To change this template use File | Settings | File Templates. */ public class KafPredicateMatrixTagger { static final String layer = "terms"; static final String name = "vua-predicate-matrix-tagger"; static final String version = "1.0"; static public void main (String[] args) { Resources resources = new Resources(); // String pathToKafFile<SUF> // String pathToKafFile = "/Users/piek/Desktop/NWR/NWR-SRL/wikinews-nl/files/14369_Airbus_offers_funding_to_search_for_black_boxes_from_Air_France_disaster.ukb.kaf"; String pathToKafFile = ""; //pathToKafFile = "/Tools/nwr-dutch-pipeline/vua-ontotagger-v1.0/nl.demo.naf"; // pathToKafFile = "/Users/piek/Desktop/NWR/NWR-SRL/wikinews-nl/files/14369_Airbus_offers_funding_to_search_for_black_boxes_from_Air_France_disaster.ukb.kaf"; String pathToMatrixFile = ""; //pathToMatrixFile = "/Tools/nwr-dutch-pipeline/vua-ontotagger-v1.0/resources/PredicateMatrix.v1.3.txt.role.odwn"; String pathToGrammaticalVerbsFile = ""; //pathToGrammaticalVerbsFile = "/Tools/ontotagger-v1.0/resources/grammaticals/Grammatical-words.nl"; String pathToFrameNetLex = ""; String pmVersion = ""; pmVersion = "1.1"; boolean ili = false; String pos = ""; String prefix = ""; String key = ""; //key = "odwn-eq"; String format = "naf"; String[] selectedMappings = null; for (int i = 0; i < args.length; i++) { String arg = args[i]; if ((arg.equalsIgnoreCase("--kaf-file")) && (args.length>(i+1))) { pathToKafFile = args[i+1]; } else if ((arg.equalsIgnoreCase("--naf-file")) && (args.length>(i+1))) { pathToKafFile = args[i+1]; } else if ((arg.equalsIgnoreCase("--pos")) && (args.length>(i+1))) { pos = args[i+1]; } else if ((arg.equalsIgnoreCase("--predicate-matrix")) && (args.length>(i+1))) { pathToMatrixFile = args[i+1]; } else if ((arg.equalsIgnoreCase("--fn-lexicon")) && (args.length>(i+1))) { pathToFrameNetLex = args[i+1]; } else if ((arg.equalsIgnoreCase("--fn-lexicon-pos")) && (args.length>(i+1))) { pathToFrameNetLex = args[i+1]; resources.frameNetLuReader.KEEPPOSTAG = true; } else if ((arg.equalsIgnoreCase("--grammatical-words")) && (args.length>(i+1))) { pathToGrammaticalVerbsFile = args[i+1]; } else if ((arg.equalsIgnoreCase("--version")) && (args.length>(i+1))) { pmVersion = args[i+1]; } else if ((arg.equalsIgnoreCase("--key")) && (args.length>(i+1))) { key = args[i+1]; } else if ((arg.equalsIgnoreCase("--ignore-prefix")) && (args.length>(i+1))) { prefix = args[i+1]; } else if ((arg.equalsIgnoreCase("--mappings")) && (args.length>(i+1))) { selectedMappings = args[i+1].split(";"); } else if ((arg.equalsIgnoreCase("--ili"))) { ili = true; } } if (!pathToMatrixFile.isEmpty()) { if (ili) { resources.processMatrixFileWithWordnetILI(pathToMatrixFile); } else if (!key.isEmpty()) { resources.processMatrixFile(pathToMatrixFile, key, prefix); // System.out.println("resources = " + resources.wordNetPredicateMap.size()); } else { resources.processMatrixFileWithWordnetLemma(pathToMatrixFile); } } if (!pathToFrameNetLex.isEmpty()) { resources.frameNetLuReader.parseFile(pathToFrameNetLex); } if (!pathToGrammaticalVerbsFile.isEmpty()) { resources.processGrammaticalWordsFile(pathToGrammaticalVerbsFile); } String strBeginDate = eu.kyotoproject.util.DateUtil.createTimestamp(); String strEndDate = null; KafSaxParser kafSaxParser = new KafSaxParser(); if (pathToKafFile.isEmpty()) { kafSaxParser.parseFile(System.in); } else { if (pathToKafFile.toLowerCase().endsWith(".gz")) { try { InputStream fileStream = new FileInputStream(pathToKafFile); InputStream gzipStream = new GZIPInputStream(fileStream); kafSaxParser.parseFile(gzipStream); } catch (IOException e) { e.printStackTrace(); } } else if (pathToKafFile.toLowerCase().endsWith(".bz2")) { try { InputStream fileStream = new FileInputStream(pathToKafFile); InputStream gzipStream = new CBZip2InputStream(fileStream); kafSaxParser.parseFile(gzipStream); } catch (IOException e) { e.printStackTrace(); } } else { kafSaxParser.parseFile(pathToKafFile); } } processKafFileWordnetNetSynsets(kafSaxParser, pmVersion, resources, selectedMappings); strEndDate = eu.kyotoproject.util.DateUtil.createTimestamp(); String host = ""; try { host = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { e.printStackTrace(); } LP lp = new LP(name,version, strBeginDate, strBeginDate, strEndDate, host); kafSaxParser.getKafMetaData().addLayer(layer, lp); if (format.equalsIgnoreCase("naf")) { kafSaxParser.writeNafToStream(System.out); /* try { OutputStream fos = new FileOutputStream("/Tools/ontotagger-v1.0/naf-example/89007714_06.ont.srl.naf"); kafSaxParser.writeNafToStream(fos); fos.close(); } catch (IOException e) { e.printStackTrace(); }*/ } else if (format.equalsIgnoreCase("kaf")) { kafSaxParser.writeKafToStream(System.out); } } static public void processKafFileVerbNet (KafSaxParser kafSaxParser, String pathToKafFile, Resources resources, String pmVersion, String pos, String [] selectedMappings) { kafSaxParser.parseFile(pathToKafFile); for (int i = 0; i < kafSaxParser.getKafTerms().size(); i++) { KafTerm kafTerm = kafSaxParser.getKafTerms().get(i); if ((pos.isEmpty() || (kafTerm.getPos().toLowerCase().startsWith(pos))) && !kafTerm.getLemma().isEmpty() && (resources.verbNetPredicateMap.containsKey(kafTerm.getLemma()))) { ArrayList<ArrayList<String>> mappings = resources.verbNetPredicateMap.get(kafTerm.getLemma()); for (int j = 0; j < mappings.size(); j++) { ArrayList<String> mapping = mappings.get(j); KafSense kafSense = new KafSense(); kafSense.setResource(pmVersion); kafSense.setSensecode(mapping.get(0));//// we assume that the first mapping represents the sensCode for (int k = 0; k < mapping.size(); k++) { String s = mapping.get(k); if (checkMappings(selectedMappings, s)) { String resource = s.substring(0, 2); KafSense child = new KafSense(); child.setResource(resource); child.setSensecode(s); kafSense.addChildren(child); } } kafTerm.addSenseTag(kafSense); } } } } static public void processKafFileWordnetNetSenseKeys (KafSaxParser kafSaxParser, String pathToKafFile, Resources resources, String pmVersion, String pos, String[] selectedMappings) { kafSaxParser.parseFile(pathToKafFile); for (int i = 0; i < kafSaxParser.getKafTerms().size(); i++) { KafTerm kafTerm = kafSaxParser.getKafTerms().get(i); if ((pos.isEmpty() || (kafTerm.getPos().toLowerCase().startsWith(pos))) && !kafTerm.getLemma().isEmpty() && (resources.wordNetLemmaSenseMap.containsKey(kafTerm.getLemma()))) { ArrayList<String> senses = resources.wordNetLemmaSenseMap.get(kafTerm.getLemma()); for (int j = 0; j < senses.size(); j++) { String senseKey = senses.get(j); KafSense kafSense = new KafSense(); kafSense.setResource(pmVersion); kafSense.setSensecode(senseKey); if (resources.wordNetPredicateMap.containsKey(senseKey)) { ArrayList<ArrayList<String>> mappings = resources.wordNetPredicateMap.get(senseKey); KafSense mChild = new KafSense (); for (int m = 0; m < mappings.size(); m++) { ArrayList<String> mapping = mappings.get(m); for (int k = 1; k < mapping.size(); k++) { String s = mapping.get(k); if (checkMappings(selectedMappings, s)) { String resource = s.substring(0, 2); KafSense child = new KafSense(); child.setResource(resource); child.setSensecode(s); mChild.addChildren(child); } } } kafSense.addChildren(mChild); } kafTerm.addSenseTag(kafSense); } } } } static public void processKafFileWordnetNetLemmas (KafSaxParser kafSaxParser, String pathToKafFile, Resources resources, String pmVersion, String pos, String[] selectedMappings) { kafSaxParser.parseFile(pathToKafFile); for (int i = 0; i < kafSaxParser.getKafTerms().size(); i++) { KafTerm kafTerm = kafSaxParser.getKafTerms().get(i); if ((pos.isEmpty() || (kafTerm.getPos().toLowerCase().startsWith(pos))) && !kafTerm.getLemma().isEmpty() && (resources.wordNetLemmaSenseMap.containsKey(kafTerm.getLemma()))) { ArrayList<String> senses = resources.wordNetLemmaSenseMap.get(kafTerm.getLemma()); for (int j = 0; j < senses.size(); j++) { String synsetId = senses.get(j); KafSense kafSense = new KafSense(); kafSense.setResource(pmVersion); kafSense.setSensecode(synsetId); boolean matchingSense = false; for (int k = 0; k < kafTerm.getSenseTags().size(); k++) { KafSense givenKafSense = kafTerm.getSenseTags().get(k); if (givenKafSense.getSensecode().equals(synsetId)) { kafSense = givenKafSense; matchingSense = true; break; } } if (resources.wordNetPredicateMap.containsKey(synsetId)) { ArrayList<ArrayList<String>> mappings = resources.wordNetPredicateMap.get(synsetId); KafSense mChild = new KafSense (); for (int m = 0; m < mappings.size(); m++) { ArrayList<String> mapping = mappings.get(m); for (int k = 1; k < mapping.size(); k++) { String s = mapping.get(k); if (checkMappings(selectedMappings, s)) { String resource = s.substring(0, 2); KafSense child = new KafSense(); child.setResource(resource); child.setSensecode(s); mChild.addChildren(child); } } } kafSense.addChildren(mChild); } if (!matchingSense) { kafTerm.addSenseTag(kafSense); } } } } } static boolean checkMappings (String[] mappings, String m) { if (mappings==null) { return true; } for (int l = 0; l < mappings.length; l++) { String selectedMapping = mappings[l]; if (m.equalsIgnoreCase(selectedMapping)) { return true; } else if (m.startsWith(selectedMapping)) { return true; } } return false; } static public void processKafFileWordnetNetSynsets (KafSaxParser kafSaxParser, String pmVersion, Resources resources, String[] selectedMappings) { for (int i = 0; i < kafSaxParser.getKafTerms().size(); i++) { KafTerm kafTerm = kafSaxParser.getKafTerms().get(i); if (resources.grammaticalWords.contains(kafTerm.getLemma())) { KafSense child = new KafSense(); child.setSensecode("grammatical"); kafTerm.addSenseTag(child); } else { boolean TAGGED = false; for (int j = 0; j < kafTerm.getSenseTags().size(); j++) { KafSense kafSense = kafTerm.getSenseTags().get(j); if (!TAGGED) TAGGED = mappSense(resources, kafSense, pmVersion, selectedMappings); } for (int j = 0; j < kafTerm.getComponents().size(); j++) { TermComponent termComponent = kafTerm.getComponents().get(j); for (int k = 0; k < termComponent.getSenseTags().size(); k++) { KafSense kafSense = termComponent.getSenseTags().get(k); if (!TAGGED) TAGGED = mappSense(resources, kafSense, pmVersion, selectedMappings); } } if (!TAGGED && resources.frameNetLuReader.lexicalUnitFrameMap!=null) { String lemma = kafTerm.getLemma(); if (resources.frameNetLuReader.KEEPPOSTAG) { if (kafTerm.getPos().toLowerCase().startsWith("n")) { lemma += ".n"; } else if (kafTerm.getPos().toLowerCase().startsWith("v")) { lemma += ".v"; } else if (kafTerm.getPos().toLowerCase().startsWith("g")) { lemma += ".a"; } } if (resources.frameNetLuReader.lexicalUnitFrameMap.containsKey(lemma)) { ArrayList<String> frames = resources.frameNetLuReader.lexicalUnitFrameMap.get(lemma); //System.out.println("frames = " + frames.toString()); if (frames.size()>0) { KafSense mChild = new KafSense(); mChild.setResource("fn-lexicon"); mChild.setSensecode(pmVersion); for (int j = 0; j < frames.size(); j++) { String frame = frames.get(j); KafSense child = new KafSense(); child.setResource("FrameNet"); child.setSensecode(frame); mChild.addChildren(child); } kafTerm.addSenseTag(mChild); } } } } } } static public void processKafFileCorefWordnetNetSynsets (KafSaxParser kafSaxParser, String pmVersion, Resources resources, String[] selectedMappings) { for (int i = 0; i < kafSaxParser.kafCorefenceArrayList.size(); i++) { KafCoreferenceSet kafCoreferenceSet = kafSaxParser.kafCorefenceArrayList.get(i); for (int j = 0; j < kafCoreferenceSet.getExternalReferences().size(); j++) { KafSense kafSense = kafCoreferenceSet.getExternalReferences().get(j); mappSense(resources, kafSense, pmVersion, selectedMappings); } } } static public void processExtendCorefForWordnetNetSynsets (KafSaxParser kafSaxParser, String pmVersion, Resources resources, String[] selectedMappings) { for (int i = 0; i < kafSaxParser.kafCorefenceArrayList.size(); i++) { KafCoreferenceSet kafCoreferenceSet = kafSaxParser.kafCorefenceArrayList.get(i); ArrayList<KafSense> concepts = new ArrayList<KafSense>(); for (int j = 0; j < kafCoreferenceSet.getExternalReferences().size(); j++) { KafSense kafSense = kafCoreferenceSet.getExternalReferences().get(j); ArrayList<KafSense> myconcepts = addSense(resources, kafSense, pmVersion, selectedMappings); for (int k = 0; k < myconcepts.size(); k++) { KafSense sense = myconcepts.get(k); boolean match = false; for (int l = 0; l < concepts.size(); l++) { KafSense kafSense1 = concepts.get(l); if (sense.getSensecode().equals(kafSense1.getSensecode())) { match = true; break; } } if (!match) concepts.add(sense); } } for (int j = 0; j < concepts.size(); j++) { KafSense kafSense = concepts.get(j); kafCoreferenceSet.addExternalReferences(kafSense); } } } static boolean mappSense (Resources resources, KafSense givenKafSense, String pmVersion, String[] selectedMappings) { boolean TAGGED = false; String senseCode = givenKafSense.getSensecode(); //System.out.println("senseCode = " + senseCode); if (!resources.wordNetPredicateMap.containsKey(givenKafSense.getSensecode())) { if (senseCode.startsWith("nld-")) { int idx = senseCode.indexOf("_"); //nld-21-d_v-3939-v if (idx>-1) { senseCode = senseCode.substring(idx-1); //d_v-3939-v } } } if (resources.wordNetPredicateMap.containsKey(senseCode)) { ArrayList<String> matchedSenseCode = new ArrayList<String>(); ArrayList<ArrayList<String>> mappings = resources.wordNetPredicateMap.get(senseCode); for (int m = 0; m < mappings.size(); m++) { boolean match = false; KafSense mChild = new KafSense (); mChild.setResource("predicate-matrix"); mChild.setSensecode(pmVersion); ArrayList<String> mapping = mappings.get(m); for (int k = 1; k < mapping.size(); k++) { String s = mapping.get(k); //System.out.println("s = " + s); if (checkMappings(selectedMappings, s)) { int idx = s.indexOf(":"); String resource = ""; if (idx > -1) { resource = s.substring(0, idx); } KafSense child = new KafSense(); child.setResource(resource); child.setSensecode(s); if (!matchedSenseCode.contains(s)) { match = true; matchedSenseCode.add(s); mChild.addChildren(child); } } } if (match) { // System.out.println("givenKafSense = " + givenKafSense.getSensecode()); givenKafSense.addChildren(mChild); TAGGED = true; } } } else { // System.out.println("cannot find senseCode = " + senseCode); } return TAGGED; } static ArrayList<KafSense> addSense (Resources resources, KafSense givenKafSense, String pmVersion, String[] selectedMappings) { ArrayList<KafSense> concepts = new ArrayList<KafSense>(); String senseCode = givenKafSense.getSensecode(); if (!resources.wordNetPredicateMap.containsKey(givenKafSense.getSensecode())) { if (senseCode.startsWith("nld-")) { int idx = senseCode.indexOf("_"); //nld-21-d_v-3939-v if (idx>-1) { senseCode = senseCode.substring(idx-1); //d_v-3939-v } } } if (resources.wordNetPredicateMap.containsKey(senseCode)) { ArrayList<String> coveredMappings = new ArrayList<String>(); ArrayList<ArrayList<String>> mappings = resources.wordNetPredicateMap.get(senseCode); for (int m = 0; m < mappings.size(); m++) { ArrayList<String> mapping = mappings.get(m); for (int k = 1; k < mapping.size(); k++) { String s = mapping.get(k); int idx = s.indexOf(":"); String resource = s; String value = s; if (idx > -1) { resource = s.substring(0, idx); value = s.substring(idx+1); } if (checkMappings(selectedMappings, resource) && !coveredMappings.contains(resource)) { coveredMappings.add(resource); /// prevent multiple fields that share prefix, take first KafSense child = new KafSense(); child.setResource(resource); child.setSensecode(value); concepts.add(child); } } } } else { // System.out.println("cannot find senseCode = " + senseCode); } return concepts; } }
198846_3
package com.twitter.search.earlybird.partition; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.annotation.Nonnull; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.Sets; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.twitter.search.common.partitioning.base.Segment; import com.twitter.search.common.schema.earlybird.FlushVersion; import com.twitter.search.earlybird.archive.ArchiveSearchPartitionManager; import com.twitter.search.earlybird.archive.ArchiveTimeSlicer; import com.twitter.search.earlybird.archive.ArchiveTimeSlicer.ArchiveTimeSlice; import com.twitter.search.earlybird.common.config.EarlybirdConfig; import com.twitter.search.earlybird.factory.EarlybirdIndexConfigUtil; /** * This class removes older flush version segments. * Considering that we almost never increase status flush versions, old statuses are not cleaned up * automatically. */ public final class SegmentVulture { private static final Logger LOG = LoggerFactory.getLogger(SegmentVulture.class); @VisibleForTesting // Not final for testing. protected static int numIndexFlushVersionsToKeep = EarlybirdConfig.getInt("number_of_flush_versions_to_keep", 2); private SegmentVulture() { // this never gets called } /** * Delete old build generations, keep currentGeneration. */ @VisibleForTesting static void removeOldBuildGenerations(String rootDirPath, String currentGeneration) { File rootDir = new File(rootDirPath); if (!rootDir.exists() || !rootDir.isDirectory()) { LOG.error("Root directory is invalid: " + rootDirPath); return; } File[] buildGenerations = rootDir.listFiles(); for (File generation : buildGenerations) { if (generation.getName().equals(currentGeneration)) { LOG.info("Skipping current generation: " + generation.getAbsoluteFile()); continue; } try { FileUtils.deleteDirectory(generation); LOG.info("Deleted old build generation: " + generation.getAbsolutePath()); } catch (IOException e) { LOG.error("Failed to delete old build generation at: " + generation.getAbsolutePath(), e); } } LOG.info("Successfully deleted all old generations"); } /** * Delete all the timeslice data outside the serving range. */ @VisibleForTesting static void removeArchiveTimesliceOutsideServingRange(PartitionConfig partitionConfig, ArchiveTimeSlicer timeSlicer, SegmentSyncConfig segmentSyncConfig) { try { long servingStartTimesliceId = Long.MAX_VALUE; long servingEndTimesliceId = 0; int partitionID = partitionConfig.getIndexingHashPartitionID(); List<ArchiveTimeSlice> timeSliceList = timeSlicer.getTimeSlicesInTierRange(); for (ArchiveTimeSlice timeSlice : timeSliceList) { if (timeSlice.getMinStatusID(partitionID) < servingStartTimesliceId) { servingStartTimesliceId = timeSlice.getMinStatusID(partitionID); } if (timeSlice.getMaxStatusID(partitionID) > servingEndTimesliceId) { servingEndTimesliceId = timeSlice.getMaxStatusID(partitionID); } } LOG.info("Got the serving range: [" + servingStartTimesliceId + ", " + servingEndTimesliceId + "], " + "[" + partitionConfig.getTierStartDate() + ", " + partitionConfig.getTierEndDate() + ") for tier: " + partitionConfig.getTierName()); // The tier configuration does not have valid serving range: do not do anything. if (servingEndTimesliceId <= servingStartTimesliceId) { LOG.error("Invalid serving range [" + partitionConfig.getTierStartDate() + ", " + partitionConfig.getTierEndDate() + "] for tier: " + partitionConfig.getTierName()); return; } int numDeleted = 0; File[] segments = getSegmentsOnRootDir(segmentSyncConfig); for (File segment : segments) { String segmentName = SegmentInfo.getSegmentNameFromFlushedDir(segment.getName()); if (segmentName == null) { LOG.error("Invalid directory for segments: " + segment.getAbsolutePath()); continue; } long timesliceId = Segment.getTimeSliceIdFromName(segmentName); if (timesliceId < 0) { LOG.error("Unknown dir/file found: " + segment.getAbsolutePath()); continue; } if (timesliceId < servingStartTimesliceId || timesliceId > servingEndTimesliceId) { LOG.info(segment.getAbsolutePath() + " will be deleted for outside serving Range[" + partitionConfig.getTierStartDate() + ", " + partitionConfig.getTierEndDate() + ")"); if (deleteSegment(segment)) { numDeleted++; } } } LOG.info("Deleted " + numDeleted + " segments out of " + segments.length + " segments"); } catch (IOException e) { LOG.error("Can not timeslice based on the document data: ", e); throw new RuntimeException(e); } } /** * Deleted segments from other partitions. When boxes are moved between * partitions, segments from other partitions may stay, we will have to * delete them. */ @VisibleForTesting static void removeIndexesFromOtherPartitions(int myPartition, int numPartitions, SegmentSyncConfig segmentSyncConfig) { File[] segments = getSegmentsOnRootDir(segmentSyncConfig); int numDeleted = 0; for (File segment : segments) { int segmentNumPartitions = Segment.numPartitionsFromName(segment.getName()); int segmentPartition = Segment.getPartitionFromName(segment.getName()); if (segmentNumPartitions < 0 || segmentPartition < 0) { // Not a segment file, ignoring LOG.info("Unknown dir/file found: " + segment.getAbsolutePath()); continue; } if (segmentNumPartitions != numPartitions || segmentPartition != myPartition) { if (deleteSegment(segment)) { numDeleted++; } } } LOG.info("Deleted " + numDeleted + " segments out of " + segments.length + " segments"); } /** * Delete flushed segments of older flush versions. */ @VisibleForTesting static void removeOldFlushVersionIndexes(int currentFlushVersion, SegmentSyncConfig segmentSyncConfig) { SortedSet<Integer> indexFlushVersions = listFlushVersions(segmentSyncConfig, currentFlushVersion); if (indexFlushVersions == null || indexFlushVersions.size() <= numIndexFlushVersionsToKeep) { return; } Set<String> suffixesToKeep = Sets.newHashSetWithExpectedSize(numIndexFlushVersionsToKeep); int flushVersionsToKeep = numIndexFlushVersionsToKeep; while (flushVersionsToKeep > 0 && !indexFlushVersions.isEmpty()) { Integer oldestFlushVersion = indexFlushVersions.last(); String flushFileExtension = FlushVersion.getVersionFileExtension(oldestFlushVersion); if (flushFileExtension != null) { suffixesToKeep.add(flushFileExtension); flushVersionsToKeep--; } else { LOG.warn("Found unknown flush versions: " + oldestFlushVersion + " Segments with this flush version will be deleted to recover disk space."); } indexFlushVersions.remove(oldestFlushVersion); } String segmentSyncRootDir = segmentSyncConfig.getLocalSegmentSyncRootDir(); File dir = new File(segmentSyncRootDir); File[] segments = dir.listFiles(); for (File segment : segments) { boolean keepSegment = false; for (String suffix : suffixesToKeep) { if (segment.getName().endsWith(suffix)) { keepSegment = true; break; } } if (!keepSegment) { try { FileUtils.deleteDirectory(segment); LOG.info("Deleted old flushed segment: " + segment.getAbsolutePath()); } catch (IOException e) { LOG.error("Failed to delete old flushed segment.", e); } } } } private static File[] getSegmentsOnRootDir(SegmentSyncConfig segmentSyncConfig) { String segmentSyncRootDir = segmentSyncConfig.getLocalSegmentSyncRootDir(); File dir = new File(segmentSyncRootDir); File[] segments = dir.listFiles(); if (segments == null) { return new File[0]; } else { return segments; } } private static boolean deleteSegment(File segment) { try { FileUtils.deleteDirectory(segment); LOG.info("Deleted segment from other partition: " + segment.getAbsolutePath()); return true; } catch (IOException e) { LOG.error("Failed to delete segment from other partition.", e); return false; } } // Returns FlushVersions found on disk. // Current FlushVersion is always added into the list, even if segments are not found on disk, // because they may not have appeared yet. @Nonnull @VisibleForTesting static SortedSet<Integer> listFlushVersions(SegmentSyncConfig sync, int currentFlushVersion) { TreeSet<Integer> flushVersions = Sets.newTreeSet(); // Always add current flush version. // It is possible that on startup when this is run, the current flush version // segments have not appeared yet. flushVersions.add(currentFlushVersion); String segmentSyncRootDir = sync.getLocalSegmentSyncRootDir(); File dir = new File(segmentSyncRootDir); if (!dir.exists()) { LOG.info("segmentSyncRootDir [" + segmentSyncRootDir + "] does not exist"); return flushVersions; } if (!dir.isDirectory()) { LOG.error("segmentSyncRootDir [" + segmentSyncRootDir + "] does not point to a directory"); return flushVersions; } if (!dir.canRead()) { LOG.error("No permission to read from segmentSyncRootDir [" + segmentSyncRootDir + "]"); return flushVersions; } if (!dir.canWrite()) { LOG.error("No permission to write to segmentSyncRootDir [" + segmentSyncRootDir + "]"); return flushVersions; } File[] segments = dir.listFiles(); for (File segment : segments) { String name = segment.getName(); if (!name.contains(FlushVersion.DELIMITER)) { // This is a not a segment with a FlushVersion, skip. LOG.info("Found segment directory without a flush version: " + name); continue; } String[] nameSplits = name.split(FlushVersion.DELIMITER); if (nameSplits.length != 2) { LOG.warn("Found segment with bad name: " + segment.getAbsolutePath()); continue; } // Second half contains flush version try { int flushVersion = Integer.parseInt(nameSplits[1]); flushVersions.add(flushVersion); } catch (NumberFormatException e) { LOG.warn("Bad flush version number in segment name: " + segment.getAbsolutePath()); } } return flushVersions; } /** * Removes old segments in the current build gen. */ @VisibleForTesting static void removeOldSegments(SegmentSyncConfig sync) { if (!sync.getScrubGen().isPresent()) { return; } File currentScrubGenSegmentDir = new File(sync.getLocalSegmentSyncRootDir()); // The unscrubbed segment root directory, used for rebuilds and for segments created before // we introduced scrub gens. The getLocalSegmentSyncRootDir should be something like: // $unscrubbedSegmentDir/scrubbed/$scrub_gen/, // get unscrubbedSegmentDir from string name here in case scrubbed dir does not exist yet File unscrubbedSegmentDir = new File(sync.getLocalSegmentSyncRootDir().split("scrubbed")[0]); if (!unscrubbedSegmentDir.exists()) { // For a new host that swapped in, it might not have flushed_segment dir yet. // return directly in that case. LOG.info(unscrubbedSegmentDir.getAbsoluteFile() + "does not exist, nothing to remove."); return; } Preconditions.checkArgument(unscrubbedSegmentDir.exists()); for (File file : unscrubbedSegmentDir.listFiles()) { if (file.getName().matches("scrubbed")) { continue; } try { LOG.info("Deleting old unscrubbed segment: " + file.getAbsolutePath()); FileUtils.deleteDirectory(file); } catch (IOException e) { LOG.error("Failed to delete directory: " + file.getPath(), e); } } // Delete all segments from previous scrub generations. File allScrubbedSegmentsDir = currentScrubGenSegmentDir.getParentFile(); if (allScrubbedSegmentsDir.exists()) { for (File file : allScrubbedSegmentsDir.listFiles()) { if (file.getPath().equals(currentScrubGenSegmentDir.getPath())) { continue; } try { LOG.info("Deleting old scrubbed segment: " + file.getAbsolutePath()); FileUtils.deleteDirectory(file); } catch (IOException e) { LOG.error("Failed to delete directory: " + file.getPath(), e); } } } } /** * Removes the data for all unused segments from the local disk. This includes: * - data for old segments * - data for segments belonging to another partition * - data for segments belonging to a different flush version. */ public static void removeUnusedSegments( PartitionManager partitionManager, PartitionConfig partitionConfig, int schemaMajorVersion, SegmentSyncConfig segmentSyncConfig) { if (EarlybirdIndexConfigUtil.isArchiveSearch()) { removeOldBuildGenerations( EarlybirdConfig.getString("root_dir"), EarlybirdConfig.getString("offline_segment_build_gen") ); removeOldSegments(segmentSyncConfig); Preconditions.checkState(partitionManager instanceof ArchiveSearchPartitionManager); removeArchiveTimesliceOutsideServingRange( partitionConfig, ((ArchiveSearchPartitionManager) partitionManager).getTimeSlicer(), segmentSyncConfig); } // Remove segments from other partitions removeIndexesFromOtherPartitions( partitionConfig.getIndexingHashPartitionID(), partitionConfig.getNumPartitions(), segmentSyncConfig); // Remove old flushed segments removeOldFlushVersionIndexes(schemaMajorVersion, segmentSyncConfig); } }
twitter/the-algorithm
src/java/com/twitter/search/earlybird/partition/SegmentVulture.java
3,610
/** * Delete old build generations, keep currentGeneration. */
block_comment
nl
package com.twitter.search.earlybird.partition; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.annotation.Nonnull; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.Sets; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.twitter.search.common.partitioning.base.Segment; import com.twitter.search.common.schema.earlybird.FlushVersion; import com.twitter.search.earlybird.archive.ArchiveSearchPartitionManager; import com.twitter.search.earlybird.archive.ArchiveTimeSlicer; import com.twitter.search.earlybird.archive.ArchiveTimeSlicer.ArchiveTimeSlice; import com.twitter.search.earlybird.common.config.EarlybirdConfig; import com.twitter.search.earlybird.factory.EarlybirdIndexConfigUtil; /** * This class removes older flush version segments. * Considering that we almost never increase status flush versions, old statuses are not cleaned up * automatically. */ public final class SegmentVulture { private static final Logger LOG = LoggerFactory.getLogger(SegmentVulture.class); @VisibleForTesting // Not final for testing. protected static int numIndexFlushVersionsToKeep = EarlybirdConfig.getInt("number_of_flush_versions_to_keep", 2); private SegmentVulture() { // this never gets called } /** * Delete old build<SUF>*/ @VisibleForTesting static void removeOldBuildGenerations(String rootDirPath, String currentGeneration) { File rootDir = new File(rootDirPath); if (!rootDir.exists() || !rootDir.isDirectory()) { LOG.error("Root directory is invalid: " + rootDirPath); return; } File[] buildGenerations = rootDir.listFiles(); for (File generation : buildGenerations) { if (generation.getName().equals(currentGeneration)) { LOG.info("Skipping current generation: " + generation.getAbsoluteFile()); continue; } try { FileUtils.deleteDirectory(generation); LOG.info("Deleted old build generation: " + generation.getAbsolutePath()); } catch (IOException e) { LOG.error("Failed to delete old build generation at: " + generation.getAbsolutePath(), e); } } LOG.info("Successfully deleted all old generations"); } /** * Delete all the timeslice data outside the serving range. */ @VisibleForTesting static void removeArchiveTimesliceOutsideServingRange(PartitionConfig partitionConfig, ArchiveTimeSlicer timeSlicer, SegmentSyncConfig segmentSyncConfig) { try { long servingStartTimesliceId = Long.MAX_VALUE; long servingEndTimesliceId = 0; int partitionID = partitionConfig.getIndexingHashPartitionID(); List<ArchiveTimeSlice> timeSliceList = timeSlicer.getTimeSlicesInTierRange(); for (ArchiveTimeSlice timeSlice : timeSliceList) { if (timeSlice.getMinStatusID(partitionID) < servingStartTimesliceId) { servingStartTimesliceId = timeSlice.getMinStatusID(partitionID); } if (timeSlice.getMaxStatusID(partitionID) > servingEndTimesliceId) { servingEndTimesliceId = timeSlice.getMaxStatusID(partitionID); } } LOG.info("Got the serving range: [" + servingStartTimesliceId + ", " + servingEndTimesliceId + "], " + "[" + partitionConfig.getTierStartDate() + ", " + partitionConfig.getTierEndDate() + ") for tier: " + partitionConfig.getTierName()); // The tier configuration does not have valid serving range: do not do anything. if (servingEndTimesliceId <= servingStartTimesliceId) { LOG.error("Invalid serving range [" + partitionConfig.getTierStartDate() + ", " + partitionConfig.getTierEndDate() + "] for tier: " + partitionConfig.getTierName()); return; } int numDeleted = 0; File[] segments = getSegmentsOnRootDir(segmentSyncConfig); for (File segment : segments) { String segmentName = SegmentInfo.getSegmentNameFromFlushedDir(segment.getName()); if (segmentName == null) { LOG.error("Invalid directory for segments: " + segment.getAbsolutePath()); continue; } long timesliceId = Segment.getTimeSliceIdFromName(segmentName); if (timesliceId < 0) { LOG.error("Unknown dir/file found: " + segment.getAbsolutePath()); continue; } if (timesliceId < servingStartTimesliceId || timesliceId > servingEndTimesliceId) { LOG.info(segment.getAbsolutePath() + " will be deleted for outside serving Range[" + partitionConfig.getTierStartDate() + ", " + partitionConfig.getTierEndDate() + ")"); if (deleteSegment(segment)) { numDeleted++; } } } LOG.info("Deleted " + numDeleted + " segments out of " + segments.length + " segments"); } catch (IOException e) { LOG.error("Can not timeslice based on the document data: ", e); throw new RuntimeException(e); } } /** * Deleted segments from other partitions. When boxes are moved between * partitions, segments from other partitions may stay, we will have to * delete them. */ @VisibleForTesting static void removeIndexesFromOtherPartitions(int myPartition, int numPartitions, SegmentSyncConfig segmentSyncConfig) { File[] segments = getSegmentsOnRootDir(segmentSyncConfig); int numDeleted = 0; for (File segment : segments) { int segmentNumPartitions = Segment.numPartitionsFromName(segment.getName()); int segmentPartition = Segment.getPartitionFromName(segment.getName()); if (segmentNumPartitions < 0 || segmentPartition < 0) { // Not a segment file, ignoring LOG.info("Unknown dir/file found: " + segment.getAbsolutePath()); continue; } if (segmentNumPartitions != numPartitions || segmentPartition != myPartition) { if (deleteSegment(segment)) { numDeleted++; } } } LOG.info("Deleted " + numDeleted + " segments out of " + segments.length + " segments"); } /** * Delete flushed segments of older flush versions. */ @VisibleForTesting static void removeOldFlushVersionIndexes(int currentFlushVersion, SegmentSyncConfig segmentSyncConfig) { SortedSet<Integer> indexFlushVersions = listFlushVersions(segmentSyncConfig, currentFlushVersion); if (indexFlushVersions == null || indexFlushVersions.size() <= numIndexFlushVersionsToKeep) { return; } Set<String> suffixesToKeep = Sets.newHashSetWithExpectedSize(numIndexFlushVersionsToKeep); int flushVersionsToKeep = numIndexFlushVersionsToKeep; while (flushVersionsToKeep > 0 && !indexFlushVersions.isEmpty()) { Integer oldestFlushVersion = indexFlushVersions.last(); String flushFileExtension = FlushVersion.getVersionFileExtension(oldestFlushVersion); if (flushFileExtension != null) { suffixesToKeep.add(flushFileExtension); flushVersionsToKeep--; } else { LOG.warn("Found unknown flush versions: " + oldestFlushVersion + " Segments with this flush version will be deleted to recover disk space."); } indexFlushVersions.remove(oldestFlushVersion); } String segmentSyncRootDir = segmentSyncConfig.getLocalSegmentSyncRootDir(); File dir = new File(segmentSyncRootDir); File[] segments = dir.listFiles(); for (File segment : segments) { boolean keepSegment = false; for (String suffix : suffixesToKeep) { if (segment.getName().endsWith(suffix)) { keepSegment = true; break; } } if (!keepSegment) { try { FileUtils.deleteDirectory(segment); LOG.info("Deleted old flushed segment: " + segment.getAbsolutePath()); } catch (IOException e) { LOG.error("Failed to delete old flushed segment.", e); } } } } private static File[] getSegmentsOnRootDir(SegmentSyncConfig segmentSyncConfig) { String segmentSyncRootDir = segmentSyncConfig.getLocalSegmentSyncRootDir(); File dir = new File(segmentSyncRootDir); File[] segments = dir.listFiles(); if (segments == null) { return new File[0]; } else { return segments; } } private static boolean deleteSegment(File segment) { try { FileUtils.deleteDirectory(segment); LOG.info("Deleted segment from other partition: " + segment.getAbsolutePath()); return true; } catch (IOException e) { LOG.error("Failed to delete segment from other partition.", e); return false; } } // Returns FlushVersions found on disk. // Current FlushVersion is always added into the list, even if segments are not found on disk, // because they may not have appeared yet. @Nonnull @VisibleForTesting static SortedSet<Integer> listFlushVersions(SegmentSyncConfig sync, int currentFlushVersion) { TreeSet<Integer> flushVersions = Sets.newTreeSet(); // Always add current flush version. // It is possible that on startup when this is run, the current flush version // segments have not appeared yet. flushVersions.add(currentFlushVersion); String segmentSyncRootDir = sync.getLocalSegmentSyncRootDir(); File dir = new File(segmentSyncRootDir); if (!dir.exists()) { LOG.info("segmentSyncRootDir [" + segmentSyncRootDir + "] does not exist"); return flushVersions; } if (!dir.isDirectory()) { LOG.error("segmentSyncRootDir [" + segmentSyncRootDir + "] does not point to a directory"); return flushVersions; } if (!dir.canRead()) { LOG.error("No permission to read from segmentSyncRootDir [" + segmentSyncRootDir + "]"); return flushVersions; } if (!dir.canWrite()) { LOG.error("No permission to write to segmentSyncRootDir [" + segmentSyncRootDir + "]"); return flushVersions; } File[] segments = dir.listFiles(); for (File segment : segments) { String name = segment.getName(); if (!name.contains(FlushVersion.DELIMITER)) { // This is a not a segment with a FlushVersion, skip. LOG.info("Found segment directory without a flush version: " + name); continue; } String[] nameSplits = name.split(FlushVersion.DELIMITER); if (nameSplits.length != 2) { LOG.warn("Found segment with bad name: " + segment.getAbsolutePath()); continue; } // Second half contains flush version try { int flushVersion = Integer.parseInt(nameSplits[1]); flushVersions.add(flushVersion); } catch (NumberFormatException e) { LOG.warn("Bad flush version number in segment name: " + segment.getAbsolutePath()); } } return flushVersions; } /** * Removes old segments in the current build gen. */ @VisibleForTesting static void removeOldSegments(SegmentSyncConfig sync) { if (!sync.getScrubGen().isPresent()) { return; } File currentScrubGenSegmentDir = new File(sync.getLocalSegmentSyncRootDir()); // The unscrubbed segment root directory, used for rebuilds and for segments created before // we introduced scrub gens. The getLocalSegmentSyncRootDir should be something like: // $unscrubbedSegmentDir/scrubbed/$scrub_gen/, // get unscrubbedSegmentDir from string name here in case scrubbed dir does not exist yet File unscrubbedSegmentDir = new File(sync.getLocalSegmentSyncRootDir().split("scrubbed")[0]); if (!unscrubbedSegmentDir.exists()) { // For a new host that swapped in, it might not have flushed_segment dir yet. // return directly in that case. LOG.info(unscrubbedSegmentDir.getAbsoluteFile() + "does not exist, nothing to remove."); return; } Preconditions.checkArgument(unscrubbedSegmentDir.exists()); for (File file : unscrubbedSegmentDir.listFiles()) { if (file.getName().matches("scrubbed")) { continue; } try { LOG.info("Deleting old unscrubbed segment: " + file.getAbsolutePath()); FileUtils.deleteDirectory(file); } catch (IOException e) { LOG.error("Failed to delete directory: " + file.getPath(), e); } } // Delete all segments from previous scrub generations. File allScrubbedSegmentsDir = currentScrubGenSegmentDir.getParentFile(); if (allScrubbedSegmentsDir.exists()) { for (File file : allScrubbedSegmentsDir.listFiles()) { if (file.getPath().equals(currentScrubGenSegmentDir.getPath())) { continue; } try { LOG.info("Deleting old scrubbed segment: " + file.getAbsolutePath()); FileUtils.deleteDirectory(file); } catch (IOException e) { LOG.error("Failed to delete directory: " + file.getPath(), e); } } } } /** * Removes the data for all unused segments from the local disk. This includes: * - data for old segments * - data for segments belonging to another partition * - data for segments belonging to a different flush version. */ public static void removeUnusedSegments( PartitionManager partitionManager, PartitionConfig partitionConfig, int schemaMajorVersion, SegmentSyncConfig segmentSyncConfig) { if (EarlybirdIndexConfigUtil.isArchiveSearch()) { removeOldBuildGenerations( EarlybirdConfig.getString("root_dir"), EarlybirdConfig.getString("offline_segment_build_gen") ); removeOldSegments(segmentSyncConfig); Preconditions.checkState(partitionManager instanceof ArchiveSearchPartitionManager); removeArchiveTimesliceOutsideServingRange( partitionConfig, ((ArchiveSearchPartitionManager) partitionManager).getTimeSlicer(), segmentSyncConfig); } // Remove segments from other partitions removeIndexesFromOtherPartitions( partitionConfig.getIndexingHashPartitionID(), partitionConfig.getNumPartitions(), segmentSyncConfig); // Remove old flushed segments removeOldFlushVersionIndexes(schemaMajorVersion, segmentSyncConfig); } }
198866_33
package hex.quantile; import hex.ModelBuilder; import hex.ModelCategory; import water.*; import water.fvec.*; import water.util.ArrayUtils; import water.util.Log; import java.util.Arrays; /** * Quantile model builder... building a simple QuantileModel */ public class Quantile extends ModelBuilder<QuantileModel,QuantileModel.QuantileParameters,QuantileModel.QuantileOutput> { private int _ncols; @Override protected boolean logMe() { return false; } @Override public boolean isSupervised() { return false; } // Called from Nano thread; start the Quantile Job on a F/J thread public Quantile( QuantileModel.QuantileParameters parms ) { super(parms); init(false); } public Quantile( QuantileModel.QuantileParameters parms, Job job ) { super(parms, job); init(false); } @Override public Driver trainModelImpl() { return new QuantileDriver(); } @Override public ModelCategory[] can_build() { return new ModelCategory[]{ModelCategory.Unknown}; } // any number of chunks is fine - don't rebalance - it's not worth it for a few passes over the data (at most) @Override protected int desiredChunks(final Frame original_fr, boolean local) { return 1; } /** Initialize the ModelBuilder, validating all arguments and preparing the * training frame. This call is expected to be overridden in the subclasses * and each subclass will start with "super.init();". This call is made * by the front-end whenever the GUI is clicked, and needs to be fast; * heavy-weight prep needs to wait for the trainModel() call. * * Validate the probs. */ @Override public void init(boolean expensive) { super.init(expensive); for( double p : _parms._probs ) if( p < 0.0 || p > 1.0 ) error("_probs","Probabilities must be between 0 and 1"); _ncols = train().numCols()-numSpecialCols(); //offset/weights/nfold - should only ever be weights if ( numSpecialCols() == 1 && _weights == null) throw new IllegalArgumentException("The only special Vec that is supported for Quantiles is observation weights."); if ( numSpecialCols() >1 ) throw new IllegalArgumentException("Cannot handle more than 1 special vec (weights)"); } private static class SumWeights extends MRTask<SumWeights> { double sum; @Override public void map(Chunk c, Chunk w) { for (int i=0;i<c.len();++i) if (!c.isNA(i)) { double wt = w.atd(i); // For now: let the user give small weights, results are probably not very good (same as for wtd.quantile in R) // if (wt > 0 && wt < 1) throw new H2OIllegalArgumentException("Quantiles only accepts weights that are either 0 or >= 1."); sum += wt; } } @Override public void reduce(SumWeights mrt) { sum+=mrt.sum; } } // ---------------------- private class QuantileDriver extends Driver { @Override public void computeImpl() { QuantileModel model = null; try { init(true); // The model to be built model = new QuantileModel(dest(), _parms, new QuantileModel.QuantileOutput(Quantile.this)); model._output._parameters = _parms; model._output._quantiles = new double[_ncols][_parms._probs.length]; model.delete_and_lock(_job); // --- // Run the main Quantile Loop Vec vecs[] = train().vecs(); for( int n=0; n<_ncols; n++ ) { if( stop_requested() ) return; // Stopped/cancelled Vec vec = vecs[n]; if (vec.isBad() || vec.isCategorical() || vec.isString() || vec.isTime() || vec.isUUID()) { model._output._quantiles[n] = new double[_parms._probs.length]; Arrays.fill(model._output._quantiles[n], Double.NaN); continue; } double sumRows=_weights == null ? vec.length()-vec.naCnt() : new SumWeights().doAll(vec, _weights).sum; // Compute top-level histogram Histo h1 = new Histo(vec.min(),vec.max(),0,sumRows,vec.isInt()); h1 = _weights==null ? h1.doAll(vec) : h1.doAll(vec, _weights); // For each probability, see if we have it exactly - or else run // passes until we do. for( int p = 0; p < _parms._probs.length; p++ ) { double prob = _parms._probs[p]; Histo h = h1; // Start from the first global histogram model._output._iterations++; // At least one iter per-prob-per-column while( Double.isNaN(model._output._quantiles[n][p] = h.findQuantile(prob,_parms._combine_method)) ) { h = _weights == null ? h.refinePass(prob).doAll(vec) : h.refinePass(prob).doAll(vec, _weights); // Full pass at higher resolution model._output._iterations++; // also count refinement iterations } // Update the model model.update(_job); // Update model in K/V store _job.update(0); // One unit of work } StringBuilder sb = new StringBuilder(); sb.append("Quantile: iter: ").append(model._output._iterations).append(" Qs=").append(Arrays.toString(model._output._quantiles[n])); Log.debug(sb); } } finally { if( model != null ) model.unlock(_job); } } } public static class StratifiedQuantilesTask extends H2O.H2OCountedCompleter<StratifiedQuantilesTask> { // INPUT final double _prob; final Vec _response; //vec to compute quantile for final Vec _weights; //obs weights final Vec _strata; //continuous integer range mapping into the _quantiles[id][] final QuantileModel.CombineMethod _combine_method; // OUTPUT public double[/*strata*/] _quantiles; public int[] _nids; public StratifiedQuantilesTask(H2O.H2OCountedCompleter cc, double prob, Vec response, // response Vec weights, // obs weights Vec strata, // stratification QuantileModel.CombineMethod combine_method) { super(cc); _response = response; _prob=prob; _combine_method=combine_method; _weights=weights; _strata=strata; } @Override public void compute2() { final int strataMin = (int)_strata.min(); final int strataMax = (int)_strata.max(); if (strataMin < 0 && strataMax < 0) { Log.warn("No quantiles can be computed since there are no non-OOB rows."); tryComplete(); return; } final int nstrata = strataMax - strataMin + 1; Log.info("Computing quantiles for (up to) " + nstrata + " different strata."); _quantiles = new double[nstrata]; _nids = new int[nstrata]; Arrays.fill(_quantiles,Double.NaN); Vec weights = _weights != null ? _weights : _response.makeCon(1); for (int i=0;i<nstrata;++i) { //loop over nodes Vec newWeights = weights.makeCopy(); //only keep weights for this stratum (node), set rest to 0 if (_strata!=null) { _nids[i] = strataMin+i; new KeepOnlyOneStrata(_nids[i]).doAll(_strata, newWeights); } double sumRows = new SumWeights().doAll(_response, newWeights).sum; if (sumRows>0) { Histo h = new Histo(_response.min(), _response.max(), 0, sumRows, _response.isInt()); h.doAll(_response, newWeights); while (Double.isNaN(_quantiles[i] = h.findQuantile(_prob, _combine_method))) h = h.refinePass(_prob).doAll(_response, newWeights); newWeights.remove(); //sanity check quantiles assert (_quantiles[i] <= _response.max() + 1e-6); assert (_quantiles[i] >= _response.min() - 1e-6); } } if (_weights != weights) weights.remove(); tryComplete(); } private static class KeepOnlyOneStrata extends MRTask<KeepOnlyOneStrata> { KeepOnlyOneStrata(int stratumToKeep) { this.stratumToKeep = stratumToKeep; } int stratumToKeep; @Override public void map(Chunk strata, Chunk newW) { for (int i=0; i<strata._len; ++i) { // Log.info("NID:" + ((int) strata.at8(i))); if ((int) strata.at8(i) != stratumToKeep) newW.set(i, 0); } } } } // ------------------------------------------------------------------------- private final static class Histo extends MRTask<Histo> { private static final int NBINS = 1024; // Default bin count private final int _nbins; // Actual bin count private final double _lb; // Lower bound of bin[0] private final double _step; // Step-size per-bin private final double _start_row; // Starting cumulative count of weighted rows for this lower-bound private final double _nrows; // Total datasets (weighted) rows private final boolean _isInt; // Column only holds ints // Big Data output result double _bins[/*nbins*/]; // Weighted count of rows in each bin double _mins[/*nbins*/]; // Smallest element in bin double _maxs[/*nbins*/]; // Largest element in bin private Histo(double lb, double ub, double start_row, double nrows, boolean isInt) { boolean is_int = (isInt && (ub - lb < NBINS)); _nbins = is_int ? (int) (ub - lb + 1) : NBINS; _lb = lb; double ulp = Math.ulp(Math.max(Math.abs(lb), Math.abs(ub))); _step = is_int ? 1 : (ub + ulp - lb) / _nbins; _start_row = start_row; _nrows = nrows; _isInt = isInt; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("range : " + _lb + " ... " + (_lb + _nbins * _step)); sb.append("\npsum0 : " + _start_row); sb.append("\ncounts: " + Arrays.toString(_bins)); sb.append("\nmaxs : " + Arrays.toString(_maxs)); sb.append("\nmins : " + Arrays.toString(_mins)); sb.append("\n"); return sb.toString(); } @Override public void map(Chunk chk, Chunk weight) { _bins = new double[_nbins]; _mins = new double[_nbins]; _maxs = new double[_nbins]; Arrays.fill(_mins, Double.MAX_VALUE); Arrays.fill(_maxs, -Double.MAX_VALUE); double d; for (int row = 0; row < chk._len; row++) { double w = weight.atd(row); if (w == 0) continue; if (!Double.isNaN(d = chk.atd(row))) { // na.rm=true double idx = (d - _lb) / _step; if (!(0.0 <= idx && idx < _bins.length)) continue; int i = (int) idx; if (_bins[i] == 0) _mins[i] = _maxs[i] = d; // Capture unique value else { if (d < _mins[i]) _mins[i] = d; if (d > _maxs[i]) _maxs[i] = d; } _bins[i] += w; // Bump row counts by row weight } } } @Override public void map(Chunk chk) { map(chk, new C0DChunk(1, chk.len())); } @Override public void reduce(Histo h) { for (int i = 0; i < _nbins; i++) { // Keep min/max if (_mins[i] > h._mins[i]) _mins[i] = h._mins[i]; if (_maxs[i] < h._maxs[i]) _maxs[i] = h._maxs[i]; } ArrayUtils.add(_bins, h._bins); } /** @return Quantile for probability prob, or NaN if another pass is needed. */ double findQuantile( double prob, QuantileModel.CombineMethod method ) { double p2 = prob*(_nrows-1); // Desired fractional row number for this probability long r2 = (long)p2; int loidx = findBin(r2); // Find bin holding low value double lo = (loidx == _nbins) ? binEdge(_nbins) : _maxs[loidx]; if( loidx<_nbins && r2==p2 && _mins[loidx]==lo ) return lo; // Exact row number, exact bin? Then quantile is exact long r3 = r2+1; int hiidx = findBin(r3); // Find bin holding high value double hi = (hiidx == _nbins) ? binEdge(_nbins) : _mins[hiidx]; if( loidx==hiidx ) // Somewhere in the same bin? return (lo==hi) ? lo : Double.NaN; // Only if bin is constant, otherwise must refine the bin // Split across bins - the interpolate between the hi of the lo bin, and // the lo of the hi bin return computeQuantile(lo,hi,r2,_nrows,prob,method); } private double binEdge( int idx ) { return _lb+_step*idx; } // bin for row; can be _nbins if just off the end (normally expect 0 to nbins-1) // row == position in (weighted) population private int findBin( double row ) { long sum = (long)_start_row; for( int i=0; i<_nbins; i++ ) if( (long)row < (sum += _bins[i]) ) return i; return _nbins; } // Run another pass over the data, with refined endpoints, to home in on // the exact elements for this probability. Histo refinePass( double prob ) { double prow = prob*(_nrows-1); // Desired fractional row number for this probability long lorow = (long)prow; // Lower integral row number int loidx = findBin(lorow); // Find bin holding low value // If loidx is the last bin, then high must be also the last bin - and we // have an exact quantile (equal to the high bin) and we didn't need // another refinement pass assert loidx < _nbins; double lo = _mins[loidx]; // Lower end of range to explore // If probability does not hit an exact row, we need the elements on // either side - so the next row up from the low row long hirow = lorow==prow ? lorow : lorow+1; int hiidx = findBin(hirow); // Find bin holding high value // Upper end of range to explore - except at the very high end cap double hi = hiidx==_nbins ? binEdge(_nbins) : _maxs[hiidx]; long sum = (long)_start_row; for( int i=0; i<loidx; i++ ) sum += _bins[i]; return new Histo(lo,hi,sum,_nrows,_isInt); } } /** Compute the correct final quantile from these 4 values. If the lo and hi * elements are equal, use them. However if they differ, then there is no * single value which exactly matches the desired quantile. There are * several well-accepted definitions in this case - including picking either * the lo or the hi, or averaging them, or doing a linear interpolation. * @param lo the highest element less than or equal to the desired quantile * @param hi the lowest element greater than or equal to the desired quantile * @param row row number (zero based) of the lo element; high element is +1 * @return desired quantile. */ static double computeQuantile( double lo, double hi, double row, double nrows, double prob, QuantileModel.CombineMethod method ) { if( lo==hi ) return lo; // Equal; pick either if( method == null ) method= QuantileModel.CombineMethod.INTERPOLATE; switch( method ) { case INTERPOLATE: return linearInterpolate(lo,hi,row,nrows,prob); case AVERAGE: return 0.5*(hi+lo); case LOW: return lo; case HIGH: return hi; default: Log.info("Unknown even sample size quantile combination type: " + method + ". Doing linear interpolation."); return linearInterpolate(lo,hi,row,nrows,prob); } } private static double linearInterpolate(double lo, double hi, double row, double nrows, double prob) { // Unequal, linear interpolation double plo = (row+0)/(nrows-1); // Note that row numbers are inclusive on the end point, means we need a -1 double phi = (row+1)/(nrows-1); // Passed in the row number for the low value, high is the next row, so +1 assert plo <= prob && prob <= phi; return lo + (hi-lo)*(prob-plo)/(phi-plo); // Classic linear interpolation } @Override public boolean haveMojo() { return false; } @Override public boolean havePojo() { return false; } public static double calcQuantile(Vec v, double quantile) { Frame fr = new Frame(Key.make(), new String[]{"V"}, new Vec[]{v}); try { DKV.put(fr._key, fr); QuantileModel.QuantileParameters parms = new QuantileModel.QuantileParameters(); parms._train = fr._key; parms._probs = new double[]{quantile}; QuantileModel kmm = new Quantile(parms).trainModelNested(null); kmm.delete(); return kmm._output._quantiles[0][0]; } finally { DKV.remove(fr._key); } } }
h2oai/h2o-3
h2o-core/src/main/java/hex/quantile/Quantile.java
4,771
// Smallest element in bin
line_comment
nl
package hex.quantile; import hex.ModelBuilder; import hex.ModelCategory; import water.*; import water.fvec.*; import water.util.ArrayUtils; import water.util.Log; import java.util.Arrays; /** * Quantile model builder... building a simple QuantileModel */ public class Quantile extends ModelBuilder<QuantileModel,QuantileModel.QuantileParameters,QuantileModel.QuantileOutput> { private int _ncols; @Override protected boolean logMe() { return false; } @Override public boolean isSupervised() { return false; } // Called from Nano thread; start the Quantile Job on a F/J thread public Quantile( QuantileModel.QuantileParameters parms ) { super(parms); init(false); } public Quantile( QuantileModel.QuantileParameters parms, Job job ) { super(parms, job); init(false); } @Override public Driver trainModelImpl() { return new QuantileDriver(); } @Override public ModelCategory[] can_build() { return new ModelCategory[]{ModelCategory.Unknown}; } // any number of chunks is fine - don't rebalance - it's not worth it for a few passes over the data (at most) @Override protected int desiredChunks(final Frame original_fr, boolean local) { return 1; } /** Initialize the ModelBuilder, validating all arguments and preparing the * training frame. This call is expected to be overridden in the subclasses * and each subclass will start with "super.init();". This call is made * by the front-end whenever the GUI is clicked, and needs to be fast; * heavy-weight prep needs to wait for the trainModel() call. * * Validate the probs. */ @Override public void init(boolean expensive) { super.init(expensive); for( double p : _parms._probs ) if( p < 0.0 || p > 1.0 ) error("_probs","Probabilities must be between 0 and 1"); _ncols = train().numCols()-numSpecialCols(); //offset/weights/nfold - should only ever be weights if ( numSpecialCols() == 1 && _weights == null) throw new IllegalArgumentException("The only special Vec that is supported for Quantiles is observation weights."); if ( numSpecialCols() >1 ) throw new IllegalArgumentException("Cannot handle more than 1 special vec (weights)"); } private static class SumWeights extends MRTask<SumWeights> { double sum; @Override public void map(Chunk c, Chunk w) { for (int i=0;i<c.len();++i) if (!c.isNA(i)) { double wt = w.atd(i); // For now: let the user give small weights, results are probably not very good (same as for wtd.quantile in R) // if (wt > 0 && wt < 1) throw new H2OIllegalArgumentException("Quantiles only accepts weights that are either 0 or >= 1."); sum += wt; } } @Override public void reduce(SumWeights mrt) { sum+=mrt.sum; } } // ---------------------- private class QuantileDriver extends Driver { @Override public void computeImpl() { QuantileModel model = null; try { init(true); // The model to be built model = new QuantileModel(dest(), _parms, new QuantileModel.QuantileOutput(Quantile.this)); model._output._parameters = _parms; model._output._quantiles = new double[_ncols][_parms._probs.length]; model.delete_and_lock(_job); // --- // Run the main Quantile Loop Vec vecs[] = train().vecs(); for( int n=0; n<_ncols; n++ ) { if( stop_requested() ) return; // Stopped/cancelled Vec vec = vecs[n]; if (vec.isBad() || vec.isCategorical() || vec.isString() || vec.isTime() || vec.isUUID()) { model._output._quantiles[n] = new double[_parms._probs.length]; Arrays.fill(model._output._quantiles[n], Double.NaN); continue; } double sumRows=_weights == null ? vec.length()-vec.naCnt() : new SumWeights().doAll(vec, _weights).sum; // Compute top-level histogram Histo h1 = new Histo(vec.min(),vec.max(),0,sumRows,vec.isInt()); h1 = _weights==null ? h1.doAll(vec) : h1.doAll(vec, _weights); // For each probability, see if we have it exactly - or else run // passes until we do. for( int p = 0; p < _parms._probs.length; p++ ) { double prob = _parms._probs[p]; Histo h = h1; // Start from the first global histogram model._output._iterations++; // At least one iter per-prob-per-column while( Double.isNaN(model._output._quantiles[n][p] = h.findQuantile(prob,_parms._combine_method)) ) { h = _weights == null ? h.refinePass(prob).doAll(vec) : h.refinePass(prob).doAll(vec, _weights); // Full pass at higher resolution model._output._iterations++; // also count refinement iterations } // Update the model model.update(_job); // Update model in K/V store _job.update(0); // One unit of work } StringBuilder sb = new StringBuilder(); sb.append("Quantile: iter: ").append(model._output._iterations).append(" Qs=").append(Arrays.toString(model._output._quantiles[n])); Log.debug(sb); } } finally { if( model != null ) model.unlock(_job); } } } public static class StratifiedQuantilesTask extends H2O.H2OCountedCompleter<StratifiedQuantilesTask> { // INPUT final double _prob; final Vec _response; //vec to compute quantile for final Vec _weights; //obs weights final Vec _strata; //continuous integer range mapping into the _quantiles[id][] final QuantileModel.CombineMethod _combine_method; // OUTPUT public double[/*strata*/] _quantiles; public int[] _nids; public StratifiedQuantilesTask(H2O.H2OCountedCompleter cc, double prob, Vec response, // response Vec weights, // obs weights Vec strata, // stratification QuantileModel.CombineMethod combine_method) { super(cc); _response = response; _prob=prob; _combine_method=combine_method; _weights=weights; _strata=strata; } @Override public void compute2() { final int strataMin = (int)_strata.min(); final int strataMax = (int)_strata.max(); if (strataMin < 0 && strataMax < 0) { Log.warn("No quantiles can be computed since there are no non-OOB rows."); tryComplete(); return; } final int nstrata = strataMax - strataMin + 1; Log.info("Computing quantiles for (up to) " + nstrata + " different strata."); _quantiles = new double[nstrata]; _nids = new int[nstrata]; Arrays.fill(_quantiles,Double.NaN); Vec weights = _weights != null ? _weights : _response.makeCon(1); for (int i=0;i<nstrata;++i) { //loop over nodes Vec newWeights = weights.makeCopy(); //only keep weights for this stratum (node), set rest to 0 if (_strata!=null) { _nids[i] = strataMin+i; new KeepOnlyOneStrata(_nids[i]).doAll(_strata, newWeights); } double sumRows = new SumWeights().doAll(_response, newWeights).sum; if (sumRows>0) { Histo h = new Histo(_response.min(), _response.max(), 0, sumRows, _response.isInt()); h.doAll(_response, newWeights); while (Double.isNaN(_quantiles[i] = h.findQuantile(_prob, _combine_method))) h = h.refinePass(_prob).doAll(_response, newWeights); newWeights.remove(); //sanity check quantiles assert (_quantiles[i] <= _response.max() + 1e-6); assert (_quantiles[i] >= _response.min() - 1e-6); } } if (_weights != weights) weights.remove(); tryComplete(); } private static class KeepOnlyOneStrata extends MRTask<KeepOnlyOneStrata> { KeepOnlyOneStrata(int stratumToKeep) { this.stratumToKeep = stratumToKeep; } int stratumToKeep; @Override public void map(Chunk strata, Chunk newW) { for (int i=0; i<strata._len; ++i) { // Log.info("NID:" + ((int) strata.at8(i))); if ((int) strata.at8(i) != stratumToKeep) newW.set(i, 0); } } } } // ------------------------------------------------------------------------- private final static class Histo extends MRTask<Histo> { private static final int NBINS = 1024; // Default bin count private final int _nbins; // Actual bin count private final double _lb; // Lower bound of bin[0] private final double _step; // Step-size per-bin private final double _start_row; // Starting cumulative count of weighted rows for this lower-bound private final double _nrows; // Total datasets (weighted) rows private final boolean _isInt; // Column only holds ints // Big Data output result double _bins[/*nbins*/]; // Weighted count of rows in each bin double _mins[/*nbins*/]; // Smallest element<SUF> double _maxs[/*nbins*/]; // Largest element in bin private Histo(double lb, double ub, double start_row, double nrows, boolean isInt) { boolean is_int = (isInt && (ub - lb < NBINS)); _nbins = is_int ? (int) (ub - lb + 1) : NBINS; _lb = lb; double ulp = Math.ulp(Math.max(Math.abs(lb), Math.abs(ub))); _step = is_int ? 1 : (ub + ulp - lb) / _nbins; _start_row = start_row; _nrows = nrows; _isInt = isInt; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("range : " + _lb + " ... " + (_lb + _nbins * _step)); sb.append("\npsum0 : " + _start_row); sb.append("\ncounts: " + Arrays.toString(_bins)); sb.append("\nmaxs : " + Arrays.toString(_maxs)); sb.append("\nmins : " + Arrays.toString(_mins)); sb.append("\n"); return sb.toString(); } @Override public void map(Chunk chk, Chunk weight) { _bins = new double[_nbins]; _mins = new double[_nbins]; _maxs = new double[_nbins]; Arrays.fill(_mins, Double.MAX_VALUE); Arrays.fill(_maxs, -Double.MAX_VALUE); double d; for (int row = 0; row < chk._len; row++) { double w = weight.atd(row); if (w == 0) continue; if (!Double.isNaN(d = chk.atd(row))) { // na.rm=true double idx = (d - _lb) / _step; if (!(0.0 <= idx && idx < _bins.length)) continue; int i = (int) idx; if (_bins[i] == 0) _mins[i] = _maxs[i] = d; // Capture unique value else { if (d < _mins[i]) _mins[i] = d; if (d > _maxs[i]) _maxs[i] = d; } _bins[i] += w; // Bump row counts by row weight } } } @Override public void map(Chunk chk) { map(chk, new C0DChunk(1, chk.len())); } @Override public void reduce(Histo h) { for (int i = 0; i < _nbins; i++) { // Keep min/max if (_mins[i] > h._mins[i]) _mins[i] = h._mins[i]; if (_maxs[i] < h._maxs[i]) _maxs[i] = h._maxs[i]; } ArrayUtils.add(_bins, h._bins); } /** @return Quantile for probability prob, or NaN if another pass is needed. */ double findQuantile( double prob, QuantileModel.CombineMethod method ) { double p2 = prob*(_nrows-1); // Desired fractional row number for this probability long r2 = (long)p2; int loidx = findBin(r2); // Find bin holding low value double lo = (loidx == _nbins) ? binEdge(_nbins) : _maxs[loidx]; if( loidx<_nbins && r2==p2 && _mins[loidx]==lo ) return lo; // Exact row number, exact bin? Then quantile is exact long r3 = r2+1; int hiidx = findBin(r3); // Find bin holding high value double hi = (hiidx == _nbins) ? binEdge(_nbins) : _mins[hiidx]; if( loidx==hiidx ) // Somewhere in the same bin? return (lo==hi) ? lo : Double.NaN; // Only if bin is constant, otherwise must refine the bin // Split across bins - the interpolate between the hi of the lo bin, and // the lo of the hi bin return computeQuantile(lo,hi,r2,_nrows,prob,method); } private double binEdge( int idx ) { return _lb+_step*idx; } // bin for row; can be _nbins if just off the end (normally expect 0 to nbins-1) // row == position in (weighted) population private int findBin( double row ) { long sum = (long)_start_row; for( int i=0; i<_nbins; i++ ) if( (long)row < (sum += _bins[i]) ) return i; return _nbins; } // Run another pass over the data, with refined endpoints, to home in on // the exact elements for this probability. Histo refinePass( double prob ) { double prow = prob*(_nrows-1); // Desired fractional row number for this probability long lorow = (long)prow; // Lower integral row number int loidx = findBin(lorow); // Find bin holding low value // If loidx is the last bin, then high must be also the last bin - and we // have an exact quantile (equal to the high bin) and we didn't need // another refinement pass assert loidx < _nbins; double lo = _mins[loidx]; // Lower end of range to explore // If probability does not hit an exact row, we need the elements on // either side - so the next row up from the low row long hirow = lorow==prow ? lorow : lorow+1; int hiidx = findBin(hirow); // Find bin holding high value // Upper end of range to explore - except at the very high end cap double hi = hiidx==_nbins ? binEdge(_nbins) : _maxs[hiidx]; long sum = (long)_start_row; for( int i=0; i<loidx; i++ ) sum += _bins[i]; return new Histo(lo,hi,sum,_nrows,_isInt); } } /** Compute the correct final quantile from these 4 values. If the lo and hi * elements are equal, use them. However if they differ, then there is no * single value which exactly matches the desired quantile. There are * several well-accepted definitions in this case - including picking either * the lo or the hi, or averaging them, or doing a linear interpolation. * @param lo the highest element less than or equal to the desired quantile * @param hi the lowest element greater than or equal to the desired quantile * @param row row number (zero based) of the lo element; high element is +1 * @return desired quantile. */ static double computeQuantile( double lo, double hi, double row, double nrows, double prob, QuantileModel.CombineMethod method ) { if( lo==hi ) return lo; // Equal; pick either if( method == null ) method= QuantileModel.CombineMethod.INTERPOLATE; switch( method ) { case INTERPOLATE: return linearInterpolate(lo,hi,row,nrows,prob); case AVERAGE: return 0.5*(hi+lo); case LOW: return lo; case HIGH: return hi; default: Log.info("Unknown even sample size quantile combination type: " + method + ". Doing linear interpolation."); return linearInterpolate(lo,hi,row,nrows,prob); } } private static double linearInterpolate(double lo, double hi, double row, double nrows, double prob) { // Unequal, linear interpolation double plo = (row+0)/(nrows-1); // Note that row numbers are inclusive on the end point, means we need a -1 double phi = (row+1)/(nrows-1); // Passed in the row number for the low value, high is the next row, so +1 assert plo <= prob && prob <= phi; return lo + (hi-lo)*(prob-plo)/(phi-plo); // Classic linear interpolation } @Override public boolean haveMojo() { return false; } @Override public boolean havePojo() { return false; } public static double calcQuantile(Vec v, double quantile) { Frame fr = new Frame(Key.make(), new String[]{"V"}, new Vec[]{v}); try { DKV.put(fr._key, fr); QuantileModel.QuantileParameters parms = new QuantileModel.QuantileParameters(); parms._train = fr._key; parms._probs = new double[]{quantile}; QuantileModel kmm = new Quantile(parms).trainModelNested(null); kmm.delete(); return kmm._output._quantiles[0][0]; } finally { DKV.remove(fr._key); } } }
198866_34
package hex.quantile; import hex.ModelBuilder; import hex.ModelCategory; import water.*; import water.fvec.*; import water.util.ArrayUtils; import water.util.Log; import java.util.Arrays; /** * Quantile model builder... building a simple QuantileModel */ public class Quantile extends ModelBuilder<QuantileModel,QuantileModel.QuantileParameters,QuantileModel.QuantileOutput> { private int _ncols; @Override protected boolean logMe() { return false; } @Override public boolean isSupervised() { return false; } // Called from Nano thread; start the Quantile Job on a F/J thread public Quantile( QuantileModel.QuantileParameters parms ) { super(parms); init(false); } public Quantile( QuantileModel.QuantileParameters parms, Job job ) { super(parms, job); init(false); } @Override public Driver trainModelImpl() { return new QuantileDriver(); } @Override public ModelCategory[] can_build() { return new ModelCategory[]{ModelCategory.Unknown}; } // any number of chunks is fine - don't rebalance - it's not worth it for a few passes over the data (at most) @Override protected int desiredChunks(final Frame original_fr, boolean local) { return 1; } /** Initialize the ModelBuilder, validating all arguments and preparing the * training frame. This call is expected to be overridden in the subclasses * and each subclass will start with "super.init();". This call is made * by the front-end whenever the GUI is clicked, and needs to be fast; * heavy-weight prep needs to wait for the trainModel() call. * * Validate the probs. */ @Override public void init(boolean expensive) { super.init(expensive); for( double p : _parms._probs ) if( p < 0.0 || p > 1.0 ) error("_probs","Probabilities must be between 0 and 1"); _ncols = train().numCols()-numSpecialCols(); //offset/weights/nfold - should only ever be weights if ( numSpecialCols() == 1 && _weights == null) throw new IllegalArgumentException("The only special Vec that is supported for Quantiles is observation weights."); if ( numSpecialCols() >1 ) throw new IllegalArgumentException("Cannot handle more than 1 special vec (weights)"); } private static class SumWeights extends MRTask<SumWeights> { double sum; @Override public void map(Chunk c, Chunk w) { for (int i=0;i<c.len();++i) if (!c.isNA(i)) { double wt = w.atd(i); // For now: let the user give small weights, results are probably not very good (same as for wtd.quantile in R) // if (wt > 0 && wt < 1) throw new H2OIllegalArgumentException("Quantiles only accepts weights that are either 0 or >= 1."); sum += wt; } } @Override public void reduce(SumWeights mrt) { sum+=mrt.sum; } } // ---------------------- private class QuantileDriver extends Driver { @Override public void computeImpl() { QuantileModel model = null; try { init(true); // The model to be built model = new QuantileModel(dest(), _parms, new QuantileModel.QuantileOutput(Quantile.this)); model._output._parameters = _parms; model._output._quantiles = new double[_ncols][_parms._probs.length]; model.delete_and_lock(_job); // --- // Run the main Quantile Loop Vec vecs[] = train().vecs(); for( int n=0; n<_ncols; n++ ) { if( stop_requested() ) return; // Stopped/cancelled Vec vec = vecs[n]; if (vec.isBad() || vec.isCategorical() || vec.isString() || vec.isTime() || vec.isUUID()) { model._output._quantiles[n] = new double[_parms._probs.length]; Arrays.fill(model._output._quantiles[n], Double.NaN); continue; } double sumRows=_weights == null ? vec.length()-vec.naCnt() : new SumWeights().doAll(vec, _weights).sum; // Compute top-level histogram Histo h1 = new Histo(vec.min(),vec.max(),0,sumRows,vec.isInt()); h1 = _weights==null ? h1.doAll(vec) : h1.doAll(vec, _weights); // For each probability, see if we have it exactly - or else run // passes until we do. for( int p = 0; p < _parms._probs.length; p++ ) { double prob = _parms._probs[p]; Histo h = h1; // Start from the first global histogram model._output._iterations++; // At least one iter per-prob-per-column while( Double.isNaN(model._output._quantiles[n][p] = h.findQuantile(prob,_parms._combine_method)) ) { h = _weights == null ? h.refinePass(prob).doAll(vec) : h.refinePass(prob).doAll(vec, _weights); // Full pass at higher resolution model._output._iterations++; // also count refinement iterations } // Update the model model.update(_job); // Update model in K/V store _job.update(0); // One unit of work } StringBuilder sb = new StringBuilder(); sb.append("Quantile: iter: ").append(model._output._iterations).append(" Qs=").append(Arrays.toString(model._output._quantiles[n])); Log.debug(sb); } } finally { if( model != null ) model.unlock(_job); } } } public static class StratifiedQuantilesTask extends H2O.H2OCountedCompleter<StratifiedQuantilesTask> { // INPUT final double _prob; final Vec _response; //vec to compute quantile for final Vec _weights; //obs weights final Vec _strata; //continuous integer range mapping into the _quantiles[id][] final QuantileModel.CombineMethod _combine_method; // OUTPUT public double[/*strata*/] _quantiles; public int[] _nids; public StratifiedQuantilesTask(H2O.H2OCountedCompleter cc, double prob, Vec response, // response Vec weights, // obs weights Vec strata, // stratification QuantileModel.CombineMethod combine_method) { super(cc); _response = response; _prob=prob; _combine_method=combine_method; _weights=weights; _strata=strata; } @Override public void compute2() { final int strataMin = (int)_strata.min(); final int strataMax = (int)_strata.max(); if (strataMin < 0 && strataMax < 0) { Log.warn("No quantiles can be computed since there are no non-OOB rows."); tryComplete(); return; } final int nstrata = strataMax - strataMin + 1; Log.info("Computing quantiles for (up to) " + nstrata + " different strata."); _quantiles = new double[nstrata]; _nids = new int[nstrata]; Arrays.fill(_quantiles,Double.NaN); Vec weights = _weights != null ? _weights : _response.makeCon(1); for (int i=0;i<nstrata;++i) { //loop over nodes Vec newWeights = weights.makeCopy(); //only keep weights for this stratum (node), set rest to 0 if (_strata!=null) { _nids[i] = strataMin+i; new KeepOnlyOneStrata(_nids[i]).doAll(_strata, newWeights); } double sumRows = new SumWeights().doAll(_response, newWeights).sum; if (sumRows>0) { Histo h = new Histo(_response.min(), _response.max(), 0, sumRows, _response.isInt()); h.doAll(_response, newWeights); while (Double.isNaN(_quantiles[i] = h.findQuantile(_prob, _combine_method))) h = h.refinePass(_prob).doAll(_response, newWeights); newWeights.remove(); //sanity check quantiles assert (_quantiles[i] <= _response.max() + 1e-6); assert (_quantiles[i] >= _response.min() - 1e-6); } } if (_weights != weights) weights.remove(); tryComplete(); } private static class KeepOnlyOneStrata extends MRTask<KeepOnlyOneStrata> { KeepOnlyOneStrata(int stratumToKeep) { this.stratumToKeep = stratumToKeep; } int stratumToKeep; @Override public void map(Chunk strata, Chunk newW) { for (int i=0; i<strata._len; ++i) { // Log.info("NID:" + ((int) strata.at8(i))); if ((int) strata.at8(i) != stratumToKeep) newW.set(i, 0); } } } } // ------------------------------------------------------------------------- private final static class Histo extends MRTask<Histo> { private static final int NBINS = 1024; // Default bin count private final int _nbins; // Actual bin count private final double _lb; // Lower bound of bin[0] private final double _step; // Step-size per-bin private final double _start_row; // Starting cumulative count of weighted rows for this lower-bound private final double _nrows; // Total datasets (weighted) rows private final boolean _isInt; // Column only holds ints // Big Data output result double _bins[/*nbins*/]; // Weighted count of rows in each bin double _mins[/*nbins*/]; // Smallest element in bin double _maxs[/*nbins*/]; // Largest element in bin private Histo(double lb, double ub, double start_row, double nrows, boolean isInt) { boolean is_int = (isInt && (ub - lb < NBINS)); _nbins = is_int ? (int) (ub - lb + 1) : NBINS; _lb = lb; double ulp = Math.ulp(Math.max(Math.abs(lb), Math.abs(ub))); _step = is_int ? 1 : (ub + ulp - lb) / _nbins; _start_row = start_row; _nrows = nrows; _isInt = isInt; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("range : " + _lb + " ... " + (_lb + _nbins * _step)); sb.append("\npsum0 : " + _start_row); sb.append("\ncounts: " + Arrays.toString(_bins)); sb.append("\nmaxs : " + Arrays.toString(_maxs)); sb.append("\nmins : " + Arrays.toString(_mins)); sb.append("\n"); return sb.toString(); } @Override public void map(Chunk chk, Chunk weight) { _bins = new double[_nbins]; _mins = new double[_nbins]; _maxs = new double[_nbins]; Arrays.fill(_mins, Double.MAX_VALUE); Arrays.fill(_maxs, -Double.MAX_VALUE); double d; for (int row = 0; row < chk._len; row++) { double w = weight.atd(row); if (w == 0) continue; if (!Double.isNaN(d = chk.atd(row))) { // na.rm=true double idx = (d - _lb) / _step; if (!(0.0 <= idx && idx < _bins.length)) continue; int i = (int) idx; if (_bins[i] == 0) _mins[i] = _maxs[i] = d; // Capture unique value else { if (d < _mins[i]) _mins[i] = d; if (d > _maxs[i]) _maxs[i] = d; } _bins[i] += w; // Bump row counts by row weight } } } @Override public void map(Chunk chk) { map(chk, new C0DChunk(1, chk.len())); } @Override public void reduce(Histo h) { for (int i = 0; i < _nbins; i++) { // Keep min/max if (_mins[i] > h._mins[i]) _mins[i] = h._mins[i]; if (_maxs[i] < h._maxs[i]) _maxs[i] = h._maxs[i]; } ArrayUtils.add(_bins, h._bins); } /** @return Quantile for probability prob, or NaN if another pass is needed. */ double findQuantile( double prob, QuantileModel.CombineMethod method ) { double p2 = prob*(_nrows-1); // Desired fractional row number for this probability long r2 = (long)p2; int loidx = findBin(r2); // Find bin holding low value double lo = (loidx == _nbins) ? binEdge(_nbins) : _maxs[loidx]; if( loidx<_nbins && r2==p2 && _mins[loidx]==lo ) return lo; // Exact row number, exact bin? Then quantile is exact long r3 = r2+1; int hiidx = findBin(r3); // Find bin holding high value double hi = (hiidx == _nbins) ? binEdge(_nbins) : _mins[hiidx]; if( loidx==hiidx ) // Somewhere in the same bin? return (lo==hi) ? lo : Double.NaN; // Only if bin is constant, otherwise must refine the bin // Split across bins - the interpolate between the hi of the lo bin, and // the lo of the hi bin return computeQuantile(lo,hi,r2,_nrows,prob,method); } private double binEdge( int idx ) { return _lb+_step*idx; } // bin for row; can be _nbins if just off the end (normally expect 0 to nbins-1) // row == position in (weighted) population private int findBin( double row ) { long sum = (long)_start_row; for( int i=0; i<_nbins; i++ ) if( (long)row < (sum += _bins[i]) ) return i; return _nbins; } // Run another pass over the data, with refined endpoints, to home in on // the exact elements for this probability. Histo refinePass( double prob ) { double prow = prob*(_nrows-1); // Desired fractional row number for this probability long lorow = (long)prow; // Lower integral row number int loidx = findBin(lorow); // Find bin holding low value // If loidx is the last bin, then high must be also the last bin - and we // have an exact quantile (equal to the high bin) and we didn't need // another refinement pass assert loidx < _nbins; double lo = _mins[loidx]; // Lower end of range to explore // If probability does not hit an exact row, we need the elements on // either side - so the next row up from the low row long hirow = lorow==prow ? lorow : lorow+1; int hiidx = findBin(hirow); // Find bin holding high value // Upper end of range to explore - except at the very high end cap double hi = hiidx==_nbins ? binEdge(_nbins) : _maxs[hiidx]; long sum = (long)_start_row; for( int i=0; i<loidx; i++ ) sum += _bins[i]; return new Histo(lo,hi,sum,_nrows,_isInt); } } /** Compute the correct final quantile from these 4 values. If the lo and hi * elements are equal, use them. However if they differ, then there is no * single value which exactly matches the desired quantile. There are * several well-accepted definitions in this case - including picking either * the lo or the hi, or averaging them, or doing a linear interpolation. * @param lo the highest element less than or equal to the desired quantile * @param hi the lowest element greater than or equal to the desired quantile * @param row row number (zero based) of the lo element; high element is +1 * @return desired quantile. */ static double computeQuantile( double lo, double hi, double row, double nrows, double prob, QuantileModel.CombineMethod method ) { if( lo==hi ) return lo; // Equal; pick either if( method == null ) method= QuantileModel.CombineMethod.INTERPOLATE; switch( method ) { case INTERPOLATE: return linearInterpolate(lo,hi,row,nrows,prob); case AVERAGE: return 0.5*(hi+lo); case LOW: return lo; case HIGH: return hi; default: Log.info("Unknown even sample size quantile combination type: " + method + ". Doing linear interpolation."); return linearInterpolate(lo,hi,row,nrows,prob); } } private static double linearInterpolate(double lo, double hi, double row, double nrows, double prob) { // Unequal, linear interpolation double plo = (row+0)/(nrows-1); // Note that row numbers are inclusive on the end point, means we need a -1 double phi = (row+1)/(nrows-1); // Passed in the row number for the low value, high is the next row, so +1 assert plo <= prob && prob <= phi; return lo + (hi-lo)*(prob-plo)/(phi-plo); // Classic linear interpolation } @Override public boolean haveMojo() { return false; } @Override public boolean havePojo() { return false; } public static double calcQuantile(Vec v, double quantile) { Frame fr = new Frame(Key.make(), new String[]{"V"}, new Vec[]{v}); try { DKV.put(fr._key, fr); QuantileModel.QuantileParameters parms = new QuantileModel.QuantileParameters(); parms._train = fr._key; parms._probs = new double[]{quantile}; QuantileModel kmm = new Quantile(parms).trainModelNested(null); kmm.delete(); return kmm._output._quantiles[0][0]; } finally { DKV.remove(fr._key); } } }
h2oai/h2o-3
h2o-core/src/main/java/hex/quantile/Quantile.java
4,771
// Largest element in bin
line_comment
nl
package hex.quantile; import hex.ModelBuilder; import hex.ModelCategory; import water.*; import water.fvec.*; import water.util.ArrayUtils; import water.util.Log; import java.util.Arrays; /** * Quantile model builder... building a simple QuantileModel */ public class Quantile extends ModelBuilder<QuantileModel,QuantileModel.QuantileParameters,QuantileModel.QuantileOutput> { private int _ncols; @Override protected boolean logMe() { return false; } @Override public boolean isSupervised() { return false; } // Called from Nano thread; start the Quantile Job on a F/J thread public Quantile( QuantileModel.QuantileParameters parms ) { super(parms); init(false); } public Quantile( QuantileModel.QuantileParameters parms, Job job ) { super(parms, job); init(false); } @Override public Driver trainModelImpl() { return new QuantileDriver(); } @Override public ModelCategory[] can_build() { return new ModelCategory[]{ModelCategory.Unknown}; } // any number of chunks is fine - don't rebalance - it's not worth it for a few passes over the data (at most) @Override protected int desiredChunks(final Frame original_fr, boolean local) { return 1; } /** Initialize the ModelBuilder, validating all arguments and preparing the * training frame. This call is expected to be overridden in the subclasses * and each subclass will start with "super.init();". This call is made * by the front-end whenever the GUI is clicked, and needs to be fast; * heavy-weight prep needs to wait for the trainModel() call. * * Validate the probs. */ @Override public void init(boolean expensive) { super.init(expensive); for( double p : _parms._probs ) if( p < 0.0 || p > 1.0 ) error("_probs","Probabilities must be between 0 and 1"); _ncols = train().numCols()-numSpecialCols(); //offset/weights/nfold - should only ever be weights if ( numSpecialCols() == 1 && _weights == null) throw new IllegalArgumentException("The only special Vec that is supported for Quantiles is observation weights."); if ( numSpecialCols() >1 ) throw new IllegalArgumentException("Cannot handle more than 1 special vec (weights)"); } private static class SumWeights extends MRTask<SumWeights> { double sum; @Override public void map(Chunk c, Chunk w) { for (int i=0;i<c.len();++i) if (!c.isNA(i)) { double wt = w.atd(i); // For now: let the user give small weights, results are probably not very good (same as for wtd.quantile in R) // if (wt > 0 && wt < 1) throw new H2OIllegalArgumentException("Quantiles only accepts weights that are either 0 or >= 1."); sum += wt; } } @Override public void reduce(SumWeights mrt) { sum+=mrt.sum; } } // ---------------------- private class QuantileDriver extends Driver { @Override public void computeImpl() { QuantileModel model = null; try { init(true); // The model to be built model = new QuantileModel(dest(), _parms, new QuantileModel.QuantileOutput(Quantile.this)); model._output._parameters = _parms; model._output._quantiles = new double[_ncols][_parms._probs.length]; model.delete_and_lock(_job); // --- // Run the main Quantile Loop Vec vecs[] = train().vecs(); for( int n=0; n<_ncols; n++ ) { if( stop_requested() ) return; // Stopped/cancelled Vec vec = vecs[n]; if (vec.isBad() || vec.isCategorical() || vec.isString() || vec.isTime() || vec.isUUID()) { model._output._quantiles[n] = new double[_parms._probs.length]; Arrays.fill(model._output._quantiles[n], Double.NaN); continue; } double sumRows=_weights == null ? vec.length()-vec.naCnt() : new SumWeights().doAll(vec, _weights).sum; // Compute top-level histogram Histo h1 = new Histo(vec.min(),vec.max(),0,sumRows,vec.isInt()); h1 = _weights==null ? h1.doAll(vec) : h1.doAll(vec, _weights); // For each probability, see if we have it exactly - or else run // passes until we do. for( int p = 0; p < _parms._probs.length; p++ ) { double prob = _parms._probs[p]; Histo h = h1; // Start from the first global histogram model._output._iterations++; // At least one iter per-prob-per-column while( Double.isNaN(model._output._quantiles[n][p] = h.findQuantile(prob,_parms._combine_method)) ) { h = _weights == null ? h.refinePass(prob).doAll(vec) : h.refinePass(prob).doAll(vec, _weights); // Full pass at higher resolution model._output._iterations++; // also count refinement iterations } // Update the model model.update(_job); // Update model in K/V store _job.update(0); // One unit of work } StringBuilder sb = new StringBuilder(); sb.append("Quantile: iter: ").append(model._output._iterations).append(" Qs=").append(Arrays.toString(model._output._quantiles[n])); Log.debug(sb); } } finally { if( model != null ) model.unlock(_job); } } } public static class StratifiedQuantilesTask extends H2O.H2OCountedCompleter<StratifiedQuantilesTask> { // INPUT final double _prob; final Vec _response; //vec to compute quantile for final Vec _weights; //obs weights final Vec _strata; //continuous integer range mapping into the _quantiles[id][] final QuantileModel.CombineMethod _combine_method; // OUTPUT public double[/*strata*/] _quantiles; public int[] _nids; public StratifiedQuantilesTask(H2O.H2OCountedCompleter cc, double prob, Vec response, // response Vec weights, // obs weights Vec strata, // stratification QuantileModel.CombineMethod combine_method) { super(cc); _response = response; _prob=prob; _combine_method=combine_method; _weights=weights; _strata=strata; } @Override public void compute2() { final int strataMin = (int)_strata.min(); final int strataMax = (int)_strata.max(); if (strataMin < 0 && strataMax < 0) { Log.warn("No quantiles can be computed since there are no non-OOB rows."); tryComplete(); return; } final int nstrata = strataMax - strataMin + 1; Log.info("Computing quantiles for (up to) " + nstrata + " different strata."); _quantiles = new double[nstrata]; _nids = new int[nstrata]; Arrays.fill(_quantiles,Double.NaN); Vec weights = _weights != null ? _weights : _response.makeCon(1); for (int i=0;i<nstrata;++i) { //loop over nodes Vec newWeights = weights.makeCopy(); //only keep weights for this stratum (node), set rest to 0 if (_strata!=null) { _nids[i] = strataMin+i; new KeepOnlyOneStrata(_nids[i]).doAll(_strata, newWeights); } double sumRows = new SumWeights().doAll(_response, newWeights).sum; if (sumRows>0) { Histo h = new Histo(_response.min(), _response.max(), 0, sumRows, _response.isInt()); h.doAll(_response, newWeights); while (Double.isNaN(_quantiles[i] = h.findQuantile(_prob, _combine_method))) h = h.refinePass(_prob).doAll(_response, newWeights); newWeights.remove(); //sanity check quantiles assert (_quantiles[i] <= _response.max() + 1e-6); assert (_quantiles[i] >= _response.min() - 1e-6); } } if (_weights != weights) weights.remove(); tryComplete(); } private static class KeepOnlyOneStrata extends MRTask<KeepOnlyOneStrata> { KeepOnlyOneStrata(int stratumToKeep) { this.stratumToKeep = stratumToKeep; } int stratumToKeep; @Override public void map(Chunk strata, Chunk newW) { for (int i=0; i<strata._len; ++i) { // Log.info("NID:" + ((int) strata.at8(i))); if ((int) strata.at8(i) != stratumToKeep) newW.set(i, 0); } } } } // ------------------------------------------------------------------------- private final static class Histo extends MRTask<Histo> { private static final int NBINS = 1024; // Default bin count private final int _nbins; // Actual bin count private final double _lb; // Lower bound of bin[0] private final double _step; // Step-size per-bin private final double _start_row; // Starting cumulative count of weighted rows for this lower-bound private final double _nrows; // Total datasets (weighted) rows private final boolean _isInt; // Column only holds ints // Big Data output result double _bins[/*nbins*/]; // Weighted count of rows in each bin double _mins[/*nbins*/]; // Smallest element in bin double _maxs[/*nbins*/]; // Largest <SUF> private Histo(double lb, double ub, double start_row, double nrows, boolean isInt) { boolean is_int = (isInt && (ub - lb < NBINS)); _nbins = is_int ? (int) (ub - lb + 1) : NBINS; _lb = lb; double ulp = Math.ulp(Math.max(Math.abs(lb), Math.abs(ub))); _step = is_int ? 1 : (ub + ulp - lb) / _nbins; _start_row = start_row; _nrows = nrows; _isInt = isInt; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("range : " + _lb + " ... " + (_lb + _nbins * _step)); sb.append("\npsum0 : " + _start_row); sb.append("\ncounts: " + Arrays.toString(_bins)); sb.append("\nmaxs : " + Arrays.toString(_maxs)); sb.append("\nmins : " + Arrays.toString(_mins)); sb.append("\n"); return sb.toString(); } @Override public void map(Chunk chk, Chunk weight) { _bins = new double[_nbins]; _mins = new double[_nbins]; _maxs = new double[_nbins]; Arrays.fill(_mins, Double.MAX_VALUE); Arrays.fill(_maxs, -Double.MAX_VALUE); double d; for (int row = 0; row < chk._len; row++) { double w = weight.atd(row); if (w == 0) continue; if (!Double.isNaN(d = chk.atd(row))) { // na.rm=true double idx = (d - _lb) / _step; if (!(0.0 <= idx && idx < _bins.length)) continue; int i = (int) idx; if (_bins[i] == 0) _mins[i] = _maxs[i] = d; // Capture unique value else { if (d < _mins[i]) _mins[i] = d; if (d > _maxs[i]) _maxs[i] = d; } _bins[i] += w; // Bump row counts by row weight } } } @Override public void map(Chunk chk) { map(chk, new C0DChunk(1, chk.len())); } @Override public void reduce(Histo h) { for (int i = 0; i < _nbins; i++) { // Keep min/max if (_mins[i] > h._mins[i]) _mins[i] = h._mins[i]; if (_maxs[i] < h._maxs[i]) _maxs[i] = h._maxs[i]; } ArrayUtils.add(_bins, h._bins); } /** @return Quantile for probability prob, or NaN if another pass is needed. */ double findQuantile( double prob, QuantileModel.CombineMethod method ) { double p2 = prob*(_nrows-1); // Desired fractional row number for this probability long r2 = (long)p2; int loidx = findBin(r2); // Find bin holding low value double lo = (loidx == _nbins) ? binEdge(_nbins) : _maxs[loidx]; if( loidx<_nbins && r2==p2 && _mins[loidx]==lo ) return lo; // Exact row number, exact bin? Then quantile is exact long r3 = r2+1; int hiidx = findBin(r3); // Find bin holding high value double hi = (hiidx == _nbins) ? binEdge(_nbins) : _mins[hiidx]; if( loidx==hiidx ) // Somewhere in the same bin? return (lo==hi) ? lo : Double.NaN; // Only if bin is constant, otherwise must refine the bin // Split across bins - the interpolate between the hi of the lo bin, and // the lo of the hi bin return computeQuantile(lo,hi,r2,_nrows,prob,method); } private double binEdge( int idx ) { return _lb+_step*idx; } // bin for row; can be _nbins if just off the end (normally expect 0 to nbins-1) // row == position in (weighted) population private int findBin( double row ) { long sum = (long)_start_row; for( int i=0; i<_nbins; i++ ) if( (long)row < (sum += _bins[i]) ) return i; return _nbins; } // Run another pass over the data, with refined endpoints, to home in on // the exact elements for this probability. Histo refinePass( double prob ) { double prow = prob*(_nrows-1); // Desired fractional row number for this probability long lorow = (long)prow; // Lower integral row number int loidx = findBin(lorow); // Find bin holding low value // If loidx is the last bin, then high must be also the last bin - and we // have an exact quantile (equal to the high bin) and we didn't need // another refinement pass assert loidx < _nbins; double lo = _mins[loidx]; // Lower end of range to explore // If probability does not hit an exact row, we need the elements on // either side - so the next row up from the low row long hirow = lorow==prow ? lorow : lorow+1; int hiidx = findBin(hirow); // Find bin holding high value // Upper end of range to explore - except at the very high end cap double hi = hiidx==_nbins ? binEdge(_nbins) : _maxs[hiidx]; long sum = (long)_start_row; for( int i=0; i<loidx; i++ ) sum += _bins[i]; return new Histo(lo,hi,sum,_nrows,_isInt); } } /** Compute the correct final quantile from these 4 values. If the lo and hi * elements are equal, use them. However if they differ, then there is no * single value which exactly matches the desired quantile. There are * several well-accepted definitions in this case - including picking either * the lo or the hi, or averaging them, or doing a linear interpolation. * @param lo the highest element less than or equal to the desired quantile * @param hi the lowest element greater than or equal to the desired quantile * @param row row number (zero based) of the lo element; high element is +1 * @return desired quantile. */ static double computeQuantile( double lo, double hi, double row, double nrows, double prob, QuantileModel.CombineMethod method ) { if( lo==hi ) return lo; // Equal; pick either if( method == null ) method= QuantileModel.CombineMethod.INTERPOLATE; switch( method ) { case INTERPOLATE: return linearInterpolate(lo,hi,row,nrows,prob); case AVERAGE: return 0.5*(hi+lo); case LOW: return lo; case HIGH: return hi; default: Log.info("Unknown even sample size quantile combination type: " + method + ". Doing linear interpolation."); return linearInterpolate(lo,hi,row,nrows,prob); } } private static double linearInterpolate(double lo, double hi, double row, double nrows, double prob) { // Unequal, linear interpolation double plo = (row+0)/(nrows-1); // Note that row numbers are inclusive on the end point, means we need a -1 double phi = (row+1)/(nrows-1); // Passed in the row number for the low value, high is the next row, so +1 assert plo <= prob && prob <= phi; return lo + (hi-lo)*(prob-plo)/(phi-plo); // Classic linear interpolation } @Override public boolean haveMojo() { return false; } @Override public boolean havePojo() { return false; } public static double calcQuantile(Vec v, double quantile) { Frame fr = new Frame(Key.make(), new String[]{"V"}, new Vec[]{v}); try { DKV.put(fr._key, fr); QuantileModel.QuantileParameters parms = new QuantileModel.QuantileParameters(); parms._train = fr._key; parms._probs = new double[]{quantile}; QuantileModel kmm = new Quantile(parms).trainModelNested(null); kmm.delete(); return kmm._output._quantiles[0][0]; } finally { DKV.remove(fr._key); } } }
198875_8
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.remoting.zookeeper; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; /** * AbstractZookeeperTransporter is abstract implements of ZookeeperTransporter. * <p> * If you want to extends this, implements createZookeeperClient. */ public abstract class AbstractZookeeperTransporter implements ZookeeperTransporter { private static final Logger logger = LoggerFactory.getLogger(ZookeeperTransporter.class); private final Map<String, ZookeeperClient> zookeeperClientMap = new ConcurrentHashMap<>(); /** * share connect for registry, metadata, etc.. * <p> * Make sure the connection is connected. * * @param url * @return */ @Override public ZookeeperClient connect(URL url) { ZookeeperClient zookeeperClient; // address format: {[username:password@]address} List<String> addressList = getURLBackupAddress(url); // The field define the zookeeper server , including protocol, host, port, username, password if ((zookeeperClient = fetchAndUpdateZookeeperClientCache(addressList)) != null && zookeeperClient.isConnected()) { logger.info("find valid zookeeper client from the cache for address: " + url); return zookeeperClient; } // avoid creating too many connections, so add lock synchronized (zookeeperClientMap) { if ((zookeeperClient = fetchAndUpdateZookeeperClientCache(addressList)) != null && zookeeperClient.isConnected()) { logger.info("find valid zookeeper client from the cache for address: " + url); return zookeeperClient; } zookeeperClient = createZookeeperClient(url); logger.info("No valid zookeeper client found from cache, therefore create a new client for url. " + url); writeToClientMap(addressList, zookeeperClient); } return zookeeperClient; } /** * @param url the url that will create zookeeper connection . * The url in AbstractZookeeperTransporter#connect parameter is rewritten by this one. * such as: zookeeper://127.0.0.1:2181/org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter * @return */ protected abstract ZookeeperClient createZookeeperClient(URL url); /** * get the ZookeeperClient from cache, the ZookeeperClient must be connected. * <p> * It is not private method for unit test. * * @param addressList * @return */ public ZookeeperClient fetchAndUpdateZookeeperClientCache(List<String> addressList) { ZookeeperClient zookeeperClient = null; for (String address : addressList) { if ((zookeeperClient = zookeeperClientMap.get(address)) != null && zookeeperClient.isConnected()) { break; } } if (zookeeperClient != null && zookeeperClient.isConnected()) { writeToClientMap(addressList, zookeeperClient); } return zookeeperClient; } /** * get all zookeeper urls (such as :zookeeper://127.0.0.1:2181?127.0.0.1:8989,127.0.0.1:9999) * * @param url such as:zookeeper://127.0.0.1:2181?127.0.0.1:8989,127.0.0.1:9999 * @return such as 127.0.0.1:2181,127.0.0.1:8989,127.0.0.1:9999 */ public List<String> getURLBackupAddress(URL url) { List<String> addressList = new ArrayList<String>(); addressList.add(url.getAddress()); addressList.addAll(url.getParameter(RemotingConstants.BACKUP_KEY, Collections.EMPTY_LIST)); String authPrefix = null; if (StringUtils.isNotEmpty(url.getUsername())) { StringBuilder buf = new StringBuilder(); buf.append(url.getUsername()); if (StringUtils.isNotEmpty(url.getPassword())) { buf.append(":"); buf.append(url.getPassword()); } buf.append("@"); authPrefix = buf.toString(); } if (StringUtils.isNotEmpty(authPrefix)) { List<String> authedAddressList = new ArrayList<>(addressList.size()); for (String addr : addressList) { authedAddressList.add(authPrefix + addr); } return authedAddressList; } return addressList; } /** * write address-ZookeeperClient relationship to Map * * @param addressList * @param zookeeperClient */ void writeToClientMap(List<String> addressList, ZookeeperClient zookeeperClient) { for (String address : addressList) { zookeeperClientMap.put(address, zookeeperClient); } } /** * redefine the url for zookeeper. just keep protocol, username, password, host, port, and individual parameter. * * @param url * @return */ URL toClientURL(URL url) { Map<String, String> parameterMap = new HashMap<>(); // for CuratorZookeeperClient if (url.getParameter(TIMEOUT_KEY) != null) { parameterMap.put(TIMEOUT_KEY, url.getParameter(TIMEOUT_KEY)); } if (url.getParameter(RemotingConstants.BACKUP_KEY) != null) { parameterMap.put(RemotingConstants.BACKUP_KEY, url.getParameter(RemotingConstants.BACKUP_KEY)); } return new URL(url.getProtocol(), url.getUsername(), url.getPassword(), url.getHost(), url.getPort(), ZookeeperTransporter.class.getName(), parameterMap); } /** * for unit test * * @return */ public Map<String, ZookeeperClient> getZookeeperClientMap() { return zookeeperClientMap; } }
apache/dubbo
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/AbstractZookeeperTransporter.java
1,798
/** * get all zookeeper urls (such as :zookeeper://127.0.0.1:2181?127.0.0.1:8989,127.0.0.1:9999) * * @param url such as:zookeeper://127.0.0.1:2181?127.0.0.1:8989,127.0.0.1:9999 * @return such as 127.0.0.1:2181,127.0.0.1:8989,127.0.0.1:9999 */
block_comment
nl
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.remoting.zookeeper; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; /** * AbstractZookeeperTransporter is abstract implements of ZookeeperTransporter. * <p> * If you want to extends this, implements createZookeeperClient. */ public abstract class AbstractZookeeperTransporter implements ZookeeperTransporter { private static final Logger logger = LoggerFactory.getLogger(ZookeeperTransporter.class); private final Map<String, ZookeeperClient> zookeeperClientMap = new ConcurrentHashMap<>(); /** * share connect for registry, metadata, etc.. * <p> * Make sure the connection is connected. * * @param url * @return */ @Override public ZookeeperClient connect(URL url) { ZookeeperClient zookeeperClient; // address format: {[username:password@]address} List<String> addressList = getURLBackupAddress(url); // The field define the zookeeper server , including protocol, host, port, username, password if ((zookeeperClient = fetchAndUpdateZookeeperClientCache(addressList)) != null && zookeeperClient.isConnected()) { logger.info("find valid zookeeper client from the cache for address: " + url); return zookeeperClient; } // avoid creating too many connections, so add lock synchronized (zookeeperClientMap) { if ((zookeeperClient = fetchAndUpdateZookeeperClientCache(addressList)) != null && zookeeperClient.isConnected()) { logger.info("find valid zookeeper client from the cache for address: " + url); return zookeeperClient; } zookeeperClient = createZookeeperClient(url); logger.info("No valid zookeeper client found from cache, therefore create a new client for url. " + url); writeToClientMap(addressList, zookeeperClient); } return zookeeperClient; } /** * @param url the url that will create zookeeper connection . * The url in AbstractZookeeperTransporter#connect parameter is rewritten by this one. * such as: zookeeper://127.0.0.1:2181/org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter * @return */ protected abstract ZookeeperClient createZookeeperClient(URL url); /** * get the ZookeeperClient from cache, the ZookeeperClient must be connected. * <p> * It is not private method for unit test. * * @param addressList * @return */ public ZookeeperClient fetchAndUpdateZookeeperClientCache(List<String> addressList) { ZookeeperClient zookeeperClient = null; for (String address : addressList) { if ((zookeeperClient = zookeeperClientMap.get(address)) != null && zookeeperClient.isConnected()) { break; } } if (zookeeperClient != null && zookeeperClient.isConnected()) { writeToClientMap(addressList, zookeeperClient); } return zookeeperClient; } /** * get all zookeeper<SUF>*/ public List<String> getURLBackupAddress(URL url) { List<String> addressList = new ArrayList<String>(); addressList.add(url.getAddress()); addressList.addAll(url.getParameter(RemotingConstants.BACKUP_KEY, Collections.EMPTY_LIST)); String authPrefix = null; if (StringUtils.isNotEmpty(url.getUsername())) { StringBuilder buf = new StringBuilder(); buf.append(url.getUsername()); if (StringUtils.isNotEmpty(url.getPassword())) { buf.append(":"); buf.append(url.getPassword()); } buf.append("@"); authPrefix = buf.toString(); } if (StringUtils.isNotEmpty(authPrefix)) { List<String> authedAddressList = new ArrayList<>(addressList.size()); for (String addr : addressList) { authedAddressList.add(authPrefix + addr); } return authedAddressList; } return addressList; } /** * write address-ZookeeperClient relationship to Map * * @param addressList * @param zookeeperClient */ void writeToClientMap(List<String> addressList, ZookeeperClient zookeeperClient) { for (String address : addressList) { zookeeperClientMap.put(address, zookeeperClient); } } /** * redefine the url for zookeeper. just keep protocol, username, password, host, port, and individual parameter. * * @param url * @return */ URL toClientURL(URL url) { Map<String, String> parameterMap = new HashMap<>(); // for CuratorZookeeperClient if (url.getParameter(TIMEOUT_KEY) != null) { parameterMap.put(TIMEOUT_KEY, url.getParameter(TIMEOUT_KEY)); } if (url.getParameter(RemotingConstants.BACKUP_KEY) != null) { parameterMap.put(RemotingConstants.BACKUP_KEY, url.getParameter(RemotingConstants.BACKUP_KEY)); } return new URL(url.getProtocol(), url.getUsername(), url.getPassword(), url.getHost(), url.getPort(), ZookeeperTransporter.class.getName(), parameterMap); } /** * for unit test * * @return */ public Map<String, ZookeeperClient> getZookeeperClientMap() { return zookeeperClientMap; } }
198879_1
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.registry.zookeeper; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Inject; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.support.AbstractRegistryFactory; import org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter; /** * ZookeeperRegistryFactory. */ public class ZookeeperRegistryFactory extends AbstractRegistryFactory { private ZookeeperTransporter zookeeperTransporter; public ZookeeperRegistryFactory() { this.zookeeperTransporter = ZookeeperTransporter.getExtension(); } /** * Invisible injection of zookeeper client via IOC/SPI * * @param zookeeperTransporter */ @Inject(enable = false) public void setZookeeperTransporter(ZookeeperTransporter zookeeperTransporter) { this.zookeeperTransporter = zookeeperTransporter; } @Override public Registry createRegistry(URL url) { return new ZookeeperRegistry(url, zookeeperTransporter); } }
apache/dubbo
dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistryFactory.java
464
/** * Invisible injection of zookeeper client via IOC/SPI * * @param zookeeperTransporter */
block_comment
nl
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.registry.zookeeper; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Inject; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.support.AbstractRegistryFactory; import org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter; /** * ZookeeperRegistryFactory. */ public class ZookeeperRegistryFactory extends AbstractRegistryFactory { private ZookeeperTransporter zookeeperTransporter; public ZookeeperRegistryFactory() { this.zookeeperTransporter = ZookeeperTransporter.getExtension(); } /** * Invisible injection of<SUF>*/ @Inject(enable = false) public void setZookeeperTransporter(ZookeeperTransporter zookeeperTransporter) { this.zookeeperTransporter = zookeeperTransporter; } @Override public Registry createRegistry(URL url) { return new ZookeeperRegistry(url, zookeeperTransporter); } }
198883_10
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.flink.configuration; import org.apache.flink.annotation.docs.Documentation; import org.apache.flink.configuration.description.Description; import org.apache.flink.configuration.description.TextElement; import java.time.Duration; import java.util.Map; import static org.apache.flink.configuration.ConfigOptions.key; import static org.apache.flink.configuration.description.LinkElement.link; import static org.apache.flink.configuration.description.TextElement.text; /** The set of configuration options relating to high-availability settings. */ public class HighAvailabilityOptions { // ------------------------------------------------------------------------ // Required High Availability Options // ------------------------------------------------------------------------ /** * Defines high-availability mode used for the cluster execution. A value of "NONE" signals no * highly available setup. To enable high-availability, set this mode to "ZOOKEEPER" or * "KUBERNETES". Can also be set to the FQN of the HighAvailability factory class. */ @Documentation.Section(value = Documentation.Sections.COMMON_HIGH_AVAILABILITY, position = 1) public static final ConfigOption<String> HA_MODE = key("high-availability.type") .stringType() .defaultValue("NONE") .withDeprecatedKeys("recovery.mode", "high-availability") .withDescription( "Defines high-availability mode used for cluster execution." + " To enable high-availability, set this mode to \"ZOOKEEPER\", \"KUBERNETES\", or specify the fully qualified name of the factory class."); /** * The ID of the Flink cluster, used to separate multiple Flink clusters Needs to be set for * standalone clusters, is automatically inferred in YARN. */ @Documentation.Section(Documentation.Sections.COMMON_HIGH_AVAILABILITY) public static final ConfigOption<String> HA_CLUSTER_ID = key("high-availability.cluster-id") .stringType() .defaultValue("/default") .withDeprecatedKeys( "high-availability.zookeeper.path.namespace", "recovery.zookeeper.path.namespace") .withDescription( "The ID of the Flink cluster, used to separate multiple Flink clusters from each other." + " Needs to be set for standalone clusters but is automatically inferred in YARN."); /** File system path (URI) where Flink persists metadata in high-availability setups. */ @Documentation.Section(Documentation.Sections.COMMON_HIGH_AVAILABILITY) public static final ConfigOption<String> HA_STORAGE_PATH = key("high-availability.storageDir") .stringType() .noDefaultValue() .withDeprecatedKeys( "high-availability.zookeeper.storageDir", "recovery.zookeeper.storageDir") .withDescription( "File system path (URI) where Flink persists metadata in high-availability setups."); // ------------------------------------------------------------------------ // Recovery Options // ------------------------------------------------------------------------ /** Optional port (range) used by the job manager in high-availability mode. */ @Documentation.Section(Documentation.Sections.EXPERT_HIGH_AVAILABILITY) public static final ConfigOption<String> HA_JOB_MANAGER_PORT_RANGE = key("high-availability.jobmanager.port") .stringType() .defaultValue("0") .withDeprecatedKeys("recovery.jobmanager.port") .withDescription( "The port (range) used by the Flink Master for its RPC connections in highly-available setups. " + "In highly-available setups, this value is used instead of '" + JobManagerOptions.PORT.key() + "'." + "A value of '0' means that a random free port is chosen. TaskManagers discover this port through " + "the high-availability services (leader election), so a random port or a port range works " + "without requiring any additional means of service discovery."); // ------------------------------------------------------------------------ // ZooKeeper Options // ------------------------------------------------------------------------ /** * The ZooKeeper quorum to use, when running Flink in a high-availability mode with ZooKeeper. */ @Documentation.Section(Documentation.Sections.COMMON_HIGH_AVAILABILITY_ZOOKEEPER) public static final ConfigOption<String> HA_ZOOKEEPER_QUORUM = key("high-availability.zookeeper.quorum") .stringType() .noDefaultValue() .withDeprecatedKeys("recovery.zookeeper.quorum") .withDescription( "The ZooKeeper quorum to use, when running Flink in a high-availability mode with ZooKeeper."); /** The root path under which Flink stores its entries in ZooKeeper. */ @Documentation.Section(Documentation.Sections.COMMON_HIGH_AVAILABILITY_ZOOKEEPER) public static final ConfigOption<String> HA_ZOOKEEPER_ROOT = key("high-availability.zookeeper.path.root") .stringType() .defaultValue("/flink") .withDeprecatedKeys("recovery.zookeeper.path.root") .withDescription( "The root path under which Flink stores its entries in ZooKeeper."); /** ZooKeeper root path (ZNode) for job graphs. */ @Documentation.Section(Documentation.Sections.EXPERT_ZOOKEEPER_HIGH_AVAILABILITY) public static final ConfigOption<String> HA_ZOOKEEPER_JOBGRAPHS_PATH = key("high-availability.zookeeper.path.jobgraphs") .stringType() .defaultValue("/jobgraphs") .withDeprecatedKeys("recovery.zookeeper.path.jobgraphs") .withDescription("ZooKeeper root path (ZNode) for job graphs"); // ------------------------------------------------------------------------ // ZooKeeper Client Settings // ------------------------------------------------------------------------ @Documentation.Section(Documentation.Sections.EXPERT_ZOOKEEPER_HIGH_AVAILABILITY) public static final ConfigOption<Integer> ZOOKEEPER_SESSION_TIMEOUT = key("high-availability.zookeeper.client.session-timeout") .intType() .defaultValue(60000) .withDeprecatedKeys("recovery.zookeeper.client.session-timeout") .withDescription( "Defines the session timeout for the ZooKeeper session in ms."); @Documentation.Section(Documentation.Sections.EXPERT_ZOOKEEPER_HIGH_AVAILABILITY) public static final ConfigOption<Integer> ZOOKEEPER_CONNECTION_TIMEOUT = key("high-availability.zookeeper.client.connection-timeout") .intType() .defaultValue(15000) .withDeprecatedKeys("recovery.zookeeper.client.connection-timeout") .withDescription("Defines the connection timeout for ZooKeeper in ms."); @Documentation.Section(Documentation.Sections.EXPERT_ZOOKEEPER_HIGH_AVAILABILITY) public static final ConfigOption<Integer> ZOOKEEPER_RETRY_WAIT = key("high-availability.zookeeper.client.retry-wait") .intType() .defaultValue(5000) .withDeprecatedKeys("recovery.zookeeper.client.retry-wait") .withDescription("Defines the pause between consecutive retries in ms."); @Documentation.Section(Documentation.Sections.EXPERT_ZOOKEEPER_HIGH_AVAILABILITY) public static final ConfigOption<Integer> ZOOKEEPER_MAX_RETRY_ATTEMPTS = key("high-availability.zookeeper.client.max-retry-attempts") .intType() .defaultValue(3) .withDeprecatedKeys("recovery.zookeeper.client.max-retry-attempts") .withDescription( "Defines the number of connection retries before the client gives up."); /** @deprecated Don't use this option anymore. It has no effect on Flink. */ @Deprecated @Documentation.Section(Documentation.Sections.EXPERT_ZOOKEEPER_HIGH_AVAILABILITY) public static final ConfigOption<String> ZOOKEEPER_RUNNING_JOB_REGISTRY_PATH = key("high-availability.zookeeper.path.running-registry") .stringType() .defaultValue("/running_job_registry/") .withDescription( "Don't use this option anymore. It has no effect on Flink. The RunningJobRegistry has been " + "replaced by the JobResultStore in Flink 1.15."); @Documentation.Section(Documentation.Sections.EXPERT_ZOOKEEPER_HIGH_AVAILABILITY) public static final ConfigOption<String> ZOOKEEPER_CLIENT_ACL = key("high-availability.zookeeper.client.acl") .stringType() .defaultValue("open") .withDescription( "Defines the ACL (open|creator) to be configured on ZK node. The configuration value can be" + " set to “creator” if the ZooKeeper server configuration has the “authProvider” property mapped to use" + " SASLAuthenticationProvider and the cluster is configured to run in secure mode (Kerberos)."); @Documentation.Section(Documentation.Sections.EXPERT_ZOOKEEPER_HIGH_AVAILABILITY) public static final ConfigOption<Boolean> ZOOKEEPER_TOLERATE_SUSPENDED_CONNECTIONS = key("high-availability.zookeeper.client.tolerate-suspended-connections") .booleanType() .defaultValue(false) .withDescription( Description.builder() .text( "Defines whether a suspended ZooKeeper connection will be treated as an error that causes the leader " + "information to be invalidated or not. In case you set this option to %s, Flink will wait until a " + "ZooKeeper connection is marked as lost before it revokes the leadership of components. This has the " + "effect that Flink is more resilient against temporary connection instabilities at the cost of running " + "more likely into timing issues with ZooKeeper.", TextElement.code("true")) .build()); @Documentation.Section(Documentation.Sections.EXPERT_ZOOKEEPER_HIGH_AVAILABILITY) public static final ConfigOption<Boolean> ZOOKEEPER_ENSEMBLE_TRACKING = key("high-availability.zookeeper.client.ensemble-tracker") .booleanType() .defaultValue(true) .withDescription( Description.builder() .text( "Defines whether Curator should enable ensemble tracker. This can be useful in certain scenarios " + "in which CuratorFramework is accessing to ZK clusters via load balancer or Virtual IPs. " + "Default Curator EnsembleTracking logic watches CuratorEventType.GET_CONFIG events and " + "changes ZooKeeper connection string. It is not desired behaviour when ZooKeeper is running under the Virtual IPs. " + "Under certain configurations EnsembleTracking can lead to setting of ZooKeeper connection string " + "with unresolvable hostnames.") .build()); public static final ConfigOption<Map<String, String>> ZOOKEEPER_CLIENT_AUTHORIZATION = key("high-availability.zookeeper.client.authorization") .mapType() .noDefaultValue() .withDescription( Description.builder() .text( "Add connection authorization Subsequent calls to this method overwrite the prior calls. " + "In certain cases ZooKeeper requires additional Authorization information. " + "For example list of valid names for ensemble in order to prevent accidentally connecting to a wrong ensemble. " + "Each entry of type Map.Entry<String, String> will be transformed " + "into an AuthInfo object with the constructor AuthInfo(String, byte[]). " + "The field entry.key() will serve as the String scheme value, while the field entry.getValue() " + "will be initially converted to a byte[] using the String#getBytes() method with %s encoding. " + "If not set the default configuration for a Curator would be applied.", text(ConfigConstants.DEFAULT_CHARSET.displayName())) .build()); public static final ConfigOption<Duration> ZOOKEEPER_MAX_CLOSE_WAIT = key("high-availability.zookeeper.client.max-close-wait") .durationType() .noDefaultValue() .withDescription( Description.builder() .text( "Defines the time Curator should wait during close to join background threads. " + "If not set the default configuration for a Curator would be applied.") .build()); public static final ConfigOption<Integer> ZOOKEEPER_SIMULATED_SESSION_EXP_PERCENT = key("high-availability.zookeeper.client.simulated-session-expiration-percent") .intType() .noDefaultValue() .withDescription( Description.builder() .text( "The percentage set by this method determines how and if Curator will check for session expiration. " + "See Curator documentation for %s property for more information.", link( "https://curator.apache.org/apidocs/org/apache/curator/framework/" + "CuratorFrameworkFactory.Builder.html#simulatedSessionExpirationPercent(int)", "simulatedSessionExpirationPercent")) .build()); // ------------------------------------------------------------------------ // Deprecated options // ------------------------------------------------------------------------ /** * The time before a JobManager after a fail over recovers the current jobs. * * @deprecated Don't use this option anymore. It has no effect on Flink. */ @Deprecated public static final ConfigOption<String> HA_JOB_DELAY = key("high-availability.job.delay") .stringType() .noDefaultValue() .withDeprecatedKeys("recovery.job.delay") .withDescription( "The time before a JobManager after a fail over recovers the current jobs."); // ------------------------------------------------------------------------ /** Not intended to be instantiated. */ private HighAvailabilityOptions() {} }
apache/flink
flink-core/src/main/java/org/apache/flink/configuration/HighAvailabilityOptions.java
3,541
// ZooKeeper Client Settings
line_comment
nl
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.flink.configuration; import org.apache.flink.annotation.docs.Documentation; import org.apache.flink.configuration.description.Description; import org.apache.flink.configuration.description.TextElement; import java.time.Duration; import java.util.Map; import static org.apache.flink.configuration.ConfigOptions.key; import static org.apache.flink.configuration.description.LinkElement.link; import static org.apache.flink.configuration.description.TextElement.text; /** The set of configuration options relating to high-availability settings. */ public class HighAvailabilityOptions { // ------------------------------------------------------------------------ // Required High Availability Options // ------------------------------------------------------------------------ /** * Defines high-availability mode used for the cluster execution. A value of "NONE" signals no * highly available setup. To enable high-availability, set this mode to "ZOOKEEPER" or * "KUBERNETES". Can also be set to the FQN of the HighAvailability factory class. */ @Documentation.Section(value = Documentation.Sections.COMMON_HIGH_AVAILABILITY, position = 1) public static final ConfigOption<String> HA_MODE = key("high-availability.type") .stringType() .defaultValue("NONE") .withDeprecatedKeys("recovery.mode", "high-availability") .withDescription( "Defines high-availability mode used for cluster execution." + " To enable high-availability, set this mode to \"ZOOKEEPER\", \"KUBERNETES\", or specify the fully qualified name of the factory class."); /** * The ID of the Flink cluster, used to separate multiple Flink clusters Needs to be set for * standalone clusters, is automatically inferred in YARN. */ @Documentation.Section(Documentation.Sections.COMMON_HIGH_AVAILABILITY) public static final ConfigOption<String> HA_CLUSTER_ID = key("high-availability.cluster-id") .stringType() .defaultValue("/default") .withDeprecatedKeys( "high-availability.zookeeper.path.namespace", "recovery.zookeeper.path.namespace") .withDescription( "The ID of the Flink cluster, used to separate multiple Flink clusters from each other." + " Needs to be set for standalone clusters but is automatically inferred in YARN."); /** File system path (URI) where Flink persists metadata in high-availability setups. */ @Documentation.Section(Documentation.Sections.COMMON_HIGH_AVAILABILITY) public static final ConfigOption<String> HA_STORAGE_PATH = key("high-availability.storageDir") .stringType() .noDefaultValue() .withDeprecatedKeys( "high-availability.zookeeper.storageDir", "recovery.zookeeper.storageDir") .withDescription( "File system path (URI) where Flink persists metadata in high-availability setups."); // ------------------------------------------------------------------------ // Recovery Options // ------------------------------------------------------------------------ /** Optional port (range) used by the job manager in high-availability mode. */ @Documentation.Section(Documentation.Sections.EXPERT_HIGH_AVAILABILITY) public static final ConfigOption<String> HA_JOB_MANAGER_PORT_RANGE = key("high-availability.jobmanager.port") .stringType() .defaultValue("0") .withDeprecatedKeys("recovery.jobmanager.port") .withDescription( "The port (range) used by the Flink Master for its RPC connections in highly-available setups. " + "In highly-available setups, this value is used instead of '" + JobManagerOptions.PORT.key() + "'." + "A value of '0' means that a random free port is chosen. TaskManagers discover this port through " + "the high-availability services (leader election), so a random port or a port range works " + "without requiring any additional means of service discovery."); // ------------------------------------------------------------------------ // ZooKeeper Options // ------------------------------------------------------------------------ /** * The ZooKeeper quorum to use, when running Flink in a high-availability mode with ZooKeeper. */ @Documentation.Section(Documentation.Sections.COMMON_HIGH_AVAILABILITY_ZOOKEEPER) public static final ConfigOption<String> HA_ZOOKEEPER_QUORUM = key("high-availability.zookeeper.quorum") .stringType() .noDefaultValue() .withDeprecatedKeys("recovery.zookeeper.quorum") .withDescription( "The ZooKeeper quorum to use, when running Flink in a high-availability mode with ZooKeeper."); /** The root path under which Flink stores its entries in ZooKeeper. */ @Documentation.Section(Documentation.Sections.COMMON_HIGH_AVAILABILITY_ZOOKEEPER) public static final ConfigOption<String> HA_ZOOKEEPER_ROOT = key("high-availability.zookeeper.path.root") .stringType() .defaultValue("/flink") .withDeprecatedKeys("recovery.zookeeper.path.root") .withDescription( "The root path under which Flink stores its entries in ZooKeeper."); /** ZooKeeper root path (ZNode) for job graphs. */ @Documentation.Section(Documentation.Sections.EXPERT_ZOOKEEPER_HIGH_AVAILABILITY) public static final ConfigOption<String> HA_ZOOKEEPER_JOBGRAPHS_PATH = key("high-availability.zookeeper.path.jobgraphs") .stringType() .defaultValue("/jobgraphs") .withDeprecatedKeys("recovery.zookeeper.path.jobgraphs") .withDescription("ZooKeeper root path (ZNode) for job graphs"); // ------------------------------------------------------------------------ // ZooKeeper Client<SUF> // ------------------------------------------------------------------------ @Documentation.Section(Documentation.Sections.EXPERT_ZOOKEEPER_HIGH_AVAILABILITY) public static final ConfigOption<Integer> ZOOKEEPER_SESSION_TIMEOUT = key("high-availability.zookeeper.client.session-timeout") .intType() .defaultValue(60000) .withDeprecatedKeys("recovery.zookeeper.client.session-timeout") .withDescription( "Defines the session timeout for the ZooKeeper session in ms."); @Documentation.Section(Documentation.Sections.EXPERT_ZOOKEEPER_HIGH_AVAILABILITY) public static final ConfigOption<Integer> ZOOKEEPER_CONNECTION_TIMEOUT = key("high-availability.zookeeper.client.connection-timeout") .intType() .defaultValue(15000) .withDeprecatedKeys("recovery.zookeeper.client.connection-timeout") .withDescription("Defines the connection timeout for ZooKeeper in ms."); @Documentation.Section(Documentation.Sections.EXPERT_ZOOKEEPER_HIGH_AVAILABILITY) public static final ConfigOption<Integer> ZOOKEEPER_RETRY_WAIT = key("high-availability.zookeeper.client.retry-wait") .intType() .defaultValue(5000) .withDeprecatedKeys("recovery.zookeeper.client.retry-wait") .withDescription("Defines the pause between consecutive retries in ms."); @Documentation.Section(Documentation.Sections.EXPERT_ZOOKEEPER_HIGH_AVAILABILITY) public static final ConfigOption<Integer> ZOOKEEPER_MAX_RETRY_ATTEMPTS = key("high-availability.zookeeper.client.max-retry-attempts") .intType() .defaultValue(3) .withDeprecatedKeys("recovery.zookeeper.client.max-retry-attempts") .withDescription( "Defines the number of connection retries before the client gives up."); /** @deprecated Don't use this option anymore. It has no effect on Flink. */ @Deprecated @Documentation.Section(Documentation.Sections.EXPERT_ZOOKEEPER_HIGH_AVAILABILITY) public static final ConfigOption<String> ZOOKEEPER_RUNNING_JOB_REGISTRY_PATH = key("high-availability.zookeeper.path.running-registry") .stringType() .defaultValue("/running_job_registry/") .withDescription( "Don't use this option anymore. It has no effect on Flink. The RunningJobRegistry has been " + "replaced by the JobResultStore in Flink 1.15."); @Documentation.Section(Documentation.Sections.EXPERT_ZOOKEEPER_HIGH_AVAILABILITY) public static final ConfigOption<String> ZOOKEEPER_CLIENT_ACL = key("high-availability.zookeeper.client.acl") .stringType() .defaultValue("open") .withDescription( "Defines the ACL (open|creator) to be configured on ZK node. The configuration value can be" + " set to “creator” if the ZooKeeper server configuration has the “authProvider” property mapped to use" + " SASLAuthenticationProvider and the cluster is configured to run in secure mode (Kerberos)."); @Documentation.Section(Documentation.Sections.EXPERT_ZOOKEEPER_HIGH_AVAILABILITY) public static final ConfigOption<Boolean> ZOOKEEPER_TOLERATE_SUSPENDED_CONNECTIONS = key("high-availability.zookeeper.client.tolerate-suspended-connections") .booleanType() .defaultValue(false) .withDescription( Description.builder() .text( "Defines whether a suspended ZooKeeper connection will be treated as an error that causes the leader " + "information to be invalidated or not. In case you set this option to %s, Flink will wait until a " + "ZooKeeper connection is marked as lost before it revokes the leadership of components. This has the " + "effect that Flink is more resilient against temporary connection instabilities at the cost of running " + "more likely into timing issues with ZooKeeper.", TextElement.code("true")) .build()); @Documentation.Section(Documentation.Sections.EXPERT_ZOOKEEPER_HIGH_AVAILABILITY) public static final ConfigOption<Boolean> ZOOKEEPER_ENSEMBLE_TRACKING = key("high-availability.zookeeper.client.ensemble-tracker") .booleanType() .defaultValue(true) .withDescription( Description.builder() .text( "Defines whether Curator should enable ensemble tracker. This can be useful in certain scenarios " + "in which CuratorFramework is accessing to ZK clusters via load balancer or Virtual IPs. " + "Default Curator EnsembleTracking logic watches CuratorEventType.GET_CONFIG events and " + "changes ZooKeeper connection string. It is not desired behaviour when ZooKeeper is running under the Virtual IPs. " + "Under certain configurations EnsembleTracking can lead to setting of ZooKeeper connection string " + "with unresolvable hostnames.") .build()); public static final ConfigOption<Map<String, String>> ZOOKEEPER_CLIENT_AUTHORIZATION = key("high-availability.zookeeper.client.authorization") .mapType() .noDefaultValue() .withDescription( Description.builder() .text( "Add connection authorization Subsequent calls to this method overwrite the prior calls. " + "In certain cases ZooKeeper requires additional Authorization information. " + "For example list of valid names for ensemble in order to prevent accidentally connecting to a wrong ensemble. " + "Each entry of type Map.Entry<String, String> will be transformed " + "into an AuthInfo object with the constructor AuthInfo(String, byte[]). " + "The field entry.key() will serve as the String scheme value, while the field entry.getValue() " + "will be initially converted to a byte[] using the String#getBytes() method with %s encoding. " + "If not set the default configuration for a Curator would be applied.", text(ConfigConstants.DEFAULT_CHARSET.displayName())) .build()); public static final ConfigOption<Duration> ZOOKEEPER_MAX_CLOSE_WAIT = key("high-availability.zookeeper.client.max-close-wait") .durationType() .noDefaultValue() .withDescription( Description.builder() .text( "Defines the time Curator should wait during close to join background threads. " + "If not set the default configuration for a Curator would be applied.") .build()); public static final ConfigOption<Integer> ZOOKEEPER_SIMULATED_SESSION_EXP_PERCENT = key("high-availability.zookeeper.client.simulated-session-expiration-percent") .intType() .noDefaultValue() .withDescription( Description.builder() .text( "The percentage set by this method determines how and if Curator will check for session expiration. " + "See Curator documentation for %s property for more information.", link( "https://curator.apache.org/apidocs/org/apache/curator/framework/" + "CuratorFrameworkFactory.Builder.html#simulatedSessionExpirationPercent(int)", "simulatedSessionExpirationPercent")) .build()); // ------------------------------------------------------------------------ // Deprecated options // ------------------------------------------------------------------------ /** * The time before a JobManager after a fail over recovers the current jobs. * * @deprecated Don't use this option anymore. It has no effect on Flink. */ @Deprecated public static final ConfigOption<String> HA_JOB_DELAY = key("high-availability.job.delay") .stringType() .noDefaultValue() .withDeprecatedKeys("recovery.job.delay") .withDescription( "The time before a JobManager after a fail over recovers the current jobs."); // ------------------------------------------------------------------------ /** Not intended to be instantiated. */ private HighAvailabilityOptions() {} }
198884_46
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.flink.runtime.util; import org.apache.flink.annotation.VisibleForTesting; import org.apache.flink.api.common.JobID; import org.apache.flink.configuration.ConfigConstants; import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.HighAvailabilityOptions; import org.apache.flink.configuration.IllegalConfigurationException; import org.apache.flink.configuration.SecurityOptions; import org.apache.flink.core.execution.RestoreMode; import org.apache.flink.runtime.checkpoint.CompletedCheckpoint; import org.apache.flink.runtime.checkpoint.CompletedCheckpointStore; import org.apache.flink.runtime.checkpoint.DefaultCompletedCheckpointStore; import org.apache.flink.runtime.checkpoint.DefaultCompletedCheckpointStoreUtils; import org.apache.flink.runtime.checkpoint.DefaultLastStateConnectionStateListener; import org.apache.flink.runtime.checkpoint.ZooKeeperCheckpointIDCounter; import org.apache.flink.runtime.checkpoint.ZooKeeperCheckpointStoreUtil; import org.apache.flink.runtime.highavailability.HighAvailabilityServicesUtils; import org.apache.flink.runtime.highavailability.zookeeper.CuratorFrameworkWithUnhandledErrorListener; import org.apache.flink.runtime.jobgraph.JobGraph; import org.apache.flink.runtime.jobmanager.DefaultJobGraphStore; import org.apache.flink.runtime.jobmanager.HighAvailabilityMode; import org.apache.flink.runtime.jobmanager.JobGraphStore; import org.apache.flink.runtime.jobmanager.ZooKeeperJobGraphStoreUtil; import org.apache.flink.runtime.jobmanager.ZooKeeperJobGraphStoreWatcher; import org.apache.flink.runtime.leaderelection.LeaderInformation; import org.apache.flink.runtime.leaderretrieval.DefaultLeaderRetrievalService; import org.apache.flink.runtime.leaderretrieval.LeaderRetrievalDriverFactory; import org.apache.flink.runtime.leaderretrieval.ZooKeeperLeaderRetrievalDriver; import org.apache.flink.runtime.leaderretrieval.ZooKeeperLeaderRetrievalDriverFactory; import org.apache.flink.runtime.persistence.RetrievableStateStorageHelper; import org.apache.flink.runtime.persistence.filesystem.FileSystemStateStorageHelper; import org.apache.flink.runtime.rpc.FatalErrorHandler; import org.apache.flink.runtime.state.SharedStateRegistryFactory; import org.apache.flink.runtime.zookeeper.ZooKeeperStateHandleStore; import org.apache.flink.util.concurrent.Executors; import org.apache.flink.util.function.RunnableWithException; import org.apache.flink.shaded.curator5.org.apache.curator.framework.AuthInfo; import org.apache.flink.shaded.curator5.org.apache.curator.framework.CuratorFramework; import org.apache.flink.shaded.curator5.org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.flink.shaded.curator5.org.apache.curator.framework.api.ACLProvider; import org.apache.flink.shaded.curator5.org.apache.curator.framework.api.UnhandledErrorListener; import org.apache.flink.shaded.curator5.org.apache.curator.framework.imps.DefaultACLProvider; import org.apache.flink.shaded.curator5.org.apache.curator.framework.recipes.cache.PathChildrenCache; import org.apache.flink.shaded.curator5.org.apache.curator.framework.recipes.cache.TreeCache; import org.apache.flink.shaded.curator5.org.apache.curator.framework.recipes.cache.TreeCacheListener; import org.apache.flink.shaded.curator5.org.apache.curator.framework.recipes.cache.TreeCacheSelector; import org.apache.flink.shaded.curator5.org.apache.curator.framework.state.SessionConnectionStateErrorPolicy; import org.apache.flink.shaded.curator5.org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.flink.shaded.zookeeper3.org.apache.zookeeper.CreateMode; import org.apache.flink.shaded.zookeeper3.org.apache.zookeeper.KeeperException; import org.apache.flink.shaded.zookeeper3.org.apache.zookeeper.ZooDefs; import org.apache.flink.shaded.zookeeper3.org.apache.zookeeper.data.ACL; import org.apache.flink.shaded.zookeeper3.org.apache.zookeeper.data.Stat; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.Executor; import java.util.function.BooleanSupplier; import java.util.stream.Collectors; import static org.apache.flink.util.Preconditions.checkNotNull; /** Class containing helper functions to interact with ZooKeeper. */ public class ZooKeeperUtils { private static final Logger LOG = LoggerFactory.getLogger(ZooKeeperUtils.class); /** The prefix of the submitted job graph file. */ public static final String HA_STORAGE_SUBMITTED_JOBGRAPH_PREFIX = "submittedJobGraph"; /** The prefix of the completed checkpoint file. */ public static final String HA_STORAGE_COMPLETED_CHECKPOINT = "completedCheckpoint"; /** The prefix of the resource manager node. */ public static final String RESOURCE_MANAGER_NODE = "resource_manager"; private static final String DISPATCHER_NODE = "dispatcher"; private static final String LEADER_NODE = "leader"; private static final String REST_SERVER_NODE = "rest_server"; private static final String LEADER_LATCH_NODE = "latch"; private static final String CONNECTION_INFO_NODE = "connection_info"; public static String getLeaderPathForJob(JobID jobId) { return generateZookeeperPath(getJobsPath(), getPathForJob(jobId)); } public static String getJobsPath() { return "/jobs"; } private static String getCheckpointsPath() { return "/checkpoints"; } public static String getCheckpointIdCounterPath() { return "/checkpoint_id_counter"; } public static String getLeaderPath() { return generateZookeeperPath(LEADER_NODE); } public static String getDispatcherNode() { return DISPATCHER_NODE; } public static String getResourceManagerNode() { return RESOURCE_MANAGER_NODE; } public static String getRestServerNode() { return REST_SERVER_NODE; } public static String getLeaderLatchPath() { return generateZookeeperPath(LEADER_LATCH_NODE); } public static String getLeaderPath(String suffix) { return generateZookeeperPath(LEADER_NODE, suffix); } public static String generateConnectionInformationPath(String path) { return generateZookeeperPath(path, CONNECTION_INFO_NODE); } public static boolean isConnectionInfoPath(String path) { return path.endsWith(CONNECTION_INFO_NODE); } public static String generateLeaderLatchPath(String path) { return generateZookeeperPath(path, LEADER_LATCH_NODE); } /** * Starts a {@link CuratorFramework} instance and connects it to the given ZooKeeper quorum. * * @param configuration {@link Configuration} object containing the configuration values * @param fatalErrorHandler {@link FatalErrorHandler} fatalErrorHandler to handle unexpected * errors of {@link CuratorFramework} * @return {@link CuratorFrameworkWithUnhandledErrorListener} instance */ public static CuratorFrameworkWithUnhandledErrorListener startCuratorFramework( Configuration configuration, FatalErrorHandler fatalErrorHandler) { checkNotNull(configuration, "configuration"); String zkQuorum = configuration.getValue(HighAvailabilityOptions.HA_ZOOKEEPER_QUORUM); if (zkQuorum == null || StringUtils.isBlank(zkQuorum)) { throw new RuntimeException( "No valid ZooKeeper quorum has been specified. " + "You can specify the quorum via the configuration key '" + HighAvailabilityOptions.HA_ZOOKEEPER_QUORUM.key() + "'."); } int sessionTimeout = configuration.get(HighAvailabilityOptions.ZOOKEEPER_SESSION_TIMEOUT); int connectionTimeout = configuration.get(HighAvailabilityOptions.ZOOKEEPER_CONNECTION_TIMEOUT); int retryWait = configuration.get(HighAvailabilityOptions.ZOOKEEPER_RETRY_WAIT); int maxRetryAttempts = configuration.get(HighAvailabilityOptions.ZOOKEEPER_MAX_RETRY_ATTEMPTS); String root = configuration.getValue(HighAvailabilityOptions.HA_ZOOKEEPER_ROOT); String namespace = configuration.getValue(HighAvailabilityOptions.HA_CLUSTER_ID); boolean disableSaslClient = configuration.get(SecurityOptions.ZOOKEEPER_SASL_DISABLE); ACLProvider aclProvider; ZkClientACLMode aclMode = ZkClientACLMode.fromConfig(configuration); if (disableSaslClient && aclMode == ZkClientACLMode.CREATOR) { String errorMessage = "Cannot set ACL role to " + ZkClientACLMode.CREATOR + " since SASL authentication is " + "disabled through the " + SecurityOptions.ZOOKEEPER_SASL_DISABLE.key() + " property"; LOG.warn(errorMessage); throw new IllegalConfigurationException(errorMessage); } if (aclMode == ZkClientACLMode.CREATOR) { LOG.info("Enforcing creator for ZK connections"); aclProvider = new SecureAclProvider(); } else { LOG.info("Enforcing default ACL for ZK connections"); aclProvider = new DefaultACLProvider(); } String rootWithNamespace = generateZookeeperPath(root, namespace); LOG.info("Using '{}' as Zookeeper namespace.", rootWithNamespace); boolean ensembleTracking = configuration.get(HighAvailabilityOptions.ZOOKEEPER_ENSEMBLE_TRACKING); final CuratorFrameworkFactory.Builder curatorFrameworkBuilder = CuratorFrameworkFactory.builder() .connectString(zkQuorum) .sessionTimeoutMs(sessionTimeout) .connectionTimeoutMs(connectionTimeout) .retryPolicy(new ExponentialBackoffRetry(retryWait, maxRetryAttempts)) // Curator prepends a '/' manually and throws an Exception if the // namespace starts with a '/'. .namespace(trimStartingSlash(rootWithNamespace)) .ensembleTracker(ensembleTracking) .aclProvider(aclProvider); if (configuration.contains(HighAvailabilityOptions.ZOOKEEPER_CLIENT_AUTHORIZATION)) { Map<String, String> authMap = configuration.get(HighAvailabilityOptions.ZOOKEEPER_CLIENT_AUTHORIZATION); List<AuthInfo> authInfos = authMap.entrySet().stream() .map( entry -> new AuthInfo( entry.getKey(), entry.getValue() .getBytes( ConfigConstants .DEFAULT_CHARSET))) .collect(Collectors.toList()); curatorFrameworkBuilder.authorization(authInfos); } if (configuration.contains(HighAvailabilityOptions.ZOOKEEPER_MAX_CLOSE_WAIT)) { long maxCloseWait = configuration.get(HighAvailabilityOptions.ZOOKEEPER_MAX_CLOSE_WAIT).toMillis(); if (maxCloseWait < 0 || maxCloseWait > Integer.MAX_VALUE) { throw new IllegalConfigurationException( "The value (%d ms) is out-of-range for %s. The milliseconds timeout is expected to be between 0 and %d ms.", maxCloseWait, HighAvailabilityOptions.ZOOKEEPER_MAX_CLOSE_WAIT.key(), Integer.MAX_VALUE); } curatorFrameworkBuilder.maxCloseWaitMs((int) maxCloseWait); } if (configuration.contains( HighAvailabilityOptions.ZOOKEEPER_SIMULATED_SESSION_EXP_PERCENT)) { curatorFrameworkBuilder.simulatedSessionExpirationPercent( configuration.get( HighAvailabilityOptions.ZOOKEEPER_SIMULATED_SESSION_EXP_PERCENT)); } if (configuration.get(HighAvailabilityOptions.ZOOKEEPER_TOLERATE_SUSPENDED_CONNECTIONS)) { curatorFrameworkBuilder.connectionStateErrorPolicy( new SessionConnectionStateErrorPolicy()); } return startCuratorFramework(curatorFrameworkBuilder, fatalErrorHandler); } /** * Starts a {@link CuratorFramework} instance and connects it to the given ZooKeeper quorum from * a builder. * * @param builder {@link CuratorFrameworkFactory.Builder} A builder for curatorFramework. * @param fatalErrorHandler {@link FatalErrorHandler} fatalErrorHandler to handle unexpected * errors of {@link CuratorFramework} * @return {@link CuratorFrameworkWithUnhandledErrorListener} instance */ @VisibleForTesting public static CuratorFrameworkWithUnhandledErrorListener startCuratorFramework( CuratorFrameworkFactory.Builder builder, FatalErrorHandler fatalErrorHandler) { CuratorFramework cf = builder.build(); UnhandledErrorListener unhandledErrorListener = (message, throwable) -> { LOG.error( "Unhandled error in curator framework, error message: {}", message, throwable); // The exception thrown in UnhandledErrorListener will be caught by // CuratorFramework. So we mostly trigger exit process or interact with main // thread to inform the failure in FatalErrorHandler. fatalErrorHandler.onFatalError(throwable); }; cf.getUnhandledErrorListenable().addListener(unhandledErrorListener); cf.start(); return new CuratorFrameworkWithUnhandledErrorListener(cf, unhandledErrorListener); } /** Returns whether {@link HighAvailabilityMode#ZOOKEEPER} is configured. */ public static boolean isZooKeeperRecoveryMode(Configuration flinkConf) { return HighAvailabilityMode.fromConfig(flinkConf).equals(HighAvailabilityMode.ZOOKEEPER); } /** * Returns the configured ZooKeeper quorum (and removes whitespace, because ZooKeeper does not * tolerate it). */ public static String getZooKeeperEnsemble(Configuration flinkConf) throws IllegalConfigurationException { String zkQuorum = flinkConf.getValue(HighAvailabilityOptions.HA_ZOOKEEPER_QUORUM); if (zkQuorum == null || StringUtils.isBlank(zkQuorum)) { throw new IllegalConfigurationException("No ZooKeeper quorum specified in config."); } // Remove all whitespace zkQuorum = zkQuorum.replaceAll("\\s+", ""); return zkQuorum; } /** * Creates a {@link DefaultLeaderRetrievalService} instance with {@link * ZooKeeperLeaderRetrievalDriver}. * * @param client The {@link CuratorFramework} ZooKeeper client to use * @return {@link DefaultLeaderRetrievalService} instance. */ public static DefaultLeaderRetrievalService createLeaderRetrievalService( final CuratorFramework client) { return createLeaderRetrievalService(client, "", new Configuration()); } /** * Creates a {@link DefaultLeaderRetrievalService} instance with {@link * ZooKeeperLeaderRetrievalDriver}. * * @param client The {@link CuratorFramework} ZooKeeper client to use * @param path The path for the leader retrieval * @param configuration configuration for further config options * @return {@link DefaultLeaderRetrievalService} instance. */ public static DefaultLeaderRetrievalService createLeaderRetrievalService( final CuratorFramework client, final String path, final Configuration configuration) { return new DefaultLeaderRetrievalService( createLeaderRetrievalDriverFactory(client, path, configuration)); } /** * Creates a {@link LeaderRetrievalDriverFactory} implemented by ZooKeeper. * * @param client The {@link CuratorFramework} ZooKeeper client to use * @return {@link LeaderRetrievalDriverFactory} instance. */ public static ZooKeeperLeaderRetrievalDriverFactory createLeaderRetrievalDriverFactory( final CuratorFramework client) { return createLeaderRetrievalDriverFactory(client, ""); } /** * Creates a {@link LeaderRetrievalDriverFactory} implemented by ZooKeeper. * * @param client The {@link CuratorFramework} ZooKeeper client to use * @param path The parent path that shall be used by the client. * @return {@link LeaderRetrievalDriverFactory} instance. */ public static ZooKeeperLeaderRetrievalDriverFactory createLeaderRetrievalDriverFactory( final CuratorFramework client, String path) { return createLeaderRetrievalDriverFactory(client, path, new Configuration()); } /** * Creates a {@link LeaderRetrievalDriverFactory} implemented by ZooKeeper. * * @param client The {@link CuratorFramework} ZooKeeper client to use * @param path The path for the leader zNode * @param configuration configuration for further config options * @return {@link LeaderRetrievalDriverFactory} instance. */ public static ZooKeeperLeaderRetrievalDriverFactory createLeaderRetrievalDriverFactory( final CuratorFramework client, final String path, final Configuration configuration) { final ZooKeeperLeaderRetrievalDriver.LeaderInformationClearancePolicy leaderInformationClearancePolicy; if (configuration.get(HighAvailabilityOptions.ZOOKEEPER_TOLERATE_SUSPENDED_CONNECTIONS)) { leaderInformationClearancePolicy = ZooKeeperLeaderRetrievalDriver.LeaderInformationClearancePolicy .ON_LOST_CONNECTION; } else { leaderInformationClearancePolicy = ZooKeeperLeaderRetrievalDriver.LeaderInformationClearancePolicy .ON_SUSPENDED_CONNECTION; } return new ZooKeeperLeaderRetrievalDriverFactory( client, path, leaderInformationClearancePolicy); } public static void writeLeaderInformationToZooKeeper( LeaderInformation leaderInformation, CuratorFramework curatorFramework, BooleanSupplier hasLeadershipCheck, String connectionInformationPath) throws Exception { final byte[] data; if (leaderInformation.isEmpty()) { data = null; } else { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeUTF(leaderInformation.getLeaderAddress()); oos.writeObject(leaderInformation.getLeaderSessionID()); oos.close(); data = baos.toByteArray(); } boolean dataWritten = false; while (!dataWritten && hasLeadershipCheck.getAsBoolean()) { Stat stat = curatorFramework.checkExists().forPath(connectionInformationPath); if (stat != null) { long owner = stat.getEphemeralOwner(); long sessionID = curatorFramework.getZookeeperClient().getZooKeeper().getSessionId(); if (owner == sessionID) { try { curatorFramework.setData().forPath(connectionInformationPath, data); dataWritten = true; } catch (KeeperException.NoNodeException noNode) { // node was deleted in the meantime } } else { try { curatorFramework.delete().forPath(connectionInformationPath); } catch (KeeperException.NoNodeException noNode) { // node was deleted in the meantime --> try again } } } else { try { curatorFramework .create() .creatingParentsIfNeeded() .withMode(CreateMode.EPHEMERAL) .forPath(connectionInformationPath, data); dataWritten = true; } catch (KeeperException.NodeExistsException nodeExists) { // node has been created in the meantime --> try again } } } } public static LeaderInformation readLeaderInformation(byte[] data) throws IOException, ClassNotFoundException { if (data != null && data.length > 0) { final ByteArrayInputStream bais = new ByteArrayInputStream(data); final String leaderAddress; final UUID leaderSessionID; try (final ObjectInputStream ois = new ObjectInputStream(bais)) { leaderAddress = ois.readUTF(); leaderSessionID = (UUID) ois.readObject(); } return LeaderInformation.known(leaderSessionID, leaderAddress); } else { return LeaderInformation.empty(); } } /** * Creates a {@link DefaultJobGraphStore} instance with {@link ZooKeeperStateHandleStore}, * {@link ZooKeeperJobGraphStoreWatcher} and {@link ZooKeeperJobGraphStoreUtil}. * * @param client The {@link CuratorFramework} ZooKeeper client to use * @param configuration {@link Configuration} object * @return {@link DefaultJobGraphStore} instance * @throws Exception if the submitted job graph store cannot be created */ public static JobGraphStore createJobGraphs( CuratorFramework client, Configuration configuration) throws Exception { checkNotNull(configuration, "Configuration"); RetrievableStateStorageHelper<JobGraph> stateStorage = createFileSystemStateStorage(configuration, HA_STORAGE_SUBMITTED_JOBGRAPH_PREFIX); // ZooKeeper submitted jobs root dir String zooKeeperJobsPath = configuration.get(HighAvailabilityOptions.HA_ZOOKEEPER_JOBGRAPHS_PATH); // Ensure that the job graphs path exists client.newNamespaceAwareEnsurePath(zooKeeperJobsPath).ensure(client.getZookeeperClient()); // All operations will have the path as root CuratorFramework facade = client.usingNamespace(client.getNamespace() + zooKeeperJobsPath); final String zooKeeperFullJobsPath = client.getNamespace() + zooKeeperJobsPath; final ZooKeeperStateHandleStore<JobGraph> zooKeeperStateHandleStore = new ZooKeeperStateHandleStore<>(facade, stateStorage); final PathChildrenCache pathCache = new PathChildrenCache(facade, "/", false); return new DefaultJobGraphStore<>( zooKeeperStateHandleStore, new ZooKeeperJobGraphStoreWatcher(pathCache), ZooKeeperJobGraphStoreUtil.INSTANCE); } /** * Creates a {@link DefaultCompletedCheckpointStore} instance with {@link * ZooKeeperStateHandleStore}. * * @param client The {@link CuratorFramework} ZooKeeper client to use * @param configuration {@link Configuration} object * @param maxNumberOfCheckpointsToRetain The maximum number of checkpoints to retain * @param executor to run ZooKeeper callbacks * @param restoreMode the mode in which the job is being restored * @return {@link DefaultCompletedCheckpointStore} instance * @throws Exception if the completed checkpoint store cannot be created */ public static CompletedCheckpointStore createCompletedCheckpoints( CuratorFramework client, Configuration configuration, int maxNumberOfCheckpointsToRetain, SharedStateRegistryFactory sharedStateRegistryFactory, Executor ioExecutor, Executor executor, RestoreMode restoreMode) throws Exception { checkNotNull(configuration, "Configuration"); RetrievableStateStorageHelper<CompletedCheckpoint> stateStorage = createFileSystemStateStorage(configuration, HA_STORAGE_COMPLETED_CHECKPOINT); final ZooKeeperStateHandleStore<CompletedCheckpoint> completedCheckpointStateHandleStore = createZooKeeperStateHandleStore(client, getCheckpointsPath(), stateStorage); Collection<CompletedCheckpoint> completedCheckpoints = DefaultCompletedCheckpointStoreUtils.retrieveCompletedCheckpoints( completedCheckpointStateHandleStore, ZooKeeperCheckpointStoreUtil.INSTANCE); final CompletedCheckpointStore zooKeeperCompletedCheckpointStore = new DefaultCompletedCheckpointStore<>( maxNumberOfCheckpointsToRetain, completedCheckpointStateHandleStore, ZooKeeperCheckpointStoreUtil.INSTANCE, completedCheckpoints, sharedStateRegistryFactory.create( ioExecutor, completedCheckpoints, restoreMode), executor); LOG.info( "Initialized {} in '{}' with {}.", DefaultCompletedCheckpointStore.class.getSimpleName(), completedCheckpointStateHandleStore, getCheckpointsPath()); return zooKeeperCompletedCheckpointStore; } /** Returns the JobID as a String (with leading slash). */ public static String getPathForJob(JobID jobId) { checkNotNull(jobId, "Job ID"); return String.format("/%s", jobId); } /** * Creates an instance of {@link ZooKeeperStateHandleStore}. * * @param client ZK client * @param path Path to use for the client namespace * @param stateStorage RetrievableStateStorageHelper that persist the actual state and whose * returned state handle is then written to ZooKeeper * @param <T> Type of state * @return {@link ZooKeeperStateHandleStore} instance * @throws Exception ZK errors */ public static <T extends Serializable> ZooKeeperStateHandleStore<T> createZooKeeperStateHandleStore( final CuratorFramework client, final String path, final RetrievableStateStorageHelper<T> stateStorage) throws Exception { return new ZooKeeperStateHandleStore<>( useNamespaceAndEnsurePath(client, path), stateStorage); } /** * Creates a {@link ZooKeeperCheckpointIDCounter} instance. * * @param client The {@link CuratorFramework} ZooKeeper client to use * @return {@link ZooKeeperCheckpointIDCounter} instance */ public static ZooKeeperCheckpointIDCounter createCheckpointIDCounter(CuratorFramework client) { return new ZooKeeperCheckpointIDCounter( client, new DefaultLastStateConnectionStateListener()); } /** * Creates a {@link FileSystemStateStorageHelper} instance. * * @param configuration {@link Configuration} object * @param prefix Prefix for the created files * @param <T> Type of the state objects * @return {@link FileSystemStateStorageHelper} instance * @throws IOException if file system state storage cannot be created */ public static <T extends Serializable> FileSystemStateStorageHelper<T> createFileSystemStateStorage( Configuration configuration, String prefix) throws IOException { return new FileSystemStateStorageHelper<>( HighAvailabilityServicesUtils.getClusterHighAvailableStoragePath(configuration), prefix); } /** Creates a ZooKeeper path of the form "/a/b/.../z". */ public static String generateZookeeperPath(String... paths) { return Arrays.stream(paths) .map(ZooKeeperUtils::trimSlashes) .filter(s -> !s.isEmpty()) .collect(Collectors.joining("/", "/", "")); } /** * Splits the given ZooKeeper path into its parts. * * @param path path to split * @return splited path */ public static String[] splitZooKeeperPath(String path) { return path.split("/"); } public static String trimStartingSlash(String path) { return path.startsWith("/") ? path.substring(1) : path; } private static String trimSlashes(String input) { int left = 0; int right = input.length() - 1; while (left <= right && input.charAt(left) == '/') { left++; } while (right >= left && input.charAt(right) == '/') { right--; } if (left <= right) { return input.substring(left, right + 1); } else { return ""; } } /** * Returns a facade of the client that uses the specified namespace, and ensures that all nodes * in the path exist. * * @param client ZK client * @param path the new namespace * @return ZK Client that uses the new namespace * @throws Exception ZK errors */ public static CuratorFramework useNamespaceAndEnsurePath( final CuratorFramework client, final String path) throws Exception { checkNotNull(client, "client must not be null"); checkNotNull(path, "path must not be null"); // Ensure that the checkpoints path exists client.newNamespaceAwareEnsurePath(path).ensure(client.getZookeeperClient()); // All operations will have the path as root final String newNamespace = generateZookeeperPath(client.getNamespace(), path); return client.usingNamespace( // Curator prepends a '/' manually and throws an Exception if the // namespace starts with a '/'. trimStartingSlash(newNamespace)); } /** * Creates a {@link TreeCache} that only observes a specific node. * * @param client ZK client * @param pathToNode full path of the node to observe * @param nodeChangeCallback callback to run if the node has changed * @return tree cache */ public static TreeCache createTreeCache( final CuratorFramework client, final String pathToNode, final RunnableWithException nodeChangeCallback) { final TreeCache cache = createTreeCache( client, pathToNode, ZooKeeperUtils.treeCacheSelectorForPath(pathToNode)); cache.getListenable().addListener(createTreeCacheListener(nodeChangeCallback)); return cache; } public static TreeCache createTreeCache( final CuratorFramework client, final String pathToNode, final TreeCacheSelector selector) { return TreeCache.newBuilder(client, pathToNode) .setCacheData(true) .setCreateParentNodes(false) .setSelector(selector) // see FLINK-32204 for further details on why the task rejection shouldn't // be enforced here .setExecutor(Executors.newDirectExecutorServiceWithNoOpShutdown()) .build(); } @VisibleForTesting static TreeCacheListener createTreeCacheListener(RunnableWithException nodeChangeCallback) { return (ignored, event) -> { // only notify listener if nodes have changed // connection issues are handled separately from the cache switch (event.getType()) { case NODE_ADDED: case NODE_UPDATED: case NODE_REMOVED: nodeChangeCallback.run(); } }; } /** * Returns a {@link TreeCacheSelector} that only accepts a specific node. * * @param fullPath node to accept * @return tree cache selector */ private static TreeCacheSelector treeCacheSelectorForPath(String fullPath) { return new TreeCacheSelector() { @Override public boolean traverseChildren(String childPath) { return false; } @Override public boolean acceptChild(String childPath) { return fullPath.equals(childPath); } }; } /** Secure {@link ACLProvider} implementation. */ public static class SecureAclProvider implements ACLProvider { @Override public List<ACL> getDefaultAcl() { return ZooDefs.Ids.CREATOR_ALL_ACL; } @Override public List<ACL> getAclForPath(String path) { return ZooDefs.Ids.CREATOR_ALL_ACL; } } /** ZooKeeper client ACL mode enum. */ public enum ZkClientACLMode { CREATOR, OPEN; /** * Return the configured {@link ZkClientACLMode}. * * @param config The config to parse * @return Configured ACL mode or the default defined by {@link * HighAvailabilityOptions#ZOOKEEPER_CLIENT_ACL} if not configured. */ public static ZkClientACLMode fromConfig(Configuration config) { String aclMode = config.get(HighAvailabilityOptions.ZOOKEEPER_CLIENT_ACL); if (aclMode == null || aclMode.equalsIgnoreCase(OPEN.name())) { return OPEN; } else if (aclMode.equalsIgnoreCase(CREATOR.name())) { return CREATOR; } else { String message = "Unsupported ACL option: [" + aclMode + "] provided"; LOG.error(message); throw new IllegalConfigurationException(message); } } } public static void deleteZNode(CuratorFramework curatorFramework, String path) throws Exception { curatorFramework.delete().idempotent().deletingChildrenIfNeeded().forPath(path); } /** Private constructor to prevent instantiation. */ private ZooKeeperUtils() { throw new RuntimeException(); } }
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/util/ZooKeeperUtils.java
7,861
/** ZooKeeper client ACL mode enum. */
block_comment
nl
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.flink.runtime.util; import org.apache.flink.annotation.VisibleForTesting; import org.apache.flink.api.common.JobID; import org.apache.flink.configuration.ConfigConstants; import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.HighAvailabilityOptions; import org.apache.flink.configuration.IllegalConfigurationException; import org.apache.flink.configuration.SecurityOptions; import org.apache.flink.core.execution.RestoreMode; import org.apache.flink.runtime.checkpoint.CompletedCheckpoint; import org.apache.flink.runtime.checkpoint.CompletedCheckpointStore; import org.apache.flink.runtime.checkpoint.DefaultCompletedCheckpointStore; import org.apache.flink.runtime.checkpoint.DefaultCompletedCheckpointStoreUtils; import org.apache.flink.runtime.checkpoint.DefaultLastStateConnectionStateListener; import org.apache.flink.runtime.checkpoint.ZooKeeperCheckpointIDCounter; import org.apache.flink.runtime.checkpoint.ZooKeeperCheckpointStoreUtil; import org.apache.flink.runtime.highavailability.HighAvailabilityServicesUtils; import org.apache.flink.runtime.highavailability.zookeeper.CuratorFrameworkWithUnhandledErrorListener; import org.apache.flink.runtime.jobgraph.JobGraph; import org.apache.flink.runtime.jobmanager.DefaultJobGraphStore; import org.apache.flink.runtime.jobmanager.HighAvailabilityMode; import org.apache.flink.runtime.jobmanager.JobGraphStore; import org.apache.flink.runtime.jobmanager.ZooKeeperJobGraphStoreUtil; import org.apache.flink.runtime.jobmanager.ZooKeeperJobGraphStoreWatcher; import org.apache.flink.runtime.leaderelection.LeaderInformation; import org.apache.flink.runtime.leaderretrieval.DefaultLeaderRetrievalService; import org.apache.flink.runtime.leaderretrieval.LeaderRetrievalDriverFactory; import org.apache.flink.runtime.leaderretrieval.ZooKeeperLeaderRetrievalDriver; import org.apache.flink.runtime.leaderretrieval.ZooKeeperLeaderRetrievalDriverFactory; import org.apache.flink.runtime.persistence.RetrievableStateStorageHelper; import org.apache.flink.runtime.persistence.filesystem.FileSystemStateStorageHelper; import org.apache.flink.runtime.rpc.FatalErrorHandler; import org.apache.flink.runtime.state.SharedStateRegistryFactory; import org.apache.flink.runtime.zookeeper.ZooKeeperStateHandleStore; import org.apache.flink.util.concurrent.Executors; import org.apache.flink.util.function.RunnableWithException; import org.apache.flink.shaded.curator5.org.apache.curator.framework.AuthInfo; import org.apache.flink.shaded.curator5.org.apache.curator.framework.CuratorFramework; import org.apache.flink.shaded.curator5.org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.flink.shaded.curator5.org.apache.curator.framework.api.ACLProvider; import org.apache.flink.shaded.curator5.org.apache.curator.framework.api.UnhandledErrorListener; import org.apache.flink.shaded.curator5.org.apache.curator.framework.imps.DefaultACLProvider; import org.apache.flink.shaded.curator5.org.apache.curator.framework.recipes.cache.PathChildrenCache; import org.apache.flink.shaded.curator5.org.apache.curator.framework.recipes.cache.TreeCache; import org.apache.flink.shaded.curator5.org.apache.curator.framework.recipes.cache.TreeCacheListener; import org.apache.flink.shaded.curator5.org.apache.curator.framework.recipes.cache.TreeCacheSelector; import org.apache.flink.shaded.curator5.org.apache.curator.framework.state.SessionConnectionStateErrorPolicy; import org.apache.flink.shaded.curator5.org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.flink.shaded.zookeeper3.org.apache.zookeeper.CreateMode; import org.apache.flink.shaded.zookeeper3.org.apache.zookeeper.KeeperException; import org.apache.flink.shaded.zookeeper3.org.apache.zookeeper.ZooDefs; import org.apache.flink.shaded.zookeeper3.org.apache.zookeeper.data.ACL; import org.apache.flink.shaded.zookeeper3.org.apache.zookeeper.data.Stat; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.Executor; import java.util.function.BooleanSupplier; import java.util.stream.Collectors; import static org.apache.flink.util.Preconditions.checkNotNull; /** Class containing helper functions to interact with ZooKeeper. */ public class ZooKeeperUtils { private static final Logger LOG = LoggerFactory.getLogger(ZooKeeperUtils.class); /** The prefix of the submitted job graph file. */ public static final String HA_STORAGE_SUBMITTED_JOBGRAPH_PREFIX = "submittedJobGraph"; /** The prefix of the completed checkpoint file. */ public static final String HA_STORAGE_COMPLETED_CHECKPOINT = "completedCheckpoint"; /** The prefix of the resource manager node. */ public static final String RESOURCE_MANAGER_NODE = "resource_manager"; private static final String DISPATCHER_NODE = "dispatcher"; private static final String LEADER_NODE = "leader"; private static final String REST_SERVER_NODE = "rest_server"; private static final String LEADER_LATCH_NODE = "latch"; private static final String CONNECTION_INFO_NODE = "connection_info"; public static String getLeaderPathForJob(JobID jobId) { return generateZookeeperPath(getJobsPath(), getPathForJob(jobId)); } public static String getJobsPath() { return "/jobs"; } private static String getCheckpointsPath() { return "/checkpoints"; } public static String getCheckpointIdCounterPath() { return "/checkpoint_id_counter"; } public static String getLeaderPath() { return generateZookeeperPath(LEADER_NODE); } public static String getDispatcherNode() { return DISPATCHER_NODE; } public static String getResourceManagerNode() { return RESOURCE_MANAGER_NODE; } public static String getRestServerNode() { return REST_SERVER_NODE; } public static String getLeaderLatchPath() { return generateZookeeperPath(LEADER_LATCH_NODE); } public static String getLeaderPath(String suffix) { return generateZookeeperPath(LEADER_NODE, suffix); } public static String generateConnectionInformationPath(String path) { return generateZookeeperPath(path, CONNECTION_INFO_NODE); } public static boolean isConnectionInfoPath(String path) { return path.endsWith(CONNECTION_INFO_NODE); } public static String generateLeaderLatchPath(String path) { return generateZookeeperPath(path, LEADER_LATCH_NODE); } /** * Starts a {@link CuratorFramework} instance and connects it to the given ZooKeeper quorum. * * @param configuration {@link Configuration} object containing the configuration values * @param fatalErrorHandler {@link FatalErrorHandler} fatalErrorHandler to handle unexpected * errors of {@link CuratorFramework} * @return {@link CuratorFrameworkWithUnhandledErrorListener} instance */ public static CuratorFrameworkWithUnhandledErrorListener startCuratorFramework( Configuration configuration, FatalErrorHandler fatalErrorHandler) { checkNotNull(configuration, "configuration"); String zkQuorum = configuration.getValue(HighAvailabilityOptions.HA_ZOOKEEPER_QUORUM); if (zkQuorum == null || StringUtils.isBlank(zkQuorum)) { throw new RuntimeException( "No valid ZooKeeper quorum has been specified. " + "You can specify the quorum via the configuration key '" + HighAvailabilityOptions.HA_ZOOKEEPER_QUORUM.key() + "'."); } int sessionTimeout = configuration.get(HighAvailabilityOptions.ZOOKEEPER_SESSION_TIMEOUT); int connectionTimeout = configuration.get(HighAvailabilityOptions.ZOOKEEPER_CONNECTION_TIMEOUT); int retryWait = configuration.get(HighAvailabilityOptions.ZOOKEEPER_RETRY_WAIT); int maxRetryAttempts = configuration.get(HighAvailabilityOptions.ZOOKEEPER_MAX_RETRY_ATTEMPTS); String root = configuration.getValue(HighAvailabilityOptions.HA_ZOOKEEPER_ROOT); String namespace = configuration.getValue(HighAvailabilityOptions.HA_CLUSTER_ID); boolean disableSaslClient = configuration.get(SecurityOptions.ZOOKEEPER_SASL_DISABLE); ACLProvider aclProvider; ZkClientACLMode aclMode = ZkClientACLMode.fromConfig(configuration); if (disableSaslClient && aclMode == ZkClientACLMode.CREATOR) { String errorMessage = "Cannot set ACL role to " + ZkClientACLMode.CREATOR + " since SASL authentication is " + "disabled through the " + SecurityOptions.ZOOKEEPER_SASL_DISABLE.key() + " property"; LOG.warn(errorMessage); throw new IllegalConfigurationException(errorMessage); } if (aclMode == ZkClientACLMode.CREATOR) { LOG.info("Enforcing creator for ZK connections"); aclProvider = new SecureAclProvider(); } else { LOG.info("Enforcing default ACL for ZK connections"); aclProvider = new DefaultACLProvider(); } String rootWithNamespace = generateZookeeperPath(root, namespace); LOG.info("Using '{}' as Zookeeper namespace.", rootWithNamespace); boolean ensembleTracking = configuration.get(HighAvailabilityOptions.ZOOKEEPER_ENSEMBLE_TRACKING); final CuratorFrameworkFactory.Builder curatorFrameworkBuilder = CuratorFrameworkFactory.builder() .connectString(zkQuorum) .sessionTimeoutMs(sessionTimeout) .connectionTimeoutMs(connectionTimeout) .retryPolicy(new ExponentialBackoffRetry(retryWait, maxRetryAttempts)) // Curator prepends a '/' manually and throws an Exception if the // namespace starts with a '/'. .namespace(trimStartingSlash(rootWithNamespace)) .ensembleTracker(ensembleTracking) .aclProvider(aclProvider); if (configuration.contains(HighAvailabilityOptions.ZOOKEEPER_CLIENT_AUTHORIZATION)) { Map<String, String> authMap = configuration.get(HighAvailabilityOptions.ZOOKEEPER_CLIENT_AUTHORIZATION); List<AuthInfo> authInfos = authMap.entrySet().stream() .map( entry -> new AuthInfo( entry.getKey(), entry.getValue() .getBytes( ConfigConstants .DEFAULT_CHARSET))) .collect(Collectors.toList()); curatorFrameworkBuilder.authorization(authInfos); } if (configuration.contains(HighAvailabilityOptions.ZOOKEEPER_MAX_CLOSE_WAIT)) { long maxCloseWait = configuration.get(HighAvailabilityOptions.ZOOKEEPER_MAX_CLOSE_WAIT).toMillis(); if (maxCloseWait < 0 || maxCloseWait > Integer.MAX_VALUE) { throw new IllegalConfigurationException( "The value (%d ms) is out-of-range for %s. The milliseconds timeout is expected to be between 0 and %d ms.", maxCloseWait, HighAvailabilityOptions.ZOOKEEPER_MAX_CLOSE_WAIT.key(), Integer.MAX_VALUE); } curatorFrameworkBuilder.maxCloseWaitMs((int) maxCloseWait); } if (configuration.contains( HighAvailabilityOptions.ZOOKEEPER_SIMULATED_SESSION_EXP_PERCENT)) { curatorFrameworkBuilder.simulatedSessionExpirationPercent( configuration.get( HighAvailabilityOptions.ZOOKEEPER_SIMULATED_SESSION_EXP_PERCENT)); } if (configuration.get(HighAvailabilityOptions.ZOOKEEPER_TOLERATE_SUSPENDED_CONNECTIONS)) { curatorFrameworkBuilder.connectionStateErrorPolicy( new SessionConnectionStateErrorPolicy()); } return startCuratorFramework(curatorFrameworkBuilder, fatalErrorHandler); } /** * Starts a {@link CuratorFramework} instance and connects it to the given ZooKeeper quorum from * a builder. * * @param builder {@link CuratorFrameworkFactory.Builder} A builder for curatorFramework. * @param fatalErrorHandler {@link FatalErrorHandler} fatalErrorHandler to handle unexpected * errors of {@link CuratorFramework} * @return {@link CuratorFrameworkWithUnhandledErrorListener} instance */ @VisibleForTesting public static CuratorFrameworkWithUnhandledErrorListener startCuratorFramework( CuratorFrameworkFactory.Builder builder, FatalErrorHandler fatalErrorHandler) { CuratorFramework cf = builder.build(); UnhandledErrorListener unhandledErrorListener = (message, throwable) -> { LOG.error( "Unhandled error in curator framework, error message: {}", message, throwable); // The exception thrown in UnhandledErrorListener will be caught by // CuratorFramework. So we mostly trigger exit process or interact with main // thread to inform the failure in FatalErrorHandler. fatalErrorHandler.onFatalError(throwable); }; cf.getUnhandledErrorListenable().addListener(unhandledErrorListener); cf.start(); return new CuratorFrameworkWithUnhandledErrorListener(cf, unhandledErrorListener); } /** Returns whether {@link HighAvailabilityMode#ZOOKEEPER} is configured. */ public static boolean isZooKeeperRecoveryMode(Configuration flinkConf) { return HighAvailabilityMode.fromConfig(flinkConf).equals(HighAvailabilityMode.ZOOKEEPER); } /** * Returns the configured ZooKeeper quorum (and removes whitespace, because ZooKeeper does not * tolerate it). */ public static String getZooKeeperEnsemble(Configuration flinkConf) throws IllegalConfigurationException { String zkQuorum = flinkConf.getValue(HighAvailabilityOptions.HA_ZOOKEEPER_QUORUM); if (zkQuorum == null || StringUtils.isBlank(zkQuorum)) { throw new IllegalConfigurationException("No ZooKeeper quorum specified in config."); } // Remove all whitespace zkQuorum = zkQuorum.replaceAll("\\s+", ""); return zkQuorum; } /** * Creates a {@link DefaultLeaderRetrievalService} instance with {@link * ZooKeeperLeaderRetrievalDriver}. * * @param client The {@link CuratorFramework} ZooKeeper client to use * @return {@link DefaultLeaderRetrievalService} instance. */ public static DefaultLeaderRetrievalService createLeaderRetrievalService( final CuratorFramework client) { return createLeaderRetrievalService(client, "", new Configuration()); } /** * Creates a {@link DefaultLeaderRetrievalService} instance with {@link * ZooKeeperLeaderRetrievalDriver}. * * @param client The {@link CuratorFramework} ZooKeeper client to use * @param path The path for the leader retrieval * @param configuration configuration for further config options * @return {@link DefaultLeaderRetrievalService} instance. */ public static DefaultLeaderRetrievalService createLeaderRetrievalService( final CuratorFramework client, final String path, final Configuration configuration) { return new DefaultLeaderRetrievalService( createLeaderRetrievalDriverFactory(client, path, configuration)); } /** * Creates a {@link LeaderRetrievalDriverFactory} implemented by ZooKeeper. * * @param client The {@link CuratorFramework} ZooKeeper client to use * @return {@link LeaderRetrievalDriverFactory} instance. */ public static ZooKeeperLeaderRetrievalDriverFactory createLeaderRetrievalDriverFactory( final CuratorFramework client) { return createLeaderRetrievalDriverFactory(client, ""); } /** * Creates a {@link LeaderRetrievalDriverFactory} implemented by ZooKeeper. * * @param client The {@link CuratorFramework} ZooKeeper client to use * @param path The parent path that shall be used by the client. * @return {@link LeaderRetrievalDriverFactory} instance. */ public static ZooKeeperLeaderRetrievalDriverFactory createLeaderRetrievalDriverFactory( final CuratorFramework client, String path) { return createLeaderRetrievalDriverFactory(client, path, new Configuration()); } /** * Creates a {@link LeaderRetrievalDriverFactory} implemented by ZooKeeper. * * @param client The {@link CuratorFramework} ZooKeeper client to use * @param path The path for the leader zNode * @param configuration configuration for further config options * @return {@link LeaderRetrievalDriverFactory} instance. */ public static ZooKeeperLeaderRetrievalDriverFactory createLeaderRetrievalDriverFactory( final CuratorFramework client, final String path, final Configuration configuration) { final ZooKeeperLeaderRetrievalDriver.LeaderInformationClearancePolicy leaderInformationClearancePolicy; if (configuration.get(HighAvailabilityOptions.ZOOKEEPER_TOLERATE_SUSPENDED_CONNECTIONS)) { leaderInformationClearancePolicy = ZooKeeperLeaderRetrievalDriver.LeaderInformationClearancePolicy .ON_LOST_CONNECTION; } else { leaderInformationClearancePolicy = ZooKeeperLeaderRetrievalDriver.LeaderInformationClearancePolicy .ON_SUSPENDED_CONNECTION; } return new ZooKeeperLeaderRetrievalDriverFactory( client, path, leaderInformationClearancePolicy); } public static void writeLeaderInformationToZooKeeper( LeaderInformation leaderInformation, CuratorFramework curatorFramework, BooleanSupplier hasLeadershipCheck, String connectionInformationPath) throws Exception { final byte[] data; if (leaderInformation.isEmpty()) { data = null; } else { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeUTF(leaderInformation.getLeaderAddress()); oos.writeObject(leaderInformation.getLeaderSessionID()); oos.close(); data = baos.toByteArray(); } boolean dataWritten = false; while (!dataWritten && hasLeadershipCheck.getAsBoolean()) { Stat stat = curatorFramework.checkExists().forPath(connectionInformationPath); if (stat != null) { long owner = stat.getEphemeralOwner(); long sessionID = curatorFramework.getZookeeperClient().getZooKeeper().getSessionId(); if (owner == sessionID) { try { curatorFramework.setData().forPath(connectionInformationPath, data); dataWritten = true; } catch (KeeperException.NoNodeException noNode) { // node was deleted in the meantime } } else { try { curatorFramework.delete().forPath(connectionInformationPath); } catch (KeeperException.NoNodeException noNode) { // node was deleted in the meantime --> try again } } } else { try { curatorFramework .create() .creatingParentsIfNeeded() .withMode(CreateMode.EPHEMERAL) .forPath(connectionInformationPath, data); dataWritten = true; } catch (KeeperException.NodeExistsException nodeExists) { // node has been created in the meantime --> try again } } } } public static LeaderInformation readLeaderInformation(byte[] data) throws IOException, ClassNotFoundException { if (data != null && data.length > 0) { final ByteArrayInputStream bais = new ByteArrayInputStream(data); final String leaderAddress; final UUID leaderSessionID; try (final ObjectInputStream ois = new ObjectInputStream(bais)) { leaderAddress = ois.readUTF(); leaderSessionID = (UUID) ois.readObject(); } return LeaderInformation.known(leaderSessionID, leaderAddress); } else { return LeaderInformation.empty(); } } /** * Creates a {@link DefaultJobGraphStore} instance with {@link ZooKeeperStateHandleStore}, * {@link ZooKeeperJobGraphStoreWatcher} and {@link ZooKeeperJobGraphStoreUtil}. * * @param client The {@link CuratorFramework} ZooKeeper client to use * @param configuration {@link Configuration} object * @return {@link DefaultJobGraphStore} instance * @throws Exception if the submitted job graph store cannot be created */ public static JobGraphStore createJobGraphs( CuratorFramework client, Configuration configuration) throws Exception { checkNotNull(configuration, "Configuration"); RetrievableStateStorageHelper<JobGraph> stateStorage = createFileSystemStateStorage(configuration, HA_STORAGE_SUBMITTED_JOBGRAPH_PREFIX); // ZooKeeper submitted jobs root dir String zooKeeperJobsPath = configuration.get(HighAvailabilityOptions.HA_ZOOKEEPER_JOBGRAPHS_PATH); // Ensure that the job graphs path exists client.newNamespaceAwareEnsurePath(zooKeeperJobsPath).ensure(client.getZookeeperClient()); // All operations will have the path as root CuratorFramework facade = client.usingNamespace(client.getNamespace() + zooKeeperJobsPath); final String zooKeeperFullJobsPath = client.getNamespace() + zooKeeperJobsPath; final ZooKeeperStateHandleStore<JobGraph> zooKeeperStateHandleStore = new ZooKeeperStateHandleStore<>(facade, stateStorage); final PathChildrenCache pathCache = new PathChildrenCache(facade, "/", false); return new DefaultJobGraphStore<>( zooKeeperStateHandleStore, new ZooKeeperJobGraphStoreWatcher(pathCache), ZooKeeperJobGraphStoreUtil.INSTANCE); } /** * Creates a {@link DefaultCompletedCheckpointStore} instance with {@link * ZooKeeperStateHandleStore}. * * @param client The {@link CuratorFramework} ZooKeeper client to use * @param configuration {@link Configuration} object * @param maxNumberOfCheckpointsToRetain The maximum number of checkpoints to retain * @param executor to run ZooKeeper callbacks * @param restoreMode the mode in which the job is being restored * @return {@link DefaultCompletedCheckpointStore} instance * @throws Exception if the completed checkpoint store cannot be created */ public static CompletedCheckpointStore createCompletedCheckpoints( CuratorFramework client, Configuration configuration, int maxNumberOfCheckpointsToRetain, SharedStateRegistryFactory sharedStateRegistryFactory, Executor ioExecutor, Executor executor, RestoreMode restoreMode) throws Exception { checkNotNull(configuration, "Configuration"); RetrievableStateStorageHelper<CompletedCheckpoint> stateStorage = createFileSystemStateStorage(configuration, HA_STORAGE_COMPLETED_CHECKPOINT); final ZooKeeperStateHandleStore<CompletedCheckpoint> completedCheckpointStateHandleStore = createZooKeeperStateHandleStore(client, getCheckpointsPath(), stateStorage); Collection<CompletedCheckpoint> completedCheckpoints = DefaultCompletedCheckpointStoreUtils.retrieveCompletedCheckpoints( completedCheckpointStateHandleStore, ZooKeeperCheckpointStoreUtil.INSTANCE); final CompletedCheckpointStore zooKeeperCompletedCheckpointStore = new DefaultCompletedCheckpointStore<>( maxNumberOfCheckpointsToRetain, completedCheckpointStateHandleStore, ZooKeeperCheckpointStoreUtil.INSTANCE, completedCheckpoints, sharedStateRegistryFactory.create( ioExecutor, completedCheckpoints, restoreMode), executor); LOG.info( "Initialized {} in '{}' with {}.", DefaultCompletedCheckpointStore.class.getSimpleName(), completedCheckpointStateHandleStore, getCheckpointsPath()); return zooKeeperCompletedCheckpointStore; } /** Returns the JobID as a String (with leading slash). */ public static String getPathForJob(JobID jobId) { checkNotNull(jobId, "Job ID"); return String.format("/%s", jobId); } /** * Creates an instance of {@link ZooKeeperStateHandleStore}. * * @param client ZK client * @param path Path to use for the client namespace * @param stateStorage RetrievableStateStorageHelper that persist the actual state and whose * returned state handle is then written to ZooKeeper * @param <T> Type of state * @return {@link ZooKeeperStateHandleStore} instance * @throws Exception ZK errors */ public static <T extends Serializable> ZooKeeperStateHandleStore<T> createZooKeeperStateHandleStore( final CuratorFramework client, final String path, final RetrievableStateStorageHelper<T> stateStorage) throws Exception { return new ZooKeeperStateHandleStore<>( useNamespaceAndEnsurePath(client, path), stateStorage); } /** * Creates a {@link ZooKeeperCheckpointIDCounter} instance. * * @param client The {@link CuratorFramework} ZooKeeper client to use * @return {@link ZooKeeperCheckpointIDCounter} instance */ public static ZooKeeperCheckpointIDCounter createCheckpointIDCounter(CuratorFramework client) { return new ZooKeeperCheckpointIDCounter( client, new DefaultLastStateConnectionStateListener()); } /** * Creates a {@link FileSystemStateStorageHelper} instance. * * @param configuration {@link Configuration} object * @param prefix Prefix for the created files * @param <T> Type of the state objects * @return {@link FileSystemStateStorageHelper} instance * @throws IOException if file system state storage cannot be created */ public static <T extends Serializable> FileSystemStateStorageHelper<T> createFileSystemStateStorage( Configuration configuration, String prefix) throws IOException { return new FileSystemStateStorageHelper<>( HighAvailabilityServicesUtils.getClusterHighAvailableStoragePath(configuration), prefix); } /** Creates a ZooKeeper path of the form "/a/b/.../z". */ public static String generateZookeeperPath(String... paths) { return Arrays.stream(paths) .map(ZooKeeperUtils::trimSlashes) .filter(s -> !s.isEmpty()) .collect(Collectors.joining("/", "/", "")); } /** * Splits the given ZooKeeper path into its parts. * * @param path path to split * @return splited path */ public static String[] splitZooKeeperPath(String path) { return path.split("/"); } public static String trimStartingSlash(String path) { return path.startsWith("/") ? path.substring(1) : path; } private static String trimSlashes(String input) { int left = 0; int right = input.length() - 1; while (left <= right && input.charAt(left) == '/') { left++; } while (right >= left && input.charAt(right) == '/') { right--; } if (left <= right) { return input.substring(left, right + 1); } else { return ""; } } /** * Returns a facade of the client that uses the specified namespace, and ensures that all nodes * in the path exist. * * @param client ZK client * @param path the new namespace * @return ZK Client that uses the new namespace * @throws Exception ZK errors */ public static CuratorFramework useNamespaceAndEnsurePath( final CuratorFramework client, final String path) throws Exception { checkNotNull(client, "client must not be null"); checkNotNull(path, "path must not be null"); // Ensure that the checkpoints path exists client.newNamespaceAwareEnsurePath(path).ensure(client.getZookeeperClient()); // All operations will have the path as root final String newNamespace = generateZookeeperPath(client.getNamespace(), path); return client.usingNamespace( // Curator prepends a '/' manually and throws an Exception if the // namespace starts with a '/'. trimStartingSlash(newNamespace)); } /** * Creates a {@link TreeCache} that only observes a specific node. * * @param client ZK client * @param pathToNode full path of the node to observe * @param nodeChangeCallback callback to run if the node has changed * @return tree cache */ public static TreeCache createTreeCache( final CuratorFramework client, final String pathToNode, final RunnableWithException nodeChangeCallback) { final TreeCache cache = createTreeCache( client, pathToNode, ZooKeeperUtils.treeCacheSelectorForPath(pathToNode)); cache.getListenable().addListener(createTreeCacheListener(nodeChangeCallback)); return cache; } public static TreeCache createTreeCache( final CuratorFramework client, final String pathToNode, final TreeCacheSelector selector) { return TreeCache.newBuilder(client, pathToNode) .setCacheData(true) .setCreateParentNodes(false) .setSelector(selector) // see FLINK-32204 for further details on why the task rejection shouldn't // be enforced here .setExecutor(Executors.newDirectExecutorServiceWithNoOpShutdown()) .build(); } @VisibleForTesting static TreeCacheListener createTreeCacheListener(RunnableWithException nodeChangeCallback) { return (ignored, event) -> { // only notify listener if nodes have changed // connection issues are handled separately from the cache switch (event.getType()) { case NODE_ADDED: case NODE_UPDATED: case NODE_REMOVED: nodeChangeCallback.run(); } }; } /** * Returns a {@link TreeCacheSelector} that only accepts a specific node. * * @param fullPath node to accept * @return tree cache selector */ private static TreeCacheSelector treeCacheSelectorForPath(String fullPath) { return new TreeCacheSelector() { @Override public boolean traverseChildren(String childPath) { return false; } @Override public boolean acceptChild(String childPath) { return fullPath.equals(childPath); } }; } /** Secure {@link ACLProvider} implementation. */ public static class SecureAclProvider implements ACLProvider { @Override public List<ACL> getDefaultAcl() { return ZooDefs.Ids.CREATOR_ALL_ACL; } @Override public List<ACL> getAclForPath(String path) { return ZooDefs.Ids.CREATOR_ALL_ACL; } } /** ZooKeeper client ACL<SUF>*/ public enum ZkClientACLMode { CREATOR, OPEN; /** * Return the configured {@link ZkClientACLMode}. * * @param config The config to parse * @return Configured ACL mode or the default defined by {@link * HighAvailabilityOptions#ZOOKEEPER_CLIENT_ACL} if not configured. */ public static ZkClientACLMode fromConfig(Configuration config) { String aclMode = config.get(HighAvailabilityOptions.ZOOKEEPER_CLIENT_ACL); if (aclMode == null || aclMode.equalsIgnoreCase(OPEN.name())) { return OPEN; } else if (aclMode.equalsIgnoreCase(CREATOR.name())) { return CREATOR; } else { String message = "Unsupported ACL option: [" + aclMode + "] provided"; LOG.error(message); throw new IllegalConfigurationException(message); } } } public static void deleteZNode(CuratorFramework curatorFramework, String path) throws Exception { curatorFramework.delete().idempotent().deletingChildrenIfNeeded().forPath(path); } /** Private constructor to prevent instantiation. */ private ZooKeeperUtils() { throw new RuntimeException(); } }
198931_6
/* * Copyright 1999-2020 Alibaba Group Holding Ltd. * * 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.alibaba.druid.pool.ha.node; import com.alibaba.druid.support.logging.Log; import com.alibaba.druid.support.logging.LogFactory; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.nodes.GroupMember; import org.apache.curator.retry.RetryForever; import java.io.IOException; import java.io.StringWriter; import java.util.List; import java.util.Properties; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * A register which is used to register a node to an ephemeral node. * * @author DigitalSonic */ public class ZookeeperNodeRegister { private static final Log LOG = LogFactory.getLog(ZookeeperNodeRegister.class); private final Lock lock = new ReentrantLock(); private String zkConnectString; private String path = "/ha-druid-datasources"; private CuratorFramework client; private GroupMember member; private boolean privateZkClient; // Should I close the client? /** * Init a CuratorFramework if there's no CuratorFramework provided. */ public void init() { if (client == null) { client = CuratorFrameworkFactory.builder() .connectionTimeoutMs(5000) .connectString(zkConnectString) .retryPolicy(new RetryForever(10000)) .sessionTimeoutMs(30000) .build(); client.start(); privateZkClient = true; } } /** * Register a Node which has a Properties as the payload. * <pre> * CAUTION: only one node can be registered, * if you want to register another one, * call deregister first * </pre> * * @param payload The information used to generate the payload Properties * @return true, register successfully; false, skip the registeration */ public boolean register(String nodeId, List<ZookeeperNodeInfo> payload) { if (payload == null || payload.isEmpty()) { return false; } lock.lock(); try { createPathIfNotExisted(); if (member != null) { LOG.warn("GroupMember has already registered. Please deregister first."); return false; } String payloadString = getPropertiesString(payload); member = new GroupMember(client, path, nodeId, payloadString.getBytes()); member.start(); LOG.info("Register Node[" + nodeId + "] in path[" + path + "]."); return true; } finally { lock.unlock(); } } /** * Close the current GroupMember. */ public void deregister() { if (member != null) { member.close(); member = null; } if (client != null && privateZkClient) { client.close(); } } /** * @see #deregister() */ public void destroy() { deregister(); } private void createPathIfNotExisted() { try { if (client.checkExists().forPath(path) == null) { LOG.info("Path[" + path + "] is NOT existed, create it."); client.create().creatingParentsIfNeeded().forPath(path); } } catch (Exception e) { LOG.error("Can NOT check the path.", e); } } private String getPropertiesString(List<ZookeeperNodeInfo> payload) { Properties properties = new Properties(); for (ZookeeperNodeInfo n : payload) { if (n.getHost() != null) { properties.setProperty(n.getPrefix() + "host", n.getHost()); } if (n.getPort() != null) { properties.setProperty(n.getPrefix() + "port", n.getPort().toString()); } if (n.getDatabase() != null) { properties.setProperty(n.getPrefix() + "database", n.getDatabase()); } if (n.getUsername() != null) { properties.setProperty(n.getPrefix() + "username", n.getUsername()); } if (n.getPassword() != null) { properties.setProperty(n.getPrefix() + "password", n.getPassword()); } } StringWriter sw = new StringWriter(); try { properties.store(sw, ""); } catch (IOException e) { LOG.error("Why Properties.store goes wrong?", e); } return sw.toString(); } public void setClient(CuratorFramework client) { if (client != null) { this.client = client; privateZkClient = false; } } public CuratorFramework getClient() { return client; } public String getZkConnectString() { return zkConnectString; } public void setZkConnectString(String zkConnectString) { this.zkConnectString = zkConnectString; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } }
wenshao/druid
core/src/main/java/com/alibaba/druid/pool/ha/node/ZookeeperNodeRegister.java
1,443
/** * @see #deregister() */
block_comment
nl
/* * Copyright 1999-2020 Alibaba Group Holding Ltd. * * 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.alibaba.druid.pool.ha.node; import com.alibaba.druid.support.logging.Log; import com.alibaba.druid.support.logging.LogFactory; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.nodes.GroupMember; import org.apache.curator.retry.RetryForever; import java.io.IOException; import java.io.StringWriter; import java.util.List; import java.util.Properties; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * A register which is used to register a node to an ephemeral node. * * @author DigitalSonic */ public class ZookeeperNodeRegister { private static final Log LOG = LogFactory.getLog(ZookeeperNodeRegister.class); private final Lock lock = new ReentrantLock(); private String zkConnectString; private String path = "/ha-druid-datasources"; private CuratorFramework client; private GroupMember member; private boolean privateZkClient; // Should I close the client? /** * Init a CuratorFramework if there's no CuratorFramework provided. */ public void init() { if (client == null) { client = CuratorFrameworkFactory.builder() .connectionTimeoutMs(5000) .connectString(zkConnectString) .retryPolicy(new RetryForever(10000)) .sessionTimeoutMs(30000) .build(); client.start(); privateZkClient = true; } } /** * Register a Node which has a Properties as the payload. * <pre> * CAUTION: only one node can be registered, * if you want to register another one, * call deregister first * </pre> * * @param payload The information used to generate the payload Properties * @return true, register successfully; false, skip the registeration */ public boolean register(String nodeId, List<ZookeeperNodeInfo> payload) { if (payload == null || payload.isEmpty()) { return false; } lock.lock(); try { createPathIfNotExisted(); if (member != null) { LOG.warn("GroupMember has already registered. Please deregister first."); return false; } String payloadString = getPropertiesString(payload); member = new GroupMember(client, path, nodeId, payloadString.getBytes()); member.start(); LOG.info("Register Node[" + nodeId + "] in path[" + path + "]."); return true; } finally { lock.unlock(); } } /** * Close the current GroupMember. */ public void deregister() { if (member != null) { member.close(); member = null; } if (client != null && privateZkClient) { client.close(); } } /** * @see #deregister() <SUF>*/ public void destroy() { deregister(); } private void createPathIfNotExisted() { try { if (client.checkExists().forPath(path) == null) { LOG.info("Path[" + path + "] is NOT existed, create it."); client.create().creatingParentsIfNeeded().forPath(path); } } catch (Exception e) { LOG.error("Can NOT check the path.", e); } } private String getPropertiesString(List<ZookeeperNodeInfo> payload) { Properties properties = new Properties(); for (ZookeeperNodeInfo n : payload) { if (n.getHost() != null) { properties.setProperty(n.getPrefix() + "host", n.getHost()); } if (n.getPort() != null) { properties.setProperty(n.getPrefix() + "port", n.getPort().toString()); } if (n.getDatabase() != null) { properties.setProperty(n.getPrefix() + "database", n.getDatabase()); } if (n.getUsername() != null) { properties.setProperty(n.getPrefix() + "username", n.getUsername()); } if (n.getPassword() != null) { properties.setProperty(n.getPrefix() + "password", n.getPassword()); } } StringWriter sw = new StringWriter(); try { properties.store(sw, ""); } catch (IOException e) { LOG.error("Why Properties.store goes wrong?", e); } return sw.toString(); } public void setClient(CuratorFramework client) { if (client != null) { this.client = client; privateZkClient = false; } } public CuratorFramework getClient() { return client; } public String getZkConnectString() { return zkConnectString; } public void setZkConnectString(String zkConnectString) { this.zkConnectString = zkConnectString; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } }
198952_12
/** * The Spider Queen. She alone can spawn Spiderlings for each Player, and if she dies the owner loses. */ // DO NOT MODIFY THIS FILE // Never try to directly create an instance of this class, or modify its member variables. // Instead, you should only be reading its variables and calling its functions. package games.spiders; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import org.json.JSONObject; import joueur.Client; import joueur.BaseGame; import joueur.BaseGameObject; // <<-- Creer-Merge: imports -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // you can add additional import(s) here // <<-- /Creer-Merge: imports -->> /** * The Spider Queen. She alone can spawn Spiderlings for each Player, and if she dies the owner loses. */ public class BroodMother extends Spider { /** * How many eggs the BroodMother has to spawn Spiderlings this turn. */ public int eggs; /** * How much health this BroodMother has left. When it reaches 0, she dies and her owner loses. */ public int health; // <<-- Creer-Merge: fields -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // you can add additional field(s) here. None of them will be tracked or updated by the server. // <<-- /Creer-Merge: fields -->> /** * Creates a new instance of a BroodMother. Used during game initialization, do not call directly. */ protected BroodMother() { super(); } /** * Consumes a Spiderling of the same owner to regain some eggs to spawn more Spiderlings. * * @param spiderling The Spiderling to consume. It must be on the same Nest as this BroodMother. * @return True if the Spiderling was consumed. False otherwise. */ public boolean consume(Spiderling spiderling) { JSONObject args = new JSONObject(); args.put("spiderling", Client.getInstance().gameManager.serializeSafe(spiderling)); return (boolean)this.runOnServer("consume", args); } /** * Spawns a new Spiderling on the same Nest as this BroodMother, consuming an egg. * * @param spiderlingType The string name of the Spiderling class you want to Spawn. Must be 'Spitter', 'Weaver', or 'Cutter'. * @return The newly spawned Spiderling if successful. Null otherwise. */ public Spiderling spawn(String spiderlingType) { JSONObject args = new JSONObject(); args.put("spiderlingType", Client.getInstance().gameManager.serializeSafe(spiderlingType)); return (Spiderling)this.runOnServer("spawn", args); } // <<-- Creer-Merge: methods -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // you can add additional method(s) here. // <<-- /Creer-Merge: methods -->> }
siggame/Joueur.java
src/main/java/games/spiders/BroodMother.java
752
// <<-- /Creer-Merge: fields -->>
line_comment
nl
/** * The Spider Queen. She alone can spawn Spiderlings for each Player, and if she dies the owner loses. */ // DO NOT MODIFY THIS FILE // Never try to directly create an instance of this class, or modify its member variables. // Instead, you should only be reading its variables and calling its functions. package games.spiders; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import org.json.JSONObject; import joueur.Client; import joueur.BaseGame; import joueur.BaseGameObject; // <<-- Creer-Merge: imports -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // you can add additional import(s) here // <<-- /Creer-Merge: imports -->> /** * The Spider Queen. She alone can spawn Spiderlings for each Player, and if she dies the owner loses. */ public class BroodMother extends Spider { /** * How many eggs the BroodMother has to spawn Spiderlings this turn. */ public int eggs; /** * How much health this BroodMother has left. When it reaches 0, she dies and her owner loses. */ public int health; // <<-- Creer-Merge: fields -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // you can add additional field(s) here. None of them will be tracked or updated by the server. // <<-- /Creer-Merge:<SUF> /** * Creates a new instance of a BroodMother. Used during game initialization, do not call directly. */ protected BroodMother() { super(); } /** * Consumes a Spiderling of the same owner to regain some eggs to spawn more Spiderlings. * * @param spiderling The Spiderling to consume. It must be on the same Nest as this BroodMother. * @return True if the Spiderling was consumed. False otherwise. */ public boolean consume(Spiderling spiderling) { JSONObject args = new JSONObject(); args.put("spiderling", Client.getInstance().gameManager.serializeSafe(spiderling)); return (boolean)this.runOnServer("consume", args); } /** * Spawns a new Spiderling on the same Nest as this BroodMother, consuming an egg. * * @param spiderlingType The string name of the Spiderling class you want to Spawn. Must be 'Spitter', 'Weaver', or 'Cutter'. * @return The newly spawned Spiderling if successful. Null otherwise. */ public Spiderling spawn(String spiderlingType) { JSONObject args = new JSONObject(); args.put("spiderlingType", Client.getInstance().gameManager.serializeSafe(spiderlingType)); return (Spiderling)this.runOnServer("spawn", args); } // <<-- Creer-Merge: methods -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // you can add additional method(s) here. // <<-- /Creer-Merge: methods -->> }
198952_18
/** * The Spider Queen. She alone can spawn Spiderlings for each Player, and if she dies the owner loses. */ // DO NOT MODIFY THIS FILE // Never try to directly create an instance of this class, or modify its member variables. // Instead, you should only be reading its variables and calling its functions. package games.spiders; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import org.json.JSONObject; import joueur.Client; import joueur.BaseGame; import joueur.BaseGameObject; // <<-- Creer-Merge: imports -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // you can add additional import(s) here // <<-- /Creer-Merge: imports -->> /** * The Spider Queen. She alone can spawn Spiderlings for each Player, and if she dies the owner loses. */ public class BroodMother extends Spider { /** * How many eggs the BroodMother has to spawn Spiderlings this turn. */ public int eggs; /** * How much health this BroodMother has left. When it reaches 0, she dies and her owner loses. */ public int health; // <<-- Creer-Merge: fields -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // you can add additional field(s) here. None of them will be tracked or updated by the server. // <<-- /Creer-Merge: fields -->> /** * Creates a new instance of a BroodMother. Used during game initialization, do not call directly. */ protected BroodMother() { super(); } /** * Consumes a Spiderling of the same owner to regain some eggs to spawn more Spiderlings. * * @param spiderling The Spiderling to consume. It must be on the same Nest as this BroodMother. * @return True if the Spiderling was consumed. False otherwise. */ public boolean consume(Spiderling spiderling) { JSONObject args = new JSONObject(); args.put("spiderling", Client.getInstance().gameManager.serializeSafe(spiderling)); return (boolean)this.runOnServer("consume", args); } /** * Spawns a new Spiderling on the same Nest as this BroodMother, consuming an egg. * * @param spiderlingType The string name of the Spiderling class you want to Spawn. Must be 'Spitter', 'Weaver', or 'Cutter'. * @return The newly spawned Spiderling if successful. Null otherwise. */ public Spiderling spawn(String spiderlingType) { JSONObject args = new JSONObject(); args.put("spiderlingType", Client.getInstance().gameManager.serializeSafe(spiderlingType)); return (Spiderling)this.runOnServer("spawn", args); } // <<-- Creer-Merge: methods -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // you can add additional method(s) here. // <<-- /Creer-Merge: methods -->> }
siggame/Joueur.java
src/main/java/games/spiders/BroodMother.java
752
// <<-- /Creer-Merge: methods -->>
line_comment
nl
/** * The Spider Queen. She alone can spawn Spiderlings for each Player, and if she dies the owner loses. */ // DO NOT MODIFY THIS FILE // Never try to directly create an instance of this class, or modify its member variables. // Instead, you should only be reading its variables and calling its functions. package games.spiders; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import org.json.JSONObject; import joueur.Client; import joueur.BaseGame; import joueur.BaseGameObject; // <<-- Creer-Merge: imports -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // you can add additional import(s) here // <<-- /Creer-Merge: imports -->> /** * The Spider Queen. She alone can spawn Spiderlings for each Player, and if she dies the owner loses. */ public class BroodMother extends Spider { /** * How many eggs the BroodMother has to spawn Spiderlings this turn. */ public int eggs; /** * How much health this BroodMother has left. When it reaches 0, she dies and her owner loses. */ public int health; // <<-- Creer-Merge: fields -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // you can add additional field(s) here. None of them will be tracked or updated by the server. // <<-- /Creer-Merge: fields -->> /** * Creates a new instance of a BroodMother. Used during game initialization, do not call directly. */ protected BroodMother() { super(); } /** * Consumes a Spiderling of the same owner to regain some eggs to spawn more Spiderlings. * * @param spiderling The Spiderling to consume. It must be on the same Nest as this BroodMother. * @return True if the Spiderling was consumed. False otherwise. */ public boolean consume(Spiderling spiderling) { JSONObject args = new JSONObject(); args.put("spiderling", Client.getInstance().gameManager.serializeSafe(spiderling)); return (boolean)this.runOnServer("consume", args); } /** * Spawns a new Spiderling on the same Nest as this BroodMother, consuming an egg. * * @param spiderlingType The string name of the Spiderling class you want to Spawn. Must be 'Spitter', 'Weaver', or 'Cutter'. * @return The newly spawned Spiderling if successful. Null otherwise. */ public Spiderling spawn(String spiderlingType) { JSONObject args = new JSONObject(); args.put("spiderlingType", Client.getInstance().gameManager.serializeSafe(spiderlingType)); return (Spiderling)this.runOnServer("spawn", args); } // <<-- Creer-Merge: methods -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // you can add additional method(s) here. // <<-- /Creer-Merge:<SUF> }
198976_2
package util; public final class Constants{ public static final byte PLATFORM_INTEL = 0x01; public static final byte PLATFORM_POWERPC = 0x02; public static final byte PLATFORM_MACOSX = 0x03; public static final byte PRODUCT_STARCRAFT = 0x01; public static final byte PRODUCT_BROODWAR = 0x02; public static final byte PRODUCT_WAR2BNE = 0x03; public static final byte PRODUCT_DIABLO2 = 0x04; public static final byte PRODUCT_LORDOFDESTRUCTION = 0x05; public static final byte PRODUCT_JAPANSTARCRAFT = 0x06; public static final byte PRODUCT_WARCRAFT3 = 0x07; public static final byte PRODUCT_THEFROZENTHRONE = 0x08; public static final byte PRODUCT_DIABLO = 0x09; public static final byte PRODUCT_DIABLOSHAREWARE = 0x0A; public static final byte PRODUCT_STARCRAFTSHAREWARE= 0x0B; public static String[] prods = {"STAR", "SEXP", "W2BN", "D2DV", "D2XP", "JSTR", "WAR3", "W3XP", "DRTL", "DSHR", "SSHR"}; public static String[][] IX86files = { {"IX86/STAR/", "StarCraft.exe", "Storm.dll", "NULL", "STAR.bin"}, {"IX86/STAR/", "StarCraft.exe", "Storm.dll", "NULL", "STAR.bin"}, {"IX86/W2BN/", "Warcraft II BNE.exe", "Storm.dll", "Battle.snp", "W2BN.bin"}, {"IX86/D2DV/", "Game.exe", "NULL", "NULL", "D2DV.bin"}, {"IX86/D2XP/", "Game.exe", "NULL", "NULL", "D2XP.bin"}, {"IX86/JSTR/", "StarcraftJ.exe", "Storm.dll", "Battle.snp", "JSTR.bin"}, {"IX86/WAR3/", "Warcraft III.exe", "NULL", "NULL", "WAR3.bin"}, {"IX86/WAR3/", "Warcraft III.exe", "NULL", "NULL", "WAR3.bin"}, {"IX86/DRTL/", "Diablo.exe", "Storm.dll", "Battle.snp", "DRTL.bin"}, {"IX86/DSHR/", "Diablo_s.exe", "Storm.dll", "Battle.snp", "DSHR.bin"}, {"IX86/SSHR/", "Starcraft.exe", "Storm.dll", "Battle.snp", "SSHR.bin"} }; public static int[] IX86verbytes = {0xD3, 0xD3, 0x4f, 0x0e, 0x0e, 0xa9, 0x1E, 0x1E, 0x2a, 0x2a, 0xa5}; public static String[] IX86versions = {"", "", "2.0.2.1", "1.14.3.71", "1.14.3.71", "", "", "", "2001, 5, 18, 1", "", ""}; public static String[] IX86certs = {"", "", "", "", "", "", "", "", "", "", ""}; public static String ArchivePath = "DLLs/"; public static String LogFilePath = "./Logs/"; public static String build="Build V3.1 Bug Fixes, SQL Stats tracking. (10-14-07)"; //public static String build="Build V3.0 BotNet Admin, Lockdown, Legacy Clients.(07-07-07)"; //public static String build="Build V2.9 Remote admin, extended admin commands w/ JSTR support.(01/18/06)"; public static int maxThreads=500; public static int BNLSPort=9367; public static boolean requireAuthorization=false; public static boolean trackStatistics=true; public static int ipAuthStatus=1; //default is IPBans on public static boolean displayPacketInfo=true; public static boolean displayParseInfo=false; public static boolean debugInfo=false; public static boolean enableLogging = false; public static int logKeepDuration = 7; public static boolean RunAdmin = false; public static String BotNetBotID = ""; public static String BotNetHubPW = ""; public static String BotNetDatabase = ""; public static String BotNetUsername = ""; public static String BotNetPassword = ""; public static String BotNetServer = "www.valhallalegends.com"; public static boolean LogStats = false; public static String StatsUsername = ""; public static String StatsPassword = ""; public static String StatsDatabase = ""; public static String StatsServer = "localhost"; public static int StatsQueue = 10; public static boolean StatsLogIps = false; public static boolean StatsLogCRevs = true; public static boolean StatsLogBotIDs = true; public static boolean StatsLogConns = true; public static boolean StatsCheckSchema = true; public static String DownloadPath = "./"; public static boolean RunHTTP = true; public static int HTTPPort = 81; public static int lngServerVer=0x01; public static int numOfNews=0; public static String[] strNews={"", "", "", "", ""}; }
BNETDocs/JBLS
util/Constants.java
1,424
//default is IPBans on
line_comment
nl
package util; public final class Constants{ public static final byte PLATFORM_INTEL = 0x01; public static final byte PLATFORM_POWERPC = 0x02; public static final byte PLATFORM_MACOSX = 0x03; public static final byte PRODUCT_STARCRAFT = 0x01; public static final byte PRODUCT_BROODWAR = 0x02; public static final byte PRODUCT_WAR2BNE = 0x03; public static final byte PRODUCT_DIABLO2 = 0x04; public static final byte PRODUCT_LORDOFDESTRUCTION = 0x05; public static final byte PRODUCT_JAPANSTARCRAFT = 0x06; public static final byte PRODUCT_WARCRAFT3 = 0x07; public static final byte PRODUCT_THEFROZENTHRONE = 0x08; public static final byte PRODUCT_DIABLO = 0x09; public static final byte PRODUCT_DIABLOSHAREWARE = 0x0A; public static final byte PRODUCT_STARCRAFTSHAREWARE= 0x0B; public static String[] prods = {"STAR", "SEXP", "W2BN", "D2DV", "D2XP", "JSTR", "WAR3", "W3XP", "DRTL", "DSHR", "SSHR"}; public static String[][] IX86files = { {"IX86/STAR/", "StarCraft.exe", "Storm.dll", "NULL", "STAR.bin"}, {"IX86/STAR/", "StarCraft.exe", "Storm.dll", "NULL", "STAR.bin"}, {"IX86/W2BN/", "Warcraft II BNE.exe", "Storm.dll", "Battle.snp", "W2BN.bin"}, {"IX86/D2DV/", "Game.exe", "NULL", "NULL", "D2DV.bin"}, {"IX86/D2XP/", "Game.exe", "NULL", "NULL", "D2XP.bin"}, {"IX86/JSTR/", "StarcraftJ.exe", "Storm.dll", "Battle.snp", "JSTR.bin"}, {"IX86/WAR3/", "Warcraft III.exe", "NULL", "NULL", "WAR3.bin"}, {"IX86/WAR3/", "Warcraft III.exe", "NULL", "NULL", "WAR3.bin"}, {"IX86/DRTL/", "Diablo.exe", "Storm.dll", "Battle.snp", "DRTL.bin"}, {"IX86/DSHR/", "Diablo_s.exe", "Storm.dll", "Battle.snp", "DSHR.bin"}, {"IX86/SSHR/", "Starcraft.exe", "Storm.dll", "Battle.snp", "SSHR.bin"} }; public static int[] IX86verbytes = {0xD3, 0xD3, 0x4f, 0x0e, 0x0e, 0xa9, 0x1E, 0x1E, 0x2a, 0x2a, 0xa5}; public static String[] IX86versions = {"", "", "2.0.2.1", "1.14.3.71", "1.14.3.71", "", "", "", "2001, 5, 18, 1", "", ""}; public static String[] IX86certs = {"", "", "", "", "", "", "", "", "", "", ""}; public static String ArchivePath = "DLLs/"; public static String LogFilePath = "./Logs/"; public static String build="Build V3.1 Bug Fixes, SQL Stats tracking. (10-14-07)"; //public static String build="Build V3.0 BotNet Admin, Lockdown, Legacy Clients.(07-07-07)"; //public static String build="Build V2.9 Remote admin, extended admin commands w/ JSTR support.(01/18/06)"; public static int maxThreads=500; public static int BNLSPort=9367; public static boolean requireAuthorization=false; public static boolean trackStatistics=true; public static int ipAuthStatus=1; //default is<SUF> public static boolean displayPacketInfo=true; public static boolean displayParseInfo=false; public static boolean debugInfo=false; public static boolean enableLogging = false; public static int logKeepDuration = 7; public static boolean RunAdmin = false; public static String BotNetBotID = ""; public static String BotNetHubPW = ""; public static String BotNetDatabase = ""; public static String BotNetUsername = ""; public static String BotNetPassword = ""; public static String BotNetServer = "www.valhallalegends.com"; public static boolean LogStats = false; public static String StatsUsername = ""; public static String StatsPassword = ""; public static String StatsDatabase = ""; public static String StatsServer = "localhost"; public static int StatsQueue = 10; public static boolean StatsLogIps = false; public static boolean StatsLogCRevs = true; public static boolean StatsLogBotIDs = true; public static boolean StatsLogConns = true; public static boolean StatsCheckSchema = true; public static String DownloadPath = "./"; public static boolean RunHTTP = true; public static int HTTPPort = 81; public static int lngServerVer=0x01; public static int numOfNews=0; public static String[] strNews={"", "", "", "", ""}; }
198981_7
/////////////////////////////////////////////////////////////////////// // Name: UnitWyvern // Desc: Big nasty wyvern // Date: 7/14/2009 - Gabe Jones // TODO: /////////////////////////////////////////////////////////////////////// package leo.shared.crusades; // imports import leo.shared.*; import java.util.Vector; public class UnitWyvern extends Unit { ///////////////////////////////////////////////////////////////// // Properties ///////////////////////////////////////////////////////////////// private boolean fed = false; private Unit meal = null; private EventWyvernMove broodmother = null; ///////////////////////////////////////////////////////////////// // Constructor ///////////////////////////////////////////////////////////////// public UnitWyvern(Castle newCastle) { castle = newCastle; // access accessLevel = Unit.LEGIONS; // Initialize id = Unit.WYVERN; category = Unit.WYRMS; name = Strings.UNIT_WYVERN_1; actions = new Vector<Action>(); damage = 4; armor = 2; life = 7; lifeMax = 7; actionsLeft = 1; actionsMax = 1; move = new ActionWyvernMove(this, (byte) 1, (byte) 0, TargetType.ANY_AREA, (byte) 4); attack = null; //new ActionAttack(this, (byte) 0, (byte) 1, TargetType.UNIT_LINE, (byte) 1); deployCost = 5; castleCost = 550; organic = true; appearance = Constants.IMG_WYVERN; add(new ActionFlight(this)); //add(new ActionBroodmother(this)); broodmother = new EventWyvernMove(this); add((Event) broodmother); add((Action) broodmother); //add(new ActionWyvernMove(this, (byte)1, (byte)0, TargetType.ANY_LINE_JUMP, (byte)4)); //Temporarily disabled. Going to be replaced /*EventDevour ed = new EventDevour(this); add((Action) ed); add((Event) ed);*/ actions.add(move); ActionAttack bite = new ActionAttack(this, (byte) 0, (byte) 1, TargetType.UNIT_LINE, (byte) 1); actions.add(bite); EventSting sting = new EventSting(this); add((Action) sting); add((Event) sting); // Add the actions //actions.add(attack); //Same as Devour //actions.add(new ActionEgg(this)); } /*public void setLocation(short newLocation) { broodmother.setEggPos(newLocation); super.setLocation(newLocation); }*/ ///////////////////////////////////////////////////////////////// // Has it fed? ///////////////////////////////////////////////////////////////// public boolean fed() { return fed; } public void feed(boolean newState) { fed = newState; } public Unit getMeal() { return meal; } public void setMeal(Unit newMeal) { meal = newMeal; } ///////////////////////////////////////////////////////////////// // Upon death or banish, lay the egg. (Actually we decided to remove this for now at least) ///////////////////////////////////////////////////////////////// /*public void die(boolean death, Unit source) { if(fed()){ broodmother.layChild(); feed(false); } // Ok, die now super.die(death, source); }*/ }
zatikon/zatikon
src/main/java/leo/shared/crusades/UnitWyvern.java
862
//Same as Devour
line_comment
nl
/////////////////////////////////////////////////////////////////////// // Name: UnitWyvern // Desc: Big nasty wyvern // Date: 7/14/2009 - Gabe Jones // TODO: /////////////////////////////////////////////////////////////////////// package leo.shared.crusades; // imports import leo.shared.*; import java.util.Vector; public class UnitWyvern extends Unit { ///////////////////////////////////////////////////////////////// // Properties ///////////////////////////////////////////////////////////////// private boolean fed = false; private Unit meal = null; private EventWyvernMove broodmother = null; ///////////////////////////////////////////////////////////////// // Constructor ///////////////////////////////////////////////////////////////// public UnitWyvern(Castle newCastle) { castle = newCastle; // access accessLevel = Unit.LEGIONS; // Initialize id = Unit.WYVERN; category = Unit.WYRMS; name = Strings.UNIT_WYVERN_1; actions = new Vector<Action>(); damage = 4; armor = 2; life = 7; lifeMax = 7; actionsLeft = 1; actionsMax = 1; move = new ActionWyvernMove(this, (byte) 1, (byte) 0, TargetType.ANY_AREA, (byte) 4); attack = null; //new ActionAttack(this, (byte) 0, (byte) 1, TargetType.UNIT_LINE, (byte) 1); deployCost = 5; castleCost = 550; organic = true; appearance = Constants.IMG_WYVERN; add(new ActionFlight(this)); //add(new ActionBroodmother(this)); broodmother = new EventWyvernMove(this); add((Event) broodmother); add((Action) broodmother); //add(new ActionWyvernMove(this, (byte)1, (byte)0, TargetType.ANY_LINE_JUMP, (byte)4)); //Temporarily disabled. Going to be replaced /*EventDevour ed = new EventDevour(this); add((Action) ed); add((Event) ed);*/ actions.add(move); ActionAttack bite = new ActionAttack(this, (byte) 0, (byte) 1, TargetType.UNIT_LINE, (byte) 1); actions.add(bite); EventSting sting = new EventSting(this); add((Action) sting); add((Event) sting); // Add the actions //actions.add(attack); //Same as<SUF> //actions.add(new ActionEgg(this)); } /*public void setLocation(short newLocation) { broodmother.setEggPos(newLocation); super.setLocation(newLocation); }*/ ///////////////////////////////////////////////////////////////// // Has it fed? ///////////////////////////////////////////////////////////////// public boolean fed() { return fed; } public void feed(boolean newState) { fed = newState; } public Unit getMeal() { return meal; } public void setMeal(Unit newMeal) { meal = newMeal; } ///////////////////////////////////////////////////////////////// // Upon death or banish, lay the egg. (Actually we decided to remove this for now at least) ///////////////////////////////////////////////////////////////// /*public void die(boolean death, Unit source) { if(fed()){ broodmother.layChild(); feed(false); } // Ok, die now super.die(death, source); }*/ }
199046_7
/*** * Copyright 2002-2010 jamod development team * * 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. * * Original implementation by jamod development team. * This file modified by Charles Hache <[email protected]> ***/ package net.wimpi.modbus.msg; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import net.wimpi.modbus.Modbus; import net.wimpi.modbus.ModbusCoupler; import net.wimpi.modbus.procimg.DigitalOut; import net.wimpi.modbus.procimg.IllegalAddressException; import net.wimpi.modbus.procimg.ProcessImage; /** * Class implementing a <tt>WriteCoilRequest</tt>. The implementation directly * correlates with the class 0 function <i>write coil (FC 5)</i>. It * encapsulates the corresponding request message. * * @author Dieter Wimberger * @version @version@ (@date@) */ public final class WriteCoilRequest extends ModbusRequest { // instance attributes private int m_Reference; private boolean m_Coil; /** * Constructs a new <tt>WriteCoilRequest</tt> instance. */ public WriteCoilRequest() { super(); setFunctionCode(Modbus.WRITE_COIL); // 4 bytes (unit id and function code is excluded) setDataLength(4); }// constructor /** * Constructs a new <tt>WriteCoilRequest</tt> instance with a given * reference and state to be written. * <p> * * @param ref * the reference number of the register to read from. * @param b * true if the coil should be set of false if it should be unset. */ public WriteCoilRequest(int ref, boolean b) { super(); setFunctionCode(Modbus.WRITE_COIL); // 4 bytes (unit id and function code is excluded) setDataLength(4); setReference(ref); setCoil(b); }// constructor public ModbusResponse createResponse() { WriteCoilResponse response = null; DigitalOut dout = null; // 1. get process image ProcessImage procimg = ModbusCoupler.getReference().getProcessImage(); // 2. get coil try { dout = procimg.getDigitalOut(this.getReference()); // 3. set coil dout.set(this.getCoil()); // if(Modbus.debug) // System.out.println("set coil ref="+this.getReference()+" state=" // + this.getCoil()); } catch (IllegalAddressException iaex) { return createExceptionResponse(Modbus.ILLEGAL_ADDRESS_EXCEPTION); } response = new WriteCoilResponse(this.getReference(), dout.isSet()); // transfer header data if (!isHeadless()) { response.setTransactionID(this.getTransactionID()); response.setProtocolID(this.getProtocolID()); } else { response.setHeadless(); } response.setUnitID(this.getUnitID()); response.setFunctionCode(this.getFunctionCode()); return response; }// createResponse /** * Sets the reference of the register of the coil that should be written to * with this <tt>ReadCoilsRequest</tt>. * <p> * * @param ref * the reference of the coil's register. */ public void setReference(int ref) { m_Reference = ref; // setChanged(true); }// setReference /** * Returns the reference of the register of the coil that should be written * to with this <tt>ReadCoilsRequest</tt>. * <p> * * @return the reference of the coil's register. */ public int getReference() { return m_Reference; }// getReference /** * Sets the state that should be written with this <tt>WriteCoilRequest</tt> * . * <p> * * @param b * true if the coil should be set of false if it should be unset. */ public void setCoil(boolean b) { m_Coil = b; // setChanged(true); }// setCoil /** * Returns the state that should be written with this * <tt>WriteCoilRequest</tt>. * <p> * * @return true if the coil should be set of false if it should be unset. */ public boolean getCoil() { return m_Coil; }// getCoil public void writeData(DataOutput dout) throws IOException { dout.writeShort(m_Reference); if (m_Coil) { dout.write(Modbus.COIL_ON_BYTES, 0, 2); } else { dout.write(Modbus.COIL_OFF_BYTES, 0, 2); } } public void readData(DataInput din) throws IOException { m_Reference = din.readUnsignedShort(); if (din.readByte() == Modbus.COIL_ON) { m_Coil = true; } else { m_Coil = false; } // skip last byte din.readByte(); }// readData public String toString() { return "WriteCoilRequest - Ref: " + m_Reference + " coil: " + m_Coil; } }// class WriteCoilRequest
jeick/jamod
src/main/java/net/wimpi/modbus/msg/WriteCoilRequest.java
1,498
// 2. get coil
line_comment
nl
/*** * Copyright 2002-2010 jamod development team * * 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. * * Original implementation by jamod development team. * This file modified by Charles Hache <[email protected]> ***/ package net.wimpi.modbus.msg; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import net.wimpi.modbus.Modbus; import net.wimpi.modbus.ModbusCoupler; import net.wimpi.modbus.procimg.DigitalOut; import net.wimpi.modbus.procimg.IllegalAddressException; import net.wimpi.modbus.procimg.ProcessImage; /** * Class implementing a <tt>WriteCoilRequest</tt>. The implementation directly * correlates with the class 0 function <i>write coil (FC 5)</i>. It * encapsulates the corresponding request message. * * @author Dieter Wimberger * @version @version@ (@date@) */ public final class WriteCoilRequest extends ModbusRequest { // instance attributes private int m_Reference; private boolean m_Coil; /** * Constructs a new <tt>WriteCoilRequest</tt> instance. */ public WriteCoilRequest() { super(); setFunctionCode(Modbus.WRITE_COIL); // 4 bytes (unit id and function code is excluded) setDataLength(4); }// constructor /** * Constructs a new <tt>WriteCoilRequest</tt> instance with a given * reference and state to be written. * <p> * * @param ref * the reference number of the register to read from. * @param b * true if the coil should be set of false if it should be unset. */ public WriteCoilRequest(int ref, boolean b) { super(); setFunctionCode(Modbus.WRITE_COIL); // 4 bytes (unit id and function code is excluded) setDataLength(4); setReference(ref); setCoil(b); }// constructor public ModbusResponse createResponse() { WriteCoilResponse response = null; DigitalOut dout = null; // 1. get process image ProcessImage procimg = ModbusCoupler.getReference().getProcessImage(); // 2. get<SUF> try { dout = procimg.getDigitalOut(this.getReference()); // 3. set coil dout.set(this.getCoil()); // if(Modbus.debug) // System.out.println("set coil ref="+this.getReference()+" state=" // + this.getCoil()); } catch (IllegalAddressException iaex) { return createExceptionResponse(Modbus.ILLEGAL_ADDRESS_EXCEPTION); } response = new WriteCoilResponse(this.getReference(), dout.isSet()); // transfer header data if (!isHeadless()) { response.setTransactionID(this.getTransactionID()); response.setProtocolID(this.getProtocolID()); } else { response.setHeadless(); } response.setUnitID(this.getUnitID()); response.setFunctionCode(this.getFunctionCode()); return response; }// createResponse /** * Sets the reference of the register of the coil that should be written to * with this <tt>ReadCoilsRequest</tt>. * <p> * * @param ref * the reference of the coil's register. */ public void setReference(int ref) { m_Reference = ref; // setChanged(true); }// setReference /** * Returns the reference of the register of the coil that should be written * to with this <tt>ReadCoilsRequest</tt>. * <p> * * @return the reference of the coil's register. */ public int getReference() { return m_Reference; }// getReference /** * Sets the state that should be written with this <tt>WriteCoilRequest</tt> * . * <p> * * @param b * true if the coil should be set of false if it should be unset. */ public void setCoil(boolean b) { m_Coil = b; // setChanged(true); }// setCoil /** * Returns the state that should be written with this * <tt>WriteCoilRequest</tt>. * <p> * * @return true if the coil should be set of false if it should be unset. */ public boolean getCoil() { return m_Coil; }// getCoil public void writeData(DataOutput dout) throws IOException { dout.writeShort(m_Reference); if (m_Coil) { dout.write(Modbus.COIL_ON_BYTES, 0, 2); } else { dout.write(Modbus.COIL_OFF_BYTES, 0, 2); } } public void readData(DataInput din) throws IOException { m_Reference = din.readUnsignedShort(); if (din.readByte() == Modbus.COIL_ON) { m_Coil = true; } else { m_Coil = false; } // skip last byte din.readByte(); }// readData public String toString() { return "WriteCoilRequest - Ref: " + m_Reference + " coil: " + m_Coil; } }// class WriteCoilRequest
199070_1
package be.kdg.pensioen.view; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; /** * LEFT: geboorteJaar * CENTER: berekenButton * RIGHT: pensioenJaar * Insets: TRouBLe */ public class PensioenView extends BorderPane { // Attributes private TextField geboorteJaarField; private TextField dataField; private Button berekenButton; // Constructors public PensioenView() { this.initialiseNodes(); this.layoutNodes(); } // Methods public void initialiseNodes() { // 3.1.1 Voorzie de drie attributen van een waarde. this.geboorteJaarField = new TextField(); this.dataField = new TextField(); this.berekenButton = new Button("Bereken"); // 3.1.2 Het 2de tekstveld mag niet editeerbaar zijn. this.dataField.setEditable(false); // 3.1.3 Beide velden hebben bij voorkeur 4 kolommen. GridPane txtGrid = new GridPane(); txtGrid.add(this.dataField, 0,0,3,3); } public void layoutNodes() { // 3.2.1 Maak gebruik van de juiste set… methode van de klasse BorderPane om de componenten op de juiste plaats te krijgen. this.setLeft(this.geboorteJaarField); this.setCenter(this.berekenButton); this.setRight(this.dataField); BorderPane.setAlignment(this.geboorteJaarField, Pos.CENTER_LEFT); BorderPane.setAlignment(this.berekenButton, Pos.CENTER); BorderPane.setAlignment(this.dataField, Pos.CENTER_RIGHT); // 3.2.2 Zorg voor een horizontale en verticale “marge” van 10 pixels tussen de cellen van de BorderPane. // Zorg ook voor een “padding” van 10 pixels. BorderPane.setMargin(this.geboorteJaarField, new Insets(10)); // Marge BorderPane.setMargin(this.berekenButton, new Insets(10)); // Marge BorderPane.setMargin(this.dataField, new Insets(10)); // Marge this.geboorteJaarField.setPadding(new Insets(10)); // Padding this.berekenButton.setPadding(new Insets(10)); // Padding this.dataField.setPadding(new Insets(10)); // Padding } Button getBerekenButton() { // Get.. return this.berekenButton; } TextField getGeboorteJaarField() { // Get.. return this.geboorteJaarField; } public void setDataField(String pensioenJaar) { // Set.. this.dataField.setText(pensioenJaar); } }
EliasDeHondt/ComputerProgramming1-JavaFX
W13P3/Pensioen/src/be/kdg/pensioen/view/PensioenView.java
736
// 3.1.1 Voorzie de drie attributen van een waarde.
line_comment
nl
package be.kdg.pensioen.view; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; /** * LEFT: geboorteJaar * CENTER: berekenButton * RIGHT: pensioenJaar * Insets: TRouBLe */ public class PensioenView extends BorderPane { // Attributes private TextField geboorteJaarField; private TextField dataField; private Button berekenButton; // Constructors public PensioenView() { this.initialiseNodes(); this.layoutNodes(); } // Methods public void initialiseNodes() { // 3.1.1 Voorzie<SUF> this.geboorteJaarField = new TextField(); this.dataField = new TextField(); this.berekenButton = new Button("Bereken"); // 3.1.2 Het 2de tekstveld mag niet editeerbaar zijn. this.dataField.setEditable(false); // 3.1.3 Beide velden hebben bij voorkeur 4 kolommen. GridPane txtGrid = new GridPane(); txtGrid.add(this.dataField, 0,0,3,3); } public void layoutNodes() { // 3.2.1 Maak gebruik van de juiste set… methode van de klasse BorderPane om de componenten op de juiste plaats te krijgen. this.setLeft(this.geboorteJaarField); this.setCenter(this.berekenButton); this.setRight(this.dataField); BorderPane.setAlignment(this.geboorteJaarField, Pos.CENTER_LEFT); BorderPane.setAlignment(this.berekenButton, Pos.CENTER); BorderPane.setAlignment(this.dataField, Pos.CENTER_RIGHT); // 3.2.2 Zorg voor een horizontale en verticale “marge” van 10 pixels tussen de cellen van de BorderPane. // Zorg ook voor een “padding” van 10 pixels. BorderPane.setMargin(this.geboorteJaarField, new Insets(10)); // Marge BorderPane.setMargin(this.berekenButton, new Insets(10)); // Marge BorderPane.setMargin(this.dataField, new Insets(10)); // Marge this.geboorteJaarField.setPadding(new Insets(10)); // Padding this.berekenButton.setPadding(new Insets(10)); // Padding this.dataField.setPadding(new Insets(10)); // Padding } Button getBerekenButton() { // Get.. return this.berekenButton; } TextField getGeboorteJaarField() { // Get.. return this.geboorteJaarField; } public void setDataField(String pensioenJaar) { // Set.. this.dataField.setText(pensioenJaar); } }
199070_2
package be.kdg.pensioen.view; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; /** * LEFT: geboorteJaar * CENTER: berekenButton * RIGHT: pensioenJaar * Insets: TRouBLe */ public class PensioenView extends BorderPane { // Attributes private TextField geboorteJaarField; private TextField dataField; private Button berekenButton; // Constructors public PensioenView() { this.initialiseNodes(); this.layoutNodes(); } // Methods public void initialiseNodes() { // 3.1.1 Voorzie de drie attributen van een waarde. this.geboorteJaarField = new TextField(); this.dataField = new TextField(); this.berekenButton = new Button("Bereken"); // 3.1.2 Het 2de tekstveld mag niet editeerbaar zijn. this.dataField.setEditable(false); // 3.1.3 Beide velden hebben bij voorkeur 4 kolommen. GridPane txtGrid = new GridPane(); txtGrid.add(this.dataField, 0,0,3,3); } public void layoutNodes() { // 3.2.1 Maak gebruik van de juiste set… methode van de klasse BorderPane om de componenten op de juiste plaats te krijgen. this.setLeft(this.geboorteJaarField); this.setCenter(this.berekenButton); this.setRight(this.dataField); BorderPane.setAlignment(this.geboorteJaarField, Pos.CENTER_LEFT); BorderPane.setAlignment(this.berekenButton, Pos.CENTER); BorderPane.setAlignment(this.dataField, Pos.CENTER_RIGHT); // 3.2.2 Zorg voor een horizontale en verticale “marge” van 10 pixels tussen de cellen van de BorderPane. // Zorg ook voor een “padding” van 10 pixels. BorderPane.setMargin(this.geboorteJaarField, new Insets(10)); // Marge BorderPane.setMargin(this.berekenButton, new Insets(10)); // Marge BorderPane.setMargin(this.dataField, new Insets(10)); // Marge this.geboorteJaarField.setPadding(new Insets(10)); // Padding this.berekenButton.setPadding(new Insets(10)); // Padding this.dataField.setPadding(new Insets(10)); // Padding } Button getBerekenButton() { // Get.. return this.berekenButton; } TextField getGeboorteJaarField() { // Get.. return this.geboorteJaarField; } public void setDataField(String pensioenJaar) { // Set.. this.dataField.setText(pensioenJaar); } }
EliasDeHondt/ComputerProgramming1-JavaFX
W13P3/Pensioen/src/be/kdg/pensioen/view/PensioenView.java
736
// 3.1.2 Het 2de tekstveld mag niet editeerbaar zijn.
line_comment
nl
package be.kdg.pensioen.view; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; /** * LEFT: geboorteJaar * CENTER: berekenButton * RIGHT: pensioenJaar * Insets: TRouBLe */ public class PensioenView extends BorderPane { // Attributes private TextField geboorteJaarField; private TextField dataField; private Button berekenButton; // Constructors public PensioenView() { this.initialiseNodes(); this.layoutNodes(); } // Methods public void initialiseNodes() { // 3.1.1 Voorzie de drie attributen van een waarde. this.geboorteJaarField = new TextField(); this.dataField = new TextField(); this.berekenButton = new Button("Bereken"); // 3.1.2 Het<SUF> this.dataField.setEditable(false); // 3.1.3 Beide velden hebben bij voorkeur 4 kolommen. GridPane txtGrid = new GridPane(); txtGrid.add(this.dataField, 0,0,3,3); } public void layoutNodes() { // 3.2.1 Maak gebruik van de juiste set… methode van de klasse BorderPane om de componenten op de juiste plaats te krijgen. this.setLeft(this.geboorteJaarField); this.setCenter(this.berekenButton); this.setRight(this.dataField); BorderPane.setAlignment(this.geboorteJaarField, Pos.CENTER_LEFT); BorderPane.setAlignment(this.berekenButton, Pos.CENTER); BorderPane.setAlignment(this.dataField, Pos.CENTER_RIGHT); // 3.2.2 Zorg voor een horizontale en verticale “marge” van 10 pixels tussen de cellen van de BorderPane. // Zorg ook voor een “padding” van 10 pixels. BorderPane.setMargin(this.geboorteJaarField, new Insets(10)); // Marge BorderPane.setMargin(this.berekenButton, new Insets(10)); // Marge BorderPane.setMargin(this.dataField, new Insets(10)); // Marge this.geboorteJaarField.setPadding(new Insets(10)); // Padding this.berekenButton.setPadding(new Insets(10)); // Padding this.dataField.setPadding(new Insets(10)); // Padding } Button getBerekenButton() { // Get.. return this.berekenButton; } TextField getGeboorteJaarField() { // Get.. return this.geboorteJaarField; } public void setDataField(String pensioenJaar) { // Set.. this.dataField.setText(pensioenJaar); } }
199070_3
package be.kdg.pensioen.view; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; /** * LEFT: geboorteJaar * CENTER: berekenButton * RIGHT: pensioenJaar * Insets: TRouBLe */ public class PensioenView extends BorderPane { // Attributes private TextField geboorteJaarField; private TextField dataField; private Button berekenButton; // Constructors public PensioenView() { this.initialiseNodes(); this.layoutNodes(); } // Methods public void initialiseNodes() { // 3.1.1 Voorzie de drie attributen van een waarde. this.geboorteJaarField = new TextField(); this.dataField = new TextField(); this.berekenButton = new Button("Bereken"); // 3.1.2 Het 2de tekstveld mag niet editeerbaar zijn. this.dataField.setEditable(false); // 3.1.3 Beide velden hebben bij voorkeur 4 kolommen. GridPane txtGrid = new GridPane(); txtGrid.add(this.dataField, 0,0,3,3); } public void layoutNodes() { // 3.2.1 Maak gebruik van de juiste set… methode van de klasse BorderPane om de componenten op de juiste plaats te krijgen. this.setLeft(this.geboorteJaarField); this.setCenter(this.berekenButton); this.setRight(this.dataField); BorderPane.setAlignment(this.geboorteJaarField, Pos.CENTER_LEFT); BorderPane.setAlignment(this.berekenButton, Pos.CENTER); BorderPane.setAlignment(this.dataField, Pos.CENTER_RIGHT); // 3.2.2 Zorg voor een horizontale en verticale “marge” van 10 pixels tussen de cellen van de BorderPane. // Zorg ook voor een “padding” van 10 pixels. BorderPane.setMargin(this.geboorteJaarField, new Insets(10)); // Marge BorderPane.setMargin(this.berekenButton, new Insets(10)); // Marge BorderPane.setMargin(this.dataField, new Insets(10)); // Marge this.geboorteJaarField.setPadding(new Insets(10)); // Padding this.berekenButton.setPadding(new Insets(10)); // Padding this.dataField.setPadding(new Insets(10)); // Padding } Button getBerekenButton() { // Get.. return this.berekenButton; } TextField getGeboorteJaarField() { // Get.. return this.geboorteJaarField; } public void setDataField(String pensioenJaar) { // Set.. this.dataField.setText(pensioenJaar); } }
EliasDeHondt/ComputerProgramming1-JavaFX
W13P3/Pensioen/src/be/kdg/pensioen/view/PensioenView.java
736
// 3.1.3 Beide velden hebben bij voorkeur 4 kolommen.
line_comment
nl
package be.kdg.pensioen.view; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; /** * LEFT: geboorteJaar * CENTER: berekenButton * RIGHT: pensioenJaar * Insets: TRouBLe */ public class PensioenView extends BorderPane { // Attributes private TextField geboorteJaarField; private TextField dataField; private Button berekenButton; // Constructors public PensioenView() { this.initialiseNodes(); this.layoutNodes(); } // Methods public void initialiseNodes() { // 3.1.1 Voorzie de drie attributen van een waarde. this.geboorteJaarField = new TextField(); this.dataField = new TextField(); this.berekenButton = new Button("Bereken"); // 3.1.2 Het 2de tekstveld mag niet editeerbaar zijn. this.dataField.setEditable(false); // 3.1.3 Beide<SUF> GridPane txtGrid = new GridPane(); txtGrid.add(this.dataField, 0,0,3,3); } public void layoutNodes() { // 3.2.1 Maak gebruik van de juiste set… methode van de klasse BorderPane om de componenten op de juiste plaats te krijgen. this.setLeft(this.geboorteJaarField); this.setCenter(this.berekenButton); this.setRight(this.dataField); BorderPane.setAlignment(this.geboorteJaarField, Pos.CENTER_LEFT); BorderPane.setAlignment(this.berekenButton, Pos.CENTER); BorderPane.setAlignment(this.dataField, Pos.CENTER_RIGHT); // 3.2.2 Zorg voor een horizontale en verticale “marge” van 10 pixels tussen de cellen van de BorderPane. // Zorg ook voor een “padding” van 10 pixels. BorderPane.setMargin(this.geboorteJaarField, new Insets(10)); // Marge BorderPane.setMargin(this.berekenButton, new Insets(10)); // Marge BorderPane.setMargin(this.dataField, new Insets(10)); // Marge this.geboorteJaarField.setPadding(new Insets(10)); // Padding this.berekenButton.setPadding(new Insets(10)); // Padding this.dataField.setPadding(new Insets(10)); // Padding } Button getBerekenButton() { // Get.. return this.berekenButton; } TextField getGeboorteJaarField() { // Get.. return this.geboorteJaarField; } public void setDataField(String pensioenJaar) { // Set.. this.dataField.setText(pensioenJaar); } }
199070_4
package be.kdg.pensioen.view; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; /** * LEFT: geboorteJaar * CENTER: berekenButton * RIGHT: pensioenJaar * Insets: TRouBLe */ public class PensioenView extends BorderPane { // Attributes private TextField geboorteJaarField; private TextField dataField; private Button berekenButton; // Constructors public PensioenView() { this.initialiseNodes(); this.layoutNodes(); } // Methods public void initialiseNodes() { // 3.1.1 Voorzie de drie attributen van een waarde. this.geboorteJaarField = new TextField(); this.dataField = new TextField(); this.berekenButton = new Button("Bereken"); // 3.1.2 Het 2de tekstveld mag niet editeerbaar zijn. this.dataField.setEditable(false); // 3.1.3 Beide velden hebben bij voorkeur 4 kolommen. GridPane txtGrid = new GridPane(); txtGrid.add(this.dataField, 0,0,3,3); } public void layoutNodes() { // 3.2.1 Maak gebruik van de juiste set… methode van de klasse BorderPane om de componenten op de juiste plaats te krijgen. this.setLeft(this.geboorteJaarField); this.setCenter(this.berekenButton); this.setRight(this.dataField); BorderPane.setAlignment(this.geboorteJaarField, Pos.CENTER_LEFT); BorderPane.setAlignment(this.berekenButton, Pos.CENTER); BorderPane.setAlignment(this.dataField, Pos.CENTER_RIGHT); // 3.2.2 Zorg voor een horizontale en verticale “marge” van 10 pixels tussen de cellen van de BorderPane. // Zorg ook voor een “padding” van 10 pixels. BorderPane.setMargin(this.geboorteJaarField, new Insets(10)); // Marge BorderPane.setMargin(this.berekenButton, new Insets(10)); // Marge BorderPane.setMargin(this.dataField, new Insets(10)); // Marge this.geboorteJaarField.setPadding(new Insets(10)); // Padding this.berekenButton.setPadding(new Insets(10)); // Padding this.dataField.setPadding(new Insets(10)); // Padding } Button getBerekenButton() { // Get.. return this.berekenButton; } TextField getGeboorteJaarField() { // Get.. return this.geboorteJaarField; } public void setDataField(String pensioenJaar) { // Set.. this.dataField.setText(pensioenJaar); } }
EliasDeHondt/ComputerProgramming1-JavaFX
W13P3/Pensioen/src/be/kdg/pensioen/view/PensioenView.java
736
// 3.2.1 Maak gebruik van de juiste set… methode van de klasse BorderPane om de componenten op de juiste plaats te krijgen.
line_comment
nl
package be.kdg.pensioen.view; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; /** * LEFT: geboorteJaar * CENTER: berekenButton * RIGHT: pensioenJaar * Insets: TRouBLe */ public class PensioenView extends BorderPane { // Attributes private TextField geboorteJaarField; private TextField dataField; private Button berekenButton; // Constructors public PensioenView() { this.initialiseNodes(); this.layoutNodes(); } // Methods public void initialiseNodes() { // 3.1.1 Voorzie de drie attributen van een waarde. this.geboorteJaarField = new TextField(); this.dataField = new TextField(); this.berekenButton = new Button("Bereken"); // 3.1.2 Het 2de tekstveld mag niet editeerbaar zijn. this.dataField.setEditable(false); // 3.1.3 Beide velden hebben bij voorkeur 4 kolommen. GridPane txtGrid = new GridPane(); txtGrid.add(this.dataField, 0,0,3,3); } public void layoutNodes() { // 3.2.1 Maak<SUF> this.setLeft(this.geboorteJaarField); this.setCenter(this.berekenButton); this.setRight(this.dataField); BorderPane.setAlignment(this.geboorteJaarField, Pos.CENTER_LEFT); BorderPane.setAlignment(this.berekenButton, Pos.CENTER); BorderPane.setAlignment(this.dataField, Pos.CENTER_RIGHT); // 3.2.2 Zorg voor een horizontale en verticale “marge” van 10 pixels tussen de cellen van de BorderPane. // Zorg ook voor een “padding” van 10 pixels. BorderPane.setMargin(this.geboorteJaarField, new Insets(10)); // Marge BorderPane.setMargin(this.berekenButton, new Insets(10)); // Marge BorderPane.setMargin(this.dataField, new Insets(10)); // Marge this.geboorteJaarField.setPadding(new Insets(10)); // Padding this.berekenButton.setPadding(new Insets(10)); // Padding this.dataField.setPadding(new Insets(10)); // Padding } Button getBerekenButton() { // Get.. return this.berekenButton; } TextField getGeboorteJaarField() { // Get.. return this.geboorteJaarField; } public void setDataField(String pensioenJaar) { // Set.. this.dataField.setText(pensioenJaar); } }
199070_5
package be.kdg.pensioen.view; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; /** * LEFT: geboorteJaar * CENTER: berekenButton * RIGHT: pensioenJaar * Insets: TRouBLe */ public class PensioenView extends BorderPane { // Attributes private TextField geboorteJaarField; private TextField dataField; private Button berekenButton; // Constructors public PensioenView() { this.initialiseNodes(); this.layoutNodes(); } // Methods public void initialiseNodes() { // 3.1.1 Voorzie de drie attributen van een waarde. this.geboorteJaarField = new TextField(); this.dataField = new TextField(); this.berekenButton = new Button("Bereken"); // 3.1.2 Het 2de tekstveld mag niet editeerbaar zijn. this.dataField.setEditable(false); // 3.1.3 Beide velden hebben bij voorkeur 4 kolommen. GridPane txtGrid = new GridPane(); txtGrid.add(this.dataField, 0,0,3,3); } public void layoutNodes() { // 3.2.1 Maak gebruik van de juiste set… methode van de klasse BorderPane om de componenten op de juiste plaats te krijgen. this.setLeft(this.geboorteJaarField); this.setCenter(this.berekenButton); this.setRight(this.dataField); BorderPane.setAlignment(this.geboorteJaarField, Pos.CENTER_LEFT); BorderPane.setAlignment(this.berekenButton, Pos.CENTER); BorderPane.setAlignment(this.dataField, Pos.CENTER_RIGHT); // 3.2.2 Zorg voor een horizontale en verticale “marge” van 10 pixels tussen de cellen van de BorderPane. // Zorg ook voor een “padding” van 10 pixels. BorderPane.setMargin(this.geboorteJaarField, new Insets(10)); // Marge BorderPane.setMargin(this.berekenButton, new Insets(10)); // Marge BorderPane.setMargin(this.dataField, new Insets(10)); // Marge this.geboorteJaarField.setPadding(new Insets(10)); // Padding this.berekenButton.setPadding(new Insets(10)); // Padding this.dataField.setPadding(new Insets(10)); // Padding } Button getBerekenButton() { // Get.. return this.berekenButton; } TextField getGeboorteJaarField() { // Get.. return this.geboorteJaarField; } public void setDataField(String pensioenJaar) { // Set.. this.dataField.setText(pensioenJaar); } }
EliasDeHondt/ComputerProgramming1-JavaFX
W13P3/Pensioen/src/be/kdg/pensioen/view/PensioenView.java
736
// 3.2.2 Zorg voor een horizontale en verticale “marge” van 10 pixels tussen de cellen van de BorderPane.
line_comment
nl
package be.kdg.pensioen.view; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; /** * LEFT: geboorteJaar * CENTER: berekenButton * RIGHT: pensioenJaar * Insets: TRouBLe */ public class PensioenView extends BorderPane { // Attributes private TextField geboorteJaarField; private TextField dataField; private Button berekenButton; // Constructors public PensioenView() { this.initialiseNodes(); this.layoutNodes(); } // Methods public void initialiseNodes() { // 3.1.1 Voorzie de drie attributen van een waarde. this.geboorteJaarField = new TextField(); this.dataField = new TextField(); this.berekenButton = new Button("Bereken"); // 3.1.2 Het 2de tekstveld mag niet editeerbaar zijn. this.dataField.setEditable(false); // 3.1.3 Beide velden hebben bij voorkeur 4 kolommen. GridPane txtGrid = new GridPane(); txtGrid.add(this.dataField, 0,0,3,3); } public void layoutNodes() { // 3.2.1 Maak gebruik van de juiste set… methode van de klasse BorderPane om de componenten op de juiste plaats te krijgen. this.setLeft(this.geboorteJaarField); this.setCenter(this.berekenButton); this.setRight(this.dataField); BorderPane.setAlignment(this.geboorteJaarField, Pos.CENTER_LEFT); BorderPane.setAlignment(this.berekenButton, Pos.CENTER); BorderPane.setAlignment(this.dataField, Pos.CENTER_RIGHT); // 3.2.2 Zorg<SUF> // Zorg ook voor een “padding” van 10 pixels. BorderPane.setMargin(this.geboorteJaarField, new Insets(10)); // Marge BorderPane.setMargin(this.berekenButton, new Insets(10)); // Marge BorderPane.setMargin(this.dataField, new Insets(10)); // Marge this.geboorteJaarField.setPadding(new Insets(10)); // Padding this.berekenButton.setPadding(new Insets(10)); // Padding this.dataField.setPadding(new Insets(10)); // Padding } Button getBerekenButton() { // Get.. return this.berekenButton; } TextField getGeboorteJaarField() { // Get.. return this.geboorteJaarField; } public void setDataField(String pensioenJaar) { // Set.. this.dataField.setText(pensioenJaar); } }
199070_6
package be.kdg.pensioen.view; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; /** * LEFT: geboorteJaar * CENTER: berekenButton * RIGHT: pensioenJaar * Insets: TRouBLe */ public class PensioenView extends BorderPane { // Attributes private TextField geboorteJaarField; private TextField dataField; private Button berekenButton; // Constructors public PensioenView() { this.initialiseNodes(); this.layoutNodes(); } // Methods public void initialiseNodes() { // 3.1.1 Voorzie de drie attributen van een waarde. this.geboorteJaarField = new TextField(); this.dataField = new TextField(); this.berekenButton = new Button("Bereken"); // 3.1.2 Het 2de tekstveld mag niet editeerbaar zijn. this.dataField.setEditable(false); // 3.1.3 Beide velden hebben bij voorkeur 4 kolommen. GridPane txtGrid = new GridPane(); txtGrid.add(this.dataField, 0,0,3,3); } public void layoutNodes() { // 3.2.1 Maak gebruik van de juiste set… methode van de klasse BorderPane om de componenten op de juiste plaats te krijgen. this.setLeft(this.geboorteJaarField); this.setCenter(this.berekenButton); this.setRight(this.dataField); BorderPane.setAlignment(this.geboorteJaarField, Pos.CENTER_LEFT); BorderPane.setAlignment(this.berekenButton, Pos.CENTER); BorderPane.setAlignment(this.dataField, Pos.CENTER_RIGHT); // 3.2.2 Zorg voor een horizontale en verticale “marge” van 10 pixels tussen de cellen van de BorderPane. // Zorg ook voor een “padding” van 10 pixels. BorderPane.setMargin(this.geboorteJaarField, new Insets(10)); // Marge BorderPane.setMargin(this.berekenButton, new Insets(10)); // Marge BorderPane.setMargin(this.dataField, new Insets(10)); // Marge this.geboorteJaarField.setPadding(new Insets(10)); // Padding this.berekenButton.setPadding(new Insets(10)); // Padding this.dataField.setPadding(new Insets(10)); // Padding } Button getBerekenButton() { // Get.. return this.berekenButton; } TextField getGeboorteJaarField() { // Get.. return this.geboorteJaarField; } public void setDataField(String pensioenJaar) { // Set.. this.dataField.setText(pensioenJaar); } }
EliasDeHondt/ComputerProgramming1-JavaFX
W13P3/Pensioen/src/be/kdg/pensioen/view/PensioenView.java
736
// Zorg ook voor een “padding” van 10 pixels.
line_comment
nl
package be.kdg.pensioen.view; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; /** * LEFT: geboorteJaar * CENTER: berekenButton * RIGHT: pensioenJaar * Insets: TRouBLe */ public class PensioenView extends BorderPane { // Attributes private TextField geboorteJaarField; private TextField dataField; private Button berekenButton; // Constructors public PensioenView() { this.initialiseNodes(); this.layoutNodes(); } // Methods public void initialiseNodes() { // 3.1.1 Voorzie de drie attributen van een waarde. this.geboorteJaarField = new TextField(); this.dataField = new TextField(); this.berekenButton = new Button("Bereken"); // 3.1.2 Het 2de tekstveld mag niet editeerbaar zijn. this.dataField.setEditable(false); // 3.1.3 Beide velden hebben bij voorkeur 4 kolommen. GridPane txtGrid = new GridPane(); txtGrid.add(this.dataField, 0,0,3,3); } public void layoutNodes() { // 3.2.1 Maak gebruik van de juiste set… methode van de klasse BorderPane om de componenten op de juiste plaats te krijgen. this.setLeft(this.geboorteJaarField); this.setCenter(this.berekenButton); this.setRight(this.dataField); BorderPane.setAlignment(this.geboorteJaarField, Pos.CENTER_LEFT); BorderPane.setAlignment(this.berekenButton, Pos.CENTER); BorderPane.setAlignment(this.dataField, Pos.CENTER_RIGHT); // 3.2.2 Zorg voor een horizontale en verticale “marge” van 10 pixels tussen de cellen van de BorderPane. // Zorg ook<SUF> BorderPane.setMargin(this.geboorteJaarField, new Insets(10)); // Marge BorderPane.setMargin(this.berekenButton, new Insets(10)); // Marge BorderPane.setMargin(this.dataField, new Insets(10)); // Marge this.geboorteJaarField.setPadding(new Insets(10)); // Padding this.berekenButton.setPadding(new Insets(10)); // Padding this.dataField.setPadding(new Insets(10)); // Padding } Button getBerekenButton() { // Get.. return this.berekenButton; } TextField getGeboorteJaarField() { // Get.. return this.geboorteJaarField; } public void setDataField(String pensioenJaar) { // Set.. this.dataField.setText(pensioenJaar); } }
199073_0
package be.kdg.pensioen.model; /* Hier mag je niets meer aan wijzigen! */ public class Pensioen { private static final int PENSIOEN_LEEFTIJD = 65; private int geboorteJaar; public void setGeboorteJaar(int geboorteJaar) { this.geboorteJaar = geboorteJaar; } public int getPensioenJaar() { return geboorteJaar + PENSIOEN_LEEFTIJD; } }
gvdhaege/KdG
Java Programming/Deel 3/W1 - GUI MVP/Oefeningen/Extra/Pensioen(1)/Pensioen/src/be/kdg/pensioen/model/Pensioen.java
128
/* Hier mag je niets meer aan wijzigen! */
block_comment
nl
package be.kdg.pensioen.model; /* Hier mag je<SUF>*/ public class Pensioen { private static final int PENSIOEN_LEEFTIJD = 65; private int geboorteJaar; public void setGeboorteJaar(int geboorteJaar) { this.geboorteJaar = geboorteJaar; } public int getPensioenJaar() { return geboorteJaar + PENSIOEN_LEEFTIJD; } }
199076_0
package be.kdg.pensioen.view; import be.kdg.pensioen.model.Pensioen; import javafx.event.ActionEvent; import javafx.event.EventHandler; public class PensioenPresenter { private Pensioen model; private PensioenView view; public PensioenPresenter(Pensioen model, PensioenView view) { this.model = model; this.view = view; // updateView(); // --> Er is nog niets om te laten zien! addEventHandlers(); } private void updateView() { // TODO } private void addEventHandlers() { // TODO } public PensioenView getView() { return view; } }
gvdhaege/KdG
Java Programming/Deel 3/W1 - GUI MVP/Oefeningen/Extra/Pensioen(1)/Pensioen/src/be/kdg/pensioen/view/PensioenPresenter.java
174
// updateView(); // --> Er is nog niets om te laten zien!
line_comment
nl
package be.kdg.pensioen.view; import be.kdg.pensioen.model.Pensioen; import javafx.event.ActionEvent; import javafx.event.EventHandler; public class PensioenPresenter { private Pensioen model; private PensioenView view; public PensioenPresenter(Pensioen model, PensioenView view) { this.model = model; this.view = view; // updateView(); //<SUF> addEventHandlers(); } private void updateView() { // TODO } private void addEventHandlers() { // TODO } public PensioenView getView() { return view; } }
199091_52
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.EmailMessage; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String accessToken; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(this, testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); accessToken = properties.getProperty("accessToken"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setAccessToken(accessToken); mailListener.setUsername(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
alisihab/iaf
test-integration/src/test/java/nl/nn/adapterframework/filesystem/ExchangeMailListenerTestBase.java
7,144
// String contents = "Tekst om te lezen";
line_comment
nl
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.EmailMessage; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String accessToken; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(this, testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); accessToken = properties.getProperty("accessToken"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setAccessToken(accessToken); mailListener.setUsername(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents<SUF> // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
199091_64
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.EmailMessage; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String accessToken; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(this, testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); accessToken = properties.getProperty("accessToken"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setAccessToken(accessToken); mailListener.setUsername(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
alisihab/iaf
test-integration/src/test/java/nl/nn/adapterframework/filesystem/ExchangeMailListenerTestBase.java
7,144
// String contents = "Tekst om te lezen";
line_comment
nl
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.EmailMessage; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String accessToken; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(this, testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); accessToken = properties.getProperty("accessToken"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setAccessToken(accessToken); mailListener.setUsername(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents<SUF> configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
199091_70
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.EmailMessage; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String accessToken; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(this, testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); accessToken = properties.getProperty("accessToken"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setAccessToken(accessToken); mailListener.setUsername(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
alisihab/iaf
test-integration/src/test/java/nl/nn/adapterframework/filesystem/ExchangeMailListenerTestBase.java
7,144
// String targetSubject="Onbestelbaar: onbestelbaar met attachments";
line_comment
nl
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.EmailMessage; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String accessToken; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(this, testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); accessToken = properties.getProperty("accessToken"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setAccessToken(accessToken); mailListener.setUsername(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar:<SUF> // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
199091_77
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.EmailMessage; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String accessToken; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(this, testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); accessToken = properties.getProperty("accessToken"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setAccessToken(accessToken); mailListener.setUsername(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
alisihab/iaf
test-integration/src/test/java/nl/nn/adapterframework/filesystem/ExchangeMailListenerTestBase.java
7,144
// String contents = "Tekst om te lezen";
line_comment
nl
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.EmailMessage; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String accessToken; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(this, testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); accessToken = properties.getProperty("accessToken"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setAccessToken(accessToken); mailListener.setUsername(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents<SUF> // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
199091_87
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.EmailMessage; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String accessToken; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(this, testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); accessToken = properties.getProperty("accessToken"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setAccessToken(accessToken); mailListener.setUsername(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
alisihab/iaf
test-integration/src/test/java/nl/nn/adapterframework/filesystem/ExchangeMailListenerTestBase.java
7,144
// String contents = "Tekst om te lezen";
line_comment
nl
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.EmailMessage; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String accessToken; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(this, testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); accessToken = properties.getProperty("accessToken"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setAccessToken(accessToken); mailListener.setUsername(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents<SUF> // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
199092_52
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Ignore; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.EmailMessage; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String mailaddress_fancy; protected String accessToken; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); mailaddress_fancy = properties.getProperty("mailaddress.fancy"); accessToken = properties.getProperty("accessToken"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setAccessToken(accessToken); mailListener.setUsername(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); mailListener.setBaseFolder(basefolder2); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test @Ignore("skip NDR filter for now") public void readFileBounce1() throws Exception { String targetFolder="Onbestelbaar 1"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test @Ignore("skip NDR filter for now") public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test @Ignore("skip NDR filter for now") public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test @Ignore("skip NDR filter for now") public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readEmptyFolder() throws Exception { String targetFolder="Empty"; mailListener.setCreateFolders(true); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNull(rawMessage); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
githubapreinders/iaf
test-integration/src/test/java/nl/nn/adapterframework/filesystem/ExchangeMailListenerTestBase.java
7,011
// String contents = "Tekst om te lezen";
line_comment
nl
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Ignore; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.EmailMessage; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String mailaddress_fancy; protected String accessToken; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); mailaddress_fancy = properties.getProperty("mailaddress.fancy"); accessToken = properties.getProperty("accessToken"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setAccessToken(accessToken); mailListener.setUsername(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); mailListener.setBaseFolder(basefolder2); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents<SUF> // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test @Ignore("skip NDR filter for now") public void readFileBounce1() throws Exception { String targetFolder="Onbestelbaar 1"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test @Ignore("skip NDR filter for now") public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test @Ignore("skip NDR filter for now") public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test @Ignore("skip NDR filter for now") public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readEmptyFolder() throws Exception { String targetFolder="Empty"; mailListener.setCreateFolders(true); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNull(rawMessage); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
199092_66
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Ignore; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.EmailMessage; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String mailaddress_fancy; protected String accessToken; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); mailaddress_fancy = properties.getProperty("mailaddress.fancy"); accessToken = properties.getProperty("accessToken"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setAccessToken(accessToken); mailListener.setUsername(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); mailListener.setBaseFolder(basefolder2); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test @Ignore("skip NDR filter for now") public void readFileBounce1() throws Exception { String targetFolder="Onbestelbaar 1"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test @Ignore("skip NDR filter for now") public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test @Ignore("skip NDR filter for now") public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test @Ignore("skip NDR filter for now") public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readEmptyFolder() throws Exception { String targetFolder="Empty"; mailListener.setCreateFolders(true); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNull(rawMessage); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
githubapreinders/iaf
test-integration/src/test/java/nl/nn/adapterframework/filesystem/ExchangeMailListenerTestBase.java
7,011
// String targetSubject="Onbestelbaar: onbestelbaar met attachments";
line_comment
nl
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Ignore; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.EmailMessage; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String mailaddress_fancy; protected String accessToken; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); mailaddress_fancy = properties.getProperty("mailaddress.fancy"); accessToken = properties.getProperty("accessToken"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setAccessToken(accessToken); mailListener.setUsername(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); mailListener.setBaseFolder(basefolder2); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test @Ignore("skip NDR filter for now") public void readFileBounce1() throws Exception { String targetFolder="Onbestelbaar 1"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test @Ignore("skip NDR filter for now") public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test @Ignore("skip NDR filter for now") public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test @Ignore("skip NDR filter for now") public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readEmptyFolder() throws Exception { String targetFolder="Empty"; mailListener.setCreateFolders(true); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNull(rawMessage); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar:<SUF> // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
199092_73
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Ignore; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.EmailMessage; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String mailaddress_fancy; protected String accessToken; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); mailaddress_fancy = properties.getProperty("mailaddress.fancy"); accessToken = properties.getProperty("accessToken"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setAccessToken(accessToken); mailListener.setUsername(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); mailListener.setBaseFolder(basefolder2); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test @Ignore("skip NDR filter for now") public void readFileBounce1() throws Exception { String targetFolder="Onbestelbaar 1"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test @Ignore("skip NDR filter for now") public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test @Ignore("skip NDR filter for now") public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test @Ignore("skip NDR filter for now") public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readEmptyFolder() throws Exception { String targetFolder="Empty"; mailListener.setCreateFolders(true); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNull(rawMessage); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
githubapreinders/iaf
test-integration/src/test/java/nl/nn/adapterframework/filesystem/ExchangeMailListenerTestBase.java
7,011
// String contents = "Tekst om te lezen";
line_comment
nl
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Ignore; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.EmailMessage; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String mailaddress_fancy; protected String accessToken; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); mailaddress_fancy = properties.getProperty("mailaddress.fancy"); accessToken = properties.getProperty("accessToken"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setAccessToken(accessToken); mailListener.setUsername(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); mailListener.setBaseFolder(basefolder2); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test @Ignore("skip NDR filter for now") public void readFileBounce1() throws Exception { String targetFolder="Onbestelbaar 1"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test @Ignore("skip NDR filter for now") public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test @Ignore("skip NDR filter for now") public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test @Ignore("skip NDR filter for now") public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readEmptyFolder() throws Exception { String targetFolder="Empty"; mailListener.setCreateFolders(true); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNull(rawMessage); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents<SUF> // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
199092_83
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Ignore; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.EmailMessage; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String mailaddress_fancy; protected String accessToken; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); mailaddress_fancy = properties.getProperty("mailaddress.fancy"); accessToken = properties.getProperty("accessToken"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setAccessToken(accessToken); mailListener.setUsername(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); mailListener.setBaseFolder(basefolder2); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test @Ignore("skip NDR filter for now") public void readFileBounce1() throws Exception { String targetFolder="Onbestelbaar 1"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test @Ignore("skip NDR filter for now") public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test @Ignore("skip NDR filter for now") public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test @Ignore("skip NDR filter for now") public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readEmptyFolder() throws Exception { String targetFolder="Empty"; mailListener.setCreateFolders(true); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNull(rawMessage); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
githubapreinders/iaf
test-integration/src/test/java/nl/nn/adapterframework/filesystem/ExchangeMailListenerTestBase.java
7,011
// String contents = "Tekst om te lezen";
line_comment
nl
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Ignore; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.EmailMessage; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String mailaddress_fancy; protected String accessToken; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); mailaddress_fancy = properties.getProperty("mailaddress.fancy"); accessToken = properties.getProperty("accessToken"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setAccessToken(accessToken); mailListener.setUsername(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); mailListener.setBaseFolder(basefolder2); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test @Ignore("skip NDR filter for now") public void readFileBounce1() throws Exception { String targetFolder="Onbestelbaar 1"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test @Ignore("skip NDR filter for now") public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test @Ignore("skip NDR filter for now") public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test @Ignore("skip NDR filter for now") public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readEmptyFolder() throws Exception { String targetFolder="Empty"; mailListener.setCreateFolders(true); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); EmailMessage rawMessage = mailListener.getRawMessage(threadContext); assertNull(rawMessage); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents<SUF> // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
199093_53
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.Item; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.util.TestAssertions; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ private String mailaddress = "[email protected]"; private String password = ""; private String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery private String username = mailaddress; private String basefolder1 = "IAF Integration Tests 1"; protected String basefolder2 = "IAF Integration Tests 2"; private String senderSmtpHost="smtp.fastmail.com"; private int senderSmtpPort=465; private boolean senderSsl=true; private String senderUserId="[email protected]"; // private String senderPassword=""; private String sendGridApiKey=""; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, sendGridApiKey); } @Override public void setUp() throws Exception { super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setUserName(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } /** * Returns the listener * @return fileSystem * @throws ConfigurationException */ protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
pedro-tavares/iaf
test-integration/src/test/java/nl/nn/adapterframework/filesystem/ExchangeMailListenerTestBase.java
6,988
// String contents = "Tekst om te lezen";
line_comment
nl
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.Item; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.util.TestAssertions; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ private String mailaddress = "[email protected]"; private String password = ""; private String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery private String username = mailaddress; private String basefolder1 = "IAF Integration Tests 1"; protected String basefolder2 = "IAF Integration Tests 2"; private String senderSmtpHost="smtp.fastmail.com"; private int senderSmtpPort=465; private boolean senderSsl=true; private String senderUserId="[email protected]"; // private String senderPassword=""; private String sendGridApiKey=""; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, sendGridApiKey); } @Override public void setUp() throws Exception { super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setUserName(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } /** * Returns the listener * @return fileSystem * @throws ConfigurationException */ protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents<SUF> // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
199093_65
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.Item; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.util.TestAssertions; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ private String mailaddress = "[email protected]"; private String password = ""; private String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery private String username = mailaddress; private String basefolder1 = "IAF Integration Tests 1"; protected String basefolder2 = "IAF Integration Tests 2"; private String senderSmtpHost="smtp.fastmail.com"; private int senderSmtpPort=465; private boolean senderSsl=true; private String senderUserId="[email protected]"; // private String senderPassword=""; private String sendGridApiKey=""; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, sendGridApiKey); } @Override public void setUp() throws Exception { super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setUserName(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } /** * Returns the listener * @return fileSystem * @throws ConfigurationException */ protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
pedro-tavares/iaf
test-integration/src/test/java/nl/nn/adapterframework/filesystem/ExchangeMailListenerTestBase.java
6,988
// String contents = "Tekst om te lezen";
line_comment
nl
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.Item; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.util.TestAssertions; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ private String mailaddress = "[email protected]"; private String password = ""; private String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery private String username = mailaddress; private String basefolder1 = "IAF Integration Tests 1"; protected String basefolder2 = "IAF Integration Tests 2"; private String senderSmtpHost="smtp.fastmail.com"; private int senderSmtpPort=465; private boolean senderSsl=true; private String senderUserId="[email protected]"; // private String senderPassword=""; private String sendGridApiKey=""; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, sendGridApiKey); } @Override public void setUp() throws Exception { super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setUserName(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } /** * Returns the listener * @return fileSystem * @throws ConfigurationException */ protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents<SUF> configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
199093_71
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.Item; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.util.TestAssertions; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ private String mailaddress = "[email protected]"; private String password = ""; private String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery private String username = mailaddress; private String basefolder1 = "IAF Integration Tests 1"; protected String basefolder2 = "IAF Integration Tests 2"; private String senderSmtpHost="smtp.fastmail.com"; private int senderSmtpPort=465; private boolean senderSsl=true; private String senderUserId="[email protected]"; // private String senderPassword=""; private String sendGridApiKey=""; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, sendGridApiKey); } @Override public void setUp() throws Exception { super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setUserName(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } /** * Returns the listener * @return fileSystem * @throws ConfigurationException */ protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
pedro-tavares/iaf
test-integration/src/test/java/nl/nn/adapterframework/filesystem/ExchangeMailListenerTestBase.java
6,988
// String targetSubject="Onbestelbaar: onbestelbaar met attachments";
line_comment
nl
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.Item; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.util.TestAssertions; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ private String mailaddress = "[email protected]"; private String password = ""; private String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery private String username = mailaddress; private String basefolder1 = "IAF Integration Tests 1"; protected String basefolder2 = "IAF Integration Tests 2"; private String senderSmtpHost="smtp.fastmail.com"; private int senderSmtpPort=465; private boolean senderSsl=true; private String senderUserId="[email protected]"; // private String senderPassword=""; private String sendGridApiKey=""; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, sendGridApiKey); } @Override public void setUp() throws Exception { super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setUserName(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } /** * Returns the listener * @return fileSystem * @throws ConfigurationException */ protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar:<SUF> // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
199093_78
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.Item; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.util.TestAssertions; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ private String mailaddress = "[email protected]"; private String password = ""; private String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery private String username = mailaddress; private String basefolder1 = "IAF Integration Tests 1"; protected String basefolder2 = "IAF Integration Tests 2"; private String senderSmtpHost="smtp.fastmail.com"; private int senderSmtpPort=465; private boolean senderSsl=true; private String senderUserId="[email protected]"; // private String senderPassword=""; private String sendGridApiKey=""; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, sendGridApiKey); } @Override public void setUp() throws Exception { super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setUserName(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } /** * Returns the listener * @return fileSystem * @throws ConfigurationException */ protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
pedro-tavares/iaf
test-integration/src/test/java/nl/nn/adapterframework/filesystem/ExchangeMailListenerTestBase.java
6,988
// String contents = "Tekst om te lezen";
line_comment
nl
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.Item; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.util.TestAssertions; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ private String mailaddress = "[email protected]"; private String password = ""; private String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery private String username = mailaddress; private String basefolder1 = "IAF Integration Tests 1"; protected String basefolder2 = "IAF Integration Tests 2"; private String senderSmtpHost="smtp.fastmail.com"; private int senderSmtpPort=465; private boolean senderSsl=true; private String senderUserId="[email protected]"; // private String senderPassword=""; private String sendGridApiKey=""; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, sendGridApiKey); } @Override public void setUp() throws Exception { super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setUserName(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } /** * Returns the listener * @return fileSystem * @throws ConfigurationException */ protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents<SUF> // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
199093_88
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.Item; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.util.TestAssertions; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ private String mailaddress = "[email protected]"; private String password = ""; private String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery private String username = mailaddress; private String basefolder1 = "IAF Integration Tests 1"; protected String basefolder2 = "IAF Integration Tests 2"; private String senderSmtpHost="smtp.fastmail.com"; private int senderSmtpPort=465; private boolean senderSsl=true; private String senderUserId="[email protected]"; // private String senderPassword=""; private String sendGridApiKey=""; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, sendGridApiKey); } @Override public void setUp() throws Exception { super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setUserName(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } /** * Returns the listener * @return fileSystem * @throws ConfigurationException */ protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
pedro-tavares/iaf
test-integration/src/test/java/nl/nn/adapterframework/filesystem/ExchangeMailListenerTestBase.java
6,988
// String contents = "Tekst om te lezen";
line_comment
nl
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.Item; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.util.TestAssertions; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ private String mailaddress = "[email protected]"; private String password = ""; private String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery private String username = mailaddress; private String basefolder1 = "IAF Integration Tests 1"; protected String basefolder2 = "IAF Integration Tests 2"; private String senderSmtpHost="smtp.fastmail.com"; private int senderSmtpPort=465; private boolean senderSsl=true; private String senderUserId="[email protected]"; // private String senderPassword=""; private String sendGridApiKey=""; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, sendGridApiKey); } @Override public void setUp() throws Exception { super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setUserName(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } /** * Returns the listener * @return fileSystem * @throws ConfigurationException */ protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.getStringFromRawMessage(rawMessage, threadContext); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents<SUF> // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
199094_53
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.Item; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(this, testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setUserName(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } /** * Returns the listener * @return fileSystem * @throws ConfigurationException */ protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
Artimunor/iaf
test-integration/src/test/java/nl/nn/adapterframework/filesystem/ExchangeMailListenerTestBase.java
7,155
// String contents = "Tekst om te lezen";
line_comment
nl
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.Item; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(this, testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setUserName(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } /** * Returns the listener * @return fileSystem * @throws ConfigurationException */ protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents<SUF> // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
199094_65
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.Item; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(this, testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setUserName(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } /** * Returns the listener * @return fileSystem * @throws ConfigurationException */ protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
Artimunor/iaf
test-integration/src/test/java/nl/nn/adapterframework/filesystem/ExchangeMailListenerTestBase.java
7,155
// String contents = "Tekst om te lezen";
line_comment
nl
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.Item; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(this, testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setUserName(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } /** * Returns the listener * @return fileSystem * @throws ConfigurationException */ protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents<SUF> configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
199094_71
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.Item; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(this, testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setUserName(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } /** * Returns the listener * @return fileSystem * @throws ConfigurationException */ protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
Artimunor/iaf
test-integration/src/test/java/nl/nn/adapterframework/filesystem/ExchangeMailListenerTestBase.java
7,155
// String targetSubject="Onbestelbaar: onbestelbaar met attachments";
line_comment
nl
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.Item; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(this, testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setUserName(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } /** * Returns the listener * @return fileSystem * @throws ConfigurationException */ protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar:<SUF> // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
199094_78
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.Item; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(this, testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setUserName(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } /** * Returns the listener * @return fileSystem * @throws ConfigurationException */ protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
Artimunor/iaf
test-integration/src/test/java/nl/nn/adapterframework/filesystem/ExchangeMailListenerTestBase.java
7,155
// String contents = "Tekst om te lezen";
line_comment
nl
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.Item; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(this, testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setUserName(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } /** * Returns the listener * @return fileSystem * @throws ConfigurationException */ protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents<SUF> // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
199094_88
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.Item; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(this, testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setUserName(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } /** * Returns the listener * @return fileSystem * @throws ConfigurationException */ protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents = "Tekst om te lezen"; // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
Artimunor/iaf
test-integration/src/test/java/nl/nn/adapterframework/filesystem/ExchangeMailListenerTestBase.java
7,155
// String contents = "Tekst om te lezen";
line_comment
nl
package nl.nn.adapterframework.filesystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Test; import microsoft.exchange.webservices.data.core.service.item.Item; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.receivers.ExchangeMailListener; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.util.ClassUtils; import nl.nn.adapterframework.util.XmlUtils; public abstract class ExchangeMailListenerTestBase extends HelperedFileSystemTestBase{ protected String mailaddress; protected String username; protected String password; protected String baseurl = "https://outlook.office365.com/EWS/Exchange.asmx"; // leave empty to use autodiscovery protected String recipient; private String testProperties="ExchangeMail.properties"; protected String basefolder1; protected String basefolder2; private String senderSmtpHost; private int senderSmtpPort; private boolean senderSsl; private String senderUserId; private String senderPassword; // private String sendGridApiKey; // private String nonExistingFileName = "AAMkAGNmZTczMWUwLWQ1MDEtNDA3Ny1hNjU4LTlmYTQzNjE0NjJmYgBGAAAAAAALFKqetECyQKQyuRBrRSzgBwDx14SZku4LS5ibCBco+nmXAAAAAAEMAADx14SZku4LS5ibCBco+nmXAABMFuwsAAA="; protected ExchangeMailListener mailListener; @Override protected IFileSystemTestHelper getFileSystemTestHelper() { return new MailSendingTestHelper(mailaddress,senderSmtpHost,senderSmtpPort, senderSsl, senderUserId, senderPassword); } @Override public void setUp() throws Exception { Properties properties=new Properties(); properties.load(ClassUtils.getResourceURL(this, testProperties).openStream()); mailaddress = properties.getProperty("mailaddress"); username = properties.getProperty("username"); password = properties.getProperty("password"); recipient= properties.getProperty("recipient"); basefolder1 = properties.getProperty("basefolder1"); basefolder2 = properties.getProperty("basefolder2"); senderSmtpHost = properties.getProperty("senderSmtpHost"); senderSmtpPort = Integer.parseInt(properties.getProperty("senderSmtpPort")); senderSsl = Boolean.parseBoolean(properties.getProperty("mailaddress")); senderUserId = properties.getProperty("senderUserId"); senderPassword = properties.getProperty("senderPassword"); super.setUp(); mailListener=createExchangeMailListener(); mailListener.setMailAddress(mailaddress); mailListener.setUserName(username); mailListener.setPassword(password); mailListener.setUrl(baseurl); } @Override public void tearDown() throws Exception { if (mailListener!=null) { mailListener.close(); } super.tearDown(); } public void configureAndOpen(String folder, String filter) throws ConfigurationException, ListenerException { if (folder!=null) mailListener.setInputFolder(folder); if (filter!=null) mailListener.setFilter(filter); mailListener.configure(); mailListener.open(); } /** * Returns the listener * @return fileSystem * @throws ConfigurationException */ protected abstract ExchangeMailListener createExchangeMailListener(); protected void equalsCheck(String content, String actual) { assertEquals(content, actual); } // public void testReadFile(Item file, String expectedContents) throws IOException, FileSystemException { // InputStream in = fileSystem.readFile(file); // String actual = StreamUtil.getReaderContents(new InputStreamReader(in)); // // test // equalsCheck(expectedContents.trim(), actual.trim()); // } @Override public void waitForActionToFinish() throws FileSystemException { try { ((MailSendingTestHelper)helper)._commitFile(); } catch (Exception e) { throw new FileSystemException(e); } } // public boolean folderContainsMessages(String subfolder) throws FileSystemException { // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // return fileIt!=null && fileIt.hasNext(); // } // // public void displayItemSummary(Item item) throws FileSystemException, IOException { // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // System.out.println("from ["+properties.get("from")+"] subject ["+properties.get("subject")+"]"); // } // // public void displayItem(Item item) throws FileSystemException, IOException { // System.out.println("item ["+ToStringBuilder.reflectionToString(item,ToStringStyle.MULTI_LINE_STYLE)+"]"); // String contents = Misc.streamToString(fileSystem.readFile(item)); // //System.out.println("message contents:\n"+contents+"\n-------------------------------\n"); // Map<String,Object> properties=fileSystem.getAdditionalFileProperties(item); // if (properties==null) { // System.out.println("no message properties"); // } else { // System.out.println("-- message properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+entry.getValue().getClass().getName()+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // // } // // public void displayAttachment(Attachment attachment) throws Exception { // Map<String,Object> properties=fileSystem.getAdditionalAttachmentProperties(attachment); // System.out.println("-- attachment ("+attachment.getClass().getName()+") --:"); // if (properties==null) { // System.out.println("-- no attachment properties --"); // } else { // System.out.println("-- attachment properties --:"); // for(Entry<String,Object> entry:properties.entrySet()) { // Object value=entry.getValue(); // if (value instanceof Map) { // for(Entry<String,Object> subentry:((Map<String,Object>)value).entrySet()) { // System.out.println("property Map ["+entry.getKey()+"] ["+subentry.getKey()+"]=["+subentry.getValue()+"]"); // } // } else { // System.out.println("property ["+(entry.getValue()==null?"null":entry.getValue().getClass().getName())+"] ["+entry.getKey()+"]=["+entry.getValue()+"]"); // } // } // } // System.out.println("-- attachment payload --:"); // if (attachment instanceof ItemAttachment) { // ItemAttachment itemAttachment=(ItemAttachment)attachment; // itemAttachment.load(); // Item attachmentItem = itemAttachment.getItem(); // System.out.println("ItemAttachment.item ["+ToStringBuilder.reflectionToString(attachmentItem,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // ExtendedPropertyCollection extendedProperties =attachmentItem.getExtendedProperties(); // for (Iterator<ExtendedProperty> it=extendedProperties.iterator();it.hasNext();) { // ExtendedProperty ep = it.next(); // System.out.println("ExtendedProperty ["+ToStringBuilder.reflectionToString(ep,ToStringStyle.MULTI_LINE_STYLE)+"]"); // } // //// InternetMessageHeaderCollection internetMessageHeaders =attachmentItem.getInternetMessageHeaders(); //// for (Iterator<InternetMessageHeader> it=internetMessageHeaders.iterator();it.hasNext();) { //// InternetMessageHeader imh = it.next(); //// System.out.println("InternetMessageHeader ["+imh.getName()+"]=["+imh.getValue()+"]"); ////// System.out.println("InternetMessageHeader ["+ToStringBuilder.reflectionToString(imh,ToStringStyle.MULTI_LINE_STYLE)+"]"); //// } // String body =MessageBody.getStringFromMessageBody(attachmentItem.getBody()); // System.out.println("ItemAttachment.item.body ["+body+"]"); // System.out.println("attachmentItem.getHasAttachments ["+attachmentItem.getHasAttachments()+"]"); // // AttachmentCollection attachments = attachmentItem.getAttachments(); // if (attachments!=null) { // for (Iterator<Attachment> it=attachments.iterator(); it.hasNext();) { // Attachment subAttachment = it.next(); // displayAttachment(subAttachment); // } // // } // } // if (attachment instanceof FileAttachment) { // FileAttachment fileAttachment=(FileAttachment)attachment; // fileAttachment.load(); // System.out.println("fileAttachment.contentType ["+fileAttachment.getContentType()+"]"); // System.out.println("fileAttachment.name ["+fileAttachment.getName()+"]"); // System.out.println("fileAttachment.filename ["+fileAttachment.getFileName()+"]"); // //System.out.println("fileAttachment ["+ToStringBuilder.reflectionToString(fileAttachment,ToStringStyle.MULTI_LINE_STYLE)+"]"); // // System.out.println(new String(fileAttachment.getContent(),"UTF-8")); // } // //// System.out.println(Misc.streamToString(fileSystem.readAttachment(attachment))); //// System.out.println(ToStringBuilder.reflectionToString(attachment)); // // } // @Test // public void listFiles() throws Exception { // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(null,null); // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // while(fileIt.hasNext()) { // Item item=fileIt.next(); // displayItemSummary(item); // } // } // // public Item findMessageBySubject(String folder, String targetSubject) throws FileSystemException, IOException { // log.debug("searching in folder ["+folder+"] for message with subject ["+targetSubject+"]"); // Iterator<Item> fileIt = fileSystem.listFiles(folder); // if (fileIt==null || !fileIt.hasNext()) { // log.debug("no files found in folder ["+folder+"]"); // return null; // } // while(fileIt.hasNext()) { // Item item=fileIt.next(); // Map<String, Object> properties=fileSystem.getAdditionalFileProperties(item); // String subject=(String)properties.get("subject"); // log.debug("found message with subject ["+subject+"]"); // if (properties!=null && subject.equals(targetSubject)) { // return item; // } // //displayItem(item); // } // log.debug("message with subject ["+targetSubject+"] not found in folder ["+folder+"]"); // return null; // } // @Test public void readFileBasicFromSubfolderOfInbox() throws Exception { String targetFolder=basefolder1; // String subfolder="Basic"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; configureAndOpen(targetFolder,null); // if (!folderContainsMessages(subfolder)) { // createFile(null, filename, contents); // waitForActionToFinish(); // } Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); //assertEquals("name","x",fileSystem.getName(file)); assertTrue(XmlUtils.isWellFormed(message,"email")); TestAssertions.assertXpathValueEquals("[email protected]", message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(senderUserId, message, "/email/from"); TestAssertions.assertXpathValueEquals("testmail 1", message, "/email/subject"); } @Test public void readFileBounce1() throws Exception { String targetFolder=basefolder1; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="onbestelbaar met attachments"; String originalMessageId="<AM0PR02MB3732B19ECFCCFA4DF3499604AAEE0@AM0PR02MB3732.eurprd02.prod.outlook.com>"; int originalAttachmentCount=1; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="MicrosoftExchange329e71ec88ae4615bbc36ab6ce41109e@integrationpartnersnl.onmicrosoft.com"; String expectedAttachmentName="onbestelbaar met attachments"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); } @Test public void readFileBounce2() throws Exception { String targetFolder="Bounce 2"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Digitale verzending pensioenoverzicht"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1601962671.67364.1537864705705.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D604248:15"; int originalAttachmentCount=0; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce3WithAttachmentInOriginalMail() throws Exception { String targetFolder="Bounce 3"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Invoice 1800000078"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1414718922.255345.1538728621718.JavaMail.wasadmin@srpzzapp0403.insim.biz>"; String xEnvironment="PRD"; String xCorrelationId="ID:EMS_PRD_P2P_LARGE.C7F75BA93B09872C7C:67234"; int originalAttachmentCount=1; String originalAttachmentName="Invoice_1800000078.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } @Test public void readFileBounce4() throws Exception { String targetFolder="Bounce 4"; String originalRecipient="[email protected]"; String originalFrom="[email protected]"; String originalSubject="Factuur 1800000045"; String originalReturnPath="<[email protected]>"; String originalMessageId="<1201979233.119885.1538570623051.JavaMail.wasadmin@srtzzapp0315.insim.biz>"; String xEnvironment="TST"; String xCorrelationId="ID:EMS_TST_ESB_P2P_LARGE.19DA5B995492D6613E2:15033"; int originalAttachmentCount=0; //String originalAttachmentName="Invoice_1800000045.pdf"; String mainRecipient=originalRecipient; String mainSubject="Onbestelbaar: "+originalSubject; String mainFrom="[email protected]"; String expectedAttachmentName="Undelivered Message"; mailListener.setFilter("NDR"); configureAndOpen(targetFolder,null); Map<String,Object> threadContext=new HashMap<String,Object>(); Item rawMessage = (Item)mailListener.getRawMessage(threadContext); assertNotNull(rawMessage); String message = mailListener.extractMessage(rawMessage, threadContext).asString(); System.out.println("message ["+message+"]"); TestAssertions.assertXpathValueEquals(mainRecipient, message, "/email/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(mainFrom, message, "/email/from"); TestAssertions.assertXpathValueEquals(mainSubject, message, "/email/subject"); TestAssertions.assertXpathValueEquals(1, message, "count(/email/attachments/attachment)"); TestAssertions.assertXpathValueEquals(expectedAttachmentName, message, "/email/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalRecipient, message, "/email/attachments/attachment/recipients/recipient[@type='to']"); TestAssertions.assertXpathValueEquals(originalFrom, message, "/email/attachments/attachment/from"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/subject"); TestAssertions.assertXpathValueEquals(originalAttachmentCount, message, "count(/email/attachments/attachment/attachments/attachment)"); //TestAssertions.assertXpathValueEquals(originalAttachmentName, message, "/email/attachments/attachment/attachments/attachment/@name"); TestAssertions.assertXpathValueEquals(originalReturnPath, message, "/email/attachments/attachment/headers/header[@name='Return-Path']"); TestAssertions.assertXpathValueEquals(originalMessageId, message, "/email/attachments/attachment/headers/header[@name='Message-ID']"); TestAssertions.assertXpathValueEquals(originalSubject, message, "/email/attachments/attachment/headers/header[@name='Subject']"); TestAssertions.assertXpathValueEquals(xEnvironment, message, "/email/attachments/attachment/headers/header[@name='x-Environment']"); TestAssertions.assertXpathValueEquals(xCorrelationId, message, "/email/attachments/attachment/headers/header[@name='x-CorrelationId']"); } // @Test // public void readFileBounceWithAttachments() throws Exception { // String targetFolder="Bounce"; // String targetSubject="Onbestelbaar: onbestelbaar met attachments"; // configureAndOpen(basefolder2,"NDR"); // // Item item = findMessageBySubject(targetFolder,targetSubject); // assertNotNull(item); // displayItemSummary(item); // // Iterator<Attachment> attachments = fileSystem.listAttachments(item); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // while(attachments.hasNext()) { // Attachment a = attachments.next(); // displayAttachment(a); // } // } // // @Test // public void readFileWithAttachments() throws Exception { // String subfolder="Bounce"; // String filename = "readFile"; // String contents = "Tekst om te lezen"; // configureAndOpen(basefolder2,null); // //// if (!folderContainsMessages(subfolder)) { //// createFile(null, filename, contents); //// waitForActionToFinish(); //// } // // Iterator<Item> fileIt = fileSystem.listFiles(subfolder); // assertNotNull(fileIt); // assertTrue(fileIt.hasNext()); // // Item file = fileIt.next(); // displayItem(file); // // Iterator<Attachment> attachments = fileSystem.listAttachments(file); // assertNotNull(attachments); // assertTrue("Expected message to contain attachment",attachments.hasNext()); // // Attachment a = attachments.next(); // // assertNotNull(a); // //assertEquals("x",fileSystem.getAttachmentName(a)); //// assertEquals("text/plain",fileSystem.getAttachmentContentType(a)); // //assertEquals("x",fileSystem.getAttachmentFileName(a)); //// assertEquals(320,fileSystem.getAttachmentSize(a)); // // displayAttachment(a); // // String attachmentContents=Misc.streamToString(fileSystem.readAttachment(a)); // System.out.println("attachmentContents ["+attachmentContents+"]"); // // // } // @Test // public void basicFileSystemTestRead() throws Exception { // String filename = "readFile"; // String contents<SUF> // // fileSystem.configure(); // fileSystem.open(); // // createFile(null, filename, contents); // waitForActionToFinish(); // // test // //existsCheck(filename); // // Item file = fileSystem.toFile(filename); // // test // testReadFile(file, contents); // } // // @Test // public void fileSystemTestListFile() throws Exception { // fileSystemTestListFile(2); // } // // @Test // public void fileSystemTestRandomFileShouldNotExist() throws Exception { // fileSystemTestRandomFileShouldNotExist(nonExistingFileName); // } }
199128_39
package cn.hutool.core.lang; import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.StrUtil; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Random; /** * 提供通用唯一识别码(universally unique identifier)(UUID)实现,UUID表示一个128位的值。<br> * 此类拷贝自java.util.UUID,用于生成不带-的UUID字符串 * * <p> * 这些通用标识符具有不同的变体。此类的方法用于操作 Leach-Salz 变体,不过构造方法允许创建任何 UUID 变体(将在下面进行描述)。 * <p> * 变体 2 (Leach-Salz) UUID 的布局如下: long 型数据的最高有效位由以下无符号字段组成: * * <pre> * 0xFFFFFFFF00000000 time_low * 0x00000000FFFF0000 time_mid * 0x000000000000F000 version * 0x0000000000000FFF time_hi * </pre> * <p> * long 型数据的最低有效位由以下无符号字段组成: * * <pre> * 0xC000000000000000 variant * 0x3FFF000000000000 clock_seq * 0x0000FFFFFFFFFFFF node * </pre> * * <p> * variant 字段包含一个表示 UUID 布局的值。以上描述的位布局仅在 UUID 的 variant 值为 2(表示 Leach-Salz 变体)时才有效。 * * <p> * version 字段保存描述此 UUID 类型的值。有 4 种不同的基本 UUID 类型:基于时间的 UUID、DCE 安全 UUID、基于名称的 UUID 和随机生成的 UUID。<br> * 这些类型的 version 值分别为 1、2、3 和 4。 * * @since 4.1.11 */ public class UUID implements java.io.Serializable, Comparable<UUID> { private static final long serialVersionUID = -1185015143654744140L; /** * {@link SecureRandom} 的单例 * * @author looly */ private static class Holder { static final SecureRandom NUMBER_GENERATOR = RandomUtil.getSecureRandom(); } /** * 此UUID的最高64有效位 */ private final long mostSigBits; /** * 此UUID的最低64有效位 */ private final long leastSigBits; /** * 私有构造 * * @param data 数据 */ private UUID(byte[] data) { long msb = 0; long lsb = 0; assert data.length == 16 : "data must be 16 bytes in length"; for (int i = 0; i < 8; i++) { msb = (msb << 8) | (data[i] & 0xff); } for (int i = 8; i < 16; i++) { lsb = (lsb << 8) | (data[i] & 0xff); } this.mostSigBits = msb; this.leastSigBits = lsb; } /** * 使用指定的数据构造新的 UUID。 * * @param mostSigBits 用于 {@code UUID} 的最高有效 64 位 * @param leastSigBits 用于 {@code UUID} 的最低有效 64 位 */ public UUID(long mostSigBits, long leastSigBits) { this.mostSigBits = mostSigBits; this.leastSigBits = leastSigBits; } /** * 获取类型 4(伪随机生成的)UUID 的静态工厂。 使用加密的本地线程伪随机数生成器生成该 UUID。 * * @return 随机生成的 {@code UUID} */ public static UUID fastUUID() { return randomUUID(false); } /** * 获取类型 4(伪随机生成的)UUID 的静态工厂。 使用加密的强伪随机数生成器生成该 UUID。 * * @return 随机生成的 {@code UUID} */ public static UUID randomUUID() { return randomUUID(true); } /** * 获取类型 4(伪随机生成的)UUID 的静态工厂。 使用加密的强伪随机数生成器生成该 UUID。 * * @param isSecure 是否使用{@link SecureRandom}如果是可以获得更安全的随机码,否则可以得到更好的性能 * @return 随机生成的 {@code UUID} */ public static UUID randomUUID(boolean isSecure) { final Random ng = isSecure ? Holder.NUMBER_GENERATOR : RandomUtil.getRandom(); final byte[] randomBytes = new byte[16]; ng.nextBytes(randomBytes); randomBytes[6] &= 0x0f; /* clear version */ randomBytes[6] |= 0x40; /* set to version 4 */ randomBytes[8] &= 0x3f; /* clear variant */ randomBytes[8] |= 0x80; /* set to IETF variant */ return new UUID(randomBytes); } /** * 根据指定的字节数组获取类型 3(基于名称的)UUID 的静态工厂。 * * @param name 用于构造 UUID 的字节数组。 * @return 根据指定数组生成的 {@code UUID} */ public static UUID nameUUIDFromBytes(byte[] name) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsae) { throw new InternalError("MD5 not supported"); } byte[] md5Bytes = md.digest(name); md5Bytes[6] &= 0x0f; /* clear version */ md5Bytes[6] |= 0x30; /* set to version 3 */ md5Bytes[8] &= 0x3f; /* clear variant */ md5Bytes[8] |= 0x80; /* set to IETF variant */ return new UUID(md5Bytes); } /** * 根据 {@link #toString()} 方法中描述的字符串标准表示形式创建{@code UUID}。 * * @param name 指定 {@code UUID} 字符串 * @return 具有指定值的 {@code UUID} * @throws IllegalArgumentException 如果 name 与 {@link #toString} 中描述的字符串表示形式不符抛出此异常 */ public static UUID fromString(String name) { String[] components = name.split("-"); if (components.length != 5) { throw new IllegalArgumentException("Invalid UUID string: " + name); } for (int i = 0; i < 5; i++) { components[i] = "0x" + components[i]; } long mostSigBits = Long.decode(components[0]); mostSigBits <<= 16; mostSigBits |= Long.decode(components[1]); mostSigBits <<= 16; mostSigBits |= Long.decode(components[2]); long leastSigBits = Long.decode(components[3]); leastSigBits <<= 48; leastSigBits |= Long.decode(components[4]); return new UUID(mostSigBits, leastSigBits); } /** * 返回此 UUID 的 128 位值中的最低有效 64 位。 * * @return 此 UUID 的 128 位值中的最低有效 64 位。 */ public long getLeastSignificantBits() { return leastSigBits; } /** * 返回此 UUID 的 128 位值中的最高有效 64 位。 * * @return 此 UUID 的 128 位值中最高有效 64 位。 */ public long getMostSignificantBits() { return mostSigBits; } /** * 与此 {@code UUID} 相关联的版本号. 版本号描述此 {@code UUID} 是如何生成的。 * <p> * 版本号具有以下含意: * <ul> * <li>1 基于时间的 UUID * <li>2 DCE 安全 UUID * <li>3 基于名称的 UUID * <li>4 随机生成的 UUID * </ul> * * @return 此 {@code UUID} 的版本号 */ public int version() { // Version is bits masked by 0x000000000000F000 in MS long return (int) ((mostSigBits >> 12) & 0x0f); } /** * 与此 {@code UUID} 相关联的变体号。变体号描述 {@code UUID} 的布局。 * <p> * 变体号具有以下含意: * <ul> * <li>0 为 NCS 向后兼容保留 * <li>2 <a href="http://www.ietf.org/rfc/rfc4122.txt">IETF&nbsp;RFC&nbsp;4122</a>(Leach-Salz), 用于此类 * <li>6 保留,微软向后兼容 * <li>7 保留供以后定义使用 * </ul> * * @return 此 {@code UUID} 相关联的变体号 */ public int variant() { // This field is composed of a varying number of bits. // 0 - - Reserved for NCS backward compatibility // 1 0 - The IETF aka Leach-Salz variant (used by this class) // 1 1 0 Reserved, Microsoft backward compatibility // 1 1 1 Reserved for future definition. return (int) ((leastSigBits >>> (64 - (leastSigBits >>> 62))) & (leastSigBits >> 63)); } /** * 与此 UUID 相关联的时间戳值。 * * <p> * 60 位的时间戳值根据此 {@code UUID} 的 time_low、time_mid 和 time_hi 字段构造。<br> * 所得到的时间戳以 100 毫微秒为单位,从 UTC(通用协调时间) 1582 年 10 月 15 日零时开始。 * * <p> * 时间戳值仅在在基于时间的 UUID(其 version 类型为 1)中才有意义。<br> * 如果此 {@code UUID} 不是基于时间的 UUID,则此方法抛出 UnsupportedOperationException。 * * @return 时间戳值 * @throws UnsupportedOperationException 如果此 {@code UUID} 不是 version 为 1 的 UUID。 */ public long timestamp() throws UnsupportedOperationException { checkTimeBase(); return (mostSigBits & 0x0FFFL) << 48// | ((mostSigBits >> 16) & 0x0FFFFL) << 32// | mostSigBits >>> 32; } /** * 与此 UUID 相关联的时钟序列值。 * * <p> * 14 位的时钟序列值根据此 UUID 的 clock_seq 字段构造。clock_seq 字段用于保证在基于时间的 UUID 中的时间唯一性。 * <p> * {@code clockSequence} 值仅在基于时间的 UUID(其 version 类型为 1)中才有意义。 如果此 UUID 不是基于时间的 UUID,则此方法抛出 UnsupportedOperationException。 * * @return 此 {@code UUID} 的时钟序列 * @throws UnsupportedOperationException 如果此 UUID 的 version 不为 1 */ public int clockSequence() throws UnsupportedOperationException { checkTimeBase(); return (int) ((leastSigBits & 0x3FFF000000000000L) >>> 48); } /** * 与此 UUID 相关的节点值。 * * <p> * 48 位的节点值根据此 UUID 的 node 字段构造。此字段旨在用于保存机器的 IEEE 802 地址,该地址用于生成此 UUID 以保证空间唯一性。 * <p> * 节点值仅在基于时间的 UUID(其 version 类型为 1)中才有意义。<br> * 如果此 UUID 不是基于时间的 UUID,则此方法抛出 UnsupportedOperationException。 * * @return 此 {@code UUID} 的节点值 * @throws UnsupportedOperationException 如果此 UUID 的 version 不为 1 */ public long node() throws UnsupportedOperationException { checkTimeBase(); return leastSigBits & 0x0000FFFFFFFFFFFFL; } // Object Inherited Methods /** * 返回此{@code UUID} 的字符串表现形式。 * * <p> * UUID 的字符串表示形式由此 BNF 描述: * * <pre> * {@code * UUID = <time_low>-<time_mid>-<time_high_and_version>-<variant_and_sequence>-<node> * time_low = 4*<hexOctet> * time_mid = 2*<hexOctet> * time_high_and_version = 2*<hexOctet> * variant_and_sequence = 2*<hexOctet> * node = 6*<hexOctet> * hexOctet = <hexDigit><hexDigit> * hexDigit = [0-9a-fA-F] * } * </pre> * * @return 此{@code UUID} 的字符串表现形式 * @see #toString(boolean) */ @Override public String toString() { return toString(false); } /** * 返回此{@code UUID} 的字符串表现形式。 * * <p> * UUID 的字符串表示形式由此 BNF 描述: * * <pre> * {@code * UUID = <time_low>-<time_mid>-<time_high_and_version>-<variant_and_sequence>-<node> * time_low = 4*<hexOctet> * time_mid = 2*<hexOctet> * time_high_and_version = 2*<hexOctet> * variant_and_sequence = 2*<hexOctet> * node = 6*<hexOctet> * hexOctet = <hexDigit><hexDigit> * hexDigit = [0-9a-fA-F] * } * </pre> * * @param isSimple 是否简单模式,简单模式为不带'-'的UUID字符串 * @return 此{@code UUID} 的字符串表现形式 */ public String toString(boolean isSimple) { final StringBuilder builder = StrUtil.builder(isSimple ? 32 : 36); // time_low builder.append(digits(mostSigBits >> 32, 8)); if (false == isSimple) { builder.append('-'); } // time_mid builder.append(digits(mostSigBits >> 16, 4)); if (false == isSimple) { builder.append('-'); } // time_high_and_version builder.append(digits(mostSigBits, 4)); if (false == isSimple) { builder.append('-'); } // variant_and_sequence builder.append(digits(leastSigBits >> 48, 4)); if (false == isSimple) { builder.append('-'); } // node builder.append(digits(leastSigBits, 12)); return builder.toString(); } /** * 返回此 UUID 的哈希码。 * * @return UUID 的哈希码值。 */ @Override public int hashCode() { long hilo = mostSigBits ^ leastSigBits; return ((int) (hilo >> 32)) ^ (int) hilo; } /** * 将此对象与指定对象比较。 * <p> * 当且仅当参数不为 {@code null}、而是一个 UUID 对象、具有与此 UUID 相同的 varriant、包含相同的值(每一位均相同)时,结果才为 {@code true}。 * * @param obj 要与之比较的对象 * @return 如果对象相同,则返回 {@code true};否则返回 {@code false} */ @Override public boolean equals(Object obj) { if ((null == obj) || (obj.getClass() != UUID.class)) { return false; } UUID id = (UUID) obj; return (mostSigBits == id.mostSigBits && leastSigBits == id.leastSigBits); } // Comparison Operations /** * 将此 UUID 与指定的 UUID 比较。 * * <p> * 如果两个 UUID 不同,且第一个 UUID 的最高有效字段大于第二个 UUID 的对应字段,则第一个 UUID 大于第二个 UUID。 * * @param val 与此 UUID 比较的 UUID * @return 在此 UUID 小于、等于或大于 val 时,分别返回 -1、0 或 1。 */ @Override public int compareTo(UUID val) { // The ordering is intentionally set up so that the UUIDs // can simply be numerically compared as two numbers int compare = Long.compare(this.mostSigBits, val.mostSigBits); if(0 == compare){ compare = Long.compare(this.leastSigBits, val.leastSigBits); } return compare; } // ------------------------------------------------------------------------------------------------------------------- Private method start /** * 返回指定数字对应的hex值 * * @param val 值 * @param digits 位 * @return 值 */ private static String digits(long val, int digits) { long hi = 1L << (digits * 4); return Long.toHexString(hi | (val & (hi - 1))).substring(1); } /** * 检查是否为time-based版本UUID */ private void checkTimeBase() { if (version() != 1) { throw new UnsupportedOperationException("Not a time-based UUID"); } } // ------------------------------------------------------------------------------------------------------------------- Private method end }
dromara/hutool
hutool-core/src/main/java/cn/hutool/core/lang/UUID.java
4,550
// ------------------------------------------------------------------------------------------------------------------- Private method end
line_comment
nl
package cn.hutool.core.lang; import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.StrUtil; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Random; /** * 提供通用唯一识别码(universally unique identifier)(UUID)实现,UUID表示一个128位的值。<br> * 此类拷贝自java.util.UUID,用于生成不带-的UUID字符串 * * <p> * 这些通用标识符具有不同的变体。此类的方法用于操作 Leach-Salz 变体,不过构造方法允许创建任何 UUID 变体(将在下面进行描述)。 * <p> * 变体 2 (Leach-Salz) UUID 的布局如下: long 型数据的最高有效位由以下无符号字段组成: * * <pre> * 0xFFFFFFFF00000000 time_low * 0x00000000FFFF0000 time_mid * 0x000000000000F000 version * 0x0000000000000FFF time_hi * </pre> * <p> * long 型数据的最低有效位由以下无符号字段组成: * * <pre> * 0xC000000000000000 variant * 0x3FFF000000000000 clock_seq * 0x0000FFFFFFFFFFFF node * </pre> * * <p> * variant 字段包含一个表示 UUID 布局的值。以上描述的位布局仅在 UUID 的 variant 值为 2(表示 Leach-Salz 变体)时才有效。 * * <p> * version 字段保存描述此 UUID 类型的值。有 4 种不同的基本 UUID 类型:基于时间的 UUID、DCE 安全 UUID、基于名称的 UUID 和随机生成的 UUID。<br> * 这些类型的 version 值分别为 1、2、3 和 4。 * * @since 4.1.11 */ public class UUID implements java.io.Serializable, Comparable<UUID> { private static final long serialVersionUID = -1185015143654744140L; /** * {@link SecureRandom} 的单例 * * @author looly */ private static class Holder { static final SecureRandom NUMBER_GENERATOR = RandomUtil.getSecureRandom(); } /** * 此UUID的最高64有效位 */ private final long mostSigBits; /** * 此UUID的最低64有效位 */ private final long leastSigBits; /** * 私有构造 * * @param data 数据 */ private UUID(byte[] data) { long msb = 0; long lsb = 0; assert data.length == 16 : "data must be 16 bytes in length"; for (int i = 0; i < 8; i++) { msb = (msb << 8) | (data[i] & 0xff); } for (int i = 8; i < 16; i++) { lsb = (lsb << 8) | (data[i] & 0xff); } this.mostSigBits = msb; this.leastSigBits = lsb; } /** * 使用指定的数据构造新的 UUID。 * * @param mostSigBits 用于 {@code UUID} 的最高有效 64 位 * @param leastSigBits 用于 {@code UUID} 的最低有效 64 位 */ public UUID(long mostSigBits, long leastSigBits) { this.mostSigBits = mostSigBits; this.leastSigBits = leastSigBits; } /** * 获取类型 4(伪随机生成的)UUID 的静态工厂。 使用加密的本地线程伪随机数生成器生成该 UUID。 * * @return 随机生成的 {@code UUID} */ public static UUID fastUUID() { return randomUUID(false); } /** * 获取类型 4(伪随机生成的)UUID 的静态工厂。 使用加密的强伪随机数生成器生成该 UUID。 * * @return 随机生成的 {@code UUID} */ public static UUID randomUUID() { return randomUUID(true); } /** * 获取类型 4(伪随机生成的)UUID 的静态工厂。 使用加密的强伪随机数生成器生成该 UUID。 * * @param isSecure 是否使用{@link SecureRandom}如果是可以获得更安全的随机码,否则可以得到更好的性能 * @return 随机生成的 {@code UUID} */ public static UUID randomUUID(boolean isSecure) { final Random ng = isSecure ? Holder.NUMBER_GENERATOR : RandomUtil.getRandom(); final byte[] randomBytes = new byte[16]; ng.nextBytes(randomBytes); randomBytes[6] &= 0x0f; /* clear version */ randomBytes[6] |= 0x40; /* set to version 4 */ randomBytes[8] &= 0x3f; /* clear variant */ randomBytes[8] |= 0x80; /* set to IETF variant */ return new UUID(randomBytes); } /** * 根据指定的字节数组获取类型 3(基于名称的)UUID 的静态工厂。 * * @param name 用于构造 UUID 的字节数组。 * @return 根据指定数组生成的 {@code UUID} */ public static UUID nameUUIDFromBytes(byte[] name) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsae) { throw new InternalError("MD5 not supported"); } byte[] md5Bytes = md.digest(name); md5Bytes[6] &= 0x0f; /* clear version */ md5Bytes[6] |= 0x30; /* set to version 3 */ md5Bytes[8] &= 0x3f; /* clear variant */ md5Bytes[8] |= 0x80; /* set to IETF variant */ return new UUID(md5Bytes); } /** * 根据 {@link #toString()} 方法中描述的字符串标准表示形式创建{@code UUID}。 * * @param name 指定 {@code UUID} 字符串 * @return 具有指定值的 {@code UUID} * @throws IllegalArgumentException 如果 name 与 {@link #toString} 中描述的字符串表示形式不符抛出此异常 */ public static UUID fromString(String name) { String[] components = name.split("-"); if (components.length != 5) { throw new IllegalArgumentException("Invalid UUID string: " + name); } for (int i = 0; i < 5; i++) { components[i] = "0x" + components[i]; } long mostSigBits = Long.decode(components[0]); mostSigBits <<= 16; mostSigBits |= Long.decode(components[1]); mostSigBits <<= 16; mostSigBits |= Long.decode(components[2]); long leastSigBits = Long.decode(components[3]); leastSigBits <<= 48; leastSigBits |= Long.decode(components[4]); return new UUID(mostSigBits, leastSigBits); } /** * 返回此 UUID 的 128 位值中的最低有效 64 位。 * * @return 此 UUID 的 128 位值中的最低有效 64 位。 */ public long getLeastSignificantBits() { return leastSigBits; } /** * 返回此 UUID 的 128 位值中的最高有效 64 位。 * * @return 此 UUID 的 128 位值中最高有效 64 位。 */ public long getMostSignificantBits() { return mostSigBits; } /** * 与此 {@code UUID} 相关联的版本号. 版本号描述此 {@code UUID} 是如何生成的。 * <p> * 版本号具有以下含意: * <ul> * <li>1 基于时间的 UUID * <li>2 DCE 安全 UUID * <li>3 基于名称的 UUID * <li>4 随机生成的 UUID * </ul> * * @return 此 {@code UUID} 的版本号 */ public int version() { // Version is bits masked by 0x000000000000F000 in MS long return (int) ((mostSigBits >> 12) & 0x0f); } /** * 与此 {@code UUID} 相关联的变体号。变体号描述 {@code UUID} 的布局。 * <p> * 变体号具有以下含意: * <ul> * <li>0 为 NCS 向后兼容保留 * <li>2 <a href="http://www.ietf.org/rfc/rfc4122.txt">IETF&nbsp;RFC&nbsp;4122</a>(Leach-Salz), 用于此类 * <li>6 保留,微软向后兼容 * <li>7 保留供以后定义使用 * </ul> * * @return 此 {@code UUID} 相关联的变体号 */ public int variant() { // This field is composed of a varying number of bits. // 0 - - Reserved for NCS backward compatibility // 1 0 - The IETF aka Leach-Salz variant (used by this class) // 1 1 0 Reserved, Microsoft backward compatibility // 1 1 1 Reserved for future definition. return (int) ((leastSigBits >>> (64 - (leastSigBits >>> 62))) & (leastSigBits >> 63)); } /** * 与此 UUID 相关联的时间戳值。 * * <p> * 60 位的时间戳值根据此 {@code UUID} 的 time_low、time_mid 和 time_hi 字段构造。<br> * 所得到的时间戳以 100 毫微秒为单位,从 UTC(通用协调时间) 1582 年 10 月 15 日零时开始。 * * <p> * 时间戳值仅在在基于时间的 UUID(其 version 类型为 1)中才有意义。<br> * 如果此 {@code UUID} 不是基于时间的 UUID,则此方法抛出 UnsupportedOperationException。 * * @return 时间戳值 * @throws UnsupportedOperationException 如果此 {@code UUID} 不是 version 为 1 的 UUID。 */ public long timestamp() throws UnsupportedOperationException { checkTimeBase(); return (mostSigBits & 0x0FFFL) << 48// | ((mostSigBits >> 16) & 0x0FFFFL) << 32// | mostSigBits >>> 32; } /** * 与此 UUID 相关联的时钟序列值。 * * <p> * 14 位的时钟序列值根据此 UUID 的 clock_seq 字段构造。clock_seq 字段用于保证在基于时间的 UUID 中的时间唯一性。 * <p> * {@code clockSequence} 值仅在基于时间的 UUID(其 version 类型为 1)中才有意义。 如果此 UUID 不是基于时间的 UUID,则此方法抛出 UnsupportedOperationException。 * * @return 此 {@code UUID} 的时钟序列 * @throws UnsupportedOperationException 如果此 UUID 的 version 不为 1 */ public int clockSequence() throws UnsupportedOperationException { checkTimeBase(); return (int) ((leastSigBits & 0x3FFF000000000000L) >>> 48); } /** * 与此 UUID 相关的节点值。 * * <p> * 48 位的节点值根据此 UUID 的 node 字段构造。此字段旨在用于保存机器的 IEEE 802 地址,该地址用于生成此 UUID 以保证空间唯一性。 * <p> * 节点值仅在基于时间的 UUID(其 version 类型为 1)中才有意义。<br> * 如果此 UUID 不是基于时间的 UUID,则此方法抛出 UnsupportedOperationException。 * * @return 此 {@code UUID} 的节点值 * @throws UnsupportedOperationException 如果此 UUID 的 version 不为 1 */ public long node() throws UnsupportedOperationException { checkTimeBase(); return leastSigBits & 0x0000FFFFFFFFFFFFL; } // Object Inherited Methods /** * 返回此{@code UUID} 的字符串表现形式。 * * <p> * UUID 的字符串表示形式由此 BNF 描述: * * <pre> * {@code * UUID = <time_low>-<time_mid>-<time_high_and_version>-<variant_and_sequence>-<node> * time_low = 4*<hexOctet> * time_mid = 2*<hexOctet> * time_high_and_version = 2*<hexOctet> * variant_and_sequence = 2*<hexOctet> * node = 6*<hexOctet> * hexOctet = <hexDigit><hexDigit> * hexDigit = [0-9a-fA-F] * } * </pre> * * @return 此{@code UUID} 的字符串表现形式 * @see #toString(boolean) */ @Override public String toString() { return toString(false); } /** * 返回此{@code UUID} 的字符串表现形式。 * * <p> * UUID 的字符串表示形式由此 BNF 描述: * * <pre> * {@code * UUID = <time_low>-<time_mid>-<time_high_and_version>-<variant_and_sequence>-<node> * time_low = 4*<hexOctet> * time_mid = 2*<hexOctet> * time_high_and_version = 2*<hexOctet> * variant_and_sequence = 2*<hexOctet> * node = 6*<hexOctet> * hexOctet = <hexDigit><hexDigit> * hexDigit = [0-9a-fA-F] * } * </pre> * * @param isSimple 是否简单模式,简单模式为不带'-'的UUID字符串 * @return 此{@code UUID} 的字符串表现形式 */ public String toString(boolean isSimple) { final StringBuilder builder = StrUtil.builder(isSimple ? 32 : 36); // time_low builder.append(digits(mostSigBits >> 32, 8)); if (false == isSimple) { builder.append('-'); } // time_mid builder.append(digits(mostSigBits >> 16, 4)); if (false == isSimple) { builder.append('-'); } // time_high_and_version builder.append(digits(mostSigBits, 4)); if (false == isSimple) { builder.append('-'); } // variant_and_sequence builder.append(digits(leastSigBits >> 48, 4)); if (false == isSimple) { builder.append('-'); } // node builder.append(digits(leastSigBits, 12)); return builder.toString(); } /** * 返回此 UUID 的哈希码。 * * @return UUID 的哈希码值。 */ @Override public int hashCode() { long hilo = mostSigBits ^ leastSigBits; return ((int) (hilo >> 32)) ^ (int) hilo; } /** * 将此对象与指定对象比较。 * <p> * 当且仅当参数不为 {@code null}、而是一个 UUID 对象、具有与此 UUID 相同的 varriant、包含相同的值(每一位均相同)时,结果才为 {@code true}。 * * @param obj 要与之比较的对象 * @return 如果对象相同,则返回 {@code true};否则返回 {@code false} */ @Override public boolean equals(Object obj) { if ((null == obj) || (obj.getClass() != UUID.class)) { return false; } UUID id = (UUID) obj; return (mostSigBits == id.mostSigBits && leastSigBits == id.leastSigBits); } // Comparison Operations /** * 将此 UUID 与指定的 UUID 比较。 * * <p> * 如果两个 UUID 不同,且第一个 UUID 的最高有效字段大于第二个 UUID 的对应字段,则第一个 UUID 大于第二个 UUID。 * * @param val 与此 UUID 比较的 UUID * @return 在此 UUID 小于、等于或大于 val 时,分别返回 -1、0 或 1。 */ @Override public int compareTo(UUID val) { // The ordering is intentionally set up so that the UUIDs // can simply be numerically compared as two numbers int compare = Long.compare(this.mostSigBits, val.mostSigBits); if(0 == compare){ compare = Long.compare(this.leastSigBits, val.leastSigBits); } return compare; } // ------------------------------------------------------------------------------------------------------------------- Private method start /** * 返回指定数字对应的hex值 * * @param val 值 * @param digits 位 * @return 值 */ private static String digits(long val, int digits) { long hi = 1L << (digits * 4); return Long.toHexString(hi | (val & (hi - 1))).substring(1); } /** * 检查是否为time-based版本UUID */ private void checkTimeBase() { if (version() != 1) { throw new UnsupportedOperationException("Not a time-based UUID"); } } // ------------------------------------------------------------------------------------------------------------------- Private<SUF> }
199152_9
/* * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.security; import java.util.*; import java.security.spec.AlgorithmParameterSpec; import java.security.Provider.Service; import sun.security.jca.*; import sun.security.jca.GetInstance.Instance; import sun.security.util.Debug; /** * The {@code KeyPairGenerator} class is used to generate pairs of * public and private keys. Key pair generators are constructed using the * {@code getInstance} factory methods (static methods that * return instances of a given class). * * <p>A Key pair generator for a particular algorithm creates a public/private * key pair that can be used with this algorithm. It also associates * algorithm-specific parameters with each of the generated keys. * * <p>There are two ways to generate a key pair: in an algorithm-independent * manner, and in an algorithm-specific manner. * The only difference between the two is the initialization of the object: * * <ul> * <li><b>Algorithm-Independent Initialization</b> * <p>All key pair generators share the concepts of a keysize and a * source of randomness. The keysize is interpreted differently for different * algorithms (e.g., in the case of the <i>DSA</i> algorithm, the keysize * corresponds to the length of the modulus). * There is an * {@link #initialize(int, java.security.SecureRandom) initialize} * method in this {@code KeyPairGenerator} class that takes these two universally * shared types of arguments. There is also one that takes just a * {@code keysize} argument, and uses the {@code SecureRandom} * implementation of the highest-priority installed provider as the source * of randomness. (If none of the installed providers supply an implementation * of {@code SecureRandom}, a system-provided source of randomness is * used.) * * <p>Since no other parameters are specified when you call the above * algorithm-independent {@code initialize} methods, it is up to the * provider what to do about the algorithm-specific parameters (if any) to be * associated with each of the keys. * * <p>If the algorithm is the <i>DSA</i> algorithm, and the keysize (modulus * size) is 512, 768, 1024, or 2048, then the <i>Sun</i> provider uses a set of * precomputed values for the {@code p}, {@code q}, and * {@code g} parameters. If the modulus size is not one of the above * values, the <i>Sun</i> provider creates a new set of parameters. Other * providers might have precomputed parameter sets for more than just the * modulus sizes mentioned above. Still others might not have a list of * precomputed parameters at all and instead always create new parameter sets. * * <li><b>Algorithm-Specific Initialization</b> * <p>For situations where a set of algorithm-specific parameters already * exists (e.g., so-called <i>community parameters</i> in DSA), there are two * {@link #initialize(java.security.spec.AlgorithmParameterSpec) * initialize} methods that have an {@code AlgorithmParameterSpec} * argument. One also has a {@code SecureRandom} argument, while * the other uses the {@code SecureRandom} * implementation of the highest-priority installed provider as the source * of randomness. (If none of the installed providers supply an implementation * of {@code SecureRandom}, a system-provided source of randomness is * used.) * </ul> * * <p>In case the client does not explicitly initialize the * {@code KeyPairGenerator} * (via a call to an {@code initialize} method), each provider must * supply (and document) a default initialization. * See the Keysize Restriction sections of the * {@extLink security_guide_jdk_providers JDK Providers} * document for information on the {@code KeyPairGenerator} defaults used by * JDK providers. * However, note that defaults may vary across different providers. * Additionally, the default value for a provider may change in a future * version. Therefore, it is recommended to explicitly initialize the * {@code KeyPairGenerator} instead of relying on provider-specific defaults. * * <p>Note that this class is abstract and extends from * {@code KeyPairGeneratorSpi} for historical reasons. * Application developers should only take notice of the methods defined in * this {@code KeyPairGenerator} class; all the methods in * the superclass are intended for cryptographic service providers who wish to * supply their own implementations of key pair generators. * * <p> Every implementation of the Java platform is required to support the * following standard {@code KeyPairGenerator} algorithms and keysizes in * parentheses: * <ul> * <li>{@code DiffieHellman} (1024, 2048, 4096)</li> * <li>{@code DSA} (1024, 2048)</li> * <li>{@code RSA} (1024, 2048, 4096)</li> * </ul> * These algorithms are described in the <a href= * "{@docRoot}/../specs/security/standard-names.html#keypairgenerator-algorithms"> * KeyPairGenerator section</a> of the * Java Security Standard Algorithm Names Specification. * Consult the release documentation for your implementation to see if any * other algorithms are supported. * * @author Benjamin Renaud * @since 1.1 * * @see java.security.spec.AlgorithmParameterSpec */ public abstract class KeyPairGenerator extends KeyPairGeneratorSpi { private static final Debug pdebug = Debug.getInstance("provider", "Provider"); private static final boolean skipDebug = Debug.isOn("engine=") && !Debug.isOn("keypairgenerator"); private final String algorithm; // The provider Provider provider; /** * Creates a {@code KeyPairGenerator} object for the specified algorithm. * * @param algorithm the standard string name of the algorithm. * See the KeyPairGenerator section in the <a href= * "{@docRoot}/../specs/security/standard-names.html#keypairgenerator-algorithms"> * Java Security Standard Algorithm Names Specification</a> * for information about standard algorithm names. */ protected KeyPairGenerator(String algorithm) { this.algorithm = algorithm; } /** * Returns the standard name of the algorithm for this key pair generator. * See the KeyPairGenerator section in the <a href= * "{@docRoot}/../specs/security/standard-names.html#keypairgenerator-algorithms"> * Java Security Standard Algorithm Names Specification</a> * for information about standard algorithm names. * * @return the standard string name of the algorithm. */ public String getAlgorithm() { return this.algorithm; } private static KeyPairGenerator getInstance(Instance instance, String algorithm) { KeyPairGenerator kpg; if (instance.impl instanceof KeyPairGenerator) { kpg = (KeyPairGenerator)instance.impl; } else { KeyPairGeneratorSpi spi = (KeyPairGeneratorSpi)instance.impl; kpg = new Delegate(spi, algorithm); } kpg.provider = instance.provider; if (!skipDebug && pdebug != null) { pdebug.println("KeyPairGenerator." + algorithm + " algorithm from: " + kpg.provider.getName()); } return kpg; } /** * Returns a {@code KeyPairGenerator} object that generates public/private * key pairs for the specified algorithm. * * <p> This method traverses the list of registered security Providers, * starting with the most preferred Provider. * A new {@code KeyPairGenerator} object encapsulating the * {@code KeyPairGeneratorSpi} implementation from the first * provider that supports the specified algorithm is returned. * * <p> Note that the list of registered providers may be retrieved via * the {@link Security#getProviders() Security.getProviders()} method. * * @implNote * The JDK Reference Implementation additionally uses the * {@code jdk.security.provider.preferred} * {@link Security#getProperty(String) Security} property to determine * the preferred provider order for the specified algorithm. This * may be different from the order of providers returned by * {@link Security#getProviders() Security.getProviders()}. * * @param algorithm the standard string name of the algorithm. * See the KeyPairGenerator section in the <a href= * "{@docRoot}/../specs/security/standard-names.html#keypairgenerator-algorithms"> * Java Security Standard Algorithm Names Specification</a> * for information about standard algorithm names. * * @return the new {@code KeyPairGenerator} object * * @throws NoSuchAlgorithmException if no {@code Provider} supports a * {@code KeyPairGeneratorSpi} implementation for the * specified algorithm * * @throws NullPointerException if {@code algorithm} is {@code null} * * @see Provider */ public static KeyPairGenerator getInstance(String algorithm) throws NoSuchAlgorithmException { Objects.requireNonNull(algorithm, "null algorithm name"); Iterator<Service> t = GetInstance.getServices("KeyPairGenerator", algorithm); if (!t.hasNext()) { throw new NoSuchAlgorithmException (algorithm + " KeyPairGenerator not available"); } // find a working Spi or KeyPairGenerator subclass NoSuchAlgorithmException failure = null; do { Service s = t.next(); try { Instance instance = GetInstance.getInstance(s, KeyPairGeneratorSpi.class); if (instance.impl instanceof KeyPairGenerator) { return getInstance(instance, algorithm); } else { return new Delegate(instance, t, algorithm); } } catch (NoSuchAlgorithmException e) { if (failure == null) { failure = e; } } } while (t.hasNext()); throw failure; } /** * Returns a {@code KeyPairGenerator} object that generates public/private * key pairs for the specified algorithm. * * <p> A new {@code KeyPairGenerator} object encapsulating the * {@code KeyPairGeneratorSpi} implementation from the specified provider * is returned. The specified provider must be registered * in the security provider list. * * <p> Note that the list of registered providers may be retrieved via * the {@link Security#getProviders() Security.getProviders()} method. * * @param algorithm the standard string name of the algorithm. * See the KeyPairGenerator section in the <a href= * "{@docRoot}/../specs/security/standard-names.html#keypairgenerator-algorithms"> * Java Security Standard Algorithm Names Specification</a> * for information about standard algorithm names. * * @param provider the string name of the provider. * * @return the new {@code KeyPairGenerator} object * * @throws IllegalArgumentException if the provider name is {@code null} * or empty * * @throws NoSuchAlgorithmException if a {@code KeyPairGeneratorSpi} * implementation for the specified algorithm is not * available from the specified provider * * @throws NoSuchProviderException if the specified provider is not * registered in the security provider list * * @throws NullPointerException if {@code algorithm} is {@code null} * * @see Provider */ public static KeyPairGenerator getInstance(String algorithm, String provider) throws NoSuchAlgorithmException, NoSuchProviderException { Objects.requireNonNull(algorithm, "null algorithm name"); Instance instance = GetInstance.getInstance("KeyPairGenerator", KeyPairGeneratorSpi.class, algorithm, provider); return getInstance(instance, algorithm); } /** * Returns a {@code KeyPairGenerator} object that generates public/private * key pairs for the specified algorithm. * * <p> A new {@code KeyPairGenerator} object encapsulating the * {@code KeyPairGeneratorSpi} implementation from the specified provider * is returned. Note that the specified provider does not * have to be registered in the provider list. * * @param algorithm the standard string name of the algorithm. * See the KeyPairGenerator section in the <a href= * "{@docRoot}/../specs/security/standard-names.html#keypairgenerator-algorithms"> * Java Security Standard Algorithm Names Specification</a> * for information about standard algorithm names. * * @param provider the provider. * * @return the new {@code KeyPairGenerator} object * * @throws IllegalArgumentException if the specified provider is * {@code null} * * @throws NoSuchAlgorithmException if a {@code KeyPairGeneratorSpi} * implementation for the specified algorithm is not available * from the specified {@code Provider} object * * @throws NullPointerException if {@code algorithm} is {@code null} * * @see Provider * * @since 1.4 */ public static KeyPairGenerator getInstance(String algorithm, Provider provider) throws NoSuchAlgorithmException { Objects.requireNonNull(algorithm, "null algorithm name"); Instance instance = GetInstance.getInstance("KeyPairGenerator", KeyPairGeneratorSpi.class, algorithm, provider); return getInstance(instance, algorithm); } /** * Returns the provider of this key pair generator object. * * @return the provider of this key pair generator object */ public final Provider getProvider() { disableFailover(); return this.provider; } void disableFailover() { // empty, overridden in Delegate } /** * Initializes the key pair generator for a certain keysize using * a default parameter set and the {@code SecureRandom} * implementation of the highest-priority installed provider as the source * of randomness. * (If none of the installed providers supply an implementation of * {@code SecureRandom}, a system-provided source of randomness is * used.) * * @param keysize the keysize. This is an * algorithm-specific metric, such as modulus length, specified in * number of bits. * * @throws InvalidParameterException if the {@code keysize} is not * supported by this {@code KeyPairGenerator} object. */ public void initialize(int keysize) { initialize(keysize, JCAUtil.getDefSecureRandom()); } /** * Initializes the key pair generator for a certain keysize with * the given source of randomness (and a default parameter set). * * @param keysize the keysize. This is an * algorithm-specific metric, such as modulus length, specified in * number of bits. * @param random the source of randomness. * * @throws InvalidParameterException if the {@code keysize} is not * supported by this {@code KeyPairGenerator} object. * * @since 1.2 */ public void initialize(int keysize, SecureRandom random) { // This does nothing, because either // 1. the implementation object returned by getInstance() is an // instance of KeyPairGenerator which has its own // initialize(keysize, random) method, so the application would // be calling that method directly, or // 2. the implementation returned by getInstance() is an instance // of Delegate, in which case initialize(keysize, random) is // overridden to call the corresponding SPI method. // (This is a special case, because the API and SPI method have the // same name.) } /** * Initializes the key pair generator using the specified parameter * set and the {@code SecureRandom} * implementation of the highest-priority installed provider as the source * of randomness. * (If none of the installed providers supply an implementation of * {@code SecureRandom}, a system-provided source of randomness is * used.) * * <p>This concrete method has been added to this previously-defined * abstract class. * This method calls the KeyPairGeneratorSpi * {@link KeyPairGeneratorSpi#initialize( * java.security.spec.AlgorithmParameterSpec, * java.security.SecureRandom) initialize} method, * passing it {@code params} and a source of randomness (obtained * from the highest-priority installed provider or system-provided if none * of the installed providers supply one). * That {@code initialize} method always throws an * {@code UnsupportedOperationException} if it is not overridden * by the provider. * @param params the parameter set used to generate the keys. * * @throws InvalidAlgorithmParameterException if the given parameters * are inappropriate for this key pair generator. * * @since 1.2 */ public void initialize(AlgorithmParameterSpec params) throws InvalidAlgorithmParameterException { initialize(params, JCAUtil.getDefSecureRandom()); } /** * Initializes the key pair generator with the given parameter * set and source of randomness. * * <p>This concrete method has been added to this previously-defined * abstract class. * This method calls the KeyPairGeneratorSpi {@link * KeyPairGeneratorSpi#initialize( * java.security.spec.AlgorithmParameterSpec, * java.security.SecureRandom) initialize} method, * passing it {@code params} and {@code random}. * That {@code initialize} * method always throws an {@code UnsupportedOperationException} * if it is not overridden by the provider. * * @param params the parameter set used to generate the keys. * @param random the source of randomness. * * @throws InvalidAlgorithmParameterException if the given parameters * are inappropriate for this key pair generator. * * @since 1.2 */ public void initialize(AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException { // This does nothing, because either // 1. the implementation object returned by getInstance() is an // instance of KeyPairGenerator which has its own // initialize(params, random) method, so the application would // be calling that method directly, or // 2. the implementation returned by getInstance() is an instance // of Delegate, in which case initialize(params, random) is // overridden to call the corresponding SPI method. // (This is a special case, because the API and SPI method have the // same name.) } /** * Generates a key pair. * * <p>If this {@code KeyPairGenerator} has not been initialized explicitly, * provider-specific defaults will be used for the size and other * (algorithm-specific) values of the generated keys. * * <p>This will generate a new key pair every time it is called. * * <p>This method is functionally equivalent to * {@link #generateKeyPair() generateKeyPair}. * * @return the generated key pair * * @since 1.2 */ public final KeyPair genKeyPair() { return generateKeyPair(); } /** * Generates a key pair. * * <p>If this {@code KeyPairGenerator} has not been initialized explicitly, * provider-specific defaults will be used for the size and other * (algorithm-specific) values of the generated keys. * * <p>This will generate a new key pair every time it is called. * * <p>This method is functionally equivalent to * {@link #genKeyPair() genKeyPair}. * * @return the generated key pair */ public KeyPair generateKeyPair() { // This does nothing (except returning null), because either: // // 1. the implementation object returned by getInstance() is an // instance of KeyPairGenerator which has its own implementation // of generateKeyPair (overriding this one), so the application // would be calling that method directly, or // // 2. the implementation returned by getInstance() is an instance // of Delegate, in which case generateKeyPair is // overridden to invoke the corresponding SPI method. // // (This is a special case, because in JDK 1.1.x the generateKeyPair // method was used both as an API and a SPI method.) return null; } /* * The following class allows providers to extend from KeyPairGeneratorSpi * rather than from KeyPairGenerator. It represents a KeyPairGenerator * with an encapsulated, provider-supplied SPI object (of type * KeyPairGeneratorSpi). * If the provider implementation is an instance of KeyPairGeneratorSpi, * the getInstance() methods above return an instance of this class, with * the SPI object encapsulated. * * Note: All SPI methods from the original KeyPairGenerator class have been * moved up the hierarchy into a new class (KeyPairGeneratorSpi), which has * been interposed in the hierarchy between the API (KeyPairGenerator) * and its original parent (Object). */ // // error failover notes: // // . we failover if the implementation throws an error during init // by retrying the init on other providers // // . we also failover if the init succeeded but the subsequent call // to generateKeyPair() fails. In order for this to work, we need // to remember the parameters to the last successful call to init // and initialize() the next spi using them. // // . although not specified, KeyPairGenerators could be thread safe, // so we make sure we do not interfere with that // // . failover is not available, if: // . getInstance(algorithm, provider) was used // . a provider extends KeyPairGenerator rather than // KeyPairGeneratorSpi (JDK 1.1 style) // . once getProvider() is called // private static final class Delegate extends KeyPairGenerator { // The provider implementation (delegate) private volatile KeyPairGeneratorSpi spi; private final Object lock = new Object(); private Iterator<Service> serviceIterator; private static final int I_NONE = 1; private static final int I_SIZE = 2; private static final int I_PARAMS = 3; private int initType; private int initKeySize; private AlgorithmParameterSpec initParams; private SecureRandom initRandom; // constructor Delegate(KeyPairGeneratorSpi spi, String algorithm) { super(algorithm); this.spi = spi; } Delegate(Instance instance, Iterator<Service> serviceIterator, String algorithm) { super(algorithm); spi = (KeyPairGeneratorSpi)instance.impl; provider = instance.provider; this.serviceIterator = serviceIterator; initType = I_NONE; if (!skipDebug && pdebug != null) { pdebug.println("KeyPairGenerator." + algorithm + " algorithm from: " + provider.getName()); } } /** * Update the active spi of this class and return the next * implementation for failover. If no more implementations are * available, this method returns {@code null}. However, the * active spi of this class is never set to {@code null}. */ private KeyPairGeneratorSpi nextSpi(KeyPairGeneratorSpi oldSpi, boolean reinit) { synchronized (lock) { // somebody else did a failover concurrently // try that spi now if ((oldSpi != null) && (oldSpi != spi)) { return spi; } if (serviceIterator == null) { return null; } while (serviceIterator.hasNext()) { Service s = serviceIterator.next(); try { Object inst = s.newInstance(null); // ignore non-spis if (!(inst instanceof KeyPairGeneratorSpi spi)) { continue; } if (inst instanceof KeyPairGenerator) { continue; } if (reinit) { if (initType == I_SIZE) { spi.initialize(initKeySize, initRandom); } else if (initType == I_PARAMS) { spi.initialize(initParams, initRandom); } else if (initType != I_NONE) { throw new AssertionError ("KeyPairGenerator initType: " + initType); } } provider = s.getProvider(); this.spi = spi; return spi; } catch (Exception e) { // ignore } } disableFailover(); return null; } } void disableFailover() { serviceIterator = null; initType = 0; initParams = null; initRandom = null; } // engine method public void initialize(int keysize, SecureRandom random) { if (serviceIterator == null) { spi.initialize(keysize, random); return; } RuntimeException failure = null; KeyPairGeneratorSpi mySpi = spi; do { try { mySpi.initialize(keysize, random); initType = I_SIZE; initKeySize = keysize; initParams = null; initRandom = random; return; } catch (RuntimeException e) { if (failure == null) { failure = e; } mySpi = nextSpi(mySpi, false); } } while (mySpi != null); throw failure; } // engine method public void initialize(AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException { if (serviceIterator == null) { spi.initialize(params, random); return; } Exception failure = null; KeyPairGeneratorSpi mySpi = spi; do { try { mySpi.initialize(params, random); initType = I_PARAMS; initKeySize = 0; initParams = params; initRandom = random; return; } catch (Exception e) { if (failure == null) { failure = e; } mySpi = nextSpi(mySpi, false); } } while (mySpi != null); if (failure instanceof RuntimeException) { throw (RuntimeException)failure; } // must be an InvalidAlgorithmParameterException throw (InvalidAlgorithmParameterException)failure; } // engine method public KeyPair generateKeyPair() { if (serviceIterator == null) { return spi.generateKeyPair(); } RuntimeException failure = null; KeyPairGeneratorSpi mySpi = spi; do { try { return mySpi.generateKeyPair(); } catch (RuntimeException e) { if (failure == null) { failure = e; } mySpi = nextSpi(mySpi, true); } } while (mySpi != null); throw failure; } } }
openjdk/jdk
src/java.base/share/classes/java/security/KeyPairGenerator.java
6,850
// empty, overridden in Delegate
line_comment
nl
/* * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.security; import java.util.*; import java.security.spec.AlgorithmParameterSpec; import java.security.Provider.Service; import sun.security.jca.*; import sun.security.jca.GetInstance.Instance; import sun.security.util.Debug; /** * The {@code KeyPairGenerator} class is used to generate pairs of * public and private keys. Key pair generators are constructed using the * {@code getInstance} factory methods (static methods that * return instances of a given class). * * <p>A Key pair generator for a particular algorithm creates a public/private * key pair that can be used with this algorithm. It also associates * algorithm-specific parameters with each of the generated keys. * * <p>There are two ways to generate a key pair: in an algorithm-independent * manner, and in an algorithm-specific manner. * The only difference between the two is the initialization of the object: * * <ul> * <li><b>Algorithm-Independent Initialization</b> * <p>All key pair generators share the concepts of a keysize and a * source of randomness. The keysize is interpreted differently for different * algorithms (e.g., in the case of the <i>DSA</i> algorithm, the keysize * corresponds to the length of the modulus). * There is an * {@link #initialize(int, java.security.SecureRandom) initialize} * method in this {@code KeyPairGenerator} class that takes these two universally * shared types of arguments. There is also one that takes just a * {@code keysize} argument, and uses the {@code SecureRandom} * implementation of the highest-priority installed provider as the source * of randomness. (If none of the installed providers supply an implementation * of {@code SecureRandom}, a system-provided source of randomness is * used.) * * <p>Since no other parameters are specified when you call the above * algorithm-independent {@code initialize} methods, it is up to the * provider what to do about the algorithm-specific parameters (if any) to be * associated with each of the keys. * * <p>If the algorithm is the <i>DSA</i> algorithm, and the keysize (modulus * size) is 512, 768, 1024, or 2048, then the <i>Sun</i> provider uses a set of * precomputed values for the {@code p}, {@code q}, and * {@code g} parameters. If the modulus size is not one of the above * values, the <i>Sun</i> provider creates a new set of parameters. Other * providers might have precomputed parameter sets for more than just the * modulus sizes mentioned above. Still others might not have a list of * precomputed parameters at all and instead always create new parameter sets. * * <li><b>Algorithm-Specific Initialization</b> * <p>For situations where a set of algorithm-specific parameters already * exists (e.g., so-called <i>community parameters</i> in DSA), there are two * {@link #initialize(java.security.spec.AlgorithmParameterSpec) * initialize} methods that have an {@code AlgorithmParameterSpec} * argument. One also has a {@code SecureRandom} argument, while * the other uses the {@code SecureRandom} * implementation of the highest-priority installed provider as the source * of randomness. (If none of the installed providers supply an implementation * of {@code SecureRandom}, a system-provided source of randomness is * used.) * </ul> * * <p>In case the client does not explicitly initialize the * {@code KeyPairGenerator} * (via a call to an {@code initialize} method), each provider must * supply (and document) a default initialization. * See the Keysize Restriction sections of the * {@extLink security_guide_jdk_providers JDK Providers} * document for information on the {@code KeyPairGenerator} defaults used by * JDK providers. * However, note that defaults may vary across different providers. * Additionally, the default value for a provider may change in a future * version. Therefore, it is recommended to explicitly initialize the * {@code KeyPairGenerator} instead of relying on provider-specific defaults. * * <p>Note that this class is abstract and extends from * {@code KeyPairGeneratorSpi} for historical reasons. * Application developers should only take notice of the methods defined in * this {@code KeyPairGenerator} class; all the methods in * the superclass are intended for cryptographic service providers who wish to * supply their own implementations of key pair generators. * * <p> Every implementation of the Java platform is required to support the * following standard {@code KeyPairGenerator} algorithms and keysizes in * parentheses: * <ul> * <li>{@code DiffieHellman} (1024, 2048, 4096)</li> * <li>{@code DSA} (1024, 2048)</li> * <li>{@code RSA} (1024, 2048, 4096)</li> * </ul> * These algorithms are described in the <a href= * "{@docRoot}/../specs/security/standard-names.html#keypairgenerator-algorithms"> * KeyPairGenerator section</a> of the * Java Security Standard Algorithm Names Specification. * Consult the release documentation for your implementation to see if any * other algorithms are supported. * * @author Benjamin Renaud * @since 1.1 * * @see java.security.spec.AlgorithmParameterSpec */ public abstract class KeyPairGenerator extends KeyPairGeneratorSpi { private static final Debug pdebug = Debug.getInstance("provider", "Provider"); private static final boolean skipDebug = Debug.isOn("engine=") && !Debug.isOn("keypairgenerator"); private final String algorithm; // The provider Provider provider; /** * Creates a {@code KeyPairGenerator} object for the specified algorithm. * * @param algorithm the standard string name of the algorithm. * See the KeyPairGenerator section in the <a href= * "{@docRoot}/../specs/security/standard-names.html#keypairgenerator-algorithms"> * Java Security Standard Algorithm Names Specification</a> * for information about standard algorithm names. */ protected KeyPairGenerator(String algorithm) { this.algorithm = algorithm; } /** * Returns the standard name of the algorithm for this key pair generator. * See the KeyPairGenerator section in the <a href= * "{@docRoot}/../specs/security/standard-names.html#keypairgenerator-algorithms"> * Java Security Standard Algorithm Names Specification</a> * for information about standard algorithm names. * * @return the standard string name of the algorithm. */ public String getAlgorithm() { return this.algorithm; } private static KeyPairGenerator getInstance(Instance instance, String algorithm) { KeyPairGenerator kpg; if (instance.impl instanceof KeyPairGenerator) { kpg = (KeyPairGenerator)instance.impl; } else { KeyPairGeneratorSpi spi = (KeyPairGeneratorSpi)instance.impl; kpg = new Delegate(spi, algorithm); } kpg.provider = instance.provider; if (!skipDebug && pdebug != null) { pdebug.println("KeyPairGenerator." + algorithm + " algorithm from: " + kpg.provider.getName()); } return kpg; } /** * Returns a {@code KeyPairGenerator} object that generates public/private * key pairs for the specified algorithm. * * <p> This method traverses the list of registered security Providers, * starting with the most preferred Provider. * A new {@code KeyPairGenerator} object encapsulating the * {@code KeyPairGeneratorSpi} implementation from the first * provider that supports the specified algorithm is returned. * * <p> Note that the list of registered providers may be retrieved via * the {@link Security#getProviders() Security.getProviders()} method. * * @implNote * The JDK Reference Implementation additionally uses the * {@code jdk.security.provider.preferred} * {@link Security#getProperty(String) Security} property to determine * the preferred provider order for the specified algorithm. This * may be different from the order of providers returned by * {@link Security#getProviders() Security.getProviders()}. * * @param algorithm the standard string name of the algorithm. * See the KeyPairGenerator section in the <a href= * "{@docRoot}/../specs/security/standard-names.html#keypairgenerator-algorithms"> * Java Security Standard Algorithm Names Specification</a> * for information about standard algorithm names. * * @return the new {@code KeyPairGenerator} object * * @throws NoSuchAlgorithmException if no {@code Provider} supports a * {@code KeyPairGeneratorSpi} implementation for the * specified algorithm * * @throws NullPointerException if {@code algorithm} is {@code null} * * @see Provider */ public static KeyPairGenerator getInstance(String algorithm) throws NoSuchAlgorithmException { Objects.requireNonNull(algorithm, "null algorithm name"); Iterator<Service> t = GetInstance.getServices("KeyPairGenerator", algorithm); if (!t.hasNext()) { throw new NoSuchAlgorithmException (algorithm + " KeyPairGenerator not available"); } // find a working Spi or KeyPairGenerator subclass NoSuchAlgorithmException failure = null; do { Service s = t.next(); try { Instance instance = GetInstance.getInstance(s, KeyPairGeneratorSpi.class); if (instance.impl instanceof KeyPairGenerator) { return getInstance(instance, algorithm); } else { return new Delegate(instance, t, algorithm); } } catch (NoSuchAlgorithmException e) { if (failure == null) { failure = e; } } } while (t.hasNext()); throw failure; } /** * Returns a {@code KeyPairGenerator} object that generates public/private * key pairs for the specified algorithm. * * <p> A new {@code KeyPairGenerator} object encapsulating the * {@code KeyPairGeneratorSpi} implementation from the specified provider * is returned. The specified provider must be registered * in the security provider list. * * <p> Note that the list of registered providers may be retrieved via * the {@link Security#getProviders() Security.getProviders()} method. * * @param algorithm the standard string name of the algorithm. * See the KeyPairGenerator section in the <a href= * "{@docRoot}/../specs/security/standard-names.html#keypairgenerator-algorithms"> * Java Security Standard Algorithm Names Specification</a> * for information about standard algorithm names. * * @param provider the string name of the provider. * * @return the new {@code KeyPairGenerator} object * * @throws IllegalArgumentException if the provider name is {@code null} * or empty * * @throws NoSuchAlgorithmException if a {@code KeyPairGeneratorSpi} * implementation for the specified algorithm is not * available from the specified provider * * @throws NoSuchProviderException if the specified provider is not * registered in the security provider list * * @throws NullPointerException if {@code algorithm} is {@code null} * * @see Provider */ public static KeyPairGenerator getInstance(String algorithm, String provider) throws NoSuchAlgorithmException, NoSuchProviderException { Objects.requireNonNull(algorithm, "null algorithm name"); Instance instance = GetInstance.getInstance("KeyPairGenerator", KeyPairGeneratorSpi.class, algorithm, provider); return getInstance(instance, algorithm); } /** * Returns a {@code KeyPairGenerator} object that generates public/private * key pairs for the specified algorithm. * * <p> A new {@code KeyPairGenerator} object encapsulating the * {@code KeyPairGeneratorSpi} implementation from the specified provider * is returned. Note that the specified provider does not * have to be registered in the provider list. * * @param algorithm the standard string name of the algorithm. * See the KeyPairGenerator section in the <a href= * "{@docRoot}/../specs/security/standard-names.html#keypairgenerator-algorithms"> * Java Security Standard Algorithm Names Specification</a> * for information about standard algorithm names. * * @param provider the provider. * * @return the new {@code KeyPairGenerator} object * * @throws IllegalArgumentException if the specified provider is * {@code null} * * @throws NoSuchAlgorithmException if a {@code KeyPairGeneratorSpi} * implementation for the specified algorithm is not available * from the specified {@code Provider} object * * @throws NullPointerException if {@code algorithm} is {@code null} * * @see Provider * * @since 1.4 */ public static KeyPairGenerator getInstance(String algorithm, Provider provider) throws NoSuchAlgorithmException { Objects.requireNonNull(algorithm, "null algorithm name"); Instance instance = GetInstance.getInstance("KeyPairGenerator", KeyPairGeneratorSpi.class, algorithm, provider); return getInstance(instance, algorithm); } /** * Returns the provider of this key pair generator object. * * @return the provider of this key pair generator object */ public final Provider getProvider() { disableFailover(); return this.provider; } void disableFailover() { // empty, overridden<SUF> } /** * Initializes the key pair generator for a certain keysize using * a default parameter set and the {@code SecureRandom} * implementation of the highest-priority installed provider as the source * of randomness. * (If none of the installed providers supply an implementation of * {@code SecureRandom}, a system-provided source of randomness is * used.) * * @param keysize the keysize. This is an * algorithm-specific metric, such as modulus length, specified in * number of bits. * * @throws InvalidParameterException if the {@code keysize} is not * supported by this {@code KeyPairGenerator} object. */ public void initialize(int keysize) { initialize(keysize, JCAUtil.getDefSecureRandom()); } /** * Initializes the key pair generator for a certain keysize with * the given source of randomness (and a default parameter set). * * @param keysize the keysize. This is an * algorithm-specific metric, such as modulus length, specified in * number of bits. * @param random the source of randomness. * * @throws InvalidParameterException if the {@code keysize} is not * supported by this {@code KeyPairGenerator} object. * * @since 1.2 */ public void initialize(int keysize, SecureRandom random) { // This does nothing, because either // 1. the implementation object returned by getInstance() is an // instance of KeyPairGenerator which has its own // initialize(keysize, random) method, so the application would // be calling that method directly, or // 2. the implementation returned by getInstance() is an instance // of Delegate, in which case initialize(keysize, random) is // overridden to call the corresponding SPI method. // (This is a special case, because the API and SPI method have the // same name.) } /** * Initializes the key pair generator using the specified parameter * set and the {@code SecureRandom} * implementation of the highest-priority installed provider as the source * of randomness. * (If none of the installed providers supply an implementation of * {@code SecureRandom}, a system-provided source of randomness is * used.) * * <p>This concrete method has been added to this previously-defined * abstract class. * This method calls the KeyPairGeneratorSpi * {@link KeyPairGeneratorSpi#initialize( * java.security.spec.AlgorithmParameterSpec, * java.security.SecureRandom) initialize} method, * passing it {@code params} and a source of randomness (obtained * from the highest-priority installed provider or system-provided if none * of the installed providers supply one). * That {@code initialize} method always throws an * {@code UnsupportedOperationException} if it is not overridden * by the provider. * @param params the parameter set used to generate the keys. * * @throws InvalidAlgorithmParameterException if the given parameters * are inappropriate for this key pair generator. * * @since 1.2 */ public void initialize(AlgorithmParameterSpec params) throws InvalidAlgorithmParameterException { initialize(params, JCAUtil.getDefSecureRandom()); } /** * Initializes the key pair generator with the given parameter * set and source of randomness. * * <p>This concrete method has been added to this previously-defined * abstract class. * This method calls the KeyPairGeneratorSpi {@link * KeyPairGeneratorSpi#initialize( * java.security.spec.AlgorithmParameterSpec, * java.security.SecureRandom) initialize} method, * passing it {@code params} and {@code random}. * That {@code initialize} * method always throws an {@code UnsupportedOperationException} * if it is not overridden by the provider. * * @param params the parameter set used to generate the keys. * @param random the source of randomness. * * @throws InvalidAlgorithmParameterException if the given parameters * are inappropriate for this key pair generator. * * @since 1.2 */ public void initialize(AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException { // This does nothing, because either // 1. the implementation object returned by getInstance() is an // instance of KeyPairGenerator which has its own // initialize(params, random) method, so the application would // be calling that method directly, or // 2. the implementation returned by getInstance() is an instance // of Delegate, in which case initialize(params, random) is // overridden to call the corresponding SPI method. // (This is a special case, because the API and SPI method have the // same name.) } /** * Generates a key pair. * * <p>If this {@code KeyPairGenerator} has not been initialized explicitly, * provider-specific defaults will be used for the size and other * (algorithm-specific) values of the generated keys. * * <p>This will generate a new key pair every time it is called. * * <p>This method is functionally equivalent to * {@link #generateKeyPair() generateKeyPair}. * * @return the generated key pair * * @since 1.2 */ public final KeyPair genKeyPair() { return generateKeyPair(); } /** * Generates a key pair. * * <p>If this {@code KeyPairGenerator} has not been initialized explicitly, * provider-specific defaults will be used for the size and other * (algorithm-specific) values of the generated keys. * * <p>This will generate a new key pair every time it is called. * * <p>This method is functionally equivalent to * {@link #genKeyPair() genKeyPair}. * * @return the generated key pair */ public KeyPair generateKeyPair() { // This does nothing (except returning null), because either: // // 1. the implementation object returned by getInstance() is an // instance of KeyPairGenerator which has its own implementation // of generateKeyPair (overriding this one), so the application // would be calling that method directly, or // // 2. the implementation returned by getInstance() is an instance // of Delegate, in which case generateKeyPair is // overridden to invoke the corresponding SPI method. // // (This is a special case, because in JDK 1.1.x the generateKeyPair // method was used both as an API and a SPI method.) return null; } /* * The following class allows providers to extend from KeyPairGeneratorSpi * rather than from KeyPairGenerator. It represents a KeyPairGenerator * with an encapsulated, provider-supplied SPI object (of type * KeyPairGeneratorSpi). * If the provider implementation is an instance of KeyPairGeneratorSpi, * the getInstance() methods above return an instance of this class, with * the SPI object encapsulated. * * Note: All SPI methods from the original KeyPairGenerator class have been * moved up the hierarchy into a new class (KeyPairGeneratorSpi), which has * been interposed in the hierarchy between the API (KeyPairGenerator) * and its original parent (Object). */ // // error failover notes: // // . we failover if the implementation throws an error during init // by retrying the init on other providers // // . we also failover if the init succeeded but the subsequent call // to generateKeyPair() fails. In order for this to work, we need // to remember the parameters to the last successful call to init // and initialize() the next spi using them. // // . although not specified, KeyPairGenerators could be thread safe, // so we make sure we do not interfere with that // // . failover is not available, if: // . getInstance(algorithm, provider) was used // . a provider extends KeyPairGenerator rather than // KeyPairGeneratorSpi (JDK 1.1 style) // . once getProvider() is called // private static final class Delegate extends KeyPairGenerator { // The provider implementation (delegate) private volatile KeyPairGeneratorSpi spi; private final Object lock = new Object(); private Iterator<Service> serviceIterator; private static final int I_NONE = 1; private static final int I_SIZE = 2; private static final int I_PARAMS = 3; private int initType; private int initKeySize; private AlgorithmParameterSpec initParams; private SecureRandom initRandom; // constructor Delegate(KeyPairGeneratorSpi spi, String algorithm) { super(algorithm); this.spi = spi; } Delegate(Instance instance, Iterator<Service> serviceIterator, String algorithm) { super(algorithm); spi = (KeyPairGeneratorSpi)instance.impl; provider = instance.provider; this.serviceIterator = serviceIterator; initType = I_NONE; if (!skipDebug && pdebug != null) { pdebug.println("KeyPairGenerator." + algorithm + " algorithm from: " + provider.getName()); } } /** * Update the active spi of this class and return the next * implementation for failover. If no more implementations are * available, this method returns {@code null}. However, the * active spi of this class is never set to {@code null}. */ private KeyPairGeneratorSpi nextSpi(KeyPairGeneratorSpi oldSpi, boolean reinit) { synchronized (lock) { // somebody else did a failover concurrently // try that spi now if ((oldSpi != null) && (oldSpi != spi)) { return spi; } if (serviceIterator == null) { return null; } while (serviceIterator.hasNext()) { Service s = serviceIterator.next(); try { Object inst = s.newInstance(null); // ignore non-spis if (!(inst instanceof KeyPairGeneratorSpi spi)) { continue; } if (inst instanceof KeyPairGenerator) { continue; } if (reinit) { if (initType == I_SIZE) { spi.initialize(initKeySize, initRandom); } else if (initType == I_PARAMS) { spi.initialize(initParams, initRandom); } else if (initType != I_NONE) { throw new AssertionError ("KeyPairGenerator initType: " + initType); } } provider = s.getProvider(); this.spi = spi; return spi; } catch (Exception e) { // ignore } } disableFailover(); return null; } } void disableFailover() { serviceIterator = null; initType = 0; initParams = null; initRandom = null; } // engine method public void initialize(int keysize, SecureRandom random) { if (serviceIterator == null) { spi.initialize(keysize, random); return; } RuntimeException failure = null; KeyPairGeneratorSpi mySpi = spi; do { try { mySpi.initialize(keysize, random); initType = I_SIZE; initKeySize = keysize; initParams = null; initRandom = random; return; } catch (RuntimeException e) { if (failure == null) { failure = e; } mySpi = nextSpi(mySpi, false); } } while (mySpi != null); throw failure; } // engine method public void initialize(AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException { if (serviceIterator == null) { spi.initialize(params, random); return; } Exception failure = null; KeyPairGeneratorSpi mySpi = spi; do { try { mySpi.initialize(params, random); initType = I_PARAMS; initKeySize = 0; initParams = params; initRandom = random; return; } catch (Exception e) { if (failure == null) { failure = e; } mySpi = nextSpi(mySpi, false); } } while (mySpi != null); if (failure instanceof RuntimeException) { throw (RuntimeException)failure; } // must be an InvalidAlgorithmParameterException throw (InvalidAlgorithmParameterException)failure; } // engine method public KeyPair generateKeyPair() { if (serviceIterator == null) { return spi.generateKeyPair(); } RuntimeException failure = null; KeyPairGeneratorSpi mySpi = spi; do { try { return mySpi.generateKeyPair(); } catch (RuntimeException e) { if (failure == null) { failure = e; } mySpi = nextSpi(mySpi, true); } } while (mySpi != null); throw failure; } } }
199323_1
package nl.hu.prog; public class Opdracht14 { public static void main(String[] args) { int a = 6; int b = 7; double c = ((double) a + (double) b) / 2; String voornaam = "Max"; String tussenvoegsel = "van"; String achternaam = "Havelaar"; String mijn_naam = voornaam + " " + tussenvoegsel + " " + achternaam; // 1. 6.75 groter is dan a en kleiner b. boolean resultaat = 6.75 > a && 6.75 < b; System.out.println("1:" + resultaat); // 2. de lengte van mijnnaam even groot is als de som van de lengte van voornaam, tussenvoegsel en achternaam. resultaat = mijn_naam.length() == voornaam.length() + tussenvoegsel.length() + achternaam.length(); System.out.println("2:" + resultaat); // 3. de lengte van mijnnaam minstens 5 maal groter is dan variabele c. resultaat = mijn_naam.length() >= (5 * c); System.out.println("3:" + resultaat); // 4. de waarde van variabele tussenvoegsel voorkomt in de waarde van variabele achternaam. resultaat = achternaam.contains(tussenvoegsel); System.out.println("4:" + resultaat); } }
TomKemperNL/hu-oop-public
src/main/java/nl/hu/prog/Opdracht14.java
363
// 2. de lengte van mijnnaam even groot is als de som van de lengte van voornaam, tussenvoegsel en achternaam.
line_comment
nl
package nl.hu.prog; public class Opdracht14 { public static void main(String[] args) { int a = 6; int b = 7; double c = ((double) a + (double) b) / 2; String voornaam = "Max"; String tussenvoegsel = "van"; String achternaam = "Havelaar"; String mijn_naam = voornaam + " " + tussenvoegsel + " " + achternaam; // 1. 6.75 groter is dan a en kleiner b. boolean resultaat = 6.75 > a && 6.75 < b; System.out.println("1:" + resultaat); // 2. de<SUF> resultaat = mijn_naam.length() == voornaam.length() + tussenvoegsel.length() + achternaam.length(); System.out.println("2:" + resultaat); // 3. de lengte van mijnnaam minstens 5 maal groter is dan variabele c. resultaat = mijn_naam.length() >= (5 * c); System.out.println("3:" + resultaat); // 4. de waarde van variabele tussenvoegsel voorkomt in de waarde van variabele achternaam. resultaat = achternaam.contains(tussenvoegsel); System.out.println("4:" + resultaat); } }
199323_2
package nl.hu.prog; public class Opdracht14 { public static void main(String[] args) { int a = 6; int b = 7; double c = ((double) a + (double) b) / 2; String voornaam = "Max"; String tussenvoegsel = "van"; String achternaam = "Havelaar"; String mijn_naam = voornaam + " " + tussenvoegsel + " " + achternaam; // 1. 6.75 groter is dan a en kleiner b. boolean resultaat = 6.75 > a && 6.75 < b; System.out.println("1:" + resultaat); // 2. de lengte van mijnnaam even groot is als de som van de lengte van voornaam, tussenvoegsel en achternaam. resultaat = mijn_naam.length() == voornaam.length() + tussenvoegsel.length() + achternaam.length(); System.out.println("2:" + resultaat); // 3. de lengte van mijnnaam minstens 5 maal groter is dan variabele c. resultaat = mijn_naam.length() >= (5 * c); System.out.println("3:" + resultaat); // 4. de waarde van variabele tussenvoegsel voorkomt in de waarde van variabele achternaam. resultaat = achternaam.contains(tussenvoegsel); System.out.println("4:" + resultaat); } }
TomKemperNL/hu-oop-public
src/main/java/nl/hu/prog/Opdracht14.java
363
// 3. de lengte van mijnnaam minstens 5 maal groter is dan variabele c.
line_comment
nl
package nl.hu.prog; public class Opdracht14 { public static void main(String[] args) { int a = 6; int b = 7; double c = ((double) a + (double) b) / 2; String voornaam = "Max"; String tussenvoegsel = "van"; String achternaam = "Havelaar"; String mijn_naam = voornaam + " " + tussenvoegsel + " " + achternaam; // 1. 6.75 groter is dan a en kleiner b. boolean resultaat = 6.75 > a && 6.75 < b; System.out.println("1:" + resultaat); // 2. de lengte van mijnnaam even groot is als de som van de lengte van voornaam, tussenvoegsel en achternaam. resultaat = mijn_naam.length() == voornaam.length() + tussenvoegsel.length() + achternaam.length(); System.out.println("2:" + resultaat); // 3. de<SUF> resultaat = mijn_naam.length() >= (5 * c); System.out.println("3:" + resultaat); // 4. de waarde van variabele tussenvoegsel voorkomt in de waarde van variabele achternaam. resultaat = achternaam.contains(tussenvoegsel); System.out.println("4:" + resultaat); } }
199323_3
package nl.hu.prog; public class Opdracht14 { public static void main(String[] args) { int a = 6; int b = 7; double c = ((double) a + (double) b) / 2; String voornaam = "Max"; String tussenvoegsel = "van"; String achternaam = "Havelaar"; String mijn_naam = voornaam + " " + tussenvoegsel + " " + achternaam; // 1. 6.75 groter is dan a en kleiner b. boolean resultaat = 6.75 > a && 6.75 < b; System.out.println("1:" + resultaat); // 2. de lengte van mijnnaam even groot is als de som van de lengte van voornaam, tussenvoegsel en achternaam. resultaat = mijn_naam.length() == voornaam.length() + tussenvoegsel.length() + achternaam.length(); System.out.println("2:" + resultaat); // 3. de lengte van mijnnaam minstens 5 maal groter is dan variabele c. resultaat = mijn_naam.length() >= (5 * c); System.out.println("3:" + resultaat); // 4. de waarde van variabele tussenvoegsel voorkomt in de waarde van variabele achternaam. resultaat = achternaam.contains(tussenvoegsel); System.out.println("4:" + resultaat); } }
TomKemperNL/hu-oop-public
src/main/java/nl/hu/prog/Opdracht14.java
363
// 4. de waarde van variabele tussenvoegsel voorkomt in de waarde van variabele achternaam.
line_comment
nl
package nl.hu.prog; public class Opdracht14 { public static void main(String[] args) { int a = 6; int b = 7; double c = ((double) a + (double) b) / 2; String voornaam = "Max"; String tussenvoegsel = "van"; String achternaam = "Havelaar"; String mijn_naam = voornaam + " " + tussenvoegsel + " " + achternaam; // 1. 6.75 groter is dan a en kleiner b. boolean resultaat = 6.75 > a && 6.75 < b; System.out.println("1:" + resultaat); // 2. de lengte van mijnnaam even groot is als de som van de lengte van voornaam, tussenvoegsel en achternaam. resultaat = mijn_naam.length() == voornaam.length() + tussenvoegsel.length() + achternaam.length(); System.out.println("2:" + resultaat); // 3. de lengte van mijnnaam minstens 5 maal groter is dan variabele c. resultaat = mijn_naam.length() >= (5 * c); System.out.println("3:" + resultaat); // 4. de<SUF> resultaat = achternaam.contains(tussenvoegsel); System.out.println("4:" + resultaat); } }
199330_0
package testen; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.NullAndEmptySource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import domein.Land; import domein.LandService; import domein.LandStatistiek; import persistentie.PersistentieController; @ExtendWith(MockitoExtension.class) class LandServiceTest { @Mock private PersistentieController persistentieControllerDummy; @InjectMocks private LandService landService; private static final int oppervlakte = 110; @ParameterizedTest @CsvSource({ "BE, 10, 0.1", "NL, 22, 0.2", "DE, 78, 0.7" }) public void testGeefLandStatistiekScenario(String landCode, int landOppervlakte, double verwachteResultaat) { Mockito.when(persistentieControllerDummy.findLand(landCode)). thenReturn(new Land(landCode, landOppervlakte)); Mockito.when(persistentieControllerDummy.findOppervlakteAlleLanden()).thenReturn(oppervlakte); LandStatistiek stat = landService.geefLandStatistiek(landCode); assertEquals(landCode, stat.landCode()); assertEquals(verwachteResultaat, stat.verhouding(), 0.01); Mockito.verify(persistentieControllerDummy).findLand(landCode); Mockito.verify(persistentieControllerDummy).findOppervlakteAlleLanden(); } @ParameterizedTest @NullAndEmptySource @ValueSource(strings = { " " }) public void lege_spaties_nullCode(String landCode) { assertThrows(IllegalArgumentException.class, () -> landService.geefLandStatistiek(landCode)); } @Test public void landBestaatNiet() { final String CODE_GEEN_LAND = "GEEN_LAND"; //findLand(CODE_GEEN_LAND) wordt minstens 1x opgeroepen Mockito.when(persistentieControllerDummy.findLand(CODE_GEEN_LAND)).thenReturn(null); //controle "findOppervlakteAlleLanden() wordt minstens 1x opgeroepen" willen we NIET Mockito.lenient(). when(persistentieControllerDummy.findOppervlakteAlleLanden()).thenReturn(100); assertNull(landService.geefLandStatistiek(CODE_GEEN_LAND)); //1x Mockito.verify(persistentieControllerDummy).findLand(CODE_GEEN_LAND); Mockito.verify(persistentieControllerDummy,Mockito.times(0)).findOppervlakteAlleLanden(); } }
Bataklik/ASD1.0_DesignMaze
Mockito/ASDI_Mockito_opgave/src/testen/LandServiceTest.java
804
//findLand(CODE_GEEN_LAND) wordt minstens 1x opgeroepen
line_comment
nl
package testen; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.NullAndEmptySource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import domein.Land; import domein.LandService; import domein.LandStatistiek; import persistentie.PersistentieController; @ExtendWith(MockitoExtension.class) class LandServiceTest { @Mock private PersistentieController persistentieControllerDummy; @InjectMocks private LandService landService; private static final int oppervlakte = 110; @ParameterizedTest @CsvSource({ "BE, 10, 0.1", "NL, 22, 0.2", "DE, 78, 0.7" }) public void testGeefLandStatistiekScenario(String landCode, int landOppervlakte, double verwachteResultaat) { Mockito.when(persistentieControllerDummy.findLand(landCode)). thenReturn(new Land(landCode, landOppervlakte)); Mockito.when(persistentieControllerDummy.findOppervlakteAlleLanden()).thenReturn(oppervlakte); LandStatistiek stat = landService.geefLandStatistiek(landCode); assertEquals(landCode, stat.landCode()); assertEquals(verwachteResultaat, stat.verhouding(), 0.01); Mockito.verify(persistentieControllerDummy).findLand(landCode); Mockito.verify(persistentieControllerDummy).findOppervlakteAlleLanden(); } @ParameterizedTest @NullAndEmptySource @ValueSource(strings = { " " }) public void lege_spaties_nullCode(String landCode) { assertThrows(IllegalArgumentException.class, () -> landService.geefLandStatistiek(landCode)); } @Test public void landBestaatNiet() { final String CODE_GEEN_LAND = "GEEN_LAND"; //findLand(CODE_GEEN_LAND) wordt<SUF> Mockito.when(persistentieControllerDummy.findLand(CODE_GEEN_LAND)).thenReturn(null); //controle "findOppervlakteAlleLanden() wordt minstens 1x opgeroepen" willen we NIET Mockito.lenient(). when(persistentieControllerDummy.findOppervlakteAlleLanden()).thenReturn(100); assertNull(landService.geefLandStatistiek(CODE_GEEN_LAND)); //1x Mockito.verify(persistentieControllerDummy).findLand(CODE_GEEN_LAND); Mockito.verify(persistentieControllerDummy,Mockito.times(0)).findOppervlakteAlleLanden(); } }
199330_1
package testen; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.NullAndEmptySource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import domein.Land; import domein.LandService; import domein.LandStatistiek; import persistentie.PersistentieController; @ExtendWith(MockitoExtension.class) class LandServiceTest { @Mock private PersistentieController persistentieControllerDummy; @InjectMocks private LandService landService; private static final int oppervlakte = 110; @ParameterizedTest @CsvSource({ "BE, 10, 0.1", "NL, 22, 0.2", "DE, 78, 0.7" }) public void testGeefLandStatistiekScenario(String landCode, int landOppervlakte, double verwachteResultaat) { Mockito.when(persistentieControllerDummy.findLand(landCode)). thenReturn(new Land(landCode, landOppervlakte)); Mockito.when(persistentieControllerDummy.findOppervlakteAlleLanden()).thenReturn(oppervlakte); LandStatistiek stat = landService.geefLandStatistiek(landCode); assertEquals(landCode, stat.landCode()); assertEquals(verwachteResultaat, stat.verhouding(), 0.01); Mockito.verify(persistentieControllerDummy).findLand(landCode); Mockito.verify(persistentieControllerDummy).findOppervlakteAlleLanden(); } @ParameterizedTest @NullAndEmptySource @ValueSource(strings = { " " }) public void lege_spaties_nullCode(String landCode) { assertThrows(IllegalArgumentException.class, () -> landService.geefLandStatistiek(landCode)); } @Test public void landBestaatNiet() { final String CODE_GEEN_LAND = "GEEN_LAND"; //findLand(CODE_GEEN_LAND) wordt minstens 1x opgeroepen Mockito.when(persistentieControllerDummy.findLand(CODE_GEEN_LAND)).thenReturn(null); //controle "findOppervlakteAlleLanden() wordt minstens 1x opgeroepen" willen we NIET Mockito.lenient(). when(persistentieControllerDummy.findOppervlakteAlleLanden()).thenReturn(100); assertNull(landService.geefLandStatistiek(CODE_GEEN_LAND)); //1x Mockito.verify(persistentieControllerDummy).findLand(CODE_GEEN_LAND); Mockito.verify(persistentieControllerDummy,Mockito.times(0)).findOppervlakteAlleLanden(); } }
Bataklik/ASD1.0_DesignMaze
Mockito/ASDI_Mockito_opgave/src/testen/LandServiceTest.java
804
//controle "findOppervlakteAlleLanden() wordt minstens 1x opgeroepen" willen we NIET
line_comment
nl
package testen; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.NullAndEmptySource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import domein.Land; import domein.LandService; import domein.LandStatistiek; import persistentie.PersistentieController; @ExtendWith(MockitoExtension.class) class LandServiceTest { @Mock private PersistentieController persistentieControllerDummy; @InjectMocks private LandService landService; private static final int oppervlakte = 110; @ParameterizedTest @CsvSource({ "BE, 10, 0.1", "NL, 22, 0.2", "DE, 78, 0.7" }) public void testGeefLandStatistiekScenario(String landCode, int landOppervlakte, double verwachteResultaat) { Mockito.when(persistentieControllerDummy.findLand(landCode)). thenReturn(new Land(landCode, landOppervlakte)); Mockito.when(persistentieControllerDummy.findOppervlakteAlleLanden()).thenReturn(oppervlakte); LandStatistiek stat = landService.geefLandStatistiek(landCode); assertEquals(landCode, stat.landCode()); assertEquals(verwachteResultaat, stat.verhouding(), 0.01); Mockito.verify(persistentieControllerDummy).findLand(landCode); Mockito.verify(persistentieControllerDummy).findOppervlakteAlleLanden(); } @ParameterizedTest @NullAndEmptySource @ValueSource(strings = { " " }) public void lege_spaties_nullCode(String landCode) { assertThrows(IllegalArgumentException.class, () -> landService.geefLandStatistiek(landCode)); } @Test public void landBestaatNiet() { final String CODE_GEEN_LAND = "GEEN_LAND"; //findLand(CODE_GEEN_LAND) wordt minstens 1x opgeroepen Mockito.when(persistentieControllerDummy.findLand(CODE_GEEN_LAND)).thenReturn(null); //controle "findOppervlakteAlleLanden()<SUF> Mockito.lenient(). when(persistentieControllerDummy.findOppervlakteAlleLanden()).thenReturn(100); assertNull(landService.geefLandStatistiek(CODE_GEEN_LAND)); //1x Mockito.verify(persistentieControllerDummy).findLand(CODE_GEEN_LAND); Mockito.verify(persistentieControllerDummy,Mockito.times(0)).findOppervlakteAlleLanden(); } }
199339_0
package domain; import java.math.BigDecimal; import jakarta.validation.constraints.*; import org.springframework.format.annotation.NumberFormat; import org.springframework.format.annotation.NumberFormat.Style; import lombok.Getter; import lombok.Setter; @Getter public class Account { //moet ingevuld zijn //minstens 10000 @NotNull @Min(10000) @NumberFormat(pattern = "#,##0.00") @Setter private BigDecimal balance = new BigDecimal("20003000.2599"); //Tussen 0 en 60% //"must be greater than or equal to 0%" //message = "must be less than or equal to 60%" @DecimalMin(value = "0.0", message = "must be greater than or equal to 0%") @DecimalMax(value = "0.6", message = "must be less than or equal to 60%") @NumberFormat(style = Style.PERCENT) @Setter private double percent = 0.25; private BigDecimal balance2; private double percent2; //moet ingevuld zijn //moet geldige email zijn @NotBlank @Email @Setter private String email; public void simpleExample() { balance2 = new BigDecimal("20003000.2599"); percent2 = percent; } }
JasperLefever/EWDJOef
Spring_Boot_Valid_WebFlow_opgave/src/main/java/domain/Account.java
357
//moet ingevuld zijn
line_comment
nl
package domain; import java.math.BigDecimal; import jakarta.validation.constraints.*; import org.springframework.format.annotation.NumberFormat; import org.springframework.format.annotation.NumberFormat.Style; import lombok.Getter; import lombok.Setter; @Getter public class Account { //moet ingevuld<SUF> //minstens 10000 @NotNull @Min(10000) @NumberFormat(pattern = "#,##0.00") @Setter private BigDecimal balance = new BigDecimal("20003000.2599"); //Tussen 0 en 60% //"must be greater than or equal to 0%" //message = "must be less than or equal to 60%" @DecimalMin(value = "0.0", message = "must be greater than or equal to 0%") @DecimalMax(value = "0.6", message = "must be less than or equal to 60%") @NumberFormat(style = Style.PERCENT) @Setter private double percent = 0.25; private BigDecimal balance2; private double percent2; //moet ingevuld zijn //moet geldige email zijn @NotBlank @Email @Setter private String email; public void simpleExample() { balance2 = new BigDecimal("20003000.2599"); percent2 = percent; } }
199339_1
package domain; import java.math.BigDecimal; import jakarta.validation.constraints.*; import org.springframework.format.annotation.NumberFormat; import org.springframework.format.annotation.NumberFormat.Style; import lombok.Getter; import lombok.Setter; @Getter public class Account { //moet ingevuld zijn //minstens 10000 @NotNull @Min(10000) @NumberFormat(pattern = "#,##0.00") @Setter private BigDecimal balance = new BigDecimal("20003000.2599"); //Tussen 0 en 60% //"must be greater than or equal to 0%" //message = "must be less than or equal to 60%" @DecimalMin(value = "0.0", message = "must be greater than or equal to 0%") @DecimalMax(value = "0.6", message = "must be less than or equal to 60%") @NumberFormat(style = Style.PERCENT) @Setter private double percent = 0.25; private BigDecimal balance2; private double percent2; //moet ingevuld zijn //moet geldige email zijn @NotBlank @Email @Setter private String email; public void simpleExample() { balance2 = new BigDecimal("20003000.2599"); percent2 = percent; } }
JasperLefever/EWDJOef
Spring_Boot_Valid_WebFlow_opgave/src/main/java/domain/Account.java
357
//Tussen 0 en 60%
line_comment
nl
package domain; import java.math.BigDecimal; import jakarta.validation.constraints.*; import org.springframework.format.annotation.NumberFormat; import org.springframework.format.annotation.NumberFormat.Style; import lombok.Getter; import lombok.Setter; @Getter public class Account { //moet ingevuld zijn //minstens 10000 @NotNull @Min(10000) @NumberFormat(pattern = "#,##0.00") @Setter private BigDecimal balance = new BigDecimal("20003000.2599"); //Tussen 0<SUF> //"must be greater than or equal to 0%" //message = "must be less than or equal to 60%" @DecimalMin(value = "0.0", message = "must be greater than or equal to 0%") @DecimalMax(value = "0.6", message = "must be less than or equal to 60%") @NumberFormat(style = Style.PERCENT) @Setter private double percent = 0.25; private BigDecimal balance2; private double percent2; //moet ingevuld zijn //moet geldige email zijn @NotBlank @Email @Setter private String email; public void simpleExample() { balance2 = new BigDecimal("20003000.2599"); percent2 = percent; } }
199339_4
package domain; import java.math.BigDecimal; import jakarta.validation.constraints.*; import org.springframework.format.annotation.NumberFormat; import org.springframework.format.annotation.NumberFormat.Style; import lombok.Getter; import lombok.Setter; @Getter public class Account { //moet ingevuld zijn //minstens 10000 @NotNull @Min(10000) @NumberFormat(pattern = "#,##0.00") @Setter private BigDecimal balance = new BigDecimal("20003000.2599"); //Tussen 0 en 60% //"must be greater than or equal to 0%" //message = "must be less than or equal to 60%" @DecimalMin(value = "0.0", message = "must be greater than or equal to 0%") @DecimalMax(value = "0.6", message = "must be less than or equal to 60%") @NumberFormat(style = Style.PERCENT) @Setter private double percent = 0.25; private BigDecimal balance2; private double percent2; //moet ingevuld zijn //moet geldige email zijn @NotBlank @Email @Setter private String email; public void simpleExample() { balance2 = new BigDecimal("20003000.2599"); percent2 = percent; } }
JasperLefever/EWDJOef
Spring_Boot_Valid_WebFlow_opgave/src/main/java/domain/Account.java
357
//moet ingevuld zijn
line_comment
nl
package domain; import java.math.BigDecimal; import jakarta.validation.constraints.*; import org.springframework.format.annotation.NumberFormat; import org.springframework.format.annotation.NumberFormat.Style; import lombok.Getter; import lombok.Setter; @Getter public class Account { //moet ingevuld zijn //minstens 10000 @NotNull @Min(10000) @NumberFormat(pattern = "#,##0.00") @Setter private BigDecimal balance = new BigDecimal("20003000.2599"); //Tussen 0 en 60% //"must be greater than or equal to 0%" //message = "must be less than or equal to 60%" @DecimalMin(value = "0.0", message = "must be greater than or equal to 0%") @DecimalMax(value = "0.6", message = "must be less than or equal to 60%") @NumberFormat(style = Style.PERCENT) @Setter private double percent = 0.25; private BigDecimal balance2; private double percent2; //moet ingevuld<SUF> //moet geldige email zijn @NotBlank @Email @Setter private String email; public void simpleExample() { balance2 = new BigDecimal("20003000.2599"); percent2 = percent; } }
199339_5
package domain; import java.math.BigDecimal; import jakarta.validation.constraints.*; import org.springframework.format.annotation.NumberFormat; import org.springframework.format.annotation.NumberFormat.Style; import lombok.Getter; import lombok.Setter; @Getter public class Account { //moet ingevuld zijn //minstens 10000 @NotNull @Min(10000) @NumberFormat(pattern = "#,##0.00") @Setter private BigDecimal balance = new BigDecimal("20003000.2599"); //Tussen 0 en 60% //"must be greater than or equal to 0%" //message = "must be less than or equal to 60%" @DecimalMin(value = "0.0", message = "must be greater than or equal to 0%") @DecimalMax(value = "0.6", message = "must be less than or equal to 60%") @NumberFormat(style = Style.PERCENT) @Setter private double percent = 0.25; private BigDecimal balance2; private double percent2; //moet ingevuld zijn //moet geldige email zijn @NotBlank @Email @Setter private String email; public void simpleExample() { balance2 = new BigDecimal("20003000.2599"); percent2 = percent; } }
JasperLefever/EWDJOef
Spring_Boot_Valid_WebFlow_opgave/src/main/java/domain/Account.java
357
//moet geldige email zijn
line_comment
nl
package domain; import java.math.BigDecimal; import jakarta.validation.constraints.*; import org.springframework.format.annotation.NumberFormat; import org.springframework.format.annotation.NumberFormat.Style; import lombok.Getter; import lombok.Setter; @Getter public class Account { //moet ingevuld zijn //minstens 10000 @NotNull @Min(10000) @NumberFormat(pattern = "#,##0.00") @Setter private BigDecimal balance = new BigDecimal("20003000.2599"); //Tussen 0 en 60% //"must be greater than or equal to 0%" //message = "must be less than or equal to 60%" @DecimalMin(value = "0.0", message = "must be greater than or equal to 0%") @DecimalMax(value = "0.6", message = "must be less than or equal to 60%") @NumberFormat(style = Style.PERCENT) @Setter private double percent = 0.25; private BigDecimal balance2; private double percent2; //moet ingevuld zijn //moet geldige<SUF> @NotBlank @Email @Setter private String email; public void simpleExample() { balance2 = new BigDecimal("20003000.2599"); percent2 = percent; } }
199343_1
package disc.command; //mindustry + arc import io.anuke.mindustry.Vars; import io.anuke.mindustry.content.Items; import io.anuke.mindustry.entities.type.Player; import io.anuke.mindustry.gen.Call; //javacord import io.anuke.mindustry.world.modules.ItemModule; import org.javacord.api.entity.message.MessageBuilder; import org.javacord.api.event.message.MessageCreateEvent; import org.javacord.api.listener.message.MessageCreateListener; public class comCommands implements MessageCreateListener { @Override public void onMessageCreate(MessageCreateEvent event){ if (event.getMessageContent().startsWith("..chat ")){ //discord -> server String[] msg = event.getMessageContent().split(" ", 2); Call.sendMessage("[sky]" +event.getMessageAuthor().getName()+ " @discord >[] " + msg[1].trim()); } //playerlist else if (event.getMessageContent().equalsIgnoreCase("..players")){ StringBuilder lijst = new StringBuilder(); lijst.append("players: " + Vars.playerGroup.size()+"\n"); //lijst.append("online admins: " + Vars.playerGroup.all().count(p->p.isAdmin)+"\n"); for (Player p :Vars.playerGroup.all()){ lijst.append("* " + p.name.trim() + "\n"); } new MessageBuilder().appendCode("", lijst.toString()).send(event.getChannel()); } //info else if (event.getMessageContent().equalsIgnoreCase("..info")){ try { StringBuilder lijst = new StringBuilder(); lijst.append("map: " + Vars.world.getMap().name() + "\n" + "author: " + Vars.world.getMap().author() + "\n"); lijst.append("wave: " + Vars.state.wave + "\n"); lijst.append("enemies: " + Vars.state.enemies + "\n"); lijst.append("players: " + Vars.playerGroup.size() + '\n'); //lijst.append("admins (online): " + Vars.playerGroup.all().count(p -> p.isAdmin)); new MessageBuilder().appendCode("", lijst.toString()).send(event.getChannel()); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } //infores, werkt enkel als er minstens 1 speler online is! else if (event.getMessageContent().equalsIgnoreCase("..infores")){ //event.getChannel().sendMessage("not implemented yet..."); if (!Vars.state.rules.waves){ event.getChannel().sendMessage("Only available when playing survivalmode!"); return; } else if(Vars.playerGroup.isEmpty()) { event.getChannel().sendMessage("No players online!"); } else { StringBuilder lijst = new StringBuilder(); lijst.append("amount of items in the core\n\n"); ItemModule core = Vars.playerGroup.all().get(0).getClosestCore().items; lijst.append("copper: " + core.get(Items.copper) + "\n"); lijst.append("lead: " + core.get(Items.lead) + "\n"); lijst.append("graphite: " + core.get(Items.graphite) + "\n"); lijst.append("metaglass: " + core.get(Items.metaglass) + "\n"); lijst.append("titanium: " + core.get(Items.titanium) + "\n"); lijst.append("thorium: " + core.get(Items.thorium) + "\n"); lijst.append("silicon: " + core.get(Items.silicon) + "\n"); lijst.append("plastanium: " + core.get(Items.plastanium) + "\n"); lijst.append("phase fabric: " + core.get(Items.phasefabric) + "\n"); lijst.append("surge alloy: " + core.get(Items.surgealloy) + "\n"); new MessageBuilder().appendCode("", lijst.toString()).send(event.getChannel()); } } } }
Prosta4okua/DiscordPlugin
src/main/java/disc/command/comCommands.java
1,007
//discord -> server
line_comment
nl
package disc.command; //mindustry + arc import io.anuke.mindustry.Vars; import io.anuke.mindustry.content.Items; import io.anuke.mindustry.entities.type.Player; import io.anuke.mindustry.gen.Call; //javacord import io.anuke.mindustry.world.modules.ItemModule; import org.javacord.api.entity.message.MessageBuilder; import org.javacord.api.event.message.MessageCreateEvent; import org.javacord.api.listener.message.MessageCreateListener; public class comCommands implements MessageCreateListener { @Override public void onMessageCreate(MessageCreateEvent event){ if (event.getMessageContent().startsWith("..chat ")){ //discord -><SUF> String[] msg = event.getMessageContent().split(" ", 2); Call.sendMessage("[sky]" +event.getMessageAuthor().getName()+ " @discord >[] " + msg[1].trim()); } //playerlist else if (event.getMessageContent().equalsIgnoreCase("..players")){ StringBuilder lijst = new StringBuilder(); lijst.append("players: " + Vars.playerGroup.size()+"\n"); //lijst.append("online admins: " + Vars.playerGroup.all().count(p->p.isAdmin)+"\n"); for (Player p :Vars.playerGroup.all()){ lijst.append("* " + p.name.trim() + "\n"); } new MessageBuilder().appendCode("", lijst.toString()).send(event.getChannel()); } //info else if (event.getMessageContent().equalsIgnoreCase("..info")){ try { StringBuilder lijst = new StringBuilder(); lijst.append("map: " + Vars.world.getMap().name() + "\n" + "author: " + Vars.world.getMap().author() + "\n"); lijst.append("wave: " + Vars.state.wave + "\n"); lijst.append("enemies: " + Vars.state.enemies + "\n"); lijst.append("players: " + Vars.playerGroup.size() + '\n'); //lijst.append("admins (online): " + Vars.playerGroup.all().count(p -> p.isAdmin)); new MessageBuilder().appendCode("", lijst.toString()).send(event.getChannel()); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } //infores, werkt enkel als er minstens 1 speler online is! else if (event.getMessageContent().equalsIgnoreCase("..infores")){ //event.getChannel().sendMessage("not implemented yet..."); if (!Vars.state.rules.waves){ event.getChannel().sendMessage("Only available when playing survivalmode!"); return; } else if(Vars.playerGroup.isEmpty()) { event.getChannel().sendMessage("No players online!"); } else { StringBuilder lijst = new StringBuilder(); lijst.append("amount of items in the core\n\n"); ItemModule core = Vars.playerGroup.all().get(0).getClosestCore().items; lijst.append("copper: " + core.get(Items.copper) + "\n"); lijst.append("lead: " + core.get(Items.lead) + "\n"); lijst.append("graphite: " + core.get(Items.graphite) + "\n"); lijst.append("metaglass: " + core.get(Items.metaglass) + "\n"); lijst.append("titanium: " + core.get(Items.titanium) + "\n"); lijst.append("thorium: " + core.get(Items.thorium) + "\n"); lijst.append("silicon: " + core.get(Items.silicon) + "\n"); lijst.append("plastanium: " + core.get(Items.plastanium) + "\n"); lijst.append("phase fabric: " + core.get(Items.phasefabric) + "\n"); lijst.append("surge alloy: " + core.get(Items.surgealloy) + "\n"); new MessageBuilder().appendCode("", lijst.toString()).send(event.getChannel()); } } } }
199343_5
package disc.command; //mindustry + arc import io.anuke.mindustry.Vars; import io.anuke.mindustry.content.Items; import io.anuke.mindustry.entities.type.Player; import io.anuke.mindustry.gen.Call; //javacord import io.anuke.mindustry.world.modules.ItemModule; import org.javacord.api.entity.message.MessageBuilder; import org.javacord.api.event.message.MessageCreateEvent; import org.javacord.api.listener.message.MessageCreateListener; public class comCommands implements MessageCreateListener { @Override public void onMessageCreate(MessageCreateEvent event){ if (event.getMessageContent().startsWith("..chat ")){ //discord -> server String[] msg = event.getMessageContent().split(" ", 2); Call.sendMessage("[sky]" +event.getMessageAuthor().getName()+ " @discord >[] " + msg[1].trim()); } //playerlist else if (event.getMessageContent().equalsIgnoreCase("..players")){ StringBuilder lijst = new StringBuilder(); lijst.append("players: " + Vars.playerGroup.size()+"\n"); //lijst.append("online admins: " + Vars.playerGroup.all().count(p->p.isAdmin)+"\n"); for (Player p :Vars.playerGroup.all()){ lijst.append("* " + p.name.trim() + "\n"); } new MessageBuilder().appendCode("", lijst.toString()).send(event.getChannel()); } //info else if (event.getMessageContent().equalsIgnoreCase("..info")){ try { StringBuilder lijst = new StringBuilder(); lijst.append("map: " + Vars.world.getMap().name() + "\n" + "author: " + Vars.world.getMap().author() + "\n"); lijst.append("wave: " + Vars.state.wave + "\n"); lijst.append("enemies: " + Vars.state.enemies + "\n"); lijst.append("players: " + Vars.playerGroup.size() + '\n'); //lijst.append("admins (online): " + Vars.playerGroup.all().count(p -> p.isAdmin)); new MessageBuilder().appendCode("", lijst.toString()).send(event.getChannel()); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } //infores, werkt enkel als er minstens 1 speler online is! else if (event.getMessageContent().equalsIgnoreCase("..infores")){ //event.getChannel().sendMessage("not implemented yet..."); if (!Vars.state.rules.waves){ event.getChannel().sendMessage("Only available when playing survivalmode!"); return; } else if(Vars.playerGroup.isEmpty()) { event.getChannel().sendMessage("No players online!"); } else { StringBuilder lijst = new StringBuilder(); lijst.append("amount of items in the core\n\n"); ItemModule core = Vars.playerGroup.all().get(0).getClosestCore().items; lijst.append("copper: " + core.get(Items.copper) + "\n"); lijst.append("lead: " + core.get(Items.lead) + "\n"); lijst.append("graphite: " + core.get(Items.graphite) + "\n"); lijst.append("metaglass: " + core.get(Items.metaglass) + "\n"); lijst.append("titanium: " + core.get(Items.titanium) + "\n"); lijst.append("thorium: " + core.get(Items.thorium) + "\n"); lijst.append("silicon: " + core.get(Items.silicon) + "\n"); lijst.append("plastanium: " + core.get(Items.plastanium) + "\n"); lijst.append("phase fabric: " + core.get(Items.phasefabric) + "\n"); lijst.append("surge alloy: " + core.get(Items.surgealloy) + "\n"); new MessageBuilder().appendCode("", lijst.toString()).send(event.getChannel()); } } } }
Prosta4okua/DiscordPlugin
src/main/java/disc/command/comCommands.java
1,007
//event.getChannel().sendMessage("not implemented yet...");
line_comment
nl
package disc.command; //mindustry + arc import io.anuke.mindustry.Vars; import io.anuke.mindustry.content.Items; import io.anuke.mindustry.entities.type.Player; import io.anuke.mindustry.gen.Call; //javacord import io.anuke.mindustry.world.modules.ItemModule; import org.javacord.api.entity.message.MessageBuilder; import org.javacord.api.event.message.MessageCreateEvent; import org.javacord.api.listener.message.MessageCreateListener; public class comCommands implements MessageCreateListener { @Override public void onMessageCreate(MessageCreateEvent event){ if (event.getMessageContent().startsWith("..chat ")){ //discord -> server String[] msg = event.getMessageContent().split(" ", 2); Call.sendMessage("[sky]" +event.getMessageAuthor().getName()+ " @discord >[] " + msg[1].trim()); } //playerlist else if (event.getMessageContent().equalsIgnoreCase("..players")){ StringBuilder lijst = new StringBuilder(); lijst.append("players: " + Vars.playerGroup.size()+"\n"); //lijst.append("online admins: " + Vars.playerGroup.all().count(p->p.isAdmin)+"\n"); for (Player p :Vars.playerGroup.all()){ lijst.append("* " + p.name.trim() + "\n"); } new MessageBuilder().appendCode("", lijst.toString()).send(event.getChannel()); } //info else if (event.getMessageContent().equalsIgnoreCase("..info")){ try { StringBuilder lijst = new StringBuilder(); lijst.append("map: " + Vars.world.getMap().name() + "\n" + "author: " + Vars.world.getMap().author() + "\n"); lijst.append("wave: " + Vars.state.wave + "\n"); lijst.append("enemies: " + Vars.state.enemies + "\n"); lijst.append("players: " + Vars.playerGroup.size() + '\n'); //lijst.append("admins (online): " + Vars.playerGroup.all().count(p -> p.isAdmin)); new MessageBuilder().appendCode("", lijst.toString()).send(event.getChannel()); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } //infores, werkt enkel als er minstens 1 speler online is! else if (event.getMessageContent().equalsIgnoreCase("..infores")){ //event.getChannel().sendMessage("not implemented<SUF> if (!Vars.state.rules.waves){ event.getChannel().sendMessage("Only available when playing survivalmode!"); return; } else if(Vars.playerGroup.isEmpty()) { event.getChannel().sendMessage("No players online!"); } else { StringBuilder lijst = new StringBuilder(); lijst.append("amount of items in the core\n\n"); ItemModule core = Vars.playerGroup.all().get(0).getClosestCore().items; lijst.append("copper: " + core.get(Items.copper) + "\n"); lijst.append("lead: " + core.get(Items.lead) + "\n"); lijst.append("graphite: " + core.get(Items.graphite) + "\n"); lijst.append("metaglass: " + core.get(Items.metaglass) + "\n"); lijst.append("titanium: " + core.get(Items.titanium) + "\n"); lijst.append("thorium: " + core.get(Items.thorium) + "\n"); lijst.append("silicon: " + core.get(Items.silicon) + "\n"); lijst.append("plastanium: " + core.get(Items.plastanium) + "\n"); lijst.append("phase fabric: " + core.get(Items.phasefabric) + "\n"); lijst.append("surge alloy: " + core.get(Items.surgealloy) + "\n"); new MessageBuilder().appendCode("", lijst.toString()).send(event.getChannel()); } } } }
199344_1
/* * Copyright the State of the Netherlands * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package nl.overheid.aerius.shared.domain.v2.nsl; public enum NSLTreeProfile { /** * Hier en daar bomen of in het geheel niet. */ NONE_OR_FEW(1.0, 100), /** * Een of meer rijen bomen met een onderlinge afstand < 15 meter met openingen tussen de kronen. */ SEPARATED(1.25, 125), /** * De kronen raken elkaar en overspannen minstens een derde gedeelte van de straatbreedte. */ PACKED(1.5, 150); private final double factor; private final int fakeId; NSLTreeProfile(final double factor, final int fakeId) { this.factor = factor; this.fakeId = fakeId; } public double getFactor() { return factor; } public static NSLTreeProfile legacySafeValueOf(final double value) { NSLTreeProfile result = null; final int treeFactorInt = (int) (value * 100); for (final NSLTreeProfile treeProfile : values()) { if (treeFactorInt == treeProfile.fakeId) { result = treeProfile; break; } } return result; } }
Hilbrand/IMAER-java
source/imaer-shared/src/main/java/nl/overheid/aerius/shared/domain/v2/nsl/NSLTreeProfile.java
501
/** * Hier en daar bomen of in het geheel niet. */
block_comment
nl
/* * Copyright the State of the Netherlands * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package nl.overheid.aerius.shared.domain.v2.nsl; public enum NSLTreeProfile { /** * Hier en daar<SUF>*/ NONE_OR_FEW(1.0, 100), /** * Een of meer rijen bomen met een onderlinge afstand < 15 meter met openingen tussen de kronen. */ SEPARATED(1.25, 125), /** * De kronen raken elkaar en overspannen minstens een derde gedeelte van de straatbreedte. */ PACKED(1.5, 150); private final double factor; private final int fakeId; NSLTreeProfile(final double factor, final int fakeId) { this.factor = factor; this.fakeId = fakeId; } public double getFactor() { return factor; } public static NSLTreeProfile legacySafeValueOf(final double value) { NSLTreeProfile result = null; final int treeFactorInt = (int) (value * 100); for (final NSLTreeProfile treeProfile : values()) { if (treeFactorInt == treeProfile.fakeId) { result = treeProfile; break; } } return result; } }
199344_2
/* * Copyright the State of the Netherlands * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package nl.overheid.aerius.shared.domain.v2.nsl; public enum NSLTreeProfile { /** * Hier en daar bomen of in het geheel niet. */ NONE_OR_FEW(1.0, 100), /** * Een of meer rijen bomen met een onderlinge afstand < 15 meter met openingen tussen de kronen. */ SEPARATED(1.25, 125), /** * De kronen raken elkaar en overspannen minstens een derde gedeelte van de straatbreedte. */ PACKED(1.5, 150); private final double factor; private final int fakeId; NSLTreeProfile(final double factor, final int fakeId) { this.factor = factor; this.fakeId = fakeId; } public double getFactor() { return factor; } public static NSLTreeProfile legacySafeValueOf(final double value) { NSLTreeProfile result = null; final int treeFactorInt = (int) (value * 100); for (final NSLTreeProfile treeProfile : values()) { if (treeFactorInt == treeProfile.fakeId) { result = treeProfile; break; } } return result; } }
Hilbrand/IMAER-java
source/imaer-shared/src/main/java/nl/overheid/aerius/shared/domain/v2/nsl/NSLTreeProfile.java
501
/** * Een of meer rijen bomen met een onderlinge afstand < 15 meter met openingen tussen de kronen. */
block_comment
nl
/* * Copyright the State of the Netherlands * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package nl.overheid.aerius.shared.domain.v2.nsl; public enum NSLTreeProfile { /** * Hier en daar bomen of in het geheel niet. */ NONE_OR_FEW(1.0, 100), /** * Een of meer<SUF>*/ SEPARATED(1.25, 125), /** * De kronen raken elkaar en overspannen minstens een derde gedeelte van de straatbreedte. */ PACKED(1.5, 150); private final double factor; private final int fakeId; NSLTreeProfile(final double factor, final int fakeId) { this.factor = factor; this.fakeId = fakeId; } public double getFactor() { return factor; } public static NSLTreeProfile legacySafeValueOf(final double value) { NSLTreeProfile result = null; final int treeFactorInt = (int) (value * 100); for (final NSLTreeProfile treeProfile : values()) { if (treeFactorInt == treeProfile.fakeId) { result = treeProfile; break; } } return result; } }
199344_3
/* * Copyright the State of the Netherlands * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package nl.overheid.aerius.shared.domain.v2.nsl; public enum NSLTreeProfile { /** * Hier en daar bomen of in het geheel niet. */ NONE_OR_FEW(1.0, 100), /** * Een of meer rijen bomen met een onderlinge afstand < 15 meter met openingen tussen de kronen. */ SEPARATED(1.25, 125), /** * De kronen raken elkaar en overspannen minstens een derde gedeelte van de straatbreedte. */ PACKED(1.5, 150); private final double factor; private final int fakeId; NSLTreeProfile(final double factor, final int fakeId) { this.factor = factor; this.fakeId = fakeId; } public double getFactor() { return factor; } public static NSLTreeProfile legacySafeValueOf(final double value) { NSLTreeProfile result = null; final int treeFactorInt = (int) (value * 100); for (final NSLTreeProfile treeProfile : values()) { if (treeFactorInt == treeProfile.fakeId) { result = treeProfile; break; } } return result; } }
Hilbrand/IMAER-java
source/imaer-shared/src/main/java/nl/overheid/aerius/shared/domain/v2/nsl/NSLTreeProfile.java
501
/** * De kronen raken elkaar en overspannen minstens een derde gedeelte van de straatbreedte. */
block_comment
nl
/* * Copyright the State of the Netherlands * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package nl.overheid.aerius.shared.domain.v2.nsl; public enum NSLTreeProfile { /** * Hier en daar bomen of in het geheel niet. */ NONE_OR_FEW(1.0, 100), /** * Een of meer rijen bomen met een onderlinge afstand < 15 meter met openingen tussen de kronen. */ SEPARATED(1.25, 125), /** * De kronen raken<SUF>*/ PACKED(1.5, 150); private final double factor; private final int fakeId; NSLTreeProfile(final double factor, final int fakeId) { this.factor = factor; this.fakeId = fakeId; } public double getFactor() { return factor; } public static NSLTreeProfile legacySafeValueOf(final double value) { NSLTreeProfile result = null; final int treeFactorInt = (int) (value * 100); for (final NSLTreeProfile treeProfile : values()) { if (treeFactorInt == treeProfile.fakeId) { result = treeProfile; break; } } return result; } }
199349_0
package model.newsItems; import model.channels.RssFeed; /** * Klasse die de verplichte elementen bevat van een nieuwsitem uit een RSS-feed * Er moet minstens een titel OF een description aanwezig zijn. * * RSS 2.0 Standaard voor een item, artikel * Meer info op: http://cyber.law.harvard.edu/rss/rss.html * * title De titel van het nieuwsitem. * description De inhoud van het artikel * */ public class NewsItemMinImpl implements NewsItem { /*** PROPERTIES ***/ //rss properties private String title; private String description; //Reference naar channel, rss-feed private String feedCategory; private RssFeed rssFeed; /*** CONSTRUCTORS ***/ public NewsItemMinImpl(){} public NewsItemMinImpl(String title, String description, String feedCategory){ this.description = description; this.title = title; this.feedCategory = feedCategory; } /*** METHODS ***/ @Override public Boolean validateNewsItem() { // TODO Auto-generated method stub return true; } /*** GETTERS & SETTERS ***/ public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getFeedCategory() { return feedCategory; } public void setFeed(String feedCategory) { this.feedCategory = feedCategory; } public RssFeed getRssFeed() { return rssFeed; } public void setRssFeed(RssFeed rssFeed) { this.rssFeed = rssFeed; } }
readerAppRafKurt/AndroidApp
RssFeedModel/src/model/newsItems/NewsItemMinImpl.java
481
/** * Klasse die de verplichte elementen bevat van een nieuwsitem uit een RSS-feed * Er moet minstens een titel OF een description aanwezig zijn. * * RSS 2.0 Standaard voor een item, artikel * Meer info op: http://cyber.law.harvard.edu/rss/rss.html * * title De titel van het nieuwsitem. * description De inhoud van het artikel * */
block_comment
nl
package model.newsItems; import model.channels.RssFeed; /** * Klasse die de<SUF>*/ public class NewsItemMinImpl implements NewsItem { /*** PROPERTIES ***/ //rss properties private String title; private String description; //Reference naar channel, rss-feed private String feedCategory; private RssFeed rssFeed; /*** CONSTRUCTORS ***/ public NewsItemMinImpl(){} public NewsItemMinImpl(String title, String description, String feedCategory){ this.description = description; this.title = title; this.feedCategory = feedCategory; } /*** METHODS ***/ @Override public Boolean validateNewsItem() { // TODO Auto-generated method stub return true; } /*** GETTERS & SETTERS ***/ public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getFeedCategory() { return feedCategory; } public void setFeed(String feedCategory) { this.feedCategory = feedCategory; } public RssFeed getRssFeed() { return rssFeed; } public void setRssFeed(RssFeed rssFeed) { this.rssFeed = rssFeed; } }
199349_1
package model.newsItems; import model.channels.RssFeed; /** * Klasse die de verplichte elementen bevat van een nieuwsitem uit een RSS-feed * Er moet minstens een titel OF een description aanwezig zijn. * * RSS 2.0 Standaard voor een item, artikel * Meer info op: http://cyber.law.harvard.edu/rss/rss.html * * title De titel van het nieuwsitem. * description De inhoud van het artikel * */ public class NewsItemMinImpl implements NewsItem { /*** PROPERTIES ***/ //rss properties private String title; private String description; //Reference naar channel, rss-feed private String feedCategory; private RssFeed rssFeed; /*** CONSTRUCTORS ***/ public NewsItemMinImpl(){} public NewsItemMinImpl(String title, String description, String feedCategory){ this.description = description; this.title = title; this.feedCategory = feedCategory; } /*** METHODS ***/ @Override public Boolean validateNewsItem() { // TODO Auto-generated method stub return true; } /*** GETTERS & SETTERS ***/ public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getFeedCategory() { return feedCategory; } public void setFeed(String feedCategory) { this.feedCategory = feedCategory; } public RssFeed getRssFeed() { return rssFeed; } public void setRssFeed(RssFeed rssFeed) { this.rssFeed = rssFeed; } }
readerAppRafKurt/AndroidApp
RssFeedModel/src/model/newsItems/NewsItemMinImpl.java
481
//Reference naar channel, rss-feed
line_comment
nl
package model.newsItems; import model.channels.RssFeed; /** * Klasse die de verplichte elementen bevat van een nieuwsitem uit een RSS-feed * Er moet minstens een titel OF een description aanwezig zijn. * * RSS 2.0 Standaard voor een item, artikel * Meer info op: http://cyber.law.harvard.edu/rss/rss.html * * title De titel van het nieuwsitem. * description De inhoud van het artikel * */ public class NewsItemMinImpl implements NewsItem { /*** PROPERTIES ***/ //rss properties private String title; private String description; //Reference naar<SUF> private String feedCategory; private RssFeed rssFeed; /*** CONSTRUCTORS ***/ public NewsItemMinImpl(){} public NewsItemMinImpl(String title, String description, String feedCategory){ this.description = description; this.title = title; this.feedCategory = feedCategory; } /*** METHODS ***/ @Override public Boolean validateNewsItem() { // TODO Auto-generated method stub return true; } /*** GETTERS & SETTERS ***/ public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getFeedCategory() { return feedCategory; } public void setFeed(String feedCategory) { this.feedCategory = feedCategory; } public RssFeed getRssFeed() { return rssFeed; } public void setRssFeed(RssFeed rssFeed) { this.rssFeed = rssFeed; } }
199353_3
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gui; import domein.DomeinController; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; /** * * @author bjorn */ public class SpelersSettings extends BorderPane{ private final DomeinController dc; private int aantalSpelers; private final Startscherm sts; public SpelersSettings(Startscherm sts, DomeinController dc){ this.sts = sts; this.dc = dc; buildGui(); } private void buildGui(){ // Panes/Boxes/CSS getStylesheets().add("/css/spelerssettings.css"); BorderPane keuzeSpelers = new BorderPane(); HBox deKeuze = new HBox(); VBox vbox = new VBox(); // Buttons Button btnNext = new Button(); Button btnCancel = new Button(); // Titel Label Spelers ************************************************************************* Label lblSpelers = new Label("Spelers"); lblSpelers.setId("lblSpelers"); // Label Aantal Spelers ************************************************************************ Label lblAantalSpelers = new Label("Aantal"); lblAantalSpelers.setId("lblAantalSpelers"); // ChoiceBox (naast lblAantalSpelers) *********************************************************** ChoiceBox cb = new ChoiceBox(FXCollections.observableArrayList(2, 3, 4, 5, 6, 7)); btnNext.disableProperty().bind(cb.valueProperty().isNull()); cb.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue ov, Number value, Number new_value) { aantalSpelers = new_value.intValue()+2;//we spelen minstens met 2 } }); // Button Next ***************************************************************************** btnNext.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent ae) { btnNextOnAction(ae); } }); btnNext.setId("btnNext"); btnNext.setPrefSize(100, 100); // Button Cancel ***************************************************************************** btnCancel.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent evt) { Stage stage = (Stage) getScene().getWindow(); stage.setScene(sts.getScene()); } }); btnCancel.setId("btnCancel"); btnCancel.setPrefSize(100, 100); // Alligning van de elementen **************************************************************** //deKeuze = HBox //vbox = VBox deKeuze.getChildren().addAll(lblAantalSpelers, cb, btnNext, btnCancel); deKeuze.setPadding(new Insets(5)); deKeuze.setSpacing(15); vbox.setAlignment(Pos.CENTER); deKeuze.setAlignment(Pos.CENTER); vbox.getChildren().addAll(lblSpelers, deKeuze); keuzeSpelers.setCenter(vbox); this.setCenter(keuzeSpelers); } private void btnNextOnAction(ActionEvent event) { // aantal spelers (ingevuld op loginscherm), willen we tonen op volgend scherm SpelersInfoSettings sis = new SpelersInfoSettings(sts, aantalSpelers, this, dc); Scene scene = new Scene(sis, 1250, 700); Stage stage = (Stage) this.getScene().getWindow(); stage.setScene(scene); stage.show(); } }
rayzorg/regenworm
src/gui/SpelersSettings.java
1,139
// Titel Label Spelers *************************************************************************
line_comment
nl
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gui; import domein.DomeinController; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; /** * * @author bjorn */ public class SpelersSettings extends BorderPane{ private final DomeinController dc; private int aantalSpelers; private final Startscherm sts; public SpelersSettings(Startscherm sts, DomeinController dc){ this.sts = sts; this.dc = dc; buildGui(); } private void buildGui(){ // Panes/Boxes/CSS getStylesheets().add("/css/spelerssettings.css"); BorderPane keuzeSpelers = new BorderPane(); HBox deKeuze = new HBox(); VBox vbox = new VBox(); // Buttons Button btnNext = new Button(); Button btnCancel = new Button(); // Titel Label<SUF> Label lblSpelers = new Label("Spelers"); lblSpelers.setId("lblSpelers"); // Label Aantal Spelers ************************************************************************ Label lblAantalSpelers = new Label("Aantal"); lblAantalSpelers.setId("lblAantalSpelers"); // ChoiceBox (naast lblAantalSpelers) *********************************************************** ChoiceBox cb = new ChoiceBox(FXCollections.observableArrayList(2, 3, 4, 5, 6, 7)); btnNext.disableProperty().bind(cb.valueProperty().isNull()); cb.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue ov, Number value, Number new_value) { aantalSpelers = new_value.intValue()+2;//we spelen minstens met 2 } }); // Button Next ***************************************************************************** btnNext.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent ae) { btnNextOnAction(ae); } }); btnNext.setId("btnNext"); btnNext.setPrefSize(100, 100); // Button Cancel ***************************************************************************** btnCancel.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent evt) { Stage stage = (Stage) getScene().getWindow(); stage.setScene(sts.getScene()); } }); btnCancel.setId("btnCancel"); btnCancel.setPrefSize(100, 100); // Alligning van de elementen **************************************************************** //deKeuze = HBox //vbox = VBox deKeuze.getChildren().addAll(lblAantalSpelers, cb, btnNext, btnCancel); deKeuze.setPadding(new Insets(5)); deKeuze.setSpacing(15); vbox.setAlignment(Pos.CENTER); deKeuze.setAlignment(Pos.CENTER); vbox.getChildren().addAll(lblSpelers, deKeuze); keuzeSpelers.setCenter(vbox); this.setCenter(keuzeSpelers); } private void btnNextOnAction(ActionEvent event) { // aantal spelers (ingevuld op loginscherm), willen we tonen op volgend scherm SpelersInfoSettings sis = new SpelersInfoSettings(sts, aantalSpelers, this, dc); Scene scene = new Scene(sis, 1250, 700); Stage stage = (Stage) this.getScene().getWindow(); stage.setScene(scene); stage.show(); } }
199353_5
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gui; import domein.DomeinController; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; /** * * @author bjorn */ public class SpelersSettings extends BorderPane{ private final DomeinController dc; private int aantalSpelers; private final Startscherm sts; public SpelersSettings(Startscherm sts, DomeinController dc){ this.sts = sts; this.dc = dc; buildGui(); } private void buildGui(){ // Panes/Boxes/CSS getStylesheets().add("/css/spelerssettings.css"); BorderPane keuzeSpelers = new BorderPane(); HBox deKeuze = new HBox(); VBox vbox = new VBox(); // Buttons Button btnNext = new Button(); Button btnCancel = new Button(); // Titel Label Spelers ************************************************************************* Label lblSpelers = new Label("Spelers"); lblSpelers.setId("lblSpelers"); // Label Aantal Spelers ************************************************************************ Label lblAantalSpelers = new Label("Aantal"); lblAantalSpelers.setId("lblAantalSpelers"); // ChoiceBox (naast lblAantalSpelers) *********************************************************** ChoiceBox cb = new ChoiceBox(FXCollections.observableArrayList(2, 3, 4, 5, 6, 7)); btnNext.disableProperty().bind(cb.valueProperty().isNull()); cb.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue ov, Number value, Number new_value) { aantalSpelers = new_value.intValue()+2;//we spelen minstens met 2 } }); // Button Next ***************************************************************************** btnNext.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent ae) { btnNextOnAction(ae); } }); btnNext.setId("btnNext"); btnNext.setPrefSize(100, 100); // Button Cancel ***************************************************************************** btnCancel.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent evt) { Stage stage = (Stage) getScene().getWindow(); stage.setScene(sts.getScene()); } }); btnCancel.setId("btnCancel"); btnCancel.setPrefSize(100, 100); // Alligning van de elementen **************************************************************** //deKeuze = HBox //vbox = VBox deKeuze.getChildren().addAll(lblAantalSpelers, cb, btnNext, btnCancel); deKeuze.setPadding(new Insets(5)); deKeuze.setSpacing(15); vbox.setAlignment(Pos.CENTER); deKeuze.setAlignment(Pos.CENTER); vbox.getChildren().addAll(lblSpelers, deKeuze); keuzeSpelers.setCenter(vbox); this.setCenter(keuzeSpelers); } private void btnNextOnAction(ActionEvent event) { // aantal spelers (ingevuld op loginscherm), willen we tonen op volgend scherm SpelersInfoSettings sis = new SpelersInfoSettings(sts, aantalSpelers, this, dc); Scene scene = new Scene(sis, 1250, 700); Stage stage = (Stage) this.getScene().getWindow(); stage.setScene(scene); stage.show(); } }
rayzorg/regenworm
src/gui/SpelersSettings.java
1,139
// ChoiceBox (naast lblAantalSpelers) ***********************************************************
line_comment
nl
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gui; import domein.DomeinController; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; /** * * @author bjorn */ public class SpelersSettings extends BorderPane{ private final DomeinController dc; private int aantalSpelers; private final Startscherm sts; public SpelersSettings(Startscherm sts, DomeinController dc){ this.sts = sts; this.dc = dc; buildGui(); } private void buildGui(){ // Panes/Boxes/CSS getStylesheets().add("/css/spelerssettings.css"); BorderPane keuzeSpelers = new BorderPane(); HBox deKeuze = new HBox(); VBox vbox = new VBox(); // Buttons Button btnNext = new Button(); Button btnCancel = new Button(); // Titel Label Spelers ************************************************************************* Label lblSpelers = new Label("Spelers"); lblSpelers.setId("lblSpelers"); // Label Aantal Spelers ************************************************************************ Label lblAantalSpelers = new Label("Aantal"); lblAantalSpelers.setId("lblAantalSpelers"); // ChoiceBox (naast<SUF> ChoiceBox cb = new ChoiceBox(FXCollections.observableArrayList(2, 3, 4, 5, 6, 7)); btnNext.disableProperty().bind(cb.valueProperty().isNull()); cb.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue ov, Number value, Number new_value) { aantalSpelers = new_value.intValue()+2;//we spelen minstens met 2 } }); // Button Next ***************************************************************************** btnNext.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent ae) { btnNextOnAction(ae); } }); btnNext.setId("btnNext"); btnNext.setPrefSize(100, 100); // Button Cancel ***************************************************************************** btnCancel.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent evt) { Stage stage = (Stage) getScene().getWindow(); stage.setScene(sts.getScene()); } }); btnCancel.setId("btnCancel"); btnCancel.setPrefSize(100, 100); // Alligning van de elementen **************************************************************** //deKeuze = HBox //vbox = VBox deKeuze.getChildren().addAll(lblAantalSpelers, cb, btnNext, btnCancel); deKeuze.setPadding(new Insets(5)); deKeuze.setSpacing(15); vbox.setAlignment(Pos.CENTER); deKeuze.setAlignment(Pos.CENTER); vbox.getChildren().addAll(lblSpelers, deKeuze); keuzeSpelers.setCenter(vbox); this.setCenter(keuzeSpelers); } private void btnNextOnAction(ActionEvent event) { // aantal spelers (ingevuld op loginscherm), willen we tonen op volgend scherm SpelersInfoSettings sis = new SpelersInfoSettings(sts, aantalSpelers, this, dc); Scene scene = new Scene(sis, 1250, 700); Stage stage = (Stage) this.getScene().getWindow(); stage.setScene(scene); stage.show(); } }
199353_9
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gui; import domein.DomeinController; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; /** * * @author bjorn */ public class SpelersSettings extends BorderPane{ private final DomeinController dc; private int aantalSpelers; private final Startscherm sts; public SpelersSettings(Startscherm sts, DomeinController dc){ this.sts = sts; this.dc = dc; buildGui(); } private void buildGui(){ // Panes/Boxes/CSS getStylesheets().add("/css/spelerssettings.css"); BorderPane keuzeSpelers = new BorderPane(); HBox deKeuze = new HBox(); VBox vbox = new VBox(); // Buttons Button btnNext = new Button(); Button btnCancel = new Button(); // Titel Label Spelers ************************************************************************* Label lblSpelers = new Label("Spelers"); lblSpelers.setId("lblSpelers"); // Label Aantal Spelers ************************************************************************ Label lblAantalSpelers = new Label("Aantal"); lblAantalSpelers.setId("lblAantalSpelers"); // ChoiceBox (naast lblAantalSpelers) *********************************************************** ChoiceBox cb = new ChoiceBox(FXCollections.observableArrayList(2, 3, 4, 5, 6, 7)); btnNext.disableProperty().bind(cb.valueProperty().isNull()); cb.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue ov, Number value, Number new_value) { aantalSpelers = new_value.intValue()+2;//we spelen minstens met 2 } }); // Button Next ***************************************************************************** btnNext.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent ae) { btnNextOnAction(ae); } }); btnNext.setId("btnNext"); btnNext.setPrefSize(100, 100); // Button Cancel ***************************************************************************** btnCancel.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent evt) { Stage stage = (Stage) getScene().getWindow(); stage.setScene(sts.getScene()); } }); btnCancel.setId("btnCancel"); btnCancel.setPrefSize(100, 100); // Alligning van de elementen **************************************************************** //deKeuze = HBox //vbox = VBox deKeuze.getChildren().addAll(lblAantalSpelers, cb, btnNext, btnCancel); deKeuze.setPadding(new Insets(5)); deKeuze.setSpacing(15); vbox.setAlignment(Pos.CENTER); deKeuze.setAlignment(Pos.CENTER); vbox.getChildren().addAll(lblSpelers, deKeuze); keuzeSpelers.setCenter(vbox); this.setCenter(keuzeSpelers); } private void btnNextOnAction(ActionEvent event) { // aantal spelers (ingevuld op loginscherm), willen we tonen op volgend scherm SpelersInfoSettings sis = new SpelersInfoSettings(sts, aantalSpelers, this, dc); Scene scene = new Scene(sis, 1250, 700); Stage stage = (Stage) this.getScene().getWindow(); stage.setScene(scene); stage.show(); } }
rayzorg/regenworm
src/gui/SpelersSettings.java
1,139
// Alligning van de elementen ****************************************************************
line_comment
nl
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gui; import domein.DomeinController; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; /** * * @author bjorn */ public class SpelersSettings extends BorderPane{ private final DomeinController dc; private int aantalSpelers; private final Startscherm sts; public SpelersSettings(Startscherm sts, DomeinController dc){ this.sts = sts; this.dc = dc; buildGui(); } private void buildGui(){ // Panes/Boxes/CSS getStylesheets().add("/css/spelerssettings.css"); BorderPane keuzeSpelers = new BorderPane(); HBox deKeuze = new HBox(); VBox vbox = new VBox(); // Buttons Button btnNext = new Button(); Button btnCancel = new Button(); // Titel Label Spelers ************************************************************************* Label lblSpelers = new Label("Spelers"); lblSpelers.setId("lblSpelers"); // Label Aantal Spelers ************************************************************************ Label lblAantalSpelers = new Label("Aantal"); lblAantalSpelers.setId("lblAantalSpelers"); // ChoiceBox (naast lblAantalSpelers) *********************************************************** ChoiceBox cb = new ChoiceBox(FXCollections.observableArrayList(2, 3, 4, 5, 6, 7)); btnNext.disableProperty().bind(cb.valueProperty().isNull()); cb.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue ov, Number value, Number new_value) { aantalSpelers = new_value.intValue()+2;//we spelen minstens met 2 } }); // Button Next ***************************************************************************** btnNext.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent ae) { btnNextOnAction(ae); } }); btnNext.setId("btnNext"); btnNext.setPrefSize(100, 100); // Button Cancel ***************************************************************************** btnCancel.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent evt) { Stage stage = (Stage) getScene().getWindow(); stage.setScene(sts.getScene()); } }); btnCancel.setId("btnCancel"); btnCancel.setPrefSize(100, 100); // Alligning van<SUF> //deKeuze = HBox //vbox = VBox deKeuze.getChildren().addAll(lblAantalSpelers, cb, btnNext, btnCancel); deKeuze.setPadding(new Insets(5)); deKeuze.setSpacing(15); vbox.setAlignment(Pos.CENTER); deKeuze.setAlignment(Pos.CENTER); vbox.getChildren().addAll(lblSpelers, deKeuze); keuzeSpelers.setCenter(vbox); this.setCenter(keuzeSpelers); } private void btnNextOnAction(ActionEvent event) { // aantal spelers (ingevuld op loginscherm), willen we tonen op volgend scherm SpelersInfoSettings sis = new SpelersInfoSettings(sts, aantalSpelers, this, dc); Scene scene = new Scene(sis, 1250, 700); Stage stage = (Stage) this.getScene().getWindow(); stage.setScene(scene); stage.show(); } }
199353_10
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gui; import domein.DomeinController; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; /** * * @author bjorn */ public class SpelersSettings extends BorderPane{ private final DomeinController dc; private int aantalSpelers; private final Startscherm sts; public SpelersSettings(Startscherm sts, DomeinController dc){ this.sts = sts; this.dc = dc; buildGui(); } private void buildGui(){ // Panes/Boxes/CSS getStylesheets().add("/css/spelerssettings.css"); BorderPane keuzeSpelers = new BorderPane(); HBox deKeuze = new HBox(); VBox vbox = new VBox(); // Buttons Button btnNext = new Button(); Button btnCancel = new Button(); // Titel Label Spelers ************************************************************************* Label lblSpelers = new Label("Spelers"); lblSpelers.setId("lblSpelers"); // Label Aantal Spelers ************************************************************************ Label lblAantalSpelers = new Label("Aantal"); lblAantalSpelers.setId("lblAantalSpelers"); // ChoiceBox (naast lblAantalSpelers) *********************************************************** ChoiceBox cb = new ChoiceBox(FXCollections.observableArrayList(2, 3, 4, 5, 6, 7)); btnNext.disableProperty().bind(cb.valueProperty().isNull()); cb.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue ov, Number value, Number new_value) { aantalSpelers = new_value.intValue()+2;//we spelen minstens met 2 } }); // Button Next ***************************************************************************** btnNext.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent ae) { btnNextOnAction(ae); } }); btnNext.setId("btnNext"); btnNext.setPrefSize(100, 100); // Button Cancel ***************************************************************************** btnCancel.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent evt) { Stage stage = (Stage) getScene().getWindow(); stage.setScene(sts.getScene()); } }); btnCancel.setId("btnCancel"); btnCancel.setPrefSize(100, 100); // Alligning van de elementen **************************************************************** //deKeuze = HBox //vbox = VBox deKeuze.getChildren().addAll(lblAantalSpelers, cb, btnNext, btnCancel); deKeuze.setPadding(new Insets(5)); deKeuze.setSpacing(15); vbox.setAlignment(Pos.CENTER); deKeuze.setAlignment(Pos.CENTER); vbox.getChildren().addAll(lblSpelers, deKeuze); keuzeSpelers.setCenter(vbox); this.setCenter(keuzeSpelers); } private void btnNextOnAction(ActionEvent event) { // aantal spelers (ingevuld op loginscherm), willen we tonen op volgend scherm SpelersInfoSettings sis = new SpelersInfoSettings(sts, aantalSpelers, this, dc); Scene scene = new Scene(sis, 1250, 700); Stage stage = (Stage) this.getScene().getWindow(); stage.setScene(scene); stage.show(); } }
rayzorg/regenworm
src/gui/SpelersSettings.java
1,139
//deKeuze = HBox
line_comment
nl
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gui; import domein.DomeinController; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; /** * * @author bjorn */ public class SpelersSettings extends BorderPane{ private final DomeinController dc; private int aantalSpelers; private final Startscherm sts; public SpelersSettings(Startscherm sts, DomeinController dc){ this.sts = sts; this.dc = dc; buildGui(); } private void buildGui(){ // Panes/Boxes/CSS getStylesheets().add("/css/spelerssettings.css"); BorderPane keuzeSpelers = new BorderPane(); HBox deKeuze = new HBox(); VBox vbox = new VBox(); // Buttons Button btnNext = new Button(); Button btnCancel = new Button(); // Titel Label Spelers ************************************************************************* Label lblSpelers = new Label("Spelers"); lblSpelers.setId("lblSpelers"); // Label Aantal Spelers ************************************************************************ Label lblAantalSpelers = new Label("Aantal"); lblAantalSpelers.setId("lblAantalSpelers"); // ChoiceBox (naast lblAantalSpelers) *********************************************************** ChoiceBox cb = new ChoiceBox(FXCollections.observableArrayList(2, 3, 4, 5, 6, 7)); btnNext.disableProperty().bind(cb.valueProperty().isNull()); cb.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue ov, Number value, Number new_value) { aantalSpelers = new_value.intValue()+2;//we spelen minstens met 2 } }); // Button Next ***************************************************************************** btnNext.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent ae) { btnNextOnAction(ae); } }); btnNext.setId("btnNext"); btnNext.setPrefSize(100, 100); // Button Cancel ***************************************************************************** btnCancel.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent evt) { Stage stage = (Stage) getScene().getWindow(); stage.setScene(sts.getScene()); } }); btnCancel.setId("btnCancel"); btnCancel.setPrefSize(100, 100); // Alligning van de elementen **************************************************************** //deKeuze =<SUF> //vbox = VBox deKeuze.getChildren().addAll(lblAantalSpelers, cb, btnNext, btnCancel); deKeuze.setPadding(new Insets(5)); deKeuze.setSpacing(15); vbox.setAlignment(Pos.CENTER); deKeuze.setAlignment(Pos.CENTER); vbox.getChildren().addAll(lblSpelers, deKeuze); keuzeSpelers.setCenter(vbox); this.setCenter(keuzeSpelers); } private void btnNextOnAction(ActionEvent event) { // aantal spelers (ingevuld op loginscherm), willen we tonen op volgend scherm SpelersInfoSettings sis = new SpelersInfoSettings(sts, aantalSpelers, this, dc); Scene scene = new Scene(sis, 1250, 700); Stage stage = (Stage) this.getScene().getWindow(); stage.setScene(scene); stage.show(); } }
199353_12
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gui; import domein.DomeinController; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; /** * * @author bjorn */ public class SpelersSettings extends BorderPane{ private final DomeinController dc; private int aantalSpelers; private final Startscherm sts; public SpelersSettings(Startscherm sts, DomeinController dc){ this.sts = sts; this.dc = dc; buildGui(); } private void buildGui(){ // Panes/Boxes/CSS getStylesheets().add("/css/spelerssettings.css"); BorderPane keuzeSpelers = new BorderPane(); HBox deKeuze = new HBox(); VBox vbox = new VBox(); // Buttons Button btnNext = new Button(); Button btnCancel = new Button(); // Titel Label Spelers ************************************************************************* Label lblSpelers = new Label("Spelers"); lblSpelers.setId("lblSpelers"); // Label Aantal Spelers ************************************************************************ Label lblAantalSpelers = new Label("Aantal"); lblAantalSpelers.setId("lblAantalSpelers"); // ChoiceBox (naast lblAantalSpelers) *********************************************************** ChoiceBox cb = new ChoiceBox(FXCollections.observableArrayList(2, 3, 4, 5, 6, 7)); btnNext.disableProperty().bind(cb.valueProperty().isNull()); cb.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue ov, Number value, Number new_value) { aantalSpelers = new_value.intValue()+2;//we spelen minstens met 2 } }); // Button Next ***************************************************************************** btnNext.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent ae) { btnNextOnAction(ae); } }); btnNext.setId("btnNext"); btnNext.setPrefSize(100, 100); // Button Cancel ***************************************************************************** btnCancel.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent evt) { Stage stage = (Stage) getScene().getWindow(); stage.setScene(sts.getScene()); } }); btnCancel.setId("btnCancel"); btnCancel.setPrefSize(100, 100); // Alligning van de elementen **************************************************************** //deKeuze = HBox //vbox = VBox deKeuze.getChildren().addAll(lblAantalSpelers, cb, btnNext, btnCancel); deKeuze.setPadding(new Insets(5)); deKeuze.setSpacing(15); vbox.setAlignment(Pos.CENTER); deKeuze.setAlignment(Pos.CENTER); vbox.getChildren().addAll(lblSpelers, deKeuze); keuzeSpelers.setCenter(vbox); this.setCenter(keuzeSpelers); } private void btnNextOnAction(ActionEvent event) { // aantal spelers (ingevuld op loginscherm), willen we tonen op volgend scherm SpelersInfoSettings sis = new SpelersInfoSettings(sts, aantalSpelers, this, dc); Scene scene = new Scene(sis, 1250, 700); Stage stage = (Stage) this.getScene().getWindow(); stage.setScene(scene); stage.show(); } }
rayzorg/regenworm
src/gui/SpelersSettings.java
1,139
// aantal spelers (ingevuld op loginscherm), willen we tonen op volgend scherm
line_comment
nl
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gui; import domein.DomeinController; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; /** * * @author bjorn */ public class SpelersSettings extends BorderPane{ private final DomeinController dc; private int aantalSpelers; private final Startscherm sts; public SpelersSettings(Startscherm sts, DomeinController dc){ this.sts = sts; this.dc = dc; buildGui(); } private void buildGui(){ // Panes/Boxes/CSS getStylesheets().add("/css/spelerssettings.css"); BorderPane keuzeSpelers = new BorderPane(); HBox deKeuze = new HBox(); VBox vbox = new VBox(); // Buttons Button btnNext = new Button(); Button btnCancel = new Button(); // Titel Label Spelers ************************************************************************* Label lblSpelers = new Label("Spelers"); lblSpelers.setId("lblSpelers"); // Label Aantal Spelers ************************************************************************ Label lblAantalSpelers = new Label("Aantal"); lblAantalSpelers.setId("lblAantalSpelers"); // ChoiceBox (naast lblAantalSpelers) *********************************************************** ChoiceBox cb = new ChoiceBox(FXCollections.observableArrayList(2, 3, 4, 5, 6, 7)); btnNext.disableProperty().bind(cb.valueProperty().isNull()); cb.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue ov, Number value, Number new_value) { aantalSpelers = new_value.intValue()+2;//we spelen minstens met 2 } }); // Button Next ***************************************************************************** btnNext.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent ae) { btnNextOnAction(ae); } }); btnNext.setId("btnNext"); btnNext.setPrefSize(100, 100); // Button Cancel ***************************************************************************** btnCancel.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent evt) { Stage stage = (Stage) getScene().getWindow(); stage.setScene(sts.getScene()); } }); btnCancel.setId("btnCancel"); btnCancel.setPrefSize(100, 100); // Alligning van de elementen **************************************************************** //deKeuze = HBox //vbox = VBox deKeuze.getChildren().addAll(lblAantalSpelers, cb, btnNext, btnCancel); deKeuze.setPadding(new Insets(5)); deKeuze.setSpacing(15); vbox.setAlignment(Pos.CENTER); deKeuze.setAlignment(Pos.CENTER); vbox.getChildren().addAll(lblSpelers, deKeuze); keuzeSpelers.setCenter(vbox); this.setCenter(keuzeSpelers); } private void btnNextOnAction(ActionEvent event) { // aantal spelers<SUF> SpelersInfoSettings sis = new SpelersInfoSettings(sts, aantalSpelers, this, dc); Scene scene = new Scene(sis, 1250, 700); Stage stage = (Stage) this.getScene().getWindow(); stage.setScene(scene); stage.show(); } }
199360_3
package be.intecbrussel; public class MainApp { public static void main(String[] args) { // for loop System.out.println(" ---- For loop ---- "); System.out.println(" ---- example 1 ---- "); for (int i = 0; i < 10; i++) { System.out.println("for loop - sit up: " + i); } System.out.println(" ---- example 2 ---- "); for (int index = 1; index <= 5; index++) { System.out.println("Hello World"); } System.out.println(" ---- example 3 ---- "); for (int index = 10; index >= 0; index--) { System.out.println("The index is: " + index); } // while System.out.println(" ---- while loop ----"); System.out.println(" ---- example 1 ---- "); int x = 0; while (x < 10) { System.out.println("while loop - sit up: " + x); x++; } System.out.println(" ---- example 2 ---- "); x = 1; int sum = 0; // Exit when x becomes greater than 4 while (x <= 10) { // summing up x sum = sum + x; // Increment the value of x for next iteration x++; } System.out.println("Summation: " + sum); System.out.println(" ---- example 3 ---- "); boolean hungry = true; int count = 0; System.out.println("Take flour"); System.out.println("Add milk"); System.out.println("Add eggs"); System.out.println("Mix ingredients"); while (hungry) { ++count; System.out.println("Bake pancake " + count); System.out.println("Eat pancake " + count); if(count == 4 ) { hungry = false; } } // do-while System.out.println(" --- do while loop --- "); System.out.println(" ---- example 1 ---- "); // wordt minstens 1 keer uitgevoerd int y = 0; do { System.out.println("do while loop - sit up: " + y); y++; } while (y < 10); System.out.println(" ---- example 2 ---- "); int index = 10; do { // Body of do-while loop System.out.println("Hello World"); // Update expression index++; // Test expression }while (index < 6); System.out.println(" ---- example 3 ---- "); x = 21; sum = 0; do { // Execution statements(Body of loop) // Here, the line will be printed even if the condition is false sum += x; x--; // Now checking condition } while (x > 10); // Summing up System.out.println("Summation: " + sum); // break keyword System.out.println(" ---- break ---- "); for (int i = 0; i < 10; i++) { System.out.println("i = " + i); for (int j = 0; j < 10; j++) { if (j == 5) { break; // break zal de eerste loop stoppen } } if (i == 5) { break; } } //label System.out.println("--- break with label ---"); search: for (int i = 0; i < 10; i++) { System.out.println("i = " + i); for (int j = 0; j < 10; j++) { if (j == 5){ i = 100; // zal eerste loop stoppen // of break search; // zal eerste loop stoppen } } } // continue keyword System.out.println(" ---- continue ---- "); for (int i = 0; i < 10; i++) { if (i % 2 == 0){ continue; // ga terug naar start, i wordt nog steeds verhoogt } System.out.println("Odd number: " + i); } // label System.out.println("--- continue with label ---"); start: for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { // if (j == 5){ // continue start; // } System.out.println("j = " + j); } System.out.println("i = " + i); } // infinite loop - danger // int z = 0; // while(z < 10){ // System.out.println("infinite loop"); // } } }
Gabe-Alvess/Loops
src/be/intecbrussel/MainApp.java
1,254
// wordt minstens 1 keer uitgevoerd
line_comment
nl
package be.intecbrussel; public class MainApp { public static void main(String[] args) { // for loop System.out.println(" ---- For loop ---- "); System.out.println(" ---- example 1 ---- "); for (int i = 0; i < 10; i++) { System.out.println("for loop - sit up: " + i); } System.out.println(" ---- example 2 ---- "); for (int index = 1; index <= 5; index++) { System.out.println("Hello World"); } System.out.println(" ---- example 3 ---- "); for (int index = 10; index >= 0; index--) { System.out.println("The index is: " + index); } // while System.out.println(" ---- while loop ----"); System.out.println(" ---- example 1 ---- "); int x = 0; while (x < 10) { System.out.println("while loop - sit up: " + x); x++; } System.out.println(" ---- example 2 ---- "); x = 1; int sum = 0; // Exit when x becomes greater than 4 while (x <= 10) { // summing up x sum = sum + x; // Increment the value of x for next iteration x++; } System.out.println("Summation: " + sum); System.out.println(" ---- example 3 ---- "); boolean hungry = true; int count = 0; System.out.println("Take flour"); System.out.println("Add milk"); System.out.println("Add eggs"); System.out.println("Mix ingredients"); while (hungry) { ++count; System.out.println("Bake pancake " + count); System.out.println("Eat pancake " + count); if(count == 4 ) { hungry = false; } } // do-while System.out.println(" --- do while loop --- "); System.out.println(" ---- example 1 ---- "); // wordt minstens<SUF> int y = 0; do { System.out.println("do while loop - sit up: " + y); y++; } while (y < 10); System.out.println(" ---- example 2 ---- "); int index = 10; do { // Body of do-while loop System.out.println("Hello World"); // Update expression index++; // Test expression }while (index < 6); System.out.println(" ---- example 3 ---- "); x = 21; sum = 0; do { // Execution statements(Body of loop) // Here, the line will be printed even if the condition is false sum += x; x--; // Now checking condition } while (x > 10); // Summing up System.out.println("Summation: " + sum); // break keyword System.out.println(" ---- break ---- "); for (int i = 0; i < 10; i++) { System.out.println("i = " + i); for (int j = 0; j < 10; j++) { if (j == 5) { break; // break zal de eerste loop stoppen } } if (i == 5) { break; } } //label System.out.println("--- break with label ---"); search: for (int i = 0; i < 10; i++) { System.out.println("i = " + i); for (int j = 0; j < 10; j++) { if (j == 5){ i = 100; // zal eerste loop stoppen // of break search; // zal eerste loop stoppen } } } // continue keyword System.out.println(" ---- continue ---- "); for (int i = 0; i < 10; i++) { if (i % 2 == 0){ continue; // ga terug naar start, i wordt nog steeds verhoogt } System.out.println("Odd number: " + i); } // label System.out.println("--- continue with label ---"); start: for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { // if (j == 5){ // continue start; // } System.out.println("j = " + j); } System.out.println("i = " + i); } // infinite loop - danger // int z = 0; // while(z < 10){ // System.out.println("infinite loop"); // } } }
199360_8
package be.intecbrussel; public class MainApp { public static void main(String[] args) { // for loop System.out.println(" ---- For loop ---- "); System.out.println(" ---- example 1 ---- "); for (int i = 0; i < 10; i++) { System.out.println("for loop - sit up: " + i); } System.out.println(" ---- example 2 ---- "); for (int index = 1; index <= 5; index++) { System.out.println("Hello World"); } System.out.println(" ---- example 3 ---- "); for (int index = 10; index >= 0; index--) { System.out.println("The index is: " + index); } // while System.out.println(" ---- while loop ----"); System.out.println(" ---- example 1 ---- "); int x = 0; while (x < 10) { System.out.println("while loop - sit up: " + x); x++; } System.out.println(" ---- example 2 ---- "); x = 1; int sum = 0; // Exit when x becomes greater than 4 while (x <= 10) { // summing up x sum = sum + x; // Increment the value of x for next iteration x++; } System.out.println("Summation: " + sum); System.out.println(" ---- example 3 ---- "); boolean hungry = true; int count = 0; System.out.println("Take flour"); System.out.println("Add milk"); System.out.println("Add eggs"); System.out.println("Mix ingredients"); while (hungry) { ++count; System.out.println("Bake pancake " + count); System.out.println("Eat pancake " + count); if(count == 4 ) { hungry = false; } } // do-while System.out.println(" --- do while loop --- "); System.out.println(" ---- example 1 ---- "); // wordt minstens 1 keer uitgevoerd int y = 0; do { System.out.println("do while loop - sit up: " + y); y++; } while (y < 10); System.out.println(" ---- example 2 ---- "); int index = 10; do { // Body of do-while loop System.out.println("Hello World"); // Update expression index++; // Test expression }while (index < 6); System.out.println(" ---- example 3 ---- "); x = 21; sum = 0; do { // Execution statements(Body of loop) // Here, the line will be printed even if the condition is false sum += x; x--; // Now checking condition } while (x > 10); // Summing up System.out.println("Summation: " + sum); // break keyword System.out.println(" ---- break ---- "); for (int i = 0; i < 10; i++) { System.out.println("i = " + i); for (int j = 0; j < 10; j++) { if (j == 5) { break; // break zal de eerste loop stoppen } } if (i == 5) { break; } } //label System.out.println("--- break with label ---"); search: for (int i = 0; i < 10; i++) { System.out.println("i = " + i); for (int j = 0; j < 10; j++) { if (j == 5){ i = 100; // zal eerste loop stoppen // of break search; // zal eerste loop stoppen } } } // continue keyword System.out.println(" ---- continue ---- "); for (int i = 0; i < 10; i++) { if (i % 2 == 0){ continue; // ga terug naar start, i wordt nog steeds verhoogt } System.out.println("Odd number: " + i); } // label System.out.println("--- continue with label ---"); start: for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { // if (j == 5){ // continue start; // } System.out.println("j = " + j); } System.out.println("i = " + i); } // infinite loop - danger // int z = 0; // while(z < 10){ // System.out.println("infinite loop"); // } } }
Gabe-Alvess/Loops
src/be/intecbrussel/MainApp.java
1,254
// break zal de eerste loop stoppen
line_comment
nl
package be.intecbrussel; public class MainApp { public static void main(String[] args) { // for loop System.out.println(" ---- For loop ---- "); System.out.println(" ---- example 1 ---- "); for (int i = 0; i < 10; i++) { System.out.println("for loop - sit up: " + i); } System.out.println(" ---- example 2 ---- "); for (int index = 1; index <= 5; index++) { System.out.println("Hello World"); } System.out.println(" ---- example 3 ---- "); for (int index = 10; index >= 0; index--) { System.out.println("The index is: " + index); } // while System.out.println(" ---- while loop ----"); System.out.println(" ---- example 1 ---- "); int x = 0; while (x < 10) { System.out.println("while loop - sit up: " + x); x++; } System.out.println(" ---- example 2 ---- "); x = 1; int sum = 0; // Exit when x becomes greater than 4 while (x <= 10) { // summing up x sum = sum + x; // Increment the value of x for next iteration x++; } System.out.println("Summation: " + sum); System.out.println(" ---- example 3 ---- "); boolean hungry = true; int count = 0; System.out.println("Take flour"); System.out.println("Add milk"); System.out.println("Add eggs"); System.out.println("Mix ingredients"); while (hungry) { ++count; System.out.println("Bake pancake " + count); System.out.println("Eat pancake " + count); if(count == 4 ) { hungry = false; } } // do-while System.out.println(" --- do while loop --- "); System.out.println(" ---- example 1 ---- "); // wordt minstens 1 keer uitgevoerd int y = 0; do { System.out.println("do while loop - sit up: " + y); y++; } while (y < 10); System.out.println(" ---- example 2 ---- "); int index = 10; do { // Body of do-while loop System.out.println("Hello World"); // Update expression index++; // Test expression }while (index < 6); System.out.println(" ---- example 3 ---- "); x = 21; sum = 0; do { // Execution statements(Body of loop) // Here, the line will be printed even if the condition is false sum += x; x--; // Now checking condition } while (x > 10); // Summing up System.out.println("Summation: " + sum); // break keyword System.out.println(" ---- break ---- "); for (int i = 0; i < 10; i++) { System.out.println("i = " + i); for (int j = 0; j < 10; j++) { if (j == 5) { break; // break zal<SUF> } } if (i == 5) { break; } } //label System.out.println("--- break with label ---"); search: for (int i = 0; i < 10; i++) { System.out.println("i = " + i); for (int j = 0; j < 10; j++) { if (j == 5){ i = 100; // zal eerste loop stoppen // of break search; // zal eerste loop stoppen } } } // continue keyword System.out.println(" ---- continue ---- "); for (int i = 0; i < 10; i++) { if (i % 2 == 0){ continue; // ga terug naar start, i wordt nog steeds verhoogt } System.out.println("Odd number: " + i); } // label System.out.println("--- continue with label ---"); start: for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { // if (j == 5){ // continue start; // } System.out.println("j = " + j); } System.out.println("i = " + i); } // infinite loop - danger // int z = 0; // while(z < 10){ // System.out.println("infinite loop"); // } } }
199360_9
package be.intecbrussel; public class MainApp { public static void main(String[] args) { // for loop System.out.println(" ---- For loop ---- "); System.out.println(" ---- example 1 ---- "); for (int i = 0; i < 10; i++) { System.out.println("for loop - sit up: " + i); } System.out.println(" ---- example 2 ---- "); for (int index = 1; index <= 5; index++) { System.out.println("Hello World"); } System.out.println(" ---- example 3 ---- "); for (int index = 10; index >= 0; index--) { System.out.println("The index is: " + index); } // while System.out.println(" ---- while loop ----"); System.out.println(" ---- example 1 ---- "); int x = 0; while (x < 10) { System.out.println("while loop - sit up: " + x); x++; } System.out.println(" ---- example 2 ---- "); x = 1; int sum = 0; // Exit when x becomes greater than 4 while (x <= 10) { // summing up x sum = sum + x; // Increment the value of x for next iteration x++; } System.out.println("Summation: " + sum); System.out.println(" ---- example 3 ---- "); boolean hungry = true; int count = 0; System.out.println("Take flour"); System.out.println("Add milk"); System.out.println("Add eggs"); System.out.println("Mix ingredients"); while (hungry) { ++count; System.out.println("Bake pancake " + count); System.out.println("Eat pancake " + count); if(count == 4 ) { hungry = false; } } // do-while System.out.println(" --- do while loop --- "); System.out.println(" ---- example 1 ---- "); // wordt minstens 1 keer uitgevoerd int y = 0; do { System.out.println("do while loop - sit up: " + y); y++; } while (y < 10); System.out.println(" ---- example 2 ---- "); int index = 10; do { // Body of do-while loop System.out.println("Hello World"); // Update expression index++; // Test expression }while (index < 6); System.out.println(" ---- example 3 ---- "); x = 21; sum = 0; do { // Execution statements(Body of loop) // Here, the line will be printed even if the condition is false sum += x; x--; // Now checking condition } while (x > 10); // Summing up System.out.println("Summation: " + sum); // break keyword System.out.println(" ---- break ---- "); for (int i = 0; i < 10; i++) { System.out.println("i = " + i); for (int j = 0; j < 10; j++) { if (j == 5) { break; // break zal de eerste loop stoppen } } if (i == 5) { break; } } //label System.out.println("--- break with label ---"); search: for (int i = 0; i < 10; i++) { System.out.println("i = " + i); for (int j = 0; j < 10; j++) { if (j == 5){ i = 100; // zal eerste loop stoppen // of break search; // zal eerste loop stoppen } } } // continue keyword System.out.println(" ---- continue ---- "); for (int i = 0; i < 10; i++) { if (i % 2 == 0){ continue; // ga terug naar start, i wordt nog steeds verhoogt } System.out.println("Odd number: " + i); } // label System.out.println("--- continue with label ---"); start: for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { // if (j == 5){ // continue start; // } System.out.println("j = " + j); } System.out.println("i = " + i); } // infinite loop - danger // int z = 0; // while(z < 10){ // System.out.println("infinite loop"); // } } }
Gabe-Alvess/Loops
src/be/intecbrussel/MainApp.java
1,254
// zal eerste loop stoppen
line_comment
nl
package be.intecbrussel; public class MainApp { public static void main(String[] args) { // for loop System.out.println(" ---- For loop ---- "); System.out.println(" ---- example 1 ---- "); for (int i = 0; i < 10; i++) { System.out.println("for loop - sit up: " + i); } System.out.println(" ---- example 2 ---- "); for (int index = 1; index <= 5; index++) { System.out.println("Hello World"); } System.out.println(" ---- example 3 ---- "); for (int index = 10; index >= 0; index--) { System.out.println("The index is: " + index); } // while System.out.println(" ---- while loop ----"); System.out.println(" ---- example 1 ---- "); int x = 0; while (x < 10) { System.out.println("while loop - sit up: " + x); x++; } System.out.println(" ---- example 2 ---- "); x = 1; int sum = 0; // Exit when x becomes greater than 4 while (x <= 10) { // summing up x sum = sum + x; // Increment the value of x for next iteration x++; } System.out.println("Summation: " + sum); System.out.println(" ---- example 3 ---- "); boolean hungry = true; int count = 0; System.out.println("Take flour"); System.out.println("Add milk"); System.out.println("Add eggs"); System.out.println("Mix ingredients"); while (hungry) { ++count; System.out.println("Bake pancake " + count); System.out.println("Eat pancake " + count); if(count == 4 ) { hungry = false; } } // do-while System.out.println(" --- do while loop --- "); System.out.println(" ---- example 1 ---- "); // wordt minstens 1 keer uitgevoerd int y = 0; do { System.out.println("do while loop - sit up: " + y); y++; } while (y < 10); System.out.println(" ---- example 2 ---- "); int index = 10; do { // Body of do-while loop System.out.println("Hello World"); // Update expression index++; // Test expression }while (index < 6); System.out.println(" ---- example 3 ---- "); x = 21; sum = 0; do { // Execution statements(Body of loop) // Here, the line will be printed even if the condition is false sum += x; x--; // Now checking condition } while (x > 10); // Summing up System.out.println("Summation: " + sum); // break keyword System.out.println(" ---- break ---- "); for (int i = 0; i < 10; i++) { System.out.println("i = " + i); for (int j = 0; j < 10; j++) { if (j == 5) { break; // break zal de eerste loop stoppen } } if (i == 5) { break; } } //label System.out.println("--- break with label ---"); search: for (int i = 0; i < 10; i++) { System.out.println("i = " + i); for (int j = 0; j < 10; j++) { if (j == 5){ i = 100; // zal eerste<SUF> // of break search; // zal eerste loop stoppen } } } // continue keyword System.out.println(" ---- continue ---- "); for (int i = 0; i < 10; i++) { if (i % 2 == 0){ continue; // ga terug naar start, i wordt nog steeds verhoogt } System.out.println("Odd number: " + i); } // label System.out.println("--- continue with label ---"); start: for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { // if (j == 5){ // continue start; // } System.out.println("j = " + j); } System.out.println("i = " + i); } // infinite loop - danger // int z = 0; // while(z < 10){ // System.out.println("infinite loop"); // } } }
199360_10
package be.intecbrussel; public class MainApp { public static void main(String[] args) { // for loop System.out.println(" ---- For loop ---- "); System.out.println(" ---- example 1 ---- "); for (int i = 0; i < 10; i++) { System.out.println("for loop - sit up: " + i); } System.out.println(" ---- example 2 ---- "); for (int index = 1; index <= 5; index++) { System.out.println("Hello World"); } System.out.println(" ---- example 3 ---- "); for (int index = 10; index >= 0; index--) { System.out.println("The index is: " + index); } // while System.out.println(" ---- while loop ----"); System.out.println(" ---- example 1 ---- "); int x = 0; while (x < 10) { System.out.println("while loop - sit up: " + x); x++; } System.out.println(" ---- example 2 ---- "); x = 1; int sum = 0; // Exit when x becomes greater than 4 while (x <= 10) { // summing up x sum = sum + x; // Increment the value of x for next iteration x++; } System.out.println("Summation: " + sum); System.out.println(" ---- example 3 ---- "); boolean hungry = true; int count = 0; System.out.println("Take flour"); System.out.println("Add milk"); System.out.println("Add eggs"); System.out.println("Mix ingredients"); while (hungry) { ++count; System.out.println("Bake pancake " + count); System.out.println("Eat pancake " + count); if(count == 4 ) { hungry = false; } } // do-while System.out.println(" --- do while loop --- "); System.out.println(" ---- example 1 ---- "); // wordt minstens 1 keer uitgevoerd int y = 0; do { System.out.println("do while loop - sit up: " + y); y++; } while (y < 10); System.out.println(" ---- example 2 ---- "); int index = 10; do { // Body of do-while loop System.out.println("Hello World"); // Update expression index++; // Test expression }while (index < 6); System.out.println(" ---- example 3 ---- "); x = 21; sum = 0; do { // Execution statements(Body of loop) // Here, the line will be printed even if the condition is false sum += x; x--; // Now checking condition } while (x > 10); // Summing up System.out.println("Summation: " + sum); // break keyword System.out.println(" ---- break ---- "); for (int i = 0; i < 10; i++) { System.out.println("i = " + i); for (int j = 0; j < 10; j++) { if (j == 5) { break; // break zal de eerste loop stoppen } } if (i == 5) { break; } } //label System.out.println("--- break with label ---"); search: for (int i = 0; i < 10; i++) { System.out.println("i = " + i); for (int j = 0; j < 10; j++) { if (j == 5){ i = 100; // zal eerste loop stoppen // of break search; // zal eerste loop stoppen } } } // continue keyword System.out.println(" ---- continue ---- "); for (int i = 0; i < 10; i++) { if (i % 2 == 0){ continue; // ga terug naar start, i wordt nog steeds verhoogt } System.out.println("Odd number: " + i); } // label System.out.println("--- continue with label ---"); start: for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { // if (j == 5){ // continue start; // } System.out.println("j = " + j); } System.out.println("i = " + i); } // infinite loop - danger // int z = 0; // while(z < 10){ // System.out.println("infinite loop"); // } } }
Gabe-Alvess/Loops
src/be/intecbrussel/MainApp.java
1,254
// zal eerste loop stoppen
line_comment
nl
package be.intecbrussel; public class MainApp { public static void main(String[] args) { // for loop System.out.println(" ---- For loop ---- "); System.out.println(" ---- example 1 ---- "); for (int i = 0; i < 10; i++) { System.out.println("for loop - sit up: " + i); } System.out.println(" ---- example 2 ---- "); for (int index = 1; index <= 5; index++) { System.out.println("Hello World"); } System.out.println(" ---- example 3 ---- "); for (int index = 10; index >= 0; index--) { System.out.println("The index is: " + index); } // while System.out.println(" ---- while loop ----"); System.out.println(" ---- example 1 ---- "); int x = 0; while (x < 10) { System.out.println("while loop - sit up: " + x); x++; } System.out.println(" ---- example 2 ---- "); x = 1; int sum = 0; // Exit when x becomes greater than 4 while (x <= 10) { // summing up x sum = sum + x; // Increment the value of x for next iteration x++; } System.out.println("Summation: " + sum); System.out.println(" ---- example 3 ---- "); boolean hungry = true; int count = 0; System.out.println("Take flour"); System.out.println("Add milk"); System.out.println("Add eggs"); System.out.println("Mix ingredients"); while (hungry) { ++count; System.out.println("Bake pancake " + count); System.out.println("Eat pancake " + count); if(count == 4 ) { hungry = false; } } // do-while System.out.println(" --- do while loop --- "); System.out.println(" ---- example 1 ---- "); // wordt minstens 1 keer uitgevoerd int y = 0; do { System.out.println("do while loop - sit up: " + y); y++; } while (y < 10); System.out.println(" ---- example 2 ---- "); int index = 10; do { // Body of do-while loop System.out.println("Hello World"); // Update expression index++; // Test expression }while (index < 6); System.out.println(" ---- example 3 ---- "); x = 21; sum = 0; do { // Execution statements(Body of loop) // Here, the line will be printed even if the condition is false sum += x; x--; // Now checking condition } while (x > 10); // Summing up System.out.println("Summation: " + sum); // break keyword System.out.println(" ---- break ---- "); for (int i = 0; i < 10; i++) { System.out.println("i = " + i); for (int j = 0; j < 10; j++) { if (j == 5) { break; // break zal de eerste loop stoppen } } if (i == 5) { break; } } //label System.out.println("--- break with label ---"); search: for (int i = 0; i < 10; i++) { System.out.println("i = " + i); for (int j = 0; j < 10; j++) { if (j == 5){ i = 100; // zal eerste loop stoppen // of break search; // zal eerste<SUF> } } } // continue keyword System.out.println(" ---- continue ---- "); for (int i = 0; i < 10; i++) { if (i % 2 == 0){ continue; // ga terug naar start, i wordt nog steeds verhoogt } System.out.println("Odd number: " + i); } // label System.out.println("--- continue with label ---"); start: for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { // if (j == 5){ // continue start; // } System.out.println("j = " + j); } System.out.println("i = " + i); } // infinite loop - danger // int z = 0; // while(z < 10){ // System.out.println("infinite loop"); // } } }
199362_0
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.common; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Password generator voor BPR wachtwoorden */ public class BrpPasswordGenerator { private final static BrpPasswordGenerator generator = new BrpPasswordGenerator(); private final static List<Character> availableChars; static { List<Character> chars = new ArrayList<>(100); for (char ch = 'a'; ch <= 'z'; ch++) { chars.add(Character.toLowerCase(ch)); chars.add(Character.toUpperCase(ch)); } for (int i = 0; i < 3; i++) { for (char ch = '0'; ch <= '9'; ch++) { chars.add(ch); } } availableChars = Collections.unmodifiableList(chars); } private final Random random = new SecureRandom(); private final Pattern rule1 = Pattern.compile("^[\\w\\d _=+/!@*].*$"); private final Pattern rule4Letters = Pattern.compile("[a-zA-Z]{3}"); private final Pattern rule4Numbers = Pattern.compile("[0-9]{3}"); private final Pattern rule4Misc = Pattern.compile("[^a-zA-Z0-9 ]{3}"); private final Pattern rule6 = Pattern.compile("[a-zA-Z]{2,}"); private final Pattern rule7 = Pattern.compile("[0-9]{2,}"); private final Pattern rule8 = Pattern.compile("[^a-zA-Z0-9 ]"); public static String newPassword() { return generator.generate(); } public static boolean checkWachtwoord(String ww) { return generator.passingRules(ww); } public String generate() { String ww = ""; while (!passingRules(ww)) { StringBuilder pass = new StringBuilder(); for (int i = 0; i < 8; i++) { pass.append(availableChars.get(random.nextInt(availableChars.size()))); } ww = pass.toString(); } return ww; } private boolean passingRules(String password) { return passes1(password) && passes2(password) && passes3(password) && passes4(password) && passes8(password); } /** * @return <code>password</code> bestaat alleen uit toegestane tekens */ public boolean passes1(String password) { return rule1.matcher(password).matches(); } /** * @return De lengte van <code>password</code> is tussen zes en acht karakters */ public boolean passes2(String password) { return (password != null) && (password.length() >= 6) && (password.length() <= 8); } /** * @return Hetzelfde teken komt maximaal 2 keer in <code>password</code> voor. */ public boolean passes3(String password) { if ((password == null) || (password.length() <= 2)) { return true; } for (char c : password.toCharArray()) { int i = 0, count = 0; while ((i = password.indexOf(c, i)) != -1) { i++; count++; } if (count > 2) { return false; } } return true; } /** * Een opeenvolgende reeks van 3 tekens mag niet telkens met 1 oplopen of afdalen. * Voorbeelden: de tekenreeksen ABC, XYZ, KLM, PQR, 456, 321, cba, vut, gfe en zyx mogen niet in een wachtwoord voorkomen */ public boolean passes4(String password) { return passesFor(password, rule4Letters) && passesFor(password, rule4Numbers) && passesFor(password, rule4Misc); } private boolean passesFor(String password, Pattern p) { if ((password == null) || (password.length() < 3)) { return true; } Matcher m = p.matcher(password); while (m.find()) { char[] chars = m.group().toCharArray(); if (oplopend(chars) || aflopend(chars)) { return false; } } return true; } private boolean oplopend(char[] chars) { if (chars.length < 3) { return false; } return (chars[0] == chars[1] - 1) && (chars[1] == chars[2] - 1); } private boolean aflopend(final char[] chars) { char[] reversed = new char[chars.length]; for (int i = 0; i < chars.length; i++) { reversed[i] = chars[chars.length - (i + 1)]; } return oplopend(reversed); } /** * @return Spaties komen alleen in de zevende en/of achtste positie van <code>password</code> voor. */ public boolean passes5(String password) { if (password == null) { return false; } int eersteSpatieOp = password.indexOf(' '); return (eersteSpatieOp == -1) || (eersteSpatieOp > 5); } /** * @return aaneengesloten reeksen van letters (groot of klein) hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes6(String password) { Matcher m = rule6.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte |= m.group().length() != 3; } return !fouteLengte; } /** * @return aaneengesloten reeksen van cijfers hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes7(String password) { Matcher m = rule7.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte = m.group().length() != 3; } return !fouteLengte; } /** * @return <code>password</code> heeft minstens 3 overige tekens of voldoet aan regels 5, 6 en 7 */ public boolean passes8(String password) { Matcher m = rule8.matcher(password); int count = 0; while (m.find()) { count++; } return (count >= 3) || passes5(password) && passes6(password) && passes7(password); } }
vrijBRP/vrijBRP-Balie
gba-utils/src/main/java/nl/procura/gba/common/BrpPasswordGenerator.java
1,930
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */
block_comment
nl
/* * Copyright 2021 -<SUF>*/ package nl.procura.gba.common; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Password generator voor BPR wachtwoorden */ public class BrpPasswordGenerator { private final static BrpPasswordGenerator generator = new BrpPasswordGenerator(); private final static List<Character> availableChars; static { List<Character> chars = new ArrayList<>(100); for (char ch = 'a'; ch <= 'z'; ch++) { chars.add(Character.toLowerCase(ch)); chars.add(Character.toUpperCase(ch)); } for (int i = 0; i < 3; i++) { for (char ch = '0'; ch <= '9'; ch++) { chars.add(ch); } } availableChars = Collections.unmodifiableList(chars); } private final Random random = new SecureRandom(); private final Pattern rule1 = Pattern.compile("^[\\w\\d _=+/!@*].*$"); private final Pattern rule4Letters = Pattern.compile("[a-zA-Z]{3}"); private final Pattern rule4Numbers = Pattern.compile("[0-9]{3}"); private final Pattern rule4Misc = Pattern.compile("[^a-zA-Z0-9 ]{3}"); private final Pattern rule6 = Pattern.compile("[a-zA-Z]{2,}"); private final Pattern rule7 = Pattern.compile("[0-9]{2,}"); private final Pattern rule8 = Pattern.compile("[^a-zA-Z0-9 ]"); public static String newPassword() { return generator.generate(); } public static boolean checkWachtwoord(String ww) { return generator.passingRules(ww); } public String generate() { String ww = ""; while (!passingRules(ww)) { StringBuilder pass = new StringBuilder(); for (int i = 0; i < 8; i++) { pass.append(availableChars.get(random.nextInt(availableChars.size()))); } ww = pass.toString(); } return ww; } private boolean passingRules(String password) { return passes1(password) && passes2(password) && passes3(password) && passes4(password) && passes8(password); } /** * @return <code>password</code> bestaat alleen uit toegestane tekens */ public boolean passes1(String password) { return rule1.matcher(password).matches(); } /** * @return De lengte van <code>password</code> is tussen zes en acht karakters */ public boolean passes2(String password) { return (password != null) && (password.length() >= 6) && (password.length() <= 8); } /** * @return Hetzelfde teken komt maximaal 2 keer in <code>password</code> voor. */ public boolean passes3(String password) { if ((password == null) || (password.length() <= 2)) { return true; } for (char c : password.toCharArray()) { int i = 0, count = 0; while ((i = password.indexOf(c, i)) != -1) { i++; count++; } if (count > 2) { return false; } } return true; } /** * Een opeenvolgende reeks van 3 tekens mag niet telkens met 1 oplopen of afdalen. * Voorbeelden: de tekenreeksen ABC, XYZ, KLM, PQR, 456, 321, cba, vut, gfe en zyx mogen niet in een wachtwoord voorkomen */ public boolean passes4(String password) { return passesFor(password, rule4Letters) && passesFor(password, rule4Numbers) && passesFor(password, rule4Misc); } private boolean passesFor(String password, Pattern p) { if ((password == null) || (password.length() < 3)) { return true; } Matcher m = p.matcher(password); while (m.find()) { char[] chars = m.group().toCharArray(); if (oplopend(chars) || aflopend(chars)) { return false; } } return true; } private boolean oplopend(char[] chars) { if (chars.length < 3) { return false; } return (chars[0] == chars[1] - 1) && (chars[1] == chars[2] - 1); } private boolean aflopend(final char[] chars) { char[] reversed = new char[chars.length]; for (int i = 0; i < chars.length; i++) { reversed[i] = chars[chars.length - (i + 1)]; } return oplopend(reversed); } /** * @return Spaties komen alleen in de zevende en/of achtste positie van <code>password</code> voor. */ public boolean passes5(String password) { if (password == null) { return false; } int eersteSpatieOp = password.indexOf(' '); return (eersteSpatieOp == -1) || (eersteSpatieOp > 5); } /** * @return aaneengesloten reeksen van letters (groot of klein) hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes6(String password) { Matcher m = rule6.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte |= m.group().length() != 3; } return !fouteLengte; } /** * @return aaneengesloten reeksen van cijfers hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes7(String password) { Matcher m = rule7.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte = m.group().length() != 3; } return !fouteLengte; } /** * @return <code>password</code> heeft minstens 3 overige tekens of voldoet aan regels 5, 6 en 7 */ public boolean passes8(String password) { Matcher m = rule8.matcher(password); int count = 0; while (m.find()) { count++; } return (count >= 3) || passes5(password) && passes6(password) && passes7(password); } }
199362_1
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.common; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Password generator voor BPR wachtwoorden */ public class BrpPasswordGenerator { private final static BrpPasswordGenerator generator = new BrpPasswordGenerator(); private final static List<Character> availableChars; static { List<Character> chars = new ArrayList<>(100); for (char ch = 'a'; ch <= 'z'; ch++) { chars.add(Character.toLowerCase(ch)); chars.add(Character.toUpperCase(ch)); } for (int i = 0; i < 3; i++) { for (char ch = '0'; ch <= '9'; ch++) { chars.add(ch); } } availableChars = Collections.unmodifiableList(chars); } private final Random random = new SecureRandom(); private final Pattern rule1 = Pattern.compile("^[\\w\\d _=+/!@*].*$"); private final Pattern rule4Letters = Pattern.compile("[a-zA-Z]{3}"); private final Pattern rule4Numbers = Pattern.compile("[0-9]{3}"); private final Pattern rule4Misc = Pattern.compile("[^a-zA-Z0-9 ]{3}"); private final Pattern rule6 = Pattern.compile("[a-zA-Z]{2,}"); private final Pattern rule7 = Pattern.compile("[0-9]{2,}"); private final Pattern rule8 = Pattern.compile("[^a-zA-Z0-9 ]"); public static String newPassword() { return generator.generate(); } public static boolean checkWachtwoord(String ww) { return generator.passingRules(ww); } public String generate() { String ww = ""; while (!passingRules(ww)) { StringBuilder pass = new StringBuilder(); for (int i = 0; i < 8; i++) { pass.append(availableChars.get(random.nextInt(availableChars.size()))); } ww = pass.toString(); } return ww; } private boolean passingRules(String password) { return passes1(password) && passes2(password) && passes3(password) && passes4(password) && passes8(password); } /** * @return <code>password</code> bestaat alleen uit toegestane tekens */ public boolean passes1(String password) { return rule1.matcher(password).matches(); } /** * @return De lengte van <code>password</code> is tussen zes en acht karakters */ public boolean passes2(String password) { return (password != null) && (password.length() >= 6) && (password.length() <= 8); } /** * @return Hetzelfde teken komt maximaal 2 keer in <code>password</code> voor. */ public boolean passes3(String password) { if ((password == null) || (password.length() <= 2)) { return true; } for (char c : password.toCharArray()) { int i = 0, count = 0; while ((i = password.indexOf(c, i)) != -1) { i++; count++; } if (count > 2) { return false; } } return true; } /** * Een opeenvolgende reeks van 3 tekens mag niet telkens met 1 oplopen of afdalen. * Voorbeelden: de tekenreeksen ABC, XYZ, KLM, PQR, 456, 321, cba, vut, gfe en zyx mogen niet in een wachtwoord voorkomen */ public boolean passes4(String password) { return passesFor(password, rule4Letters) && passesFor(password, rule4Numbers) && passesFor(password, rule4Misc); } private boolean passesFor(String password, Pattern p) { if ((password == null) || (password.length() < 3)) { return true; } Matcher m = p.matcher(password); while (m.find()) { char[] chars = m.group().toCharArray(); if (oplopend(chars) || aflopend(chars)) { return false; } } return true; } private boolean oplopend(char[] chars) { if (chars.length < 3) { return false; } return (chars[0] == chars[1] - 1) && (chars[1] == chars[2] - 1); } private boolean aflopend(final char[] chars) { char[] reversed = new char[chars.length]; for (int i = 0; i < chars.length; i++) { reversed[i] = chars[chars.length - (i + 1)]; } return oplopend(reversed); } /** * @return Spaties komen alleen in de zevende en/of achtste positie van <code>password</code> voor. */ public boolean passes5(String password) { if (password == null) { return false; } int eersteSpatieOp = password.indexOf(' '); return (eersteSpatieOp == -1) || (eersteSpatieOp > 5); } /** * @return aaneengesloten reeksen van letters (groot of klein) hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes6(String password) { Matcher m = rule6.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte |= m.group().length() != 3; } return !fouteLengte; } /** * @return aaneengesloten reeksen van cijfers hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes7(String password) { Matcher m = rule7.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte = m.group().length() != 3; } return !fouteLengte; } /** * @return <code>password</code> heeft minstens 3 overige tekens of voldoet aan regels 5, 6 en 7 */ public boolean passes8(String password) { Matcher m = rule8.matcher(password); int count = 0; while (m.find()) { count++; } return (count >= 3) || passes5(password) && passes6(password) && passes7(password); } }
vrijBRP/vrijBRP-Balie
gba-utils/src/main/java/nl/procura/gba/common/BrpPasswordGenerator.java
1,930
/** * Password generator voor BPR wachtwoorden */
block_comment
nl
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.common; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Password generator voor<SUF>*/ public class BrpPasswordGenerator { private final static BrpPasswordGenerator generator = new BrpPasswordGenerator(); private final static List<Character> availableChars; static { List<Character> chars = new ArrayList<>(100); for (char ch = 'a'; ch <= 'z'; ch++) { chars.add(Character.toLowerCase(ch)); chars.add(Character.toUpperCase(ch)); } for (int i = 0; i < 3; i++) { for (char ch = '0'; ch <= '9'; ch++) { chars.add(ch); } } availableChars = Collections.unmodifiableList(chars); } private final Random random = new SecureRandom(); private final Pattern rule1 = Pattern.compile("^[\\w\\d _=+/!@*].*$"); private final Pattern rule4Letters = Pattern.compile("[a-zA-Z]{3}"); private final Pattern rule4Numbers = Pattern.compile("[0-9]{3}"); private final Pattern rule4Misc = Pattern.compile("[^a-zA-Z0-9 ]{3}"); private final Pattern rule6 = Pattern.compile("[a-zA-Z]{2,}"); private final Pattern rule7 = Pattern.compile("[0-9]{2,}"); private final Pattern rule8 = Pattern.compile("[^a-zA-Z0-9 ]"); public static String newPassword() { return generator.generate(); } public static boolean checkWachtwoord(String ww) { return generator.passingRules(ww); } public String generate() { String ww = ""; while (!passingRules(ww)) { StringBuilder pass = new StringBuilder(); for (int i = 0; i < 8; i++) { pass.append(availableChars.get(random.nextInt(availableChars.size()))); } ww = pass.toString(); } return ww; } private boolean passingRules(String password) { return passes1(password) && passes2(password) && passes3(password) && passes4(password) && passes8(password); } /** * @return <code>password</code> bestaat alleen uit toegestane tekens */ public boolean passes1(String password) { return rule1.matcher(password).matches(); } /** * @return De lengte van <code>password</code> is tussen zes en acht karakters */ public boolean passes2(String password) { return (password != null) && (password.length() >= 6) && (password.length() <= 8); } /** * @return Hetzelfde teken komt maximaal 2 keer in <code>password</code> voor. */ public boolean passes3(String password) { if ((password == null) || (password.length() <= 2)) { return true; } for (char c : password.toCharArray()) { int i = 0, count = 0; while ((i = password.indexOf(c, i)) != -1) { i++; count++; } if (count > 2) { return false; } } return true; } /** * Een opeenvolgende reeks van 3 tekens mag niet telkens met 1 oplopen of afdalen. * Voorbeelden: de tekenreeksen ABC, XYZ, KLM, PQR, 456, 321, cba, vut, gfe en zyx mogen niet in een wachtwoord voorkomen */ public boolean passes4(String password) { return passesFor(password, rule4Letters) && passesFor(password, rule4Numbers) && passesFor(password, rule4Misc); } private boolean passesFor(String password, Pattern p) { if ((password == null) || (password.length() < 3)) { return true; } Matcher m = p.matcher(password); while (m.find()) { char[] chars = m.group().toCharArray(); if (oplopend(chars) || aflopend(chars)) { return false; } } return true; } private boolean oplopend(char[] chars) { if (chars.length < 3) { return false; } return (chars[0] == chars[1] - 1) && (chars[1] == chars[2] - 1); } private boolean aflopend(final char[] chars) { char[] reversed = new char[chars.length]; for (int i = 0; i < chars.length; i++) { reversed[i] = chars[chars.length - (i + 1)]; } return oplopend(reversed); } /** * @return Spaties komen alleen in de zevende en/of achtste positie van <code>password</code> voor. */ public boolean passes5(String password) { if (password == null) { return false; } int eersteSpatieOp = password.indexOf(' '); return (eersteSpatieOp == -1) || (eersteSpatieOp > 5); } /** * @return aaneengesloten reeksen van letters (groot of klein) hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes6(String password) { Matcher m = rule6.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte |= m.group().length() != 3; } return !fouteLengte; } /** * @return aaneengesloten reeksen van cijfers hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes7(String password) { Matcher m = rule7.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte = m.group().length() != 3; } return !fouteLengte; } /** * @return <code>password</code> heeft minstens 3 overige tekens of voldoet aan regels 5, 6 en 7 */ public boolean passes8(String password) { Matcher m = rule8.matcher(password); int count = 0; while (m.find()) { count++; } return (count >= 3) || passes5(password) && passes6(password) && passes7(password); } }
199362_2
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.common; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Password generator voor BPR wachtwoorden */ public class BrpPasswordGenerator { private final static BrpPasswordGenerator generator = new BrpPasswordGenerator(); private final static List<Character> availableChars; static { List<Character> chars = new ArrayList<>(100); for (char ch = 'a'; ch <= 'z'; ch++) { chars.add(Character.toLowerCase(ch)); chars.add(Character.toUpperCase(ch)); } for (int i = 0; i < 3; i++) { for (char ch = '0'; ch <= '9'; ch++) { chars.add(ch); } } availableChars = Collections.unmodifiableList(chars); } private final Random random = new SecureRandom(); private final Pattern rule1 = Pattern.compile("^[\\w\\d _=+/!@*].*$"); private final Pattern rule4Letters = Pattern.compile("[a-zA-Z]{3}"); private final Pattern rule4Numbers = Pattern.compile("[0-9]{3}"); private final Pattern rule4Misc = Pattern.compile("[^a-zA-Z0-9 ]{3}"); private final Pattern rule6 = Pattern.compile("[a-zA-Z]{2,}"); private final Pattern rule7 = Pattern.compile("[0-9]{2,}"); private final Pattern rule8 = Pattern.compile("[^a-zA-Z0-9 ]"); public static String newPassword() { return generator.generate(); } public static boolean checkWachtwoord(String ww) { return generator.passingRules(ww); } public String generate() { String ww = ""; while (!passingRules(ww)) { StringBuilder pass = new StringBuilder(); for (int i = 0; i < 8; i++) { pass.append(availableChars.get(random.nextInt(availableChars.size()))); } ww = pass.toString(); } return ww; } private boolean passingRules(String password) { return passes1(password) && passes2(password) && passes3(password) && passes4(password) && passes8(password); } /** * @return <code>password</code> bestaat alleen uit toegestane tekens */ public boolean passes1(String password) { return rule1.matcher(password).matches(); } /** * @return De lengte van <code>password</code> is tussen zes en acht karakters */ public boolean passes2(String password) { return (password != null) && (password.length() >= 6) && (password.length() <= 8); } /** * @return Hetzelfde teken komt maximaal 2 keer in <code>password</code> voor. */ public boolean passes3(String password) { if ((password == null) || (password.length() <= 2)) { return true; } for (char c : password.toCharArray()) { int i = 0, count = 0; while ((i = password.indexOf(c, i)) != -1) { i++; count++; } if (count > 2) { return false; } } return true; } /** * Een opeenvolgende reeks van 3 tekens mag niet telkens met 1 oplopen of afdalen. * Voorbeelden: de tekenreeksen ABC, XYZ, KLM, PQR, 456, 321, cba, vut, gfe en zyx mogen niet in een wachtwoord voorkomen */ public boolean passes4(String password) { return passesFor(password, rule4Letters) && passesFor(password, rule4Numbers) && passesFor(password, rule4Misc); } private boolean passesFor(String password, Pattern p) { if ((password == null) || (password.length() < 3)) { return true; } Matcher m = p.matcher(password); while (m.find()) { char[] chars = m.group().toCharArray(); if (oplopend(chars) || aflopend(chars)) { return false; } } return true; } private boolean oplopend(char[] chars) { if (chars.length < 3) { return false; } return (chars[0] == chars[1] - 1) && (chars[1] == chars[2] - 1); } private boolean aflopend(final char[] chars) { char[] reversed = new char[chars.length]; for (int i = 0; i < chars.length; i++) { reversed[i] = chars[chars.length - (i + 1)]; } return oplopend(reversed); } /** * @return Spaties komen alleen in de zevende en/of achtste positie van <code>password</code> voor. */ public boolean passes5(String password) { if (password == null) { return false; } int eersteSpatieOp = password.indexOf(' '); return (eersteSpatieOp == -1) || (eersteSpatieOp > 5); } /** * @return aaneengesloten reeksen van letters (groot of klein) hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes6(String password) { Matcher m = rule6.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte |= m.group().length() != 3; } return !fouteLengte; } /** * @return aaneengesloten reeksen van cijfers hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes7(String password) { Matcher m = rule7.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte = m.group().length() != 3; } return !fouteLengte; } /** * @return <code>password</code> heeft minstens 3 overige tekens of voldoet aan regels 5, 6 en 7 */ public boolean passes8(String password) { Matcher m = rule8.matcher(password); int count = 0; while (m.find()) { count++; } return (count >= 3) || passes5(password) && passes6(password) && passes7(password); } }
vrijBRP/vrijBRP-Balie
gba-utils/src/main/java/nl/procura/gba/common/BrpPasswordGenerator.java
1,930
/** * @return <code>password</code> bestaat alleen uit toegestane tekens */
block_comment
nl
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.common; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Password generator voor BPR wachtwoorden */ public class BrpPasswordGenerator { private final static BrpPasswordGenerator generator = new BrpPasswordGenerator(); private final static List<Character> availableChars; static { List<Character> chars = new ArrayList<>(100); for (char ch = 'a'; ch <= 'z'; ch++) { chars.add(Character.toLowerCase(ch)); chars.add(Character.toUpperCase(ch)); } for (int i = 0; i < 3; i++) { for (char ch = '0'; ch <= '9'; ch++) { chars.add(ch); } } availableChars = Collections.unmodifiableList(chars); } private final Random random = new SecureRandom(); private final Pattern rule1 = Pattern.compile("^[\\w\\d _=+/!@*].*$"); private final Pattern rule4Letters = Pattern.compile("[a-zA-Z]{3}"); private final Pattern rule4Numbers = Pattern.compile("[0-9]{3}"); private final Pattern rule4Misc = Pattern.compile("[^a-zA-Z0-9 ]{3}"); private final Pattern rule6 = Pattern.compile("[a-zA-Z]{2,}"); private final Pattern rule7 = Pattern.compile("[0-9]{2,}"); private final Pattern rule8 = Pattern.compile("[^a-zA-Z0-9 ]"); public static String newPassword() { return generator.generate(); } public static boolean checkWachtwoord(String ww) { return generator.passingRules(ww); } public String generate() { String ww = ""; while (!passingRules(ww)) { StringBuilder pass = new StringBuilder(); for (int i = 0; i < 8; i++) { pass.append(availableChars.get(random.nextInt(availableChars.size()))); } ww = pass.toString(); } return ww; } private boolean passingRules(String password) { return passes1(password) && passes2(password) && passes3(password) && passes4(password) && passes8(password); } /** * @return <code>password</code> bestaat<SUF>*/ public boolean passes1(String password) { return rule1.matcher(password).matches(); } /** * @return De lengte van <code>password</code> is tussen zes en acht karakters */ public boolean passes2(String password) { return (password != null) && (password.length() >= 6) && (password.length() <= 8); } /** * @return Hetzelfde teken komt maximaal 2 keer in <code>password</code> voor. */ public boolean passes3(String password) { if ((password == null) || (password.length() <= 2)) { return true; } for (char c : password.toCharArray()) { int i = 0, count = 0; while ((i = password.indexOf(c, i)) != -1) { i++; count++; } if (count > 2) { return false; } } return true; } /** * Een opeenvolgende reeks van 3 tekens mag niet telkens met 1 oplopen of afdalen. * Voorbeelden: de tekenreeksen ABC, XYZ, KLM, PQR, 456, 321, cba, vut, gfe en zyx mogen niet in een wachtwoord voorkomen */ public boolean passes4(String password) { return passesFor(password, rule4Letters) && passesFor(password, rule4Numbers) && passesFor(password, rule4Misc); } private boolean passesFor(String password, Pattern p) { if ((password == null) || (password.length() < 3)) { return true; } Matcher m = p.matcher(password); while (m.find()) { char[] chars = m.group().toCharArray(); if (oplopend(chars) || aflopend(chars)) { return false; } } return true; } private boolean oplopend(char[] chars) { if (chars.length < 3) { return false; } return (chars[0] == chars[1] - 1) && (chars[1] == chars[2] - 1); } private boolean aflopend(final char[] chars) { char[] reversed = new char[chars.length]; for (int i = 0; i < chars.length; i++) { reversed[i] = chars[chars.length - (i + 1)]; } return oplopend(reversed); } /** * @return Spaties komen alleen in de zevende en/of achtste positie van <code>password</code> voor. */ public boolean passes5(String password) { if (password == null) { return false; } int eersteSpatieOp = password.indexOf(' '); return (eersteSpatieOp == -1) || (eersteSpatieOp > 5); } /** * @return aaneengesloten reeksen van letters (groot of klein) hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes6(String password) { Matcher m = rule6.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte |= m.group().length() != 3; } return !fouteLengte; } /** * @return aaneengesloten reeksen van cijfers hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes7(String password) { Matcher m = rule7.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte = m.group().length() != 3; } return !fouteLengte; } /** * @return <code>password</code> heeft minstens 3 overige tekens of voldoet aan regels 5, 6 en 7 */ public boolean passes8(String password) { Matcher m = rule8.matcher(password); int count = 0; while (m.find()) { count++; } return (count >= 3) || passes5(password) && passes6(password) && passes7(password); } }
199362_3
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.common; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Password generator voor BPR wachtwoorden */ public class BrpPasswordGenerator { private final static BrpPasswordGenerator generator = new BrpPasswordGenerator(); private final static List<Character> availableChars; static { List<Character> chars = new ArrayList<>(100); for (char ch = 'a'; ch <= 'z'; ch++) { chars.add(Character.toLowerCase(ch)); chars.add(Character.toUpperCase(ch)); } for (int i = 0; i < 3; i++) { for (char ch = '0'; ch <= '9'; ch++) { chars.add(ch); } } availableChars = Collections.unmodifiableList(chars); } private final Random random = new SecureRandom(); private final Pattern rule1 = Pattern.compile("^[\\w\\d _=+/!@*].*$"); private final Pattern rule4Letters = Pattern.compile("[a-zA-Z]{3}"); private final Pattern rule4Numbers = Pattern.compile("[0-9]{3}"); private final Pattern rule4Misc = Pattern.compile("[^a-zA-Z0-9 ]{3}"); private final Pattern rule6 = Pattern.compile("[a-zA-Z]{2,}"); private final Pattern rule7 = Pattern.compile("[0-9]{2,}"); private final Pattern rule8 = Pattern.compile("[^a-zA-Z0-9 ]"); public static String newPassword() { return generator.generate(); } public static boolean checkWachtwoord(String ww) { return generator.passingRules(ww); } public String generate() { String ww = ""; while (!passingRules(ww)) { StringBuilder pass = new StringBuilder(); for (int i = 0; i < 8; i++) { pass.append(availableChars.get(random.nextInt(availableChars.size()))); } ww = pass.toString(); } return ww; } private boolean passingRules(String password) { return passes1(password) && passes2(password) && passes3(password) && passes4(password) && passes8(password); } /** * @return <code>password</code> bestaat alleen uit toegestane tekens */ public boolean passes1(String password) { return rule1.matcher(password).matches(); } /** * @return De lengte van <code>password</code> is tussen zes en acht karakters */ public boolean passes2(String password) { return (password != null) && (password.length() >= 6) && (password.length() <= 8); } /** * @return Hetzelfde teken komt maximaal 2 keer in <code>password</code> voor. */ public boolean passes3(String password) { if ((password == null) || (password.length() <= 2)) { return true; } for (char c : password.toCharArray()) { int i = 0, count = 0; while ((i = password.indexOf(c, i)) != -1) { i++; count++; } if (count > 2) { return false; } } return true; } /** * Een opeenvolgende reeks van 3 tekens mag niet telkens met 1 oplopen of afdalen. * Voorbeelden: de tekenreeksen ABC, XYZ, KLM, PQR, 456, 321, cba, vut, gfe en zyx mogen niet in een wachtwoord voorkomen */ public boolean passes4(String password) { return passesFor(password, rule4Letters) && passesFor(password, rule4Numbers) && passesFor(password, rule4Misc); } private boolean passesFor(String password, Pattern p) { if ((password == null) || (password.length() < 3)) { return true; } Matcher m = p.matcher(password); while (m.find()) { char[] chars = m.group().toCharArray(); if (oplopend(chars) || aflopend(chars)) { return false; } } return true; } private boolean oplopend(char[] chars) { if (chars.length < 3) { return false; } return (chars[0] == chars[1] - 1) && (chars[1] == chars[2] - 1); } private boolean aflopend(final char[] chars) { char[] reversed = new char[chars.length]; for (int i = 0; i < chars.length; i++) { reversed[i] = chars[chars.length - (i + 1)]; } return oplopend(reversed); } /** * @return Spaties komen alleen in de zevende en/of achtste positie van <code>password</code> voor. */ public boolean passes5(String password) { if (password == null) { return false; } int eersteSpatieOp = password.indexOf(' '); return (eersteSpatieOp == -1) || (eersteSpatieOp > 5); } /** * @return aaneengesloten reeksen van letters (groot of klein) hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes6(String password) { Matcher m = rule6.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte |= m.group().length() != 3; } return !fouteLengte; } /** * @return aaneengesloten reeksen van cijfers hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes7(String password) { Matcher m = rule7.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte = m.group().length() != 3; } return !fouteLengte; } /** * @return <code>password</code> heeft minstens 3 overige tekens of voldoet aan regels 5, 6 en 7 */ public boolean passes8(String password) { Matcher m = rule8.matcher(password); int count = 0; while (m.find()) { count++; } return (count >= 3) || passes5(password) && passes6(password) && passes7(password); } }
vrijBRP/vrijBRP-Balie
gba-utils/src/main/java/nl/procura/gba/common/BrpPasswordGenerator.java
1,930
/** * @return De lengte van <code>password</code> is tussen zes en acht karakters */
block_comment
nl
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.common; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Password generator voor BPR wachtwoorden */ public class BrpPasswordGenerator { private final static BrpPasswordGenerator generator = new BrpPasswordGenerator(); private final static List<Character> availableChars; static { List<Character> chars = new ArrayList<>(100); for (char ch = 'a'; ch <= 'z'; ch++) { chars.add(Character.toLowerCase(ch)); chars.add(Character.toUpperCase(ch)); } for (int i = 0; i < 3; i++) { for (char ch = '0'; ch <= '9'; ch++) { chars.add(ch); } } availableChars = Collections.unmodifiableList(chars); } private final Random random = new SecureRandom(); private final Pattern rule1 = Pattern.compile("^[\\w\\d _=+/!@*].*$"); private final Pattern rule4Letters = Pattern.compile("[a-zA-Z]{3}"); private final Pattern rule4Numbers = Pattern.compile("[0-9]{3}"); private final Pattern rule4Misc = Pattern.compile("[^a-zA-Z0-9 ]{3}"); private final Pattern rule6 = Pattern.compile("[a-zA-Z]{2,}"); private final Pattern rule7 = Pattern.compile("[0-9]{2,}"); private final Pattern rule8 = Pattern.compile("[^a-zA-Z0-9 ]"); public static String newPassword() { return generator.generate(); } public static boolean checkWachtwoord(String ww) { return generator.passingRules(ww); } public String generate() { String ww = ""; while (!passingRules(ww)) { StringBuilder pass = new StringBuilder(); for (int i = 0; i < 8; i++) { pass.append(availableChars.get(random.nextInt(availableChars.size()))); } ww = pass.toString(); } return ww; } private boolean passingRules(String password) { return passes1(password) && passes2(password) && passes3(password) && passes4(password) && passes8(password); } /** * @return <code>password</code> bestaat alleen uit toegestane tekens */ public boolean passes1(String password) { return rule1.matcher(password).matches(); } /** * @return De lengte<SUF>*/ public boolean passes2(String password) { return (password != null) && (password.length() >= 6) && (password.length() <= 8); } /** * @return Hetzelfde teken komt maximaal 2 keer in <code>password</code> voor. */ public boolean passes3(String password) { if ((password == null) || (password.length() <= 2)) { return true; } for (char c : password.toCharArray()) { int i = 0, count = 0; while ((i = password.indexOf(c, i)) != -1) { i++; count++; } if (count > 2) { return false; } } return true; } /** * Een opeenvolgende reeks van 3 tekens mag niet telkens met 1 oplopen of afdalen. * Voorbeelden: de tekenreeksen ABC, XYZ, KLM, PQR, 456, 321, cba, vut, gfe en zyx mogen niet in een wachtwoord voorkomen */ public boolean passes4(String password) { return passesFor(password, rule4Letters) && passesFor(password, rule4Numbers) && passesFor(password, rule4Misc); } private boolean passesFor(String password, Pattern p) { if ((password == null) || (password.length() < 3)) { return true; } Matcher m = p.matcher(password); while (m.find()) { char[] chars = m.group().toCharArray(); if (oplopend(chars) || aflopend(chars)) { return false; } } return true; } private boolean oplopend(char[] chars) { if (chars.length < 3) { return false; } return (chars[0] == chars[1] - 1) && (chars[1] == chars[2] - 1); } private boolean aflopend(final char[] chars) { char[] reversed = new char[chars.length]; for (int i = 0; i < chars.length; i++) { reversed[i] = chars[chars.length - (i + 1)]; } return oplopend(reversed); } /** * @return Spaties komen alleen in de zevende en/of achtste positie van <code>password</code> voor. */ public boolean passes5(String password) { if (password == null) { return false; } int eersteSpatieOp = password.indexOf(' '); return (eersteSpatieOp == -1) || (eersteSpatieOp > 5); } /** * @return aaneengesloten reeksen van letters (groot of klein) hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes6(String password) { Matcher m = rule6.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte |= m.group().length() != 3; } return !fouteLengte; } /** * @return aaneengesloten reeksen van cijfers hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes7(String password) { Matcher m = rule7.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte = m.group().length() != 3; } return !fouteLengte; } /** * @return <code>password</code> heeft minstens 3 overige tekens of voldoet aan regels 5, 6 en 7 */ public boolean passes8(String password) { Matcher m = rule8.matcher(password); int count = 0; while (m.find()) { count++; } return (count >= 3) || passes5(password) && passes6(password) && passes7(password); } }
199362_4
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.common; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Password generator voor BPR wachtwoorden */ public class BrpPasswordGenerator { private final static BrpPasswordGenerator generator = new BrpPasswordGenerator(); private final static List<Character> availableChars; static { List<Character> chars = new ArrayList<>(100); for (char ch = 'a'; ch <= 'z'; ch++) { chars.add(Character.toLowerCase(ch)); chars.add(Character.toUpperCase(ch)); } for (int i = 0; i < 3; i++) { for (char ch = '0'; ch <= '9'; ch++) { chars.add(ch); } } availableChars = Collections.unmodifiableList(chars); } private final Random random = new SecureRandom(); private final Pattern rule1 = Pattern.compile("^[\\w\\d _=+/!@*].*$"); private final Pattern rule4Letters = Pattern.compile("[a-zA-Z]{3}"); private final Pattern rule4Numbers = Pattern.compile("[0-9]{3}"); private final Pattern rule4Misc = Pattern.compile("[^a-zA-Z0-9 ]{3}"); private final Pattern rule6 = Pattern.compile("[a-zA-Z]{2,}"); private final Pattern rule7 = Pattern.compile("[0-9]{2,}"); private final Pattern rule8 = Pattern.compile("[^a-zA-Z0-9 ]"); public static String newPassword() { return generator.generate(); } public static boolean checkWachtwoord(String ww) { return generator.passingRules(ww); } public String generate() { String ww = ""; while (!passingRules(ww)) { StringBuilder pass = new StringBuilder(); for (int i = 0; i < 8; i++) { pass.append(availableChars.get(random.nextInt(availableChars.size()))); } ww = pass.toString(); } return ww; } private boolean passingRules(String password) { return passes1(password) && passes2(password) && passes3(password) && passes4(password) && passes8(password); } /** * @return <code>password</code> bestaat alleen uit toegestane tekens */ public boolean passes1(String password) { return rule1.matcher(password).matches(); } /** * @return De lengte van <code>password</code> is tussen zes en acht karakters */ public boolean passes2(String password) { return (password != null) && (password.length() >= 6) && (password.length() <= 8); } /** * @return Hetzelfde teken komt maximaal 2 keer in <code>password</code> voor. */ public boolean passes3(String password) { if ((password == null) || (password.length() <= 2)) { return true; } for (char c : password.toCharArray()) { int i = 0, count = 0; while ((i = password.indexOf(c, i)) != -1) { i++; count++; } if (count > 2) { return false; } } return true; } /** * Een opeenvolgende reeks van 3 tekens mag niet telkens met 1 oplopen of afdalen. * Voorbeelden: de tekenreeksen ABC, XYZ, KLM, PQR, 456, 321, cba, vut, gfe en zyx mogen niet in een wachtwoord voorkomen */ public boolean passes4(String password) { return passesFor(password, rule4Letters) && passesFor(password, rule4Numbers) && passesFor(password, rule4Misc); } private boolean passesFor(String password, Pattern p) { if ((password == null) || (password.length() < 3)) { return true; } Matcher m = p.matcher(password); while (m.find()) { char[] chars = m.group().toCharArray(); if (oplopend(chars) || aflopend(chars)) { return false; } } return true; } private boolean oplopend(char[] chars) { if (chars.length < 3) { return false; } return (chars[0] == chars[1] - 1) && (chars[1] == chars[2] - 1); } private boolean aflopend(final char[] chars) { char[] reversed = new char[chars.length]; for (int i = 0; i < chars.length; i++) { reversed[i] = chars[chars.length - (i + 1)]; } return oplopend(reversed); } /** * @return Spaties komen alleen in de zevende en/of achtste positie van <code>password</code> voor. */ public boolean passes5(String password) { if (password == null) { return false; } int eersteSpatieOp = password.indexOf(' '); return (eersteSpatieOp == -1) || (eersteSpatieOp > 5); } /** * @return aaneengesloten reeksen van letters (groot of klein) hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes6(String password) { Matcher m = rule6.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte |= m.group().length() != 3; } return !fouteLengte; } /** * @return aaneengesloten reeksen van cijfers hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes7(String password) { Matcher m = rule7.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte = m.group().length() != 3; } return !fouteLengte; } /** * @return <code>password</code> heeft minstens 3 overige tekens of voldoet aan regels 5, 6 en 7 */ public boolean passes8(String password) { Matcher m = rule8.matcher(password); int count = 0; while (m.find()) { count++; } return (count >= 3) || passes5(password) && passes6(password) && passes7(password); } }
vrijBRP/vrijBRP-Balie
gba-utils/src/main/java/nl/procura/gba/common/BrpPasswordGenerator.java
1,930
/** * @return Hetzelfde teken komt maximaal 2 keer in <code>password</code> voor. */
block_comment
nl
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.common; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Password generator voor BPR wachtwoorden */ public class BrpPasswordGenerator { private final static BrpPasswordGenerator generator = new BrpPasswordGenerator(); private final static List<Character> availableChars; static { List<Character> chars = new ArrayList<>(100); for (char ch = 'a'; ch <= 'z'; ch++) { chars.add(Character.toLowerCase(ch)); chars.add(Character.toUpperCase(ch)); } for (int i = 0; i < 3; i++) { for (char ch = '0'; ch <= '9'; ch++) { chars.add(ch); } } availableChars = Collections.unmodifiableList(chars); } private final Random random = new SecureRandom(); private final Pattern rule1 = Pattern.compile("^[\\w\\d _=+/!@*].*$"); private final Pattern rule4Letters = Pattern.compile("[a-zA-Z]{3}"); private final Pattern rule4Numbers = Pattern.compile("[0-9]{3}"); private final Pattern rule4Misc = Pattern.compile("[^a-zA-Z0-9 ]{3}"); private final Pattern rule6 = Pattern.compile("[a-zA-Z]{2,}"); private final Pattern rule7 = Pattern.compile("[0-9]{2,}"); private final Pattern rule8 = Pattern.compile("[^a-zA-Z0-9 ]"); public static String newPassword() { return generator.generate(); } public static boolean checkWachtwoord(String ww) { return generator.passingRules(ww); } public String generate() { String ww = ""; while (!passingRules(ww)) { StringBuilder pass = new StringBuilder(); for (int i = 0; i < 8; i++) { pass.append(availableChars.get(random.nextInt(availableChars.size()))); } ww = pass.toString(); } return ww; } private boolean passingRules(String password) { return passes1(password) && passes2(password) && passes3(password) && passes4(password) && passes8(password); } /** * @return <code>password</code> bestaat alleen uit toegestane tekens */ public boolean passes1(String password) { return rule1.matcher(password).matches(); } /** * @return De lengte van <code>password</code> is tussen zes en acht karakters */ public boolean passes2(String password) { return (password != null) && (password.length() >= 6) && (password.length() <= 8); } /** * @return Hetzelfde teken<SUF>*/ public boolean passes3(String password) { if ((password == null) || (password.length() <= 2)) { return true; } for (char c : password.toCharArray()) { int i = 0, count = 0; while ((i = password.indexOf(c, i)) != -1) { i++; count++; } if (count > 2) { return false; } } return true; } /** * Een opeenvolgende reeks van 3 tekens mag niet telkens met 1 oplopen of afdalen. * Voorbeelden: de tekenreeksen ABC, XYZ, KLM, PQR, 456, 321, cba, vut, gfe en zyx mogen niet in een wachtwoord voorkomen */ public boolean passes4(String password) { return passesFor(password, rule4Letters) && passesFor(password, rule4Numbers) && passesFor(password, rule4Misc); } private boolean passesFor(String password, Pattern p) { if ((password == null) || (password.length() < 3)) { return true; } Matcher m = p.matcher(password); while (m.find()) { char[] chars = m.group().toCharArray(); if (oplopend(chars) || aflopend(chars)) { return false; } } return true; } private boolean oplopend(char[] chars) { if (chars.length < 3) { return false; } return (chars[0] == chars[1] - 1) && (chars[1] == chars[2] - 1); } private boolean aflopend(final char[] chars) { char[] reversed = new char[chars.length]; for (int i = 0; i < chars.length; i++) { reversed[i] = chars[chars.length - (i + 1)]; } return oplopend(reversed); } /** * @return Spaties komen alleen in de zevende en/of achtste positie van <code>password</code> voor. */ public boolean passes5(String password) { if (password == null) { return false; } int eersteSpatieOp = password.indexOf(' '); return (eersteSpatieOp == -1) || (eersteSpatieOp > 5); } /** * @return aaneengesloten reeksen van letters (groot of klein) hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes6(String password) { Matcher m = rule6.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte |= m.group().length() != 3; } return !fouteLengte; } /** * @return aaneengesloten reeksen van cijfers hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes7(String password) { Matcher m = rule7.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte = m.group().length() != 3; } return !fouteLengte; } /** * @return <code>password</code> heeft minstens 3 overige tekens of voldoet aan regels 5, 6 en 7 */ public boolean passes8(String password) { Matcher m = rule8.matcher(password); int count = 0; while (m.find()) { count++; } return (count >= 3) || passes5(password) && passes6(password) && passes7(password); } }
199362_5
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.common; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Password generator voor BPR wachtwoorden */ public class BrpPasswordGenerator { private final static BrpPasswordGenerator generator = new BrpPasswordGenerator(); private final static List<Character> availableChars; static { List<Character> chars = new ArrayList<>(100); for (char ch = 'a'; ch <= 'z'; ch++) { chars.add(Character.toLowerCase(ch)); chars.add(Character.toUpperCase(ch)); } for (int i = 0; i < 3; i++) { for (char ch = '0'; ch <= '9'; ch++) { chars.add(ch); } } availableChars = Collections.unmodifiableList(chars); } private final Random random = new SecureRandom(); private final Pattern rule1 = Pattern.compile("^[\\w\\d _=+/!@*].*$"); private final Pattern rule4Letters = Pattern.compile("[a-zA-Z]{3}"); private final Pattern rule4Numbers = Pattern.compile("[0-9]{3}"); private final Pattern rule4Misc = Pattern.compile("[^a-zA-Z0-9 ]{3}"); private final Pattern rule6 = Pattern.compile("[a-zA-Z]{2,}"); private final Pattern rule7 = Pattern.compile("[0-9]{2,}"); private final Pattern rule8 = Pattern.compile("[^a-zA-Z0-9 ]"); public static String newPassword() { return generator.generate(); } public static boolean checkWachtwoord(String ww) { return generator.passingRules(ww); } public String generate() { String ww = ""; while (!passingRules(ww)) { StringBuilder pass = new StringBuilder(); for (int i = 0; i < 8; i++) { pass.append(availableChars.get(random.nextInt(availableChars.size()))); } ww = pass.toString(); } return ww; } private boolean passingRules(String password) { return passes1(password) && passes2(password) && passes3(password) && passes4(password) && passes8(password); } /** * @return <code>password</code> bestaat alleen uit toegestane tekens */ public boolean passes1(String password) { return rule1.matcher(password).matches(); } /** * @return De lengte van <code>password</code> is tussen zes en acht karakters */ public boolean passes2(String password) { return (password != null) && (password.length() >= 6) && (password.length() <= 8); } /** * @return Hetzelfde teken komt maximaal 2 keer in <code>password</code> voor. */ public boolean passes3(String password) { if ((password == null) || (password.length() <= 2)) { return true; } for (char c : password.toCharArray()) { int i = 0, count = 0; while ((i = password.indexOf(c, i)) != -1) { i++; count++; } if (count > 2) { return false; } } return true; } /** * Een opeenvolgende reeks van 3 tekens mag niet telkens met 1 oplopen of afdalen. * Voorbeelden: de tekenreeksen ABC, XYZ, KLM, PQR, 456, 321, cba, vut, gfe en zyx mogen niet in een wachtwoord voorkomen */ public boolean passes4(String password) { return passesFor(password, rule4Letters) && passesFor(password, rule4Numbers) && passesFor(password, rule4Misc); } private boolean passesFor(String password, Pattern p) { if ((password == null) || (password.length() < 3)) { return true; } Matcher m = p.matcher(password); while (m.find()) { char[] chars = m.group().toCharArray(); if (oplopend(chars) || aflopend(chars)) { return false; } } return true; } private boolean oplopend(char[] chars) { if (chars.length < 3) { return false; } return (chars[0] == chars[1] - 1) && (chars[1] == chars[2] - 1); } private boolean aflopend(final char[] chars) { char[] reversed = new char[chars.length]; for (int i = 0; i < chars.length; i++) { reversed[i] = chars[chars.length - (i + 1)]; } return oplopend(reversed); } /** * @return Spaties komen alleen in de zevende en/of achtste positie van <code>password</code> voor. */ public boolean passes5(String password) { if (password == null) { return false; } int eersteSpatieOp = password.indexOf(' '); return (eersteSpatieOp == -1) || (eersteSpatieOp > 5); } /** * @return aaneengesloten reeksen van letters (groot of klein) hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes6(String password) { Matcher m = rule6.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte |= m.group().length() != 3; } return !fouteLengte; } /** * @return aaneengesloten reeksen van cijfers hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes7(String password) { Matcher m = rule7.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte = m.group().length() != 3; } return !fouteLengte; } /** * @return <code>password</code> heeft minstens 3 overige tekens of voldoet aan regels 5, 6 en 7 */ public boolean passes8(String password) { Matcher m = rule8.matcher(password); int count = 0; while (m.find()) { count++; } return (count >= 3) || passes5(password) && passes6(password) && passes7(password); } }
vrijBRP/vrijBRP-Balie
gba-utils/src/main/java/nl/procura/gba/common/BrpPasswordGenerator.java
1,930
/** * Een opeenvolgende reeks van 3 tekens mag niet telkens met 1 oplopen of afdalen. * Voorbeelden: de tekenreeksen ABC, XYZ, KLM, PQR, 456, 321, cba, vut, gfe en zyx mogen niet in een wachtwoord voorkomen */
block_comment
nl
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.common; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Password generator voor BPR wachtwoorden */ public class BrpPasswordGenerator { private final static BrpPasswordGenerator generator = new BrpPasswordGenerator(); private final static List<Character> availableChars; static { List<Character> chars = new ArrayList<>(100); for (char ch = 'a'; ch <= 'z'; ch++) { chars.add(Character.toLowerCase(ch)); chars.add(Character.toUpperCase(ch)); } for (int i = 0; i < 3; i++) { for (char ch = '0'; ch <= '9'; ch++) { chars.add(ch); } } availableChars = Collections.unmodifiableList(chars); } private final Random random = new SecureRandom(); private final Pattern rule1 = Pattern.compile("^[\\w\\d _=+/!@*].*$"); private final Pattern rule4Letters = Pattern.compile("[a-zA-Z]{3}"); private final Pattern rule4Numbers = Pattern.compile("[0-9]{3}"); private final Pattern rule4Misc = Pattern.compile("[^a-zA-Z0-9 ]{3}"); private final Pattern rule6 = Pattern.compile("[a-zA-Z]{2,}"); private final Pattern rule7 = Pattern.compile("[0-9]{2,}"); private final Pattern rule8 = Pattern.compile("[^a-zA-Z0-9 ]"); public static String newPassword() { return generator.generate(); } public static boolean checkWachtwoord(String ww) { return generator.passingRules(ww); } public String generate() { String ww = ""; while (!passingRules(ww)) { StringBuilder pass = new StringBuilder(); for (int i = 0; i < 8; i++) { pass.append(availableChars.get(random.nextInt(availableChars.size()))); } ww = pass.toString(); } return ww; } private boolean passingRules(String password) { return passes1(password) && passes2(password) && passes3(password) && passes4(password) && passes8(password); } /** * @return <code>password</code> bestaat alleen uit toegestane tekens */ public boolean passes1(String password) { return rule1.matcher(password).matches(); } /** * @return De lengte van <code>password</code> is tussen zes en acht karakters */ public boolean passes2(String password) { return (password != null) && (password.length() >= 6) && (password.length() <= 8); } /** * @return Hetzelfde teken komt maximaal 2 keer in <code>password</code> voor. */ public boolean passes3(String password) { if ((password == null) || (password.length() <= 2)) { return true; } for (char c : password.toCharArray()) { int i = 0, count = 0; while ((i = password.indexOf(c, i)) != -1) { i++; count++; } if (count > 2) { return false; } } return true; } /** * Een opeenvolgende reeks<SUF>*/ public boolean passes4(String password) { return passesFor(password, rule4Letters) && passesFor(password, rule4Numbers) && passesFor(password, rule4Misc); } private boolean passesFor(String password, Pattern p) { if ((password == null) || (password.length() < 3)) { return true; } Matcher m = p.matcher(password); while (m.find()) { char[] chars = m.group().toCharArray(); if (oplopend(chars) || aflopend(chars)) { return false; } } return true; } private boolean oplopend(char[] chars) { if (chars.length < 3) { return false; } return (chars[0] == chars[1] - 1) && (chars[1] == chars[2] - 1); } private boolean aflopend(final char[] chars) { char[] reversed = new char[chars.length]; for (int i = 0; i < chars.length; i++) { reversed[i] = chars[chars.length - (i + 1)]; } return oplopend(reversed); } /** * @return Spaties komen alleen in de zevende en/of achtste positie van <code>password</code> voor. */ public boolean passes5(String password) { if (password == null) { return false; } int eersteSpatieOp = password.indexOf(' '); return (eersteSpatieOp == -1) || (eersteSpatieOp > 5); } /** * @return aaneengesloten reeksen van letters (groot of klein) hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes6(String password) { Matcher m = rule6.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte |= m.group().length() != 3; } return !fouteLengte; } /** * @return aaneengesloten reeksen van cijfers hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes7(String password) { Matcher m = rule7.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte = m.group().length() != 3; } return !fouteLengte; } /** * @return <code>password</code> heeft minstens 3 overige tekens of voldoet aan regels 5, 6 en 7 */ public boolean passes8(String password) { Matcher m = rule8.matcher(password); int count = 0; while (m.find()) { count++; } return (count >= 3) || passes5(password) && passes6(password) && passes7(password); } }
199362_6
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.common; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Password generator voor BPR wachtwoorden */ public class BrpPasswordGenerator { private final static BrpPasswordGenerator generator = new BrpPasswordGenerator(); private final static List<Character> availableChars; static { List<Character> chars = new ArrayList<>(100); for (char ch = 'a'; ch <= 'z'; ch++) { chars.add(Character.toLowerCase(ch)); chars.add(Character.toUpperCase(ch)); } for (int i = 0; i < 3; i++) { for (char ch = '0'; ch <= '9'; ch++) { chars.add(ch); } } availableChars = Collections.unmodifiableList(chars); } private final Random random = new SecureRandom(); private final Pattern rule1 = Pattern.compile("^[\\w\\d _=+/!@*].*$"); private final Pattern rule4Letters = Pattern.compile("[a-zA-Z]{3}"); private final Pattern rule4Numbers = Pattern.compile("[0-9]{3}"); private final Pattern rule4Misc = Pattern.compile("[^a-zA-Z0-9 ]{3}"); private final Pattern rule6 = Pattern.compile("[a-zA-Z]{2,}"); private final Pattern rule7 = Pattern.compile("[0-9]{2,}"); private final Pattern rule8 = Pattern.compile("[^a-zA-Z0-9 ]"); public static String newPassword() { return generator.generate(); } public static boolean checkWachtwoord(String ww) { return generator.passingRules(ww); } public String generate() { String ww = ""; while (!passingRules(ww)) { StringBuilder pass = new StringBuilder(); for (int i = 0; i < 8; i++) { pass.append(availableChars.get(random.nextInt(availableChars.size()))); } ww = pass.toString(); } return ww; } private boolean passingRules(String password) { return passes1(password) && passes2(password) && passes3(password) && passes4(password) && passes8(password); } /** * @return <code>password</code> bestaat alleen uit toegestane tekens */ public boolean passes1(String password) { return rule1.matcher(password).matches(); } /** * @return De lengte van <code>password</code> is tussen zes en acht karakters */ public boolean passes2(String password) { return (password != null) && (password.length() >= 6) && (password.length() <= 8); } /** * @return Hetzelfde teken komt maximaal 2 keer in <code>password</code> voor. */ public boolean passes3(String password) { if ((password == null) || (password.length() <= 2)) { return true; } for (char c : password.toCharArray()) { int i = 0, count = 0; while ((i = password.indexOf(c, i)) != -1) { i++; count++; } if (count > 2) { return false; } } return true; } /** * Een opeenvolgende reeks van 3 tekens mag niet telkens met 1 oplopen of afdalen. * Voorbeelden: de tekenreeksen ABC, XYZ, KLM, PQR, 456, 321, cba, vut, gfe en zyx mogen niet in een wachtwoord voorkomen */ public boolean passes4(String password) { return passesFor(password, rule4Letters) && passesFor(password, rule4Numbers) && passesFor(password, rule4Misc); } private boolean passesFor(String password, Pattern p) { if ((password == null) || (password.length() < 3)) { return true; } Matcher m = p.matcher(password); while (m.find()) { char[] chars = m.group().toCharArray(); if (oplopend(chars) || aflopend(chars)) { return false; } } return true; } private boolean oplopend(char[] chars) { if (chars.length < 3) { return false; } return (chars[0] == chars[1] - 1) && (chars[1] == chars[2] - 1); } private boolean aflopend(final char[] chars) { char[] reversed = new char[chars.length]; for (int i = 0; i < chars.length; i++) { reversed[i] = chars[chars.length - (i + 1)]; } return oplopend(reversed); } /** * @return Spaties komen alleen in de zevende en/of achtste positie van <code>password</code> voor. */ public boolean passes5(String password) { if (password == null) { return false; } int eersteSpatieOp = password.indexOf(' '); return (eersteSpatieOp == -1) || (eersteSpatieOp > 5); } /** * @return aaneengesloten reeksen van letters (groot of klein) hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes6(String password) { Matcher m = rule6.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte |= m.group().length() != 3; } return !fouteLengte; } /** * @return aaneengesloten reeksen van cijfers hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes7(String password) { Matcher m = rule7.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte = m.group().length() != 3; } return !fouteLengte; } /** * @return <code>password</code> heeft minstens 3 overige tekens of voldoet aan regels 5, 6 en 7 */ public boolean passes8(String password) { Matcher m = rule8.matcher(password); int count = 0; while (m.find()) { count++; } return (count >= 3) || passes5(password) && passes6(password) && passes7(password); } }
vrijBRP/vrijBRP-Balie
gba-utils/src/main/java/nl/procura/gba/common/BrpPasswordGenerator.java
1,930
/** * @return Spaties komen alleen in de zevende en/of achtste positie van <code>password</code> voor. */
block_comment
nl
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.common; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Password generator voor BPR wachtwoorden */ public class BrpPasswordGenerator { private final static BrpPasswordGenerator generator = new BrpPasswordGenerator(); private final static List<Character> availableChars; static { List<Character> chars = new ArrayList<>(100); for (char ch = 'a'; ch <= 'z'; ch++) { chars.add(Character.toLowerCase(ch)); chars.add(Character.toUpperCase(ch)); } for (int i = 0; i < 3; i++) { for (char ch = '0'; ch <= '9'; ch++) { chars.add(ch); } } availableChars = Collections.unmodifiableList(chars); } private final Random random = new SecureRandom(); private final Pattern rule1 = Pattern.compile("^[\\w\\d _=+/!@*].*$"); private final Pattern rule4Letters = Pattern.compile("[a-zA-Z]{3}"); private final Pattern rule4Numbers = Pattern.compile("[0-9]{3}"); private final Pattern rule4Misc = Pattern.compile("[^a-zA-Z0-9 ]{3}"); private final Pattern rule6 = Pattern.compile("[a-zA-Z]{2,}"); private final Pattern rule7 = Pattern.compile("[0-9]{2,}"); private final Pattern rule8 = Pattern.compile("[^a-zA-Z0-9 ]"); public static String newPassword() { return generator.generate(); } public static boolean checkWachtwoord(String ww) { return generator.passingRules(ww); } public String generate() { String ww = ""; while (!passingRules(ww)) { StringBuilder pass = new StringBuilder(); for (int i = 0; i < 8; i++) { pass.append(availableChars.get(random.nextInt(availableChars.size()))); } ww = pass.toString(); } return ww; } private boolean passingRules(String password) { return passes1(password) && passes2(password) && passes3(password) && passes4(password) && passes8(password); } /** * @return <code>password</code> bestaat alleen uit toegestane tekens */ public boolean passes1(String password) { return rule1.matcher(password).matches(); } /** * @return De lengte van <code>password</code> is tussen zes en acht karakters */ public boolean passes2(String password) { return (password != null) && (password.length() >= 6) && (password.length() <= 8); } /** * @return Hetzelfde teken komt maximaal 2 keer in <code>password</code> voor. */ public boolean passes3(String password) { if ((password == null) || (password.length() <= 2)) { return true; } for (char c : password.toCharArray()) { int i = 0, count = 0; while ((i = password.indexOf(c, i)) != -1) { i++; count++; } if (count > 2) { return false; } } return true; } /** * Een opeenvolgende reeks van 3 tekens mag niet telkens met 1 oplopen of afdalen. * Voorbeelden: de tekenreeksen ABC, XYZ, KLM, PQR, 456, 321, cba, vut, gfe en zyx mogen niet in een wachtwoord voorkomen */ public boolean passes4(String password) { return passesFor(password, rule4Letters) && passesFor(password, rule4Numbers) && passesFor(password, rule4Misc); } private boolean passesFor(String password, Pattern p) { if ((password == null) || (password.length() < 3)) { return true; } Matcher m = p.matcher(password); while (m.find()) { char[] chars = m.group().toCharArray(); if (oplopend(chars) || aflopend(chars)) { return false; } } return true; } private boolean oplopend(char[] chars) { if (chars.length < 3) { return false; } return (chars[0] == chars[1] - 1) && (chars[1] == chars[2] - 1); } private boolean aflopend(final char[] chars) { char[] reversed = new char[chars.length]; for (int i = 0; i < chars.length; i++) { reversed[i] = chars[chars.length - (i + 1)]; } return oplopend(reversed); } /** * @return Spaties komen<SUF>*/ public boolean passes5(String password) { if (password == null) { return false; } int eersteSpatieOp = password.indexOf(' '); return (eersteSpatieOp == -1) || (eersteSpatieOp > 5); } /** * @return aaneengesloten reeksen van letters (groot of klein) hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes6(String password) { Matcher m = rule6.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte |= m.group().length() != 3; } return !fouteLengte; } /** * @return aaneengesloten reeksen van cijfers hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes7(String password) { Matcher m = rule7.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte = m.group().length() != 3; } return !fouteLengte; } /** * @return <code>password</code> heeft minstens 3 overige tekens of voldoet aan regels 5, 6 en 7 */ public boolean passes8(String password) { Matcher m = rule8.matcher(password); int count = 0; while (m.find()) { count++; } return (count >= 3) || passes5(password) && passes6(password) && passes7(password); } }
199362_7
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.common; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Password generator voor BPR wachtwoorden */ public class BrpPasswordGenerator { private final static BrpPasswordGenerator generator = new BrpPasswordGenerator(); private final static List<Character> availableChars; static { List<Character> chars = new ArrayList<>(100); for (char ch = 'a'; ch <= 'z'; ch++) { chars.add(Character.toLowerCase(ch)); chars.add(Character.toUpperCase(ch)); } for (int i = 0; i < 3; i++) { for (char ch = '0'; ch <= '9'; ch++) { chars.add(ch); } } availableChars = Collections.unmodifiableList(chars); } private final Random random = new SecureRandom(); private final Pattern rule1 = Pattern.compile("^[\\w\\d _=+/!@*].*$"); private final Pattern rule4Letters = Pattern.compile("[a-zA-Z]{3}"); private final Pattern rule4Numbers = Pattern.compile("[0-9]{3}"); private final Pattern rule4Misc = Pattern.compile("[^a-zA-Z0-9 ]{3}"); private final Pattern rule6 = Pattern.compile("[a-zA-Z]{2,}"); private final Pattern rule7 = Pattern.compile("[0-9]{2,}"); private final Pattern rule8 = Pattern.compile("[^a-zA-Z0-9 ]"); public static String newPassword() { return generator.generate(); } public static boolean checkWachtwoord(String ww) { return generator.passingRules(ww); } public String generate() { String ww = ""; while (!passingRules(ww)) { StringBuilder pass = new StringBuilder(); for (int i = 0; i < 8; i++) { pass.append(availableChars.get(random.nextInt(availableChars.size()))); } ww = pass.toString(); } return ww; } private boolean passingRules(String password) { return passes1(password) && passes2(password) && passes3(password) && passes4(password) && passes8(password); } /** * @return <code>password</code> bestaat alleen uit toegestane tekens */ public boolean passes1(String password) { return rule1.matcher(password).matches(); } /** * @return De lengte van <code>password</code> is tussen zes en acht karakters */ public boolean passes2(String password) { return (password != null) && (password.length() >= 6) && (password.length() <= 8); } /** * @return Hetzelfde teken komt maximaal 2 keer in <code>password</code> voor. */ public boolean passes3(String password) { if ((password == null) || (password.length() <= 2)) { return true; } for (char c : password.toCharArray()) { int i = 0, count = 0; while ((i = password.indexOf(c, i)) != -1) { i++; count++; } if (count > 2) { return false; } } return true; } /** * Een opeenvolgende reeks van 3 tekens mag niet telkens met 1 oplopen of afdalen. * Voorbeelden: de tekenreeksen ABC, XYZ, KLM, PQR, 456, 321, cba, vut, gfe en zyx mogen niet in een wachtwoord voorkomen */ public boolean passes4(String password) { return passesFor(password, rule4Letters) && passesFor(password, rule4Numbers) && passesFor(password, rule4Misc); } private boolean passesFor(String password, Pattern p) { if ((password == null) || (password.length() < 3)) { return true; } Matcher m = p.matcher(password); while (m.find()) { char[] chars = m.group().toCharArray(); if (oplopend(chars) || aflopend(chars)) { return false; } } return true; } private boolean oplopend(char[] chars) { if (chars.length < 3) { return false; } return (chars[0] == chars[1] - 1) && (chars[1] == chars[2] - 1); } private boolean aflopend(final char[] chars) { char[] reversed = new char[chars.length]; for (int i = 0; i < chars.length; i++) { reversed[i] = chars[chars.length - (i + 1)]; } return oplopend(reversed); } /** * @return Spaties komen alleen in de zevende en/of achtste positie van <code>password</code> voor. */ public boolean passes5(String password) { if (password == null) { return false; } int eersteSpatieOp = password.indexOf(' '); return (eersteSpatieOp == -1) || (eersteSpatieOp > 5); } /** * @return aaneengesloten reeksen van letters (groot of klein) hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes6(String password) { Matcher m = rule6.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte |= m.group().length() != 3; } return !fouteLengte; } /** * @return aaneengesloten reeksen van cijfers hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes7(String password) { Matcher m = rule7.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte = m.group().length() != 3; } return !fouteLengte; } /** * @return <code>password</code> heeft minstens 3 overige tekens of voldoet aan regels 5, 6 en 7 */ public boolean passes8(String password) { Matcher m = rule8.matcher(password); int count = 0; while (m.find()) { count++; } return (count >= 3) || passes5(password) && passes6(password) && passes7(password); } }
vrijBRP/vrijBRP-Balie
gba-utils/src/main/java/nl/procura/gba/common/BrpPasswordGenerator.java
1,930
/** * @return aaneengesloten reeksen van letters (groot of klein) hebben een lengte van 1 of 3 in <code>password</code> */
block_comment
nl
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.common; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Password generator voor BPR wachtwoorden */ public class BrpPasswordGenerator { private final static BrpPasswordGenerator generator = new BrpPasswordGenerator(); private final static List<Character> availableChars; static { List<Character> chars = new ArrayList<>(100); for (char ch = 'a'; ch <= 'z'; ch++) { chars.add(Character.toLowerCase(ch)); chars.add(Character.toUpperCase(ch)); } for (int i = 0; i < 3; i++) { for (char ch = '0'; ch <= '9'; ch++) { chars.add(ch); } } availableChars = Collections.unmodifiableList(chars); } private final Random random = new SecureRandom(); private final Pattern rule1 = Pattern.compile("^[\\w\\d _=+/!@*].*$"); private final Pattern rule4Letters = Pattern.compile("[a-zA-Z]{3}"); private final Pattern rule4Numbers = Pattern.compile("[0-9]{3}"); private final Pattern rule4Misc = Pattern.compile("[^a-zA-Z0-9 ]{3}"); private final Pattern rule6 = Pattern.compile("[a-zA-Z]{2,}"); private final Pattern rule7 = Pattern.compile("[0-9]{2,}"); private final Pattern rule8 = Pattern.compile("[^a-zA-Z0-9 ]"); public static String newPassword() { return generator.generate(); } public static boolean checkWachtwoord(String ww) { return generator.passingRules(ww); } public String generate() { String ww = ""; while (!passingRules(ww)) { StringBuilder pass = new StringBuilder(); for (int i = 0; i < 8; i++) { pass.append(availableChars.get(random.nextInt(availableChars.size()))); } ww = pass.toString(); } return ww; } private boolean passingRules(String password) { return passes1(password) && passes2(password) && passes3(password) && passes4(password) && passes8(password); } /** * @return <code>password</code> bestaat alleen uit toegestane tekens */ public boolean passes1(String password) { return rule1.matcher(password).matches(); } /** * @return De lengte van <code>password</code> is tussen zes en acht karakters */ public boolean passes2(String password) { return (password != null) && (password.length() >= 6) && (password.length() <= 8); } /** * @return Hetzelfde teken komt maximaal 2 keer in <code>password</code> voor. */ public boolean passes3(String password) { if ((password == null) || (password.length() <= 2)) { return true; } for (char c : password.toCharArray()) { int i = 0, count = 0; while ((i = password.indexOf(c, i)) != -1) { i++; count++; } if (count > 2) { return false; } } return true; } /** * Een opeenvolgende reeks van 3 tekens mag niet telkens met 1 oplopen of afdalen. * Voorbeelden: de tekenreeksen ABC, XYZ, KLM, PQR, 456, 321, cba, vut, gfe en zyx mogen niet in een wachtwoord voorkomen */ public boolean passes4(String password) { return passesFor(password, rule4Letters) && passesFor(password, rule4Numbers) && passesFor(password, rule4Misc); } private boolean passesFor(String password, Pattern p) { if ((password == null) || (password.length() < 3)) { return true; } Matcher m = p.matcher(password); while (m.find()) { char[] chars = m.group().toCharArray(); if (oplopend(chars) || aflopend(chars)) { return false; } } return true; } private boolean oplopend(char[] chars) { if (chars.length < 3) { return false; } return (chars[0] == chars[1] - 1) && (chars[1] == chars[2] - 1); } private boolean aflopend(final char[] chars) { char[] reversed = new char[chars.length]; for (int i = 0; i < chars.length; i++) { reversed[i] = chars[chars.length - (i + 1)]; } return oplopend(reversed); } /** * @return Spaties komen alleen in de zevende en/of achtste positie van <code>password</code> voor. */ public boolean passes5(String password) { if (password == null) { return false; } int eersteSpatieOp = password.indexOf(' '); return (eersteSpatieOp == -1) || (eersteSpatieOp > 5); } /** * @return aaneengesloten reeksen<SUF>*/ public boolean passes6(String password) { Matcher m = rule6.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte |= m.group().length() != 3; } return !fouteLengte; } /** * @return aaneengesloten reeksen van cijfers hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes7(String password) { Matcher m = rule7.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte = m.group().length() != 3; } return !fouteLengte; } /** * @return <code>password</code> heeft minstens 3 overige tekens of voldoet aan regels 5, 6 en 7 */ public boolean passes8(String password) { Matcher m = rule8.matcher(password); int count = 0; while (m.find()) { count++; } return (count >= 3) || passes5(password) && passes6(password) && passes7(password); } }
199362_8
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.common; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Password generator voor BPR wachtwoorden */ public class BrpPasswordGenerator { private final static BrpPasswordGenerator generator = new BrpPasswordGenerator(); private final static List<Character> availableChars; static { List<Character> chars = new ArrayList<>(100); for (char ch = 'a'; ch <= 'z'; ch++) { chars.add(Character.toLowerCase(ch)); chars.add(Character.toUpperCase(ch)); } for (int i = 0; i < 3; i++) { for (char ch = '0'; ch <= '9'; ch++) { chars.add(ch); } } availableChars = Collections.unmodifiableList(chars); } private final Random random = new SecureRandom(); private final Pattern rule1 = Pattern.compile("^[\\w\\d _=+/!@*].*$"); private final Pattern rule4Letters = Pattern.compile("[a-zA-Z]{3}"); private final Pattern rule4Numbers = Pattern.compile("[0-9]{3}"); private final Pattern rule4Misc = Pattern.compile("[^a-zA-Z0-9 ]{3}"); private final Pattern rule6 = Pattern.compile("[a-zA-Z]{2,}"); private final Pattern rule7 = Pattern.compile("[0-9]{2,}"); private final Pattern rule8 = Pattern.compile("[^a-zA-Z0-9 ]"); public static String newPassword() { return generator.generate(); } public static boolean checkWachtwoord(String ww) { return generator.passingRules(ww); } public String generate() { String ww = ""; while (!passingRules(ww)) { StringBuilder pass = new StringBuilder(); for (int i = 0; i < 8; i++) { pass.append(availableChars.get(random.nextInt(availableChars.size()))); } ww = pass.toString(); } return ww; } private boolean passingRules(String password) { return passes1(password) && passes2(password) && passes3(password) && passes4(password) && passes8(password); } /** * @return <code>password</code> bestaat alleen uit toegestane tekens */ public boolean passes1(String password) { return rule1.matcher(password).matches(); } /** * @return De lengte van <code>password</code> is tussen zes en acht karakters */ public boolean passes2(String password) { return (password != null) && (password.length() >= 6) && (password.length() <= 8); } /** * @return Hetzelfde teken komt maximaal 2 keer in <code>password</code> voor. */ public boolean passes3(String password) { if ((password == null) || (password.length() <= 2)) { return true; } for (char c : password.toCharArray()) { int i = 0, count = 0; while ((i = password.indexOf(c, i)) != -1) { i++; count++; } if (count > 2) { return false; } } return true; } /** * Een opeenvolgende reeks van 3 tekens mag niet telkens met 1 oplopen of afdalen. * Voorbeelden: de tekenreeksen ABC, XYZ, KLM, PQR, 456, 321, cba, vut, gfe en zyx mogen niet in een wachtwoord voorkomen */ public boolean passes4(String password) { return passesFor(password, rule4Letters) && passesFor(password, rule4Numbers) && passesFor(password, rule4Misc); } private boolean passesFor(String password, Pattern p) { if ((password == null) || (password.length() < 3)) { return true; } Matcher m = p.matcher(password); while (m.find()) { char[] chars = m.group().toCharArray(); if (oplopend(chars) || aflopend(chars)) { return false; } } return true; } private boolean oplopend(char[] chars) { if (chars.length < 3) { return false; } return (chars[0] == chars[1] - 1) && (chars[1] == chars[2] - 1); } private boolean aflopend(final char[] chars) { char[] reversed = new char[chars.length]; for (int i = 0; i < chars.length; i++) { reversed[i] = chars[chars.length - (i + 1)]; } return oplopend(reversed); } /** * @return Spaties komen alleen in de zevende en/of achtste positie van <code>password</code> voor. */ public boolean passes5(String password) { if (password == null) { return false; } int eersteSpatieOp = password.indexOf(' '); return (eersteSpatieOp == -1) || (eersteSpatieOp > 5); } /** * @return aaneengesloten reeksen van letters (groot of klein) hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes6(String password) { Matcher m = rule6.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte |= m.group().length() != 3; } return !fouteLengte; } /** * @return aaneengesloten reeksen van cijfers hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes7(String password) { Matcher m = rule7.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte = m.group().length() != 3; } return !fouteLengte; } /** * @return <code>password</code> heeft minstens 3 overige tekens of voldoet aan regels 5, 6 en 7 */ public boolean passes8(String password) { Matcher m = rule8.matcher(password); int count = 0; while (m.find()) { count++; } return (count >= 3) || passes5(password) && passes6(password) && passes7(password); } }
vrijBRP/vrijBRP-Balie
gba-utils/src/main/java/nl/procura/gba/common/BrpPasswordGenerator.java
1,930
/** * @return aaneengesloten reeksen van cijfers hebben een lengte van 1 of 3 in <code>password</code> */
block_comment
nl
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.common; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Password generator voor BPR wachtwoorden */ public class BrpPasswordGenerator { private final static BrpPasswordGenerator generator = new BrpPasswordGenerator(); private final static List<Character> availableChars; static { List<Character> chars = new ArrayList<>(100); for (char ch = 'a'; ch <= 'z'; ch++) { chars.add(Character.toLowerCase(ch)); chars.add(Character.toUpperCase(ch)); } for (int i = 0; i < 3; i++) { for (char ch = '0'; ch <= '9'; ch++) { chars.add(ch); } } availableChars = Collections.unmodifiableList(chars); } private final Random random = new SecureRandom(); private final Pattern rule1 = Pattern.compile("^[\\w\\d _=+/!@*].*$"); private final Pattern rule4Letters = Pattern.compile("[a-zA-Z]{3}"); private final Pattern rule4Numbers = Pattern.compile("[0-9]{3}"); private final Pattern rule4Misc = Pattern.compile("[^a-zA-Z0-9 ]{3}"); private final Pattern rule6 = Pattern.compile("[a-zA-Z]{2,}"); private final Pattern rule7 = Pattern.compile("[0-9]{2,}"); private final Pattern rule8 = Pattern.compile("[^a-zA-Z0-9 ]"); public static String newPassword() { return generator.generate(); } public static boolean checkWachtwoord(String ww) { return generator.passingRules(ww); } public String generate() { String ww = ""; while (!passingRules(ww)) { StringBuilder pass = new StringBuilder(); for (int i = 0; i < 8; i++) { pass.append(availableChars.get(random.nextInt(availableChars.size()))); } ww = pass.toString(); } return ww; } private boolean passingRules(String password) { return passes1(password) && passes2(password) && passes3(password) && passes4(password) && passes8(password); } /** * @return <code>password</code> bestaat alleen uit toegestane tekens */ public boolean passes1(String password) { return rule1.matcher(password).matches(); } /** * @return De lengte van <code>password</code> is tussen zes en acht karakters */ public boolean passes2(String password) { return (password != null) && (password.length() >= 6) && (password.length() <= 8); } /** * @return Hetzelfde teken komt maximaal 2 keer in <code>password</code> voor. */ public boolean passes3(String password) { if ((password == null) || (password.length() <= 2)) { return true; } for (char c : password.toCharArray()) { int i = 0, count = 0; while ((i = password.indexOf(c, i)) != -1) { i++; count++; } if (count > 2) { return false; } } return true; } /** * Een opeenvolgende reeks van 3 tekens mag niet telkens met 1 oplopen of afdalen. * Voorbeelden: de tekenreeksen ABC, XYZ, KLM, PQR, 456, 321, cba, vut, gfe en zyx mogen niet in een wachtwoord voorkomen */ public boolean passes4(String password) { return passesFor(password, rule4Letters) && passesFor(password, rule4Numbers) && passesFor(password, rule4Misc); } private boolean passesFor(String password, Pattern p) { if ((password == null) || (password.length() < 3)) { return true; } Matcher m = p.matcher(password); while (m.find()) { char[] chars = m.group().toCharArray(); if (oplopend(chars) || aflopend(chars)) { return false; } } return true; } private boolean oplopend(char[] chars) { if (chars.length < 3) { return false; } return (chars[0] == chars[1] - 1) && (chars[1] == chars[2] - 1); } private boolean aflopend(final char[] chars) { char[] reversed = new char[chars.length]; for (int i = 0; i < chars.length; i++) { reversed[i] = chars[chars.length - (i + 1)]; } return oplopend(reversed); } /** * @return Spaties komen alleen in de zevende en/of achtste positie van <code>password</code> voor. */ public boolean passes5(String password) { if (password == null) { return false; } int eersteSpatieOp = password.indexOf(' '); return (eersteSpatieOp == -1) || (eersteSpatieOp > 5); } /** * @return aaneengesloten reeksen van letters (groot of klein) hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes6(String password) { Matcher m = rule6.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte |= m.group().length() != 3; } return !fouteLengte; } /** * @return aaneengesloten reeksen<SUF>*/ public boolean passes7(String password) { Matcher m = rule7.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte = m.group().length() != 3; } return !fouteLengte; } /** * @return <code>password</code> heeft minstens 3 overige tekens of voldoet aan regels 5, 6 en 7 */ public boolean passes8(String password) { Matcher m = rule8.matcher(password); int count = 0; while (m.find()) { count++; } return (count >= 3) || passes5(password) && passes6(password) && passes7(password); } }
199362_9
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.common; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Password generator voor BPR wachtwoorden */ public class BrpPasswordGenerator { private final static BrpPasswordGenerator generator = new BrpPasswordGenerator(); private final static List<Character> availableChars; static { List<Character> chars = new ArrayList<>(100); for (char ch = 'a'; ch <= 'z'; ch++) { chars.add(Character.toLowerCase(ch)); chars.add(Character.toUpperCase(ch)); } for (int i = 0; i < 3; i++) { for (char ch = '0'; ch <= '9'; ch++) { chars.add(ch); } } availableChars = Collections.unmodifiableList(chars); } private final Random random = new SecureRandom(); private final Pattern rule1 = Pattern.compile("^[\\w\\d _=+/!@*].*$"); private final Pattern rule4Letters = Pattern.compile("[a-zA-Z]{3}"); private final Pattern rule4Numbers = Pattern.compile("[0-9]{3}"); private final Pattern rule4Misc = Pattern.compile("[^a-zA-Z0-9 ]{3}"); private final Pattern rule6 = Pattern.compile("[a-zA-Z]{2,}"); private final Pattern rule7 = Pattern.compile("[0-9]{2,}"); private final Pattern rule8 = Pattern.compile("[^a-zA-Z0-9 ]"); public static String newPassword() { return generator.generate(); } public static boolean checkWachtwoord(String ww) { return generator.passingRules(ww); } public String generate() { String ww = ""; while (!passingRules(ww)) { StringBuilder pass = new StringBuilder(); for (int i = 0; i < 8; i++) { pass.append(availableChars.get(random.nextInt(availableChars.size()))); } ww = pass.toString(); } return ww; } private boolean passingRules(String password) { return passes1(password) && passes2(password) && passes3(password) && passes4(password) && passes8(password); } /** * @return <code>password</code> bestaat alleen uit toegestane tekens */ public boolean passes1(String password) { return rule1.matcher(password).matches(); } /** * @return De lengte van <code>password</code> is tussen zes en acht karakters */ public boolean passes2(String password) { return (password != null) && (password.length() >= 6) && (password.length() <= 8); } /** * @return Hetzelfde teken komt maximaal 2 keer in <code>password</code> voor. */ public boolean passes3(String password) { if ((password == null) || (password.length() <= 2)) { return true; } for (char c : password.toCharArray()) { int i = 0, count = 0; while ((i = password.indexOf(c, i)) != -1) { i++; count++; } if (count > 2) { return false; } } return true; } /** * Een opeenvolgende reeks van 3 tekens mag niet telkens met 1 oplopen of afdalen. * Voorbeelden: de tekenreeksen ABC, XYZ, KLM, PQR, 456, 321, cba, vut, gfe en zyx mogen niet in een wachtwoord voorkomen */ public boolean passes4(String password) { return passesFor(password, rule4Letters) && passesFor(password, rule4Numbers) && passesFor(password, rule4Misc); } private boolean passesFor(String password, Pattern p) { if ((password == null) || (password.length() < 3)) { return true; } Matcher m = p.matcher(password); while (m.find()) { char[] chars = m.group().toCharArray(); if (oplopend(chars) || aflopend(chars)) { return false; } } return true; } private boolean oplopend(char[] chars) { if (chars.length < 3) { return false; } return (chars[0] == chars[1] - 1) && (chars[1] == chars[2] - 1); } private boolean aflopend(final char[] chars) { char[] reversed = new char[chars.length]; for (int i = 0; i < chars.length; i++) { reversed[i] = chars[chars.length - (i + 1)]; } return oplopend(reversed); } /** * @return Spaties komen alleen in de zevende en/of achtste positie van <code>password</code> voor. */ public boolean passes5(String password) { if (password == null) { return false; } int eersteSpatieOp = password.indexOf(' '); return (eersteSpatieOp == -1) || (eersteSpatieOp > 5); } /** * @return aaneengesloten reeksen van letters (groot of klein) hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes6(String password) { Matcher m = rule6.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte |= m.group().length() != 3; } return !fouteLengte; } /** * @return aaneengesloten reeksen van cijfers hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes7(String password) { Matcher m = rule7.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte = m.group().length() != 3; } return !fouteLengte; } /** * @return <code>password</code> heeft minstens 3 overige tekens of voldoet aan regels 5, 6 en 7 */ public boolean passes8(String password) { Matcher m = rule8.matcher(password); int count = 0; while (m.find()) { count++; } return (count >= 3) || passes5(password) && passes6(password) && passes7(password); } }
vrijBRP/vrijBRP-Balie
gba-utils/src/main/java/nl/procura/gba/common/BrpPasswordGenerator.java
1,930
/** * @return <code>password</code> heeft minstens 3 overige tekens of voldoet aan regels 5, 6 en 7 */
block_comment
nl
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.common; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Password generator voor BPR wachtwoorden */ public class BrpPasswordGenerator { private final static BrpPasswordGenerator generator = new BrpPasswordGenerator(); private final static List<Character> availableChars; static { List<Character> chars = new ArrayList<>(100); for (char ch = 'a'; ch <= 'z'; ch++) { chars.add(Character.toLowerCase(ch)); chars.add(Character.toUpperCase(ch)); } for (int i = 0; i < 3; i++) { for (char ch = '0'; ch <= '9'; ch++) { chars.add(ch); } } availableChars = Collections.unmodifiableList(chars); } private final Random random = new SecureRandom(); private final Pattern rule1 = Pattern.compile("^[\\w\\d _=+/!@*].*$"); private final Pattern rule4Letters = Pattern.compile("[a-zA-Z]{3}"); private final Pattern rule4Numbers = Pattern.compile("[0-9]{3}"); private final Pattern rule4Misc = Pattern.compile("[^a-zA-Z0-9 ]{3}"); private final Pattern rule6 = Pattern.compile("[a-zA-Z]{2,}"); private final Pattern rule7 = Pattern.compile("[0-9]{2,}"); private final Pattern rule8 = Pattern.compile("[^a-zA-Z0-9 ]"); public static String newPassword() { return generator.generate(); } public static boolean checkWachtwoord(String ww) { return generator.passingRules(ww); } public String generate() { String ww = ""; while (!passingRules(ww)) { StringBuilder pass = new StringBuilder(); for (int i = 0; i < 8; i++) { pass.append(availableChars.get(random.nextInt(availableChars.size()))); } ww = pass.toString(); } return ww; } private boolean passingRules(String password) { return passes1(password) && passes2(password) && passes3(password) && passes4(password) && passes8(password); } /** * @return <code>password</code> bestaat alleen uit toegestane tekens */ public boolean passes1(String password) { return rule1.matcher(password).matches(); } /** * @return De lengte van <code>password</code> is tussen zes en acht karakters */ public boolean passes2(String password) { return (password != null) && (password.length() >= 6) && (password.length() <= 8); } /** * @return Hetzelfde teken komt maximaal 2 keer in <code>password</code> voor. */ public boolean passes3(String password) { if ((password == null) || (password.length() <= 2)) { return true; } for (char c : password.toCharArray()) { int i = 0, count = 0; while ((i = password.indexOf(c, i)) != -1) { i++; count++; } if (count > 2) { return false; } } return true; } /** * Een opeenvolgende reeks van 3 tekens mag niet telkens met 1 oplopen of afdalen. * Voorbeelden: de tekenreeksen ABC, XYZ, KLM, PQR, 456, 321, cba, vut, gfe en zyx mogen niet in een wachtwoord voorkomen */ public boolean passes4(String password) { return passesFor(password, rule4Letters) && passesFor(password, rule4Numbers) && passesFor(password, rule4Misc); } private boolean passesFor(String password, Pattern p) { if ((password == null) || (password.length() < 3)) { return true; } Matcher m = p.matcher(password); while (m.find()) { char[] chars = m.group().toCharArray(); if (oplopend(chars) || aflopend(chars)) { return false; } } return true; } private boolean oplopend(char[] chars) { if (chars.length < 3) { return false; } return (chars[0] == chars[1] - 1) && (chars[1] == chars[2] - 1); } private boolean aflopend(final char[] chars) { char[] reversed = new char[chars.length]; for (int i = 0; i < chars.length; i++) { reversed[i] = chars[chars.length - (i + 1)]; } return oplopend(reversed); } /** * @return Spaties komen alleen in de zevende en/of achtste positie van <code>password</code> voor. */ public boolean passes5(String password) { if (password == null) { return false; } int eersteSpatieOp = password.indexOf(' '); return (eersteSpatieOp == -1) || (eersteSpatieOp > 5); } /** * @return aaneengesloten reeksen van letters (groot of klein) hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes6(String password) { Matcher m = rule6.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte |= m.group().length() != 3; } return !fouteLengte; } /** * @return aaneengesloten reeksen van cijfers hebben een lengte van 1 of 3 in <code>password</code> */ public boolean passes7(String password) { Matcher m = rule7.matcher(password); boolean fouteLengte = false; while (m.find() && !fouteLengte) { fouteLengte = m.group().length() != 3; } return !fouteLengte; } /** * @return <code>password</code> heeft<SUF>*/ public boolean passes8(String password) { Matcher m = rule8.matcher(password); int count = 0; while (m.find()) { count++; } return (count >= 3) || passes5(password) && passes6(password) && passes7(password); } }
199363_1
package be.kuleuven.jchr.compiler.CHRIntermediateForm.matching; import static be.kuleuven.jchr.util.comparing.Comparison.AMBIGUOUS; import static be.kuleuven.jchr.util.comparing.Comparison.BETTER; import static be.kuleuven.jchr.util.comparing.Comparison.EQUAL; import static be.kuleuven.jchr.util.comparing.Comparison.WORSE; import java.util.Arrays; import be.kuleuven.jchr.util.comparing.Comparison; /** * @author Peter Van Weert */ public class MatchingInfos extends AbstractMatchingInfo<MatchingInfos> { private MatchingInfo[] assignmentInfos; private boolean ignoreImplicitArgument; public final static MatchingInfos NO_MATCH = new MatchingInfos() { @Override protected byte getInfo() { return NO_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return false; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "NO MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { return other.isMatch()? WORSE : EQUAL; } }, EXACT_MATCH = new MatchingInfos() { @Override public MatchingInfo getAssignmentInfoAt(int index) { return MatchingInfo.EXACT_MATCH; } @Override protected byte getInfo() { return EXACT_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "EXACT MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { throw new UnsupportedOperationException( "This constant wasn't intended to be used in comparisons!" ); } }, AMBIGUOUS_NO_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return BETTER; else if (other.isCoerceMatch()) return AMBIGUOUS; else if (other.isExactMatch()) return WORSE; else return BETTER; } }, AMBIGUOUS_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; /* hoeft niet echt, maar all? */ } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return true; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return AMBIGUOUS; else if (other.isCoerceMatch() || other.isExactMatch()) return WORSE; else return BETTER; } }; protected MatchingInfos() { // NOP (just declaring this has to be a protected constructor) } public MatchingInfos(int arity, boolean ignoreImplicitArgument) { this(new MatchingInfo[arity], ignoreImplicitArgument); } public MatchingInfos(MatchingInfo[] assignmentInfos, boolean ignoreImplicitArgument) { setAssignmentInfos(assignmentInfos); setIgnoreImplicitArgument(ignoreImplicitArgument); } public MatchingInfos(MatchingInfo assignmentInfo, boolean ignoreImplicitArgument) { this(new MatchingInfo[] {assignmentInfo}, ignoreImplicitArgument); } public MatchingInfo[] getAssignmentInfos() { return assignmentInfos; } public int getArity() { return getAssignmentInfos().length; } protected void setAssignmentInfos(MatchingInfo[] assignmentInfos) { this.assignmentInfos = assignmentInfos; } public MatchingInfo getAssignmentInfoAt(int index) { return getAssignmentInfos()[index]; } public void setAssignmentInfoAt(MatchingInfo info, int index) { getAssignmentInfos()[index] = info; } @Override protected byte getInfo() { byte result = 0; for (MatchingInfo info : getAssignmentInfos()) result |= EXACT_MATCH_INFO ^ info.getInfo(); return (byte)(EXACT_MATCH_INFO ^ result); } public Comparison compareTo(MatchingInfos other) { if ((other == NO_MATCH) || (other == AMBIGUOUS_INIT) || (other == AMBIGUOUS_NO_INIT)) return Comparison.flip(other.compareTo(this)); Comparison comparison = Comparison.get(this.getMatchClass() - other.getMatchClass()); if (comparison == EQUAL && isNonExactMatch()) { // als beiden coerces zijn, en minstens 1 ervan ambigu, // is vergelijking niet mogelijk if (this.isAmbiguous() || other.isAmbiguous()) return AMBIGUOUS; final int arity = this.getArity(); Comparison temp; for (int i = this.getStartIndex(), j = other.getStartIndex(); i < arity; i++, j++) { temp = this.getAssignmentInfoAt(i).compareTo(other.getAssignmentInfoAt(j)); switch (temp) { // als er minstens 1 vergelijking ambigu is, is vergelijking niet mogelijk case AMBIGUOUS: return AMBIGUOUS; /*break;*/ // als er een verschil is moet... case BETTER: case WORSE: if (comparison == EQUAL) // ... na de eerste keer ... comparison = temp; else if (comparison != temp) // ... de vergelijking steeds hetzelfde zijn return AMBIGUOUS; } } } return comparison; } @Override public String toString() { return Arrays.deepToString(getAssignmentInfos()) + " (" + getInfo() + ")"; } public boolean haveToIgnoreImplicitArgument() { return ignoreImplicitArgument; } protected int getStartIndex() { return haveToIgnoreImplicitArgument()? 1 : 0; } protected void setIgnoreImplicitArgument(boolean ignoreImplicitArgument) { this.ignoreImplicitArgument = ignoreImplicitArgument; } public static MatchingInfos fromBoolean(boolean bool) { return bool? EXACT_MATCH : NO_MATCH; } }
hendrikvanantwerpen/jchr
src/be/kuleuven/jchr/compiler/CHRIntermediateForm/matching/MatchingInfos.java
2,352
/* hoeft niet echt, maar all? */
block_comment
nl
package be.kuleuven.jchr.compiler.CHRIntermediateForm.matching; import static be.kuleuven.jchr.util.comparing.Comparison.AMBIGUOUS; import static be.kuleuven.jchr.util.comparing.Comparison.BETTER; import static be.kuleuven.jchr.util.comparing.Comparison.EQUAL; import static be.kuleuven.jchr.util.comparing.Comparison.WORSE; import java.util.Arrays; import be.kuleuven.jchr.util.comparing.Comparison; /** * @author Peter Van Weert */ public class MatchingInfos extends AbstractMatchingInfo<MatchingInfos> { private MatchingInfo[] assignmentInfos; private boolean ignoreImplicitArgument; public final static MatchingInfos NO_MATCH = new MatchingInfos() { @Override protected byte getInfo() { return NO_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return false; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "NO MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { return other.isMatch()? WORSE : EQUAL; } }, EXACT_MATCH = new MatchingInfos() { @Override public MatchingInfo getAssignmentInfoAt(int index) { return MatchingInfo.EXACT_MATCH; } @Override protected byte getInfo() { return EXACT_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "EXACT MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { throw new UnsupportedOperationException( "This constant wasn't intended to be used in comparisons!" ); } }, AMBIGUOUS_NO_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return BETTER; else if (other.isCoerceMatch()) return AMBIGUOUS; else if (other.isExactMatch()) return WORSE; else return BETTER; } }, AMBIGUOUS_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; /* hoeft niet echt,<SUF>*/ } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return true; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return AMBIGUOUS; else if (other.isCoerceMatch() || other.isExactMatch()) return WORSE; else return BETTER; } }; protected MatchingInfos() { // NOP (just declaring this has to be a protected constructor) } public MatchingInfos(int arity, boolean ignoreImplicitArgument) { this(new MatchingInfo[arity], ignoreImplicitArgument); } public MatchingInfos(MatchingInfo[] assignmentInfos, boolean ignoreImplicitArgument) { setAssignmentInfos(assignmentInfos); setIgnoreImplicitArgument(ignoreImplicitArgument); } public MatchingInfos(MatchingInfo assignmentInfo, boolean ignoreImplicitArgument) { this(new MatchingInfo[] {assignmentInfo}, ignoreImplicitArgument); } public MatchingInfo[] getAssignmentInfos() { return assignmentInfos; } public int getArity() { return getAssignmentInfos().length; } protected void setAssignmentInfos(MatchingInfo[] assignmentInfos) { this.assignmentInfos = assignmentInfos; } public MatchingInfo getAssignmentInfoAt(int index) { return getAssignmentInfos()[index]; } public void setAssignmentInfoAt(MatchingInfo info, int index) { getAssignmentInfos()[index] = info; } @Override protected byte getInfo() { byte result = 0; for (MatchingInfo info : getAssignmentInfos()) result |= EXACT_MATCH_INFO ^ info.getInfo(); return (byte)(EXACT_MATCH_INFO ^ result); } public Comparison compareTo(MatchingInfos other) { if ((other == NO_MATCH) || (other == AMBIGUOUS_INIT) || (other == AMBIGUOUS_NO_INIT)) return Comparison.flip(other.compareTo(this)); Comparison comparison = Comparison.get(this.getMatchClass() - other.getMatchClass()); if (comparison == EQUAL && isNonExactMatch()) { // als beiden coerces zijn, en minstens 1 ervan ambigu, // is vergelijking niet mogelijk if (this.isAmbiguous() || other.isAmbiguous()) return AMBIGUOUS; final int arity = this.getArity(); Comparison temp; for (int i = this.getStartIndex(), j = other.getStartIndex(); i < arity; i++, j++) { temp = this.getAssignmentInfoAt(i).compareTo(other.getAssignmentInfoAt(j)); switch (temp) { // als er minstens 1 vergelijking ambigu is, is vergelijking niet mogelijk case AMBIGUOUS: return AMBIGUOUS; /*break;*/ // als er een verschil is moet... case BETTER: case WORSE: if (comparison == EQUAL) // ... na de eerste keer ... comparison = temp; else if (comparison != temp) // ... de vergelijking steeds hetzelfde zijn return AMBIGUOUS; } } } return comparison; } @Override public String toString() { return Arrays.deepToString(getAssignmentInfos()) + " (" + getInfo() + ")"; } public boolean haveToIgnoreImplicitArgument() { return ignoreImplicitArgument; } protected int getStartIndex() { return haveToIgnoreImplicitArgument()? 1 : 0; } protected void setIgnoreImplicitArgument(boolean ignoreImplicitArgument) { this.ignoreImplicitArgument = ignoreImplicitArgument; } public static MatchingInfos fromBoolean(boolean bool) { return bool? EXACT_MATCH : NO_MATCH; } }
199363_3
package be.kuleuven.jchr.compiler.CHRIntermediateForm.matching; import static be.kuleuven.jchr.util.comparing.Comparison.AMBIGUOUS; import static be.kuleuven.jchr.util.comparing.Comparison.BETTER; import static be.kuleuven.jchr.util.comparing.Comparison.EQUAL; import static be.kuleuven.jchr.util.comparing.Comparison.WORSE; import java.util.Arrays; import be.kuleuven.jchr.util.comparing.Comparison; /** * @author Peter Van Weert */ public class MatchingInfos extends AbstractMatchingInfo<MatchingInfos> { private MatchingInfo[] assignmentInfos; private boolean ignoreImplicitArgument; public final static MatchingInfos NO_MATCH = new MatchingInfos() { @Override protected byte getInfo() { return NO_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return false; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "NO MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { return other.isMatch()? WORSE : EQUAL; } }, EXACT_MATCH = new MatchingInfos() { @Override public MatchingInfo getAssignmentInfoAt(int index) { return MatchingInfo.EXACT_MATCH; } @Override protected byte getInfo() { return EXACT_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "EXACT MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { throw new UnsupportedOperationException( "This constant wasn't intended to be used in comparisons!" ); } }, AMBIGUOUS_NO_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return BETTER; else if (other.isCoerceMatch()) return AMBIGUOUS; else if (other.isExactMatch()) return WORSE; else return BETTER; } }, AMBIGUOUS_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; /* hoeft niet echt, maar all? */ } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return true; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return AMBIGUOUS; else if (other.isCoerceMatch() || other.isExactMatch()) return WORSE; else return BETTER; } }; protected MatchingInfos() { // NOP (just declaring this has to be a protected constructor) } public MatchingInfos(int arity, boolean ignoreImplicitArgument) { this(new MatchingInfo[arity], ignoreImplicitArgument); } public MatchingInfos(MatchingInfo[] assignmentInfos, boolean ignoreImplicitArgument) { setAssignmentInfos(assignmentInfos); setIgnoreImplicitArgument(ignoreImplicitArgument); } public MatchingInfos(MatchingInfo assignmentInfo, boolean ignoreImplicitArgument) { this(new MatchingInfo[] {assignmentInfo}, ignoreImplicitArgument); } public MatchingInfo[] getAssignmentInfos() { return assignmentInfos; } public int getArity() { return getAssignmentInfos().length; } protected void setAssignmentInfos(MatchingInfo[] assignmentInfos) { this.assignmentInfos = assignmentInfos; } public MatchingInfo getAssignmentInfoAt(int index) { return getAssignmentInfos()[index]; } public void setAssignmentInfoAt(MatchingInfo info, int index) { getAssignmentInfos()[index] = info; } @Override protected byte getInfo() { byte result = 0; for (MatchingInfo info : getAssignmentInfos()) result |= EXACT_MATCH_INFO ^ info.getInfo(); return (byte)(EXACT_MATCH_INFO ^ result); } public Comparison compareTo(MatchingInfos other) { if ((other == NO_MATCH) || (other == AMBIGUOUS_INIT) || (other == AMBIGUOUS_NO_INIT)) return Comparison.flip(other.compareTo(this)); Comparison comparison = Comparison.get(this.getMatchClass() - other.getMatchClass()); if (comparison == EQUAL && isNonExactMatch()) { // als beiden coerces zijn, en minstens 1 ervan ambigu, // is vergelijking niet mogelijk if (this.isAmbiguous() || other.isAmbiguous()) return AMBIGUOUS; final int arity = this.getArity(); Comparison temp; for (int i = this.getStartIndex(), j = other.getStartIndex(); i < arity; i++, j++) { temp = this.getAssignmentInfoAt(i).compareTo(other.getAssignmentInfoAt(j)); switch (temp) { // als er minstens 1 vergelijking ambigu is, is vergelijking niet mogelijk case AMBIGUOUS: return AMBIGUOUS; /*break;*/ // als er een verschil is moet... case BETTER: case WORSE: if (comparison == EQUAL) // ... na de eerste keer ... comparison = temp; else if (comparison != temp) // ... de vergelijking steeds hetzelfde zijn return AMBIGUOUS; } } } return comparison; } @Override public String toString() { return Arrays.deepToString(getAssignmentInfos()) + " (" + getInfo() + ")"; } public boolean haveToIgnoreImplicitArgument() { return ignoreImplicitArgument; } protected int getStartIndex() { return haveToIgnoreImplicitArgument()? 1 : 0; } protected void setIgnoreImplicitArgument(boolean ignoreImplicitArgument) { this.ignoreImplicitArgument = ignoreImplicitArgument; } public static MatchingInfos fromBoolean(boolean bool) { return bool? EXACT_MATCH : NO_MATCH; } }
hendrikvanantwerpen/jchr
src/be/kuleuven/jchr/compiler/CHRIntermediateForm/matching/MatchingInfos.java
2,352
// als beiden coerces zijn, en minstens 1 ervan ambigu,
line_comment
nl
package be.kuleuven.jchr.compiler.CHRIntermediateForm.matching; import static be.kuleuven.jchr.util.comparing.Comparison.AMBIGUOUS; import static be.kuleuven.jchr.util.comparing.Comparison.BETTER; import static be.kuleuven.jchr.util.comparing.Comparison.EQUAL; import static be.kuleuven.jchr.util.comparing.Comparison.WORSE; import java.util.Arrays; import be.kuleuven.jchr.util.comparing.Comparison; /** * @author Peter Van Weert */ public class MatchingInfos extends AbstractMatchingInfo<MatchingInfos> { private MatchingInfo[] assignmentInfos; private boolean ignoreImplicitArgument; public final static MatchingInfos NO_MATCH = new MatchingInfos() { @Override protected byte getInfo() { return NO_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return false; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "NO MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { return other.isMatch()? WORSE : EQUAL; } }, EXACT_MATCH = new MatchingInfos() { @Override public MatchingInfo getAssignmentInfoAt(int index) { return MatchingInfo.EXACT_MATCH; } @Override protected byte getInfo() { return EXACT_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "EXACT MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { throw new UnsupportedOperationException( "This constant wasn't intended to be used in comparisons!" ); } }, AMBIGUOUS_NO_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return BETTER; else if (other.isCoerceMatch()) return AMBIGUOUS; else if (other.isExactMatch()) return WORSE; else return BETTER; } }, AMBIGUOUS_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; /* hoeft niet echt, maar all? */ } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return true; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return AMBIGUOUS; else if (other.isCoerceMatch() || other.isExactMatch()) return WORSE; else return BETTER; } }; protected MatchingInfos() { // NOP (just declaring this has to be a protected constructor) } public MatchingInfos(int arity, boolean ignoreImplicitArgument) { this(new MatchingInfo[arity], ignoreImplicitArgument); } public MatchingInfos(MatchingInfo[] assignmentInfos, boolean ignoreImplicitArgument) { setAssignmentInfos(assignmentInfos); setIgnoreImplicitArgument(ignoreImplicitArgument); } public MatchingInfos(MatchingInfo assignmentInfo, boolean ignoreImplicitArgument) { this(new MatchingInfo[] {assignmentInfo}, ignoreImplicitArgument); } public MatchingInfo[] getAssignmentInfos() { return assignmentInfos; } public int getArity() { return getAssignmentInfos().length; } protected void setAssignmentInfos(MatchingInfo[] assignmentInfos) { this.assignmentInfos = assignmentInfos; } public MatchingInfo getAssignmentInfoAt(int index) { return getAssignmentInfos()[index]; } public void setAssignmentInfoAt(MatchingInfo info, int index) { getAssignmentInfos()[index] = info; } @Override protected byte getInfo() { byte result = 0; for (MatchingInfo info : getAssignmentInfos()) result |= EXACT_MATCH_INFO ^ info.getInfo(); return (byte)(EXACT_MATCH_INFO ^ result); } public Comparison compareTo(MatchingInfos other) { if ((other == NO_MATCH) || (other == AMBIGUOUS_INIT) || (other == AMBIGUOUS_NO_INIT)) return Comparison.flip(other.compareTo(this)); Comparison comparison = Comparison.get(this.getMatchClass() - other.getMatchClass()); if (comparison == EQUAL && isNonExactMatch()) { // als beiden<SUF> // is vergelijking niet mogelijk if (this.isAmbiguous() || other.isAmbiguous()) return AMBIGUOUS; final int arity = this.getArity(); Comparison temp; for (int i = this.getStartIndex(), j = other.getStartIndex(); i < arity; i++, j++) { temp = this.getAssignmentInfoAt(i).compareTo(other.getAssignmentInfoAt(j)); switch (temp) { // als er minstens 1 vergelijking ambigu is, is vergelijking niet mogelijk case AMBIGUOUS: return AMBIGUOUS; /*break;*/ // als er een verschil is moet... case BETTER: case WORSE: if (comparison == EQUAL) // ... na de eerste keer ... comparison = temp; else if (comparison != temp) // ... de vergelijking steeds hetzelfde zijn return AMBIGUOUS; } } } return comparison; } @Override public String toString() { return Arrays.deepToString(getAssignmentInfos()) + " (" + getInfo() + ")"; } public boolean haveToIgnoreImplicitArgument() { return ignoreImplicitArgument; } protected int getStartIndex() { return haveToIgnoreImplicitArgument()? 1 : 0; } protected void setIgnoreImplicitArgument(boolean ignoreImplicitArgument) { this.ignoreImplicitArgument = ignoreImplicitArgument; } public static MatchingInfos fromBoolean(boolean bool) { return bool? EXACT_MATCH : NO_MATCH; } }
199363_4
package be.kuleuven.jchr.compiler.CHRIntermediateForm.matching; import static be.kuleuven.jchr.util.comparing.Comparison.AMBIGUOUS; import static be.kuleuven.jchr.util.comparing.Comparison.BETTER; import static be.kuleuven.jchr.util.comparing.Comparison.EQUAL; import static be.kuleuven.jchr.util.comparing.Comparison.WORSE; import java.util.Arrays; import be.kuleuven.jchr.util.comparing.Comparison; /** * @author Peter Van Weert */ public class MatchingInfos extends AbstractMatchingInfo<MatchingInfos> { private MatchingInfo[] assignmentInfos; private boolean ignoreImplicitArgument; public final static MatchingInfos NO_MATCH = new MatchingInfos() { @Override protected byte getInfo() { return NO_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return false; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "NO MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { return other.isMatch()? WORSE : EQUAL; } }, EXACT_MATCH = new MatchingInfos() { @Override public MatchingInfo getAssignmentInfoAt(int index) { return MatchingInfo.EXACT_MATCH; } @Override protected byte getInfo() { return EXACT_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "EXACT MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { throw new UnsupportedOperationException( "This constant wasn't intended to be used in comparisons!" ); } }, AMBIGUOUS_NO_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return BETTER; else if (other.isCoerceMatch()) return AMBIGUOUS; else if (other.isExactMatch()) return WORSE; else return BETTER; } }, AMBIGUOUS_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; /* hoeft niet echt, maar all? */ } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return true; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return AMBIGUOUS; else if (other.isCoerceMatch() || other.isExactMatch()) return WORSE; else return BETTER; } }; protected MatchingInfos() { // NOP (just declaring this has to be a protected constructor) } public MatchingInfos(int arity, boolean ignoreImplicitArgument) { this(new MatchingInfo[arity], ignoreImplicitArgument); } public MatchingInfos(MatchingInfo[] assignmentInfos, boolean ignoreImplicitArgument) { setAssignmentInfos(assignmentInfos); setIgnoreImplicitArgument(ignoreImplicitArgument); } public MatchingInfos(MatchingInfo assignmentInfo, boolean ignoreImplicitArgument) { this(new MatchingInfo[] {assignmentInfo}, ignoreImplicitArgument); } public MatchingInfo[] getAssignmentInfos() { return assignmentInfos; } public int getArity() { return getAssignmentInfos().length; } protected void setAssignmentInfos(MatchingInfo[] assignmentInfos) { this.assignmentInfos = assignmentInfos; } public MatchingInfo getAssignmentInfoAt(int index) { return getAssignmentInfos()[index]; } public void setAssignmentInfoAt(MatchingInfo info, int index) { getAssignmentInfos()[index] = info; } @Override protected byte getInfo() { byte result = 0; for (MatchingInfo info : getAssignmentInfos()) result |= EXACT_MATCH_INFO ^ info.getInfo(); return (byte)(EXACT_MATCH_INFO ^ result); } public Comparison compareTo(MatchingInfos other) { if ((other == NO_MATCH) || (other == AMBIGUOUS_INIT) || (other == AMBIGUOUS_NO_INIT)) return Comparison.flip(other.compareTo(this)); Comparison comparison = Comparison.get(this.getMatchClass() - other.getMatchClass()); if (comparison == EQUAL && isNonExactMatch()) { // als beiden coerces zijn, en minstens 1 ervan ambigu, // is vergelijking niet mogelijk if (this.isAmbiguous() || other.isAmbiguous()) return AMBIGUOUS; final int arity = this.getArity(); Comparison temp; for (int i = this.getStartIndex(), j = other.getStartIndex(); i < arity; i++, j++) { temp = this.getAssignmentInfoAt(i).compareTo(other.getAssignmentInfoAt(j)); switch (temp) { // als er minstens 1 vergelijking ambigu is, is vergelijking niet mogelijk case AMBIGUOUS: return AMBIGUOUS; /*break;*/ // als er een verschil is moet... case BETTER: case WORSE: if (comparison == EQUAL) // ... na de eerste keer ... comparison = temp; else if (comparison != temp) // ... de vergelijking steeds hetzelfde zijn return AMBIGUOUS; } } } return comparison; } @Override public String toString() { return Arrays.deepToString(getAssignmentInfos()) + " (" + getInfo() + ")"; } public boolean haveToIgnoreImplicitArgument() { return ignoreImplicitArgument; } protected int getStartIndex() { return haveToIgnoreImplicitArgument()? 1 : 0; } protected void setIgnoreImplicitArgument(boolean ignoreImplicitArgument) { this.ignoreImplicitArgument = ignoreImplicitArgument; } public static MatchingInfos fromBoolean(boolean bool) { return bool? EXACT_MATCH : NO_MATCH; } }
hendrikvanantwerpen/jchr
src/be/kuleuven/jchr/compiler/CHRIntermediateForm/matching/MatchingInfos.java
2,352
// is vergelijking niet mogelijk
line_comment
nl
package be.kuleuven.jchr.compiler.CHRIntermediateForm.matching; import static be.kuleuven.jchr.util.comparing.Comparison.AMBIGUOUS; import static be.kuleuven.jchr.util.comparing.Comparison.BETTER; import static be.kuleuven.jchr.util.comparing.Comparison.EQUAL; import static be.kuleuven.jchr.util.comparing.Comparison.WORSE; import java.util.Arrays; import be.kuleuven.jchr.util.comparing.Comparison; /** * @author Peter Van Weert */ public class MatchingInfos extends AbstractMatchingInfo<MatchingInfos> { private MatchingInfo[] assignmentInfos; private boolean ignoreImplicitArgument; public final static MatchingInfos NO_MATCH = new MatchingInfos() { @Override protected byte getInfo() { return NO_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return false; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "NO MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { return other.isMatch()? WORSE : EQUAL; } }, EXACT_MATCH = new MatchingInfos() { @Override public MatchingInfo getAssignmentInfoAt(int index) { return MatchingInfo.EXACT_MATCH; } @Override protected byte getInfo() { return EXACT_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "EXACT MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { throw new UnsupportedOperationException( "This constant wasn't intended to be used in comparisons!" ); } }, AMBIGUOUS_NO_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return BETTER; else if (other.isCoerceMatch()) return AMBIGUOUS; else if (other.isExactMatch()) return WORSE; else return BETTER; } }, AMBIGUOUS_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; /* hoeft niet echt, maar all? */ } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return true; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return AMBIGUOUS; else if (other.isCoerceMatch() || other.isExactMatch()) return WORSE; else return BETTER; } }; protected MatchingInfos() { // NOP (just declaring this has to be a protected constructor) } public MatchingInfos(int arity, boolean ignoreImplicitArgument) { this(new MatchingInfo[arity], ignoreImplicitArgument); } public MatchingInfos(MatchingInfo[] assignmentInfos, boolean ignoreImplicitArgument) { setAssignmentInfos(assignmentInfos); setIgnoreImplicitArgument(ignoreImplicitArgument); } public MatchingInfos(MatchingInfo assignmentInfo, boolean ignoreImplicitArgument) { this(new MatchingInfo[] {assignmentInfo}, ignoreImplicitArgument); } public MatchingInfo[] getAssignmentInfos() { return assignmentInfos; } public int getArity() { return getAssignmentInfos().length; } protected void setAssignmentInfos(MatchingInfo[] assignmentInfos) { this.assignmentInfos = assignmentInfos; } public MatchingInfo getAssignmentInfoAt(int index) { return getAssignmentInfos()[index]; } public void setAssignmentInfoAt(MatchingInfo info, int index) { getAssignmentInfos()[index] = info; } @Override protected byte getInfo() { byte result = 0; for (MatchingInfo info : getAssignmentInfos()) result |= EXACT_MATCH_INFO ^ info.getInfo(); return (byte)(EXACT_MATCH_INFO ^ result); } public Comparison compareTo(MatchingInfos other) { if ((other == NO_MATCH) || (other == AMBIGUOUS_INIT) || (other == AMBIGUOUS_NO_INIT)) return Comparison.flip(other.compareTo(this)); Comparison comparison = Comparison.get(this.getMatchClass() - other.getMatchClass()); if (comparison == EQUAL && isNonExactMatch()) { // als beiden coerces zijn, en minstens 1 ervan ambigu, // is vergelijking<SUF> if (this.isAmbiguous() || other.isAmbiguous()) return AMBIGUOUS; final int arity = this.getArity(); Comparison temp; for (int i = this.getStartIndex(), j = other.getStartIndex(); i < arity; i++, j++) { temp = this.getAssignmentInfoAt(i).compareTo(other.getAssignmentInfoAt(j)); switch (temp) { // als er minstens 1 vergelijking ambigu is, is vergelijking niet mogelijk case AMBIGUOUS: return AMBIGUOUS; /*break;*/ // als er een verschil is moet... case BETTER: case WORSE: if (comparison == EQUAL) // ... na de eerste keer ... comparison = temp; else if (comparison != temp) // ... de vergelijking steeds hetzelfde zijn return AMBIGUOUS; } } } return comparison; } @Override public String toString() { return Arrays.deepToString(getAssignmentInfos()) + " (" + getInfo() + ")"; } public boolean haveToIgnoreImplicitArgument() { return ignoreImplicitArgument; } protected int getStartIndex() { return haveToIgnoreImplicitArgument()? 1 : 0; } protected void setIgnoreImplicitArgument(boolean ignoreImplicitArgument) { this.ignoreImplicitArgument = ignoreImplicitArgument; } public static MatchingInfos fromBoolean(boolean bool) { return bool? EXACT_MATCH : NO_MATCH; } }
199363_5
package be.kuleuven.jchr.compiler.CHRIntermediateForm.matching; import static be.kuleuven.jchr.util.comparing.Comparison.AMBIGUOUS; import static be.kuleuven.jchr.util.comparing.Comparison.BETTER; import static be.kuleuven.jchr.util.comparing.Comparison.EQUAL; import static be.kuleuven.jchr.util.comparing.Comparison.WORSE; import java.util.Arrays; import be.kuleuven.jchr.util.comparing.Comparison; /** * @author Peter Van Weert */ public class MatchingInfos extends AbstractMatchingInfo<MatchingInfos> { private MatchingInfo[] assignmentInfos; private boolean ignoreImplicitArgument; public final static MatchingInfos NO_MATCH = new MatchingInfos() { @Override protected byte getInfo() { return NO_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return false; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "NO MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { return other.isMatch()? WORSE : EQUAL; } }, EXACT_MATCH = new MatchingInfos() { @Override public MatchingInfo getAssignmentInfoAt(int index) { return MatchingInfo.EXACT_MATCH; } @Override protected byte getInfo() { return EXACT_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "EXACT MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { throw new UnsupportedOperationException( "This constant wasn't intended to be used in comparisons!" ); } }, AMBIGUOUS_NO_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return BETTER; else if (other.isCoerceMatch()) return AMBIGUOUS; else if (other.isExactMatch()) return WORSE; else return BETTER; } }, AMBIGUOUS_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; /* hoeft niet echt, maar all? */ } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return true; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return AMBIGUOUS; else if (other.isCoerceMatch() || other.isExactMatch()) return WORSE; else return BETTER; } }; protected MatchingInfos() { // NOP (just declaring this has to be a protected constructor) } public MatchingInfos(int arity, boolean ignoreImplicitArgument) { this(new MatchingInfo[arity], ignoreImplicitArgument); } public MatchingInfos(MatchingInfo[] assignmentInfos, boolean ignoreImplicitArgument) { setAssignmentInfos(assignmentInfos); setIgnoreImplicitArgument(ignoreImplicitArgument); } public MatchingInfos(MatchingInfo assignmentInfo, boolean ignoreImplicitArgument) { this(new MatchingInfo[] {assignmentInfo}, ignoreImplicitArgument); } public MatchingInfo[] getAssignmentInfos() { return assignmentInfos; } public int getArity() { return getAssignmentInfos().length; } protected void setAssignmentInfos(MatchingInfo[] assignmentInfos) { this.assignmentInfos = assignmentInfos; } public MatchingInfo getAssignmentInfoAt(int index) { return getAssignmentInfos()[index]; } public void setAssignmentInfoAt(MatchingInfo info, int index) { getAssignmentInfos()[index] = info; } @Override protected byte getInfo() { byte result = 0; for (MatchingInfo info : getAssignmentInfos()) result |= EXACT_MATCH_INFO ^ info.getInfo(); return (byte)(EXACT_MATCH_INFO ^ result); } public Comparison compareTo(MatchingInfos other) { if ((other == NO_MATCH) || (other == AMBIGUOUS_INIT) || (other == AMBIGUOUS_NO_INIT)) return Comparison.flip(other.compareTo(this)); Comparison comparison = Comparison.get(this.getMatchClass() - other.getMatchClass()); if (comparison == EQUAL && isNonExactMatch()) { // als beiden coerces zijn, en minstens 1 ervan ambigu, // is vergelijking niet mogelijk if (this.isAmbiguous() || other.isAmbiguous()) return AMBIGUOUS; final int arity = this.getArity(); Comparison temp; for (int i = this.getStartIndex(), j = other.getStartIndex(); i < arity; i++, j++) { temp = this.getAssignmentInfoAt(i).compareTo(other.getAssignmentInfoAt(j)); switch (temp) { // als er minstens 1 vergelijking ambigu is, is vergelijking niet mogelijk case AMBIGUOUS: return AMBIGUOUS; /*break;*/ // als er een verschil is moet... case BETTER: case WORSE: if (comparison == EQUAL) // ... na de eerste keer ... comparison = temp; else if (comparison != temp) // ... de vergelijking steeds hetzelfde zijn return AMBIGUOUS; } } } return comparison; } @Override public String toString() { return Arrays.deepToString(getAssignmentInfos()) + " (" + getInfo() + ")"; } public boolean haveToIgnoreImplicitArgument() { return ignoreImplicitArgument; } protected int getStartIndex() { return haveToIgnoreImplicitArgument()? 1 : 0; } protected void setIgnoreImplicitArgument(boolean ignoreImplicitArgument) { this.ignoreImplicitArgument = ignoreImplicitArgument; } public static MatchingInfos fromBoolean(boolean bool) { return bool? EXACT_MATCH : NO_MATCH; } }
hendrikvanantwerpen/jchr
src/be/kuleuven/jchr/compiler/CHRIntermediateForm/matching/MatchingInfos.java
2,352
// als er minstens 1 vergelijking ambigu is, is vergelijking niet mogelijk
line_comment
nl
package be.kuleuven.jchr.compiler.CHRIntermediateForm.matching; import static be.kuleuven.jchr.util.comparing.Comparison.AMBIGUOUS; import static be.kuleuven.jchr.util.comparing.Comparison.BETTER; import static be.kuleuven.jchr.util.comparing.Comparison.EQUAL; import static be.kuleuven.jchr.util.comparing.Comparison.WORSE; import java.util.Arrays; import be.kuleuven.jchr.util.comparing.Comparison; /** * @author Peter Van Weert */ public class MatchingInfos extends AbstractMatchingInfo<MatchingInfos> { private MatchingInfo[] assignmentInfos; private boolean ignoreImplicitArgument; public final static MatchingInfos NO_MATCH = new MatchingInfos() { @Override protected byte getInfo() { return NO_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return false; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "NO MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { return other.isMatch()? WORSE : EQUAL; } }, EXACT_MATCH = new MatchingInfos() { @Override public MatchingInfo getAssignmentInfoAt(int index) { return MatchingInfo.EXACT_MATCH; } @Override protected byte getInfo() { return EXACT_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "EXACT MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { throw new UnsupportedOperationException( "This constant wasn't intended to be used in comparisons!" ); } }, AMBIGUOUS_NO_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return BETTER; else if (other.isCoerceMatch()) return AMBIGUOUS; else if (other.isExactMatch()) return WORSE; else return BETTER; } }, AMBIGUOUS_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; /* hoeft niet echt, maar all? */ } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return true; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return AMBIGUOUS; else if (other.isCoerceMatch() || other.isExactMatch()) return WORSE; else return BETTER; } }; protected MatchingInfos() { // NOP (just declaring this has to be a protected constructor) } public MatchingInfos(int arity, boolean ignoreImplicitArgument) { this(new MatchingInfo[arity], ignoreImplicitArgument); } public MatchingInfos(MatchingInfo[] assignmentInfos, boolean ignoreImplicitArgument) { setAssignmentInfos(assignmentInfos); setIgnoreImplicitArgument(ignoreImplicitArgument); } public MatchingInfos(MatchingInfo assignmentInfo, boolean ignoreImplicitArgument) { this(new MatchingInfo[] {assignmentInfo}, ignoreImplicitArgument); } public MatchingInfo[] getAssignmentInfos() { return assignmentInfos; } public int getArity() { return getAssignmentInfos().length; } protected void setAssignmentInfos(MatchingInfo[] assignmentInfos) { this.assignmentInfos = assignmentInfos; } public MatchingInfo getAssignmentInfoAt(int index) { return getAssignmentInfos()[index]; } public void setAssignmentInfoAt(MatchingInfo info, int index) { getAssignmentInfos()[index] = info; } @Override protected byte getInfo() { byte result = 0; for (MatchingInfo info : getAssignmentInfos()) result |= EXACT_MATCH_INFO ^ info.getInfo(); return (byte)(EXACT_MATCH_INFO ^ result); } public Comparison compareTo(MatchingInfos other) { if ((other == NO_MATCH) || (other == AMBIGUOUS_INIT) || (other == AMBIGUOUS_NO_INIT)) return Comparison.flip(other.compareTo(this)); Comparison comparison = Comparison.get(this.getMatchClass() - other.getMatchClass()); if (comparison == EQUAL && isNonExactMatch()) { // als beiden coerces zijn, en minstens 1 ervan ambigu, // is vergelijking niet mogelijk if (this.isAmbiguous() || other.isAmbiguous()) return AMBIGUOUS; final int arity = this.getArity(); Comparison temp; for (int i = this.getStartIndex(), j = other.getStartIndex(); i < arity; i++, j++) { temp = this.getAssignmentInfoAt(i).compareTo(other.getAssignmentInfoAt(j)); switch (temp) { // als er<SUF> case AMBIGUOUS: return AMBIGUOUS; /*break;*/ // als er een verschil is moet... case BETTER: case WORSE: if (comparison == EQUAL) // ... na de eerste keer ... comparison = temp; else if (comparison != temp) // ... de vergelijking steeds hetzelfde zijn return AMBIGUOUS; } } } return comparison; } @Override public String toString() { return Arrays.deepToString(getAssignmentInfos()) + " (" + getInfo() + ")"; } public boolean haveToIgnoreImplicitArgument() { return ignoreImplicitArgument; } protected int getStartIndex() { return haveToIgnoreImplicitArgument()? 1 : 0; } protected void setIgnoreImplicitArgument(boolean ignoreImplicitArgument) { this.ignoreImplicitArgument = ignoreImplicitArgument; } public static MatchingInfos fromBoolean(boolean bool) { return bool? EXACT_MATCH : NO_MATCH; } }
199363_6
package be.kuleuven.jchr.compiler.CHRIntermediateForm.matching; import static be.kuleuven.jchr.util.comparing.Comparison.AMBIGUOUS; import static be.kuleuven.jchr.util.comparing.Comparison.BETTER; import static be.kuleuven.jchr.util.comparing.Comparison.EQUAL; import static be.kuleuven.jchr.util.comparing.Comparison.WORSE; import java.util.Arrays; import be.kuleuven.jchr.util.comparing.Comparison; /** * @author Peter Van Weert */ public class MatchingInfos extends AbstractMatchingInfo<MatchingInfos> { private MatchingInfo[] assignmentInfos; private boolean ignoreImplicitArgument; public final static MatchingInfos NO_MATCH = new MatchingInfos() { @Override protected byte getInfo() { return NO_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return false; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "NO MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { return other.isMatch()? WORSE : EQUAL; } }, EXACT_MATCH = new MatchingInfos() { @Override public MatchingInfo getAssignmentInfoAt(int index) { return MatchingInfo.EXACT_MATCH; } @Override protected byte getInfo() { return EXACT_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "EXACT MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { throw new UnsupportedOperationException( "This constant wasn't intended to be used in comparisons!" ); } }, AMBIGUOUS_NO_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return BETTER; else if (other.isCoerceMatch()) return AMBIGUOUS; else if (other.isExactMatch()) return WORSE; else return BETTER; } }, AMBIGUOUS_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; /* hoeft niet echt, maar all? */ } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return true; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return AMBIGUOUS; else if (other.isCoerceMatch() || other.isExactMatch()) return WORSE; else return BETTER; } }; protected MatchingInfos() { // NOP (just declaring this has to be a protected constructor) } public MatchingInfos(int arity, boolean ignoreImplicitArgument) { this(new MatchingInfo[arity], ignoreImplicitArgument); } public MatchingInfos(MatchingInfo[] assignmentInfos, boolean ignoreImplicitArgument) { setAssignmentInfos(assignmentInfos); setIgnoreImplicitArgument(ignoreImplicitArgument); } public MatchingInfos(MatchingInfo assignmentInfo, boolean ignoreImplicitArgument) { this(new MatchingInfo[] {assignmentInfo}, ignoreImplicitArgument); } public MatchingInfo[] getAssignmentInfos() { return assignmentInfos; } public int getArity() { return getAssignmentInfos().length; } protected void setAssignmentInfos(MatchingInfo[] assignmentInfos) { this.assignmentInfos = assignmentInfos; } public MatchingInfo getAssignmentInfoAt(int index) { return getAssignmentInfos()[index]; } public void setAssignmentInfoAt(MatchingInfo info, int index) { getAssignmentInfos()[index] = info; } @Override protected byte getInfo() { byte result = 0; for (MatchingInfo info : getAssignmentInfos()) result |= EXACT_MATCH_INFO ^ info.getInfo(); return (byte)(EXACT_MATCH_INFO ^ result); } public Comparison compareTo(MatchingInfos other) { if ((other == NO_MATCH) || (other == AMBIGUOUS_INIT) || (other == AMBIGUOUS_NO_INIT)) return Comparison.flip(other.compareTo(this)); Comparison comparison = Comparison.get(this.getMatchClass() - other.getMatchClass()); if (comparison == EQUAL && isNonExactMatch()) { // als beiden coerces zijn, en minstens 1 ervan ambigu, // is vergelijking niet mogelijk if (this.isAmbiguous() || other.isAmbiguous()) return AMBIGUOUS; final int arity = this.getArity(); Comparison temp; for (int i = this.getStartIndex(), j = other.getStartIndex(); i < arity; i++, j++) { temp = this.getAssignmentInfoAt(i).compareTo(other.getAssignmentInfoAt(j)); switch (temp) { // als er minstens 1 vergelijking ambigu is, is vergelijking niet mogelijk case AMBIGUOUS: return AMBIGUOUS; /*break;*/ // als er een verschil is moet... case BETTER: case WORSE: if (comparison == EQUAL) // ... na de eerste keer ... comparison = temp; else if (comparison != temp) // ... de vergelijking steeds hetzelfde zijn return AMBIGUOUS; } } } return comparison; } @Override public String toString() { return Arrays.deepToString(getAssignmentInfos()) + " (" + getInfo() + ")"; } public boolean haveToIgnoreImplicitArgument() { return ignoreImplicitArgument; } protected int getStartIndex() { return haveToIgnoreImplicitArgument()? 1 : 0; } protected void setIgnoreImplicitArgument(boolean ignoreImplicitArgument) { this.ignoreImplicitArgument = ignoreImplicitArgument; } public static MatchingInfos fromBoolean(boolean bool) { return bool? EXACT_MATCH : NO_MATCH; } }
hendrikvanantwerpen/jchr
src/be/kuleuven/jchr/compiler/CHRIntermediateForm/matching/MatchingInfos.java
2,352
// als er een verschil is moet...
line_comment
nl
package be.kuleuven.jchr.compiler.CHRIntermediateForm.matching; import static be.kuleuven.jchr.util.comparing.Comparison.AMBIGUOUS; import static be.kuleuven.jchr.util.comparing.Comparison.BETTER; import static be.kuleuven.jchr.util.comparing.Comparison.EQUAL; import static be.kuleuven.jchr.util.comparing.Comparison.WORSE; import java.util.Arrays; import be.kuleuven.jchr.util.comparing.Comparison; /** * @author Peter Van Weert */ public class MatchingInfos extends AbstractMatchingInfo<MatchingInfos> { private MatchingInfo[] assignmentInfos; private boolean ignoreImplicitArgument; public final static MatchingInfos NO_MATCH = new MatchingInfos() { @Override protected byte getInfo() { return NO_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return false; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "NO MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { return other.isMatch()? WORSE : EQUAL; } }, EXACT_MATCH = new MatchingInfos() { @Override public MatchingInfo getAssignmentInfoAt(int index) { return MatchingInfo.EXACT_MATCH; } @Override protected byte getInfo() { return EXACT_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "EXACT MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { throw new UnsupportedOperationException( "This constant wasn't intended to be used in comparisons!" ); } }, AMBIGUOUS_NO_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return BETTER; else if (other.isCoerceMatch()) return AMBIGUOUS; else if (other.isExactMatch()) return WORSE; else return BETTER; } }, AMBIGUOUS_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; /* hoeft niet echt, maar all? */ } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return true; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return AMBIGUOUS; else if (other.isCoerceMatch() || other.isExactMatch()) return WORSE; else return BETTER; } }; protected MatchingInfos() { // NOP (just declaring this has to be a protected constructor) } public MatchingInfos(int arity, boolean ignoreImplicitArgument) { this(new MatchingInfo[arity], ignoreImplicitArgument); } public MatchingInfos(MatchingInfo[] assignmentInfos, boolean ignoreImplicitArgument) { setAssignmentInfos(assignmentInfos); setIgnoreImplicitArgument(ignoreImplicitArgument); } public MatchingInfos(MatchingInfo assignmentInfo, boolean ignoreImplicitArgument) { this(new MatchingInfo[] {assignmentInfo}, ignoreImplicitArgument); } public MatchingInfo[] getAssignmentInfos() { return assignmentInfos; } public int getArity() { return getAssignmentInfos().length; } protected void setAssignmentInfos(MatchingInfo[] assignmentInfos) { this.assignmentInfos = assignmentInfos; } public MatchingInfo getAssignmentInfoAt(int index) { return getAssignmentInfos()[index]; } public void setAssignmentInfoAt(MatchingInfo info, int index) { getAssignmentInfos()[index] = info; } @Override protected byte getInfo() { byte result = 0; for (MatchingInfo info : getAssignmentInfos()) result |= EXACT_MATCH_INFO ^ info.getInfo(); return (byte)(EXACT_MATCH_INFO ^ result); } public Comparison compareTo(MatchingInfos other) { if ((other == NO_MATCH) || (other == AMBIGUOUS_INIT) || (other == AMBIGUOUS_NO_INIT)) return Comparison.flip(other.compareTo(this)); Comparison comparison = Comparison.get(this.getMatchClass() - other.getMatchClass()); if (comparison == EQUAL && isNonExactMatch()) { // als beiden coerces zijn, en minstens 1 ervan ambigu, // is vergelijking niet mogelijk if (this.isAmbiguous() || other.isAmbiguous()) return AMBIGUOUS; final int arity = this.getArity(); Comparison temp; for (int i = this.getStartIndex(), j = other.getStartIndex(); i < arity; i++, j++) { temp = this.getAssignmentInfoAt(i).compareTo(other.getAssignmentInfoAt(j)); switch (temp) { // als er minstens 1 vergelijking ambigu is, is vergelijking niet mogelijk case AMBIGUOUS: return AMBIGUOUS; /*break;*/ // als er<SUF> case BETTER: case WORSE: if (comparison == EQUAL) // ... na de eerste keer ... comparison = temp; else if (comparison != temp) // ... de vergelijking steeds hetzelfde zijn return AMBIGUOUS; } } } return comparison; } @Override public String toString() { return Arrays.deepToString(getAssignmentInfos()) + " (" + getInfo() + ")"; } public boolean haveToIgnoreImplicitArgument() { return ignoreImplicitArgument; } protected int getStartIndex() { return haveToIgnoreImplicitArgument()? 1 : 0; } protected void setIgnoreImplicitArgument(boolean ignoreImplicitArgument) { this.ignoreImplicitArgument = ignoreImplicitArgument; } public static MatchingInfos fromBoolean(boolean bool) { return bool? EXACT_MATCH : NO_MATCH; } }
199363_7
package be.kuleuven.jchr.compiler.CHRIntermediateForm.matching; import static be.kuleuven.jchr.util.comparing.Comparison.AMBIGUOUS; import static be.kuleuven.jchr.util.comparing.Comparison.BETTER; import static be.kuleuven.jchr.util.comparing.Comparison.EQUAL; import static be.kuleuven.jchr.util.comparing.Comparison.WORSE; import java.util.Arrays; import be.kuleuven.jchr.util.comparing.Comparison; /** * @author Peter Van Weert */ public class MatchingInfos extends AbstractMatchingInfo<MatchingInfos> { private MatchingInfo[] assignmentInfos; private boolean ignoreImplicitArgument; public final static MatchingInfos NO_MATCH = new MatchingInfos() { @Override protected byte getInfo() { return NO_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return false; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "NO MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { return other.isMatch()? WORSE : EQUAL; } }, EXACT_MATCH = new MatchingInfos() { @Override public MatchingInfo getAssignmentInfoAt(int index) { return MatchingInfo.EXACT_MATCH; } @Override protected byte getInfo() { return EXACT_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "EXACT MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { throw new UnsupportedOperationException( "This constant wasn't intended to be used in comparisons!" ); } }, AMBIGUOUS_NO_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return BETTER; else if (other.isCoerceMatch()) return AMBIGUOUS; else if (other.isExactMatch()) return WORSE; else return BETTER; } }, AMBIGUOUS_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; /* hoeft niet echt, maar all? */ } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return true; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return AMBIGUOUS; else if (other.isCoerceMatch() || other.isExactMatch()) return WORSE; else return BETTER; } }; protected MatchingInfos() { // NOP (just declaring this has to be a protected constructor) } public MatchingInfos(int arity, boolean ignoreImplicitArgument) { this(new MatchingInfo[arity], ignoreImplicitArgument); } public MatchingInfos(MatchingInfo[] assignmentInfos, boolean ignoreImplicitArgument) { setAssignmentInfos(assignmentInfos); setIgnoreImplicitArgument(ignoreImplicitArgument); } public MatchingInfos(MatchingInfo assignmentInfo, boolean ignoreImplicitArgument) { this(new MatchingInfo[] {assignmentInfo}, ignoreImplicitArgument); } public MatchingInfo[] getAssignmentInfos() { return assignmentInfos; } public int getArity() { return getAssignmentInfos().length; } protected void setAssignmentInfos(MatchingInfo[] assignmentInfos) { this.assignmentInfos = assignmentInfos; } public MatchingInfo getAssignmentInfoAt(int index) { return getAssignmentInfos()[index]; } public void setAssignmentInfoAt(MatchingInfo info, int index) { getAssignmentInfos()[index] = info; } @Override protected byte getInfo() { byte result = 0; for (MatchingInfo info : getAssignmentInfos()) result |= EXACT_MATCH_INFO ^ info.getInfo(); return (byte)(EXACT_MATCH_INFO ^ result); } public Comparison compareTo(MatchingInfos other) { if ((other == NO_MATCH) || (other == AMBIGUOUS_INIT) || (other == AMBIGUOUS_NO_INIT)) return Comparison.flip(other.compareTo(this)); Comparison comparison = Comparison.get(this.getMatchClass() - other.getMatchClass()); if (comparison == EQUAL && isNonExactMatch()) { // als beiden coerces zijn, en minstens 1 ervan ambigu, // is vergelijking niet mogelijk if (this.isAmbiguous() || other.isAmbiguous()) return AMBIGUOUS; final int arity = this.getArity(); Comparison temp; for (int i = this.getStartIndex(), j = other.getStartIndex(); i < arity; i++, j++) { temp = this.getAssignmentInfoAt(i).compareTo(other.getAssignmentInfoAt(j)); switch (temp) { // als er minstens 1 vergelijking ambigu is, is vergelijking niet mogelijk case AMBIGUOUS: return AMBIGUOUS; /*break;*/ // als er een verschil is moet... case BETTER: case WORSE: if (comparison == EQUAL) // ... na de eerste keer ... comparison = temp; else if (comparison != temp) // ... de vergelijking steeds hetzelfde zijn return AMBIGUOUS; } } } return comparison; } @Override public String toString() { return Arrays.deepToString(getAssignmentInfos()) + " (" + getInfo() + ")"; } public boolean haveToIgnoreImplicitArgument() { return ignoreImplicitArgument; } protected int getStartIndex() { return haveToIgnoreImplicitArgument()? 1 : 0; } protected void setIgnoreImplicitArgument(boolean ignoreImplicitArgument) { this.ignoreImplicitArgument = ignoreImplicitArgument; } public static MatchingInfos fromBoolean(boolean bool) { return bool? EXACT_MATCH : NO_MATCH; } }
hendrikvanantwerpen/jchr
src/be/kuleuven/jchr/compiler/CHRIntermediateForm/matching/MatchingInfos.java
2,352
// ... na de eerste keer ...
line_comment
nl
package be.kuleuven.jchr.compiler.CHRIntermediateForm.matching; import static be.kuleuven.jchr.util.comparing.Comparison.AMBIGUOUS; import static be.kuleuven.jchr.util.comparing.Comparison.BETTER; import static be.kuleuven.jchr.util.comparing.Comparison.EQUAL; import static be.kuleuven.jchr.util.comparing.Comparison.WORSE; import java.util.Arrays; import be.kuleuven.jchr.util.comparing.Comparison; /** * @author Peter Van Weert */ public class MatchingInfos extends AbstractMatchingInfo<MatchingInfos> { private MatchingInfo[] assignmentInfos; private boolean ignoreImplicitArgument; public final static MatchingInfos NO_MATCH = new MatchingInfos() { @Override protected byte getInfo() { return NO_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return false; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "NO MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { return other.isMatch()? WORSE : EQUAL; } }, EXACT_MATCH = new MatchingInfos() { @Override public MatchingInfo getAssignmentInfoAt(int index) { return MatchingInfo.EXACT_MATCH; } @Override protected byte getInfo() { return EXACT_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "EXACT MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { throw new UnsupportedOperationException( "This constant wasn't intended to be used in comparisons!" ); } }, AMBIGUOUS_NO_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return BETTER; else if (other.isCoerceMatch()) return AMBIGUOUS; else if (other.isExactMatch()) return WORSE; else return BETTER; } }, AMBIGUOUS_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; /* hoeft niet echt, maar all? */ } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return true; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return AMBIGUOUS; else if (other.isCoerceMatch() || other.isExactMatch()) return WORSE; else return BETTER; } }; protected MatchingInfos() { // NOP (just declaring this has to be a protected constructor) } public MatchingInfos(int arity, boolean ignoreImplicitArgument) { this(new MatchingInfo[arity], ignoreImplicitArgument); } public MatchingInfos(MatchingInfo[] assignmentInfos, boolean ignoreImplicitArgument) { setAssignmentInfos(assignmentInfos); setIgnoreImplicitArgument(ignoreImplicitArgument); } public MatchingInfos(MatchingInfo assignmentInfo, boolean ignoreImplicitArgument) { this(new MatchingInfo[] {assignmentInfo}, ignoreImplicitArgument); } public MatchingInfo[] getAssignmentInfos() { return assignmentInfos; } public int getArity() { return getAssignmentInfos().length; } protected void setAssignmentInfos(MatchingInfo[] assignmentInfos) { this.assignmentInfos = assignmentInfos; } public MatchingInfo getAssignmentInfoAt(int index) { return getAssignmentInfos()[index]; } public void setAssignmentInfoAt(MatchingInfo info, int index) { getAssignmentInfos()[index] = info; } @Override protected byte getInfo() { byte result = 0; for (MatchingInfo info : getAssignmentInfos()) result |= EXACT_MATCH_INFO ^ info.getInfo(); return (byte)(EXACT_MATCH_INFO ^ result); } public Comparison compareTo(MatchingInfos other) { if ((other == NO_MATCH) || (other == AMBIGUOUS_INIT) || (other == AMBIGUOUS_NO_INIT)) return Comparison.flip(other.compareTo(this)); Comparison comparison = Comparison.get(this.getMatchClass() - other.getMatchClass()); if (comparison == EQUAL && isNonExactMatch()) { // als beiden coerces zijn, en minstens 1 ervan ambigu, // is vergelijking niet mogelijk if (this.isAmbiguous() || other.isAmbiguous()) return AMBIGUOUS; final int arity = this.getArity(); Comparison temp; for (int i = this.getStartIndex(), j = other.getStartIndex(); i < arity; i++, j++) { temp = this.getAssignmentInfoAt(i).compareTo(other.getAssignmentInfoAt(j)); switch (temp) { // als er minstens 1 vergelijking ambigu is, is vergelijking niet mogelijk case AMBIGUOUS: return AMBIGUOUS; /*break;*/ // als er een verschil is moet... case BETTER: case WORSE: if (comparison == EQUAL) // ... na<SUF> comparison = temp; else if (comparison != temp) // ... de vergelijking steeds hetzelfde zijn return AMBIGUOUS; } } } return comparison; } @Override public String toString() { return Arrays.deepToString(getAssignmentInfos()) + " (" + getInfo() + ")"; } public boolean haveToIgnoreImplicitArgument() { return ignoreImplicitArgument; } protected int getStartIndex() { return haveToIgnoreImplicitArgument()? 1 : 0; } protected void setIgnoreImplicitArgument(boolean ignoreImplicitArgument) { this.ignoreImplicitArgument = ignoreImplicitArgument; } public static MatchingInfos fromBoolean(boolean bool) { return bool? EXACT_MATCH : NO_MATCH; } }
199363_8
package be.kuleuven.jchr.compiler.CHRIntermediateForm.matching; import static be.kuleuven.jchr.util.comparing.Comparison.AMBIGUOUS; import static be.kuleuven.jchr.util.comparing.Comparison.BETTER; import static be.kuleuven.jchr.util.comparing.Comparison.EQUAL; import static be.kuleuven.jchr.util.comparing.Comparison.WORSE; import java.util.Arrays; import be.kuleuven.jchr.util.comparing.Comparison; /** * @author Peter Van Weert */ public class MatchingInfos extends AbstractMatchingInfo<MatchingInfos> { private MatchingInfo[] assignmentInfos; private boolean ignoreImplicitArgument; public final static MatchingInfos NO_MATCH = new MatchingInfos() { @Override protected byte getInfo() { return NO_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return false; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "NO MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { return other.isMatch()? WORSE : EQUAL; } }, EXACT_MATCH = new MatchingInfos() { @Override public MatchingInfo getAssignmentInfoAt(int index) { return MatchingInfo.EXACT_MATCH; } @Override protected byte getInfo() { return EXACT_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "EXACT MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { throw new UnsupportedOperationException( "This constant wasn't intended to be used in comparisons!" ); } }, AMBIGUOUS_NO_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return BETTER; else if (other.isCoerceMatch()) return AMBIGUOUS; else if (other.isExactMatch()) return WORSE; else return BETTER; } }, AMBIGUOUS_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; /* hoeft niet echt, maar all? */ } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return true; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return AMBIGUOUS; else if (other.isCoerceMatch() || other.isExactMatch()) return WORSE; else return BETTER; } }; protected MatchingInfos() { // NOP (just declaring this has to be a protected constructor) } public MatchingInfos(int arity, boolean ignoreImplicitArgument) { this(new MatchingInfo[arity], ignoreImplicitArgument); } public MatchingInfos(MatchingInfo[] assignmentInfos, boolean ignoreImplicitArgument) { setAssignmentInfos(assignmentInfos); setIgnoreImplicitArgument(ignoreImplicitArgument); } public MatchingInfos(MatchingInfo assignmentInfo, boolean ignoreImplicitArgument) { this(new MatchingInfo[] {assignmentInfo}, ignoreImplicitArgument); } public MatchingInfo[] getAssignmentInfos() { return assignmentInfos; } public int getArity() { return getAssignmentInfos().length; } protected void setAssignmentInfos(MatchingInfo[] assignmentInfos) { this.assignmentInfos = assignmentInfos; } public MatchingInfo getAssignmentInfoAt(int index) { return getAssignmentInfos()[index]; } public void setAssignmentInfoAt(MatchingInfo info, int index) { getAssignmentInfos()[index] = info; } @Override protected byte getInfo() { byte result = 0; for (MatchingInfo info : getAssignmentInfos()) result |= EXACT_MATCH_INFO ^ info.getInfo(); return (byte)(EXACT_MATCH_INFO ^ result); } public Comparison compareTo(MatchingInfos other) { if ((other == NO_MATCH) || (other == AMBIGUOUS_INIT) || (other == AMBIGUOUS_NO_INIT)) return Comparison.flip(other.compareTo(this)); Comparison comparison = Comparison.get(this.getMatchClass() - other.getMatchClass()); if (comparison == EQUAL && isNonExactMatch()) { // als beiden coerces zijn, en minstens 1 ervan ambigu, // is vergelijking niet mogelijk if (this.isAmbiguous() || other.isAmbiguous()) return AMBIGUOUS; final int arity = this.getArity(); Comparison temp; for (int i = this.getStartIndex(), j = other.getStartIndex(); i < arity; i++, j++) { temp = this.getAssignmentInfoAt(i).compareTo(other.getAssignmentInfoAt(j)); switch (temp) { // als er minstens 1 vergelijking ambigu is, is vergelijking niet mogelijk case AMBIGUOUS: return AMBIGUOUS; /*break;*/ // als er een verschil is moet... case BETTER: case WORSE: if (comparison == EQUAL) // ... na de eerste keer ... comparison = temp; else if (comparison != temp) // ... de vergelijking steeds hetzelfde zijn return AMBIGUOUS; } } } return comparison; } @Override public String toString() { return Arrays.deepToString(getAssignmentInfos()) + " (" + getInfo() + ")"; } public boolean haveToIgnoreImplicitArgument() { return ignoreImplicitArgument; } protected int getStartIndex() { return haveToIgnoreImplicitArgument()? 1 : 0; } protected void setIgnoreImplicitArgument(boolean ignoreImplicitArgument) { this.ignoreImplicitArgument = ignoreImplicitArgument; } public static MatchingInfos fromBoolean(boolean bool) { return bool? EXACT_MATCH : NO_MATCH; } }
hendrikvanantwerpen/jchr
src/be/kuleuven/jchr/compiler/CHRIntermediateForm/matching/MatchingInfos.java
2,352
// ... de vergelijking steeds hetzelfde zijn
line_comment
nl
package be.kuleuven.jchr.compiler.CHRIntermediateForm.matching; import static be.kuleuven.jchr.util.comparing.Comparison.AMBIGUOUS; import static be.kuleuven.jchr.util.comparing.Comparison.BETTER; import static be.kuleuven.jchr.util.comparing.Comparison.EQUAL; import static be.kuleuven.jchr.util.comparing.Comparison.WORSE; import java.util.Arrays; import be.kuleuven.jchr.util.comparing.Comparison; /** * @author Peter Van Weert */ public class MatchingInfos extends AbstractMatchingInfo<MatchingInfos> { private MatchingInfo[] assignmentInfos; private boolean ignoreImplicitArgument; public final static MatchingInfos NO_MATCH = new MatchingInfos() { @Override protected byte getInfo() { return NO_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return false; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "NO MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { return other.isMatch()? WORSE : EQUAL; } }, EXACT_MATCH = new MatchingInfos() { @Override public MatchingInfo getAssignmentInfoAt(int index) { return MatchingInfo.EXACT_MATCH; } @Override protected byte getInfo() { return EXACT_MATCH_INFO; } @Override public boolean isAmbiguous() { return false; } @Override public boolean isCoerceMatch() { return false; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return false; } @Override public String toString() { return "EXACT MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { throw new UnsupportedOperationException( "This constant wasn't intended to be used in comparisons!" ); } }, AMBIGUOUS_NO_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return false; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return BETTER; else if (other.isCoerceMatch()) return AMBIGUOUS; else if (other.isExactMatch()) return WORSE; else return BETTER; } }, AMBIGUOUS_INIT = new MatchingInfos() { @Override protected byte getInfo() { return AMBIGUOUS_INFO; } @Override public boolean isAmbiguous() { return true; } @Override public boolean isCoerceMatch() { return true; /* hoeft niet echt, maar all? */ } @Override public boolean isExactMatch() { return false; } @Override public boolean isMatch() { return true; } @Override public boolean isInitMatch() { return true; } @Override public boolean isNonAmbiguousMatch() { return false; } @Override public boolean isNonExactMatch() { return true; } @Override public String toString() { return "AMBIGUOUS MATCH"; } @Override public Comparison compareTo(MatchingInfos other) { if (other.isInitMatch()) return AMBIGUOUS; else if (other.isCoerceMatch() || other.isExactMatch()) return WORSE; else return BETTER; } }; protected MatchingInfos() { // NOP (just declaring this has to be a protected constructor) } public MatchingInfos(int arity, boolean ignoreImplicitArgument) { this(new MatchingInfo[arity], ignoreImplicitArgument); } public MatchingInfos(MatchingInfo[] assignmentInfos, boolean ignoreImplicitArgument) { setAssignmentInfos(assignmentInfos); setIgnoreImplicitArgument(ignoreImplicitArgument); } public MatchingInfos(MatchingInfo assignmentInfo, boolean ignoreImplicitArgument) { this(new MatchingInfo[] {assignmentInfo}, ignoreImplicitArgument); } public MatchingInfo[] getAssignmentInfos() { return assignmentInfos; } public int getArity() { return getAssignmentInfos().length; } protected void setAssignmentInfos(MatchingInfo[] assignmentInfos) { this.assignmentInfos = assignmentInfos; } public MatchingInfo getAssignmentInfoAt(int index) { return getAssignmentInfos()[index]; } public void setAssignmentInfoAt(MatchingInfo info, int index) { getAssignmentInfos()[index] = info; } @Override protected byte getInfo() { byte result = 0; for (MatchingInfo info : getAssignmentInfos()) result |= EXACT_MATCH_INFO ^ info.getInfo(); return (byte)(EXACT_MATCH_INFO ^ result); } public Comparison compareTo(MatchingInfos other) { if ((other == NO_MATCH) || (other == AMBIGUOUS_INIT) || (other == AMBIGUOUS_NO_INIT)) return Comparison.flip(other.compareTo(this)); Comparison comparison = Comparison.get(this.getMatchClass() - other.getMatchClass()); if (comparison == EQUAL && isNonExactMatch()) { // als beiden coerces zijn, en minstens 1 ervan ambigu, // is vergelijking niet mogelijk if (this.isAmbiguous() || other.isAmbiguous()) return AMBIGUOUS; final int arity = this.getArity(); Comparison temp; for (int i = this.getStartIndex(), j = other.getStartIndex(); i < arity; i++, j++) { temp = this.getAssignmentInfoAt(i).compareTo(other.getAssignmentInfoAt(j)); switch (temp) { // als er minstens 1 vergelijking ambigu is, is vergelijking niet mogelijk case AMBIGUOUS: return AMBIGUOUS; /*break;*/ // als er een verschil is moet... case BETTER: case WORSE: if (comparison == EQUAL) // ... na de eerste keer ... comparison = temp; else if (comparison != temp) // ... de<SUF> return AMBIGUOUS; } } } return comparison; } @Override public String toString() { return Arrays.deepToString(getAssignmentInfos()) + " (" + getInfo() + ")"; } public boolean haveToIgnoreImplicitArgument() { return ignoreImplicitArgument; } protected int getStartIndex() { return haveToIgnoreImplicitArgument()? 1 : 0; } protected void setIgnoreImplicitArgument(boolean ignoreImplicitArgument) { this.ignoreImplicitArgument = ignoreImplicitArgument; } public static MatchingInfos fromBoolean(boolean bool) { return bool? EXACT_MATCH : NO_MATCH; } }
199365_0
package nl.novi.jnoldenfacturatie.dtos; import jakarta.validation.constraints.*; import java.util.Date; import java.util.List; public class FactuurInputDto extends FactuurBaseDto { @NotNull(message = "Klant is verplicht") private Long klantId; @Max(100) // korting mag niet hoger dan 100% zijn @Min(0) // korting mag niet negatief zijn private Integer kortingPercentage; @Size(message = "Factuur moet minstens een orderregel bevatten", min = 1) private List<OrderRegelInputDto> orderRegels; public FactuurInputDto(Date factuurDatum, Date betaalDatum, Long klantId, Integer kortingPercentage, List<OrderRegelInputDto> orderRegels){ super(factuurDatum, betaalDatum); this.kortingPercentage = kortingPercentage; this.klantId = klantId; this.orderRegels = orderRegels; } public FactuurInputDto(){ super(); } public Long getKlantId() { return klantId; } public void setKlantId(Long klantId) { this.klantId = klantId; } public Integer getKortingPercentage() { return kortingPercentage; } public void setKortingPercentage(Integer kortingPercentage) { this.kortingPercentage = kortingPercentage; } public List<OrderRegelInputDto> getOrderRegels() { return orderRegels; } public void setOrderRegels(List<OrderRegelInputDto> orderRegels) { this.orderRegels = orderRegels; } }
josnolden/JNoldenFacturatie
src/main/java/nl/novi/jnoldenfacturatie/dtos/FactuurInputDto.java
417
// korting mag niet hoger dan 100% zijn
line_comment
nl
package nl.novi.jnoldenfacturatie.dtos; import jakarta.validation.constraints.*; import java.util.Date; import java.util.List; public class FactuurInputDto extends FactuurBaseDto { @NotNull(message = "Klant is verplicht") private Long klantId; @Max(100) // korting mag<SUF> @Min(0) // korting mag niet negatief zijn private Integer kortingPercentage; @Size(message = "Factuur moet minstens een orderregel bevatten", min = 1) private List<OrderRegelInputDto> orderRegels; public FactuurInputDto(Date factuurDatum, Date betaalDatum, Long klantId, Integer kortingPercentage, List<OrderRegelInputDto> orderRegels){ super(factuurDatum, betaalDatum); this.kortingPercentage = kortingPercentage; this.klantId = klantId; this.orderRegels = orderRegels; } public FactuurInputDto(){ super(); } public Long getKlantId() { return klantId; } public void setKlantId(Long klantId) { this.klantId = klantId; } public Integer getKortingPercentage() { return kortingPercentage; } public void setKortingPercentage(Integer kortingPercentage) { this.kortingPercentage = kortingPercentage; } public List<OrderRegelInputDto> getOrderRegels() { return orderRegels; } public void setOrderRegels(List<OrderRegelInputDto> orderRegels) { this.orderRegels = orderRegels; } }
199365_1
package nl.novi.jnoldenfacturatie.dtos; import jakarta.validation.constraints.*; import java.util.Date; import java.util.List; public class FactuurInputDto extends FactuurBaseDto { @NotNull(message = "Klant is verplicht") private Long klantId; @Max(100) // korting mag niet hoger dan 100% zijn @Min(0) // korting mag niet negatief zijn private Integer kortingPercentage; @Size(message = "Factuur moet minstens een orderregel bevatten", min = 1) private List<OrderRegelInputDto> orderRegels; public FactuurInputDto(Date factuurDatum, Date betaalDatum, Long klantId, Integer kortingPercentage, List<OrderRegelInputDto> orderRegels){ super(factuurDatum, betaalDatum); this.kortingPercentage = kortingPercentage; this.klantId = klantId; this.orderRegels = orderRegels; } public FactuurInputDto(){ super(); } public Long getKlantId() { return klantId; } public void setKlantId(Long klantId) { this.klantId = klantId; } public Integer getKortingPercentage() { return kortingPercentage; } public void setKortingPercentage(Integer kortingPercentage) { this.kortingPercentage = kortingPercentage; } public List<OrderRegelInputDto> getOrderRegels() { return orderRegels; } public void setOrderRegels(List<OrderRegelInputDto> orderRegels) { this.orderRegels = orderRegels; } }
josnolden/JNoldenFacturatie
src/main/java/nl/novi/jnoldenfacturatie/dtos/FactuurInputDto.java
417
// korting mag niet negatief zijn
line_comment
nl
package nl.novi.jnoldenfacturatie.dtos; import jakarta.validation.constraints.*; import java.util.Date; import java.util.List; public class FactuurInputDto extends FactuurBaseDto { @NotNull(message = "Klant is verplicht") private Long klantId; @Max(100) // korting mag niet hoger dan 100% zijn @Min(0) // korting mag<SUF> private Integer kortingPercentage; @Size(message = "Factuur moet minstens een orderregel bevatten", min = 1) private List<OrderRegelInputDto> orderRegels; public FactuurInputDto(Date factuurDatum, Date betaalDatum, Long klantId, Integer kortingPercentage, List<OrderRegelInputDto> orderRegels){ super(factuurDatum, betaalDatum); this.kortingPercentage = kortingPercentage; this.klantId = klantId; this.orderRegels = orderRegels; } public FactuurInputDto(){ super(); } public Long getKlantId() { return klantId; } public void setKlantId(Long klantId) { this.klantId = klantId; } public Integer getKortingPercentage() { return kortingPercentage; } public void setKortingPercentage(Integer kortingPercentage) { this.kortingPercentage = kortingPercentage; } public List<OrderRegelInputDto> getOrderRegels() { return orderRegels; } public void setOrderRegels(List<OrderRegelInputDto> orderRegels) { this.orderRegels = orderRegels; } }
199373_1
package be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.argumentable; import static be.kuleuven.jchr.util.comparing.Comparison.AMBIGUOUS; import static be.kuleuven.jchr.util.comparing.Comparison.EQUAL; import be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.argument.IArgument; import be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.argumented.IArgumented; import be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.arguments.IArguments; import be.kuleuven.jchr.compiler.CHRIntermediateForm.matching.MatchingInfo; import be.kuleuven.jchr.compiler.CHRIntermediateForm.matching.MatchingInfos; import be.kuleuven.jchr.compiler.CHRIntermediateForm.types.IType; import be.kuleuven.jchr.util.comparing.Comparison; /** * @author Peter Van Weert */ public abstract class Argumentable<T extends IArgumentable<?>> implements IArgumentable<T> { public IType[] getFormalParameters() { final IType[] result = new IType[getArity()]; for (int i = 0; i < result.length; i++) result[i] = getFormalParameterAt(i); return result; } public static MatchingInfos canHaveAsArguments(final IArgumentable<?> argumentable, final IArguments arguments) { final int arity = argumentable.getArity(); if (arity != arguments.getArity()) return MatchingInfos.NO_MATCH; MatchingInfos result = new MatchingInfos( arity, argumentable.haveToIgnoreImplicitArgument() ); MatchingInfo temp; for (int i = 0; i < arity; i++) { temp = argumentable.canHaveAsArgumentAt(i, arguments.getArgumentAt(i)); if (temp.isAmbiguous()) return temp.isInitMatch() ? MatchingInfos.AMBIGUOUS_INIT : MatchingInfos.AMBIGUOUS_NO_INIT; else if (!temp.isMatch()) return MatchingInfos.NO_MATCH; else result.setAssignmentInfoAt(temp, i); } return result; } public MatchingInfos canHaveAsArguments(IArguments arguments) { return canHaveAsArguments(this, arguments); } public MatchingInfo canHaveAsArgumentAt(int index, IArgument argument) { return argument.isAssignableTo(getFormalParameterAt(index)); } @Override public String toString() { return toString(this); } public IArgumented<T> getInstance(IArguments arguments, MatchingInfos infos) { arguments.incorporate(infos, haveToIgnoreImplicitArgument()); return getInstance(arguments); } public static String toString(IArgumentable<?> argumentable) { StringBuilder result = new StringBuilder().append('('); final int arity = argumentable.getArity(); if (arity > 0) result.append(argumentable.getFormalParameterAt(0).toTypeString()); for (int i = 1; i < arity; i++) result.append(", ").append(argumentable.getFormalParameterAt(i).toTypeString()); return result.append(')').toString(); } public static Comparison compare(IArgumentable<?> one, IArgumentable<?> other) { final int arity = one.getArity(); Comparison comparison = EQUAL, temp; for (int i = 0; i < arity; i++) { temp = other.getFormalParameterAt(i).compareTo(one.getFormalParameterAt(i)); switch (temp) { // als er minstens 1 vergelijking ambigu is, is vergelijking niet mogelijk case AMBIGUOUS: return AMBIGUOUS; /*break;*/ // als er een verschil is moet... case BETTER: case WORSE: if (comparison == EQUAL) // ... na de eerste keer ... comparison = temp; else if (comparison != temp) // ... de vergelijking steeds hetzelfde zijn return AMBIGUOUS; break; } } return comparison; } public Comparison compareTo(IArgumentable<?> other) { return compare(this, other); } @Override public int hashCode() { int result = 23; final int arity = getArity(); for (int i = 0; i < arity; i++) result = 37 * result + getFormalParameterAt(i).hashCode(); return result; } @Override public abstract boolean equals(Object obj); }
hendrikvanantwerpen/jchr
src/be/kuleuven/jchr/compiler/CHRIntermediateForm/arg/argumentable/Argumentable.java
1,255
// als er minstens 1 vergelijking ambigu is, is vergelijking niet mogelijk
line_comment
nl
package be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.argumentable; import static be.kuleuven.jchr.util.comparing.Comparison.AMBIGUOUS; import static be.kuleuven.jchr.util.comparing.Comparison.EQUAL; import be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.argument.IArgument; import be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.argumented.IArgumented; import be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.arguments.IArguments; import be.kuleuven.jchr.compiler.CHRIntermediateForm.matching.MatchingInfo; import be.kuleuven.jchr.compiler.CHRIntermediateForm.matching.MatchingInfos; import be.kuleuven.jchr.compiler.CHRIntermediateForm.types.IType; import be.kuleuven.jchr.util.comparing.Comparison; /** * @author Peter Van Weert */ public abstract class Argumentable<T extends IArgumentable<?>> implements IArgumentable<T> { public IType[] getFormalParameters() { final IType[] result = new IType[getArity()]; for (int i = 0; i < result.length; i++) result[i] = getFormalParameterAt(i); return result; } public static MatchingInfos canHaveAsArguments(final IArgumentable<?> argumentable, final IArguments arguments) { final int arity = argumentable.getArity(); if (arity != arguments.getArity()) return MatchingInfos.NO_MATCH; MatchingInfos result = new MatchingInfos( arity, argumentable.haveToIgnoreImplicitArgument() ); MatchingInfo temp; for (int i = 0; i < arity; i++) { temp = argumentable.canHaveAsArgumentAt(i, arguments.getArgumentAt(i)); if (temp.isAmbiguous()) return temp.isInitMatch() ? MatchingInfos.AMBIGUOUS_INIT : MatchingInfos.AMBIGUOUS_NO_INIT; else if (!temp.isMatch()) return MatchingInfos.NO_MATCH; else result.setAssignmentInfoAt(temp, i); } return result; } public MatchingInfos canHaveAsArguments(IArguments arguments) { return canHaveAsArguments(this, arguments); } public MatchingInfo canHaveAsArgumentAt(int index, IArgument argument) { return argument.isAssignableTo(getFormalParameterAt(index)); } @Override public String toString() { return toString(this); } public IArgumented<T> getInstance(IArguments arguments, MatchingInfos infos) { arguments.incorporate(infos, haveToIgnoreImplicitArgument()); return getInstance(arguments); } public static String toString(IArgumentable<?> argumentable) { StringBuilder result = new StringBuilder().append('('); final int arity = argumentable.getArity(); if (arity > 0) result.append(argumentable.getFormalParameterAt(0).toTypeString()); for (int i = 1; i < arity; i++) result.append(", ").append(argumentable.getFormalParameterAt(i).toTypeString()); return result.append(')').toString(); } public static Comparison compare(IArgumentable<?> one, IArgumentable<?> other) { final int arity = one.getArity(); Comparison comparison = EQUAL, temp; for (int i = 0; i < arity; i++) { temp = other.getFormalParameterAt(i).compareTo(one.getFormalParameterAt(i)); switch (temp) { // als er<SUF> case AMBIGUOUS: return AMBIGUOUS; /*break;*/ // als er een verschil is moet... case BETTER: case WORSE: if (comparison == EQUAL) // ... na de eerste keer ... comparison = temp; else if (comparison != temp) // ... de vergelijking steeds hetzelfde zijn return AMBIGUOUS; break; } } return comparison; } public Comparison compareTo(IArgumentable<?> other) { return compare(this, other); } @Override public int hashCode() { int result = 23; final int arity = getArity(); for (int i = 0; i < arity; i++) result = 37 * result + getFormalParameterAt(i).hashCode(); return result; } @Override public abstract boolean equals(Object obj); }
199373_2
package be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.argumentable; import static be.kuleuven.jchr.util.comparing.Comparison.AMBIGUOUS; import static be.kuleuven.jchr.util.comparing.Comparison.EQUAL; import be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.argument.IArgument; import be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.argumented.IArgumented; import be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.arguments.IArguments; import be.kuleuven.jchr.compiler.CHRIntermediateForm.matching.MatchingInfo; import be.kuleuven.jchr.compiler.CHRIntermediateForm.matching.MatchingInfos; import be.kuleuven.jchr.compiler.CHRIntermediateForm.types.IType; import be.kuleuven.jchr.util.comparing.Comparison; /** * @author Peter Van Weert */ public abstract class Argumentable<T extends IArgumentable<?>> implements IArgumentable<T> { public IType[] getFormalParameters() { final IType[] result = new IType[getArity()]; for (int i = 0; i < result.length; i++) result[i] = getFormalParameterAt(i); return result; } public static MatchingInfos canHaveAsArguments(final IArgumentable<?> argumentable, final IArguments arguments) { final int arity = argumentable.getArity(); if (arity != arguments.getArity()) return MatchingInfos.NO_MATCH; MatchingInfos result = new MatchingInfos( arity, argumentable.haveToIgnoreImplicitArgument() ); MatchingInfo temp; for (int i = 0; i < arity; i++) { temp = argumentable.canHaveAsArgumentAt(i, arguments.getArgumentAt(i)); if (temp.isAmbiguous()) return temp.isInitMatch() ? MatchingInfos.AMBIGUOUS_INIT : MatchingInfos.AMBIGUOUS_NO_INIT; else if (!temp.isMatch()) return MatchingInfos.NO_MATCH; else result.setAssignmentInfoAt(temp, i); } return result; } public MatchingInfos canHaveAsArguments(IArguments arguments) { return canHaveAsArguments(this, arguments); } public MatchingInfo canHaveAsArgumentAt(int index, IArgument argument) { return argument.isAssignableTo(getFormalParameterAt(index)); } @Override public String toString() { return toString(this); } public IArgumented<T> getInstance(IArguments arguments, MatchingInfos infos) { arguments.incorporate(infos, haveToIgnoreImplicitArgument()); return getInstance(arguments); } public static String toString(IArgumentable<?> argumentable) { StringBuilder result = new StringBuilder().append('('); final int arity = argumentable.getArity(); if (arity > 0) result.append(argumentable.getFormalParameterAt(0).toTypeString()); for (int i = 1; i < arity; i++) result.append(", ").append(argumentable.getFormalParameterAt(i).toTypeString()); return result.append(')').toString(); } public static Comparison compare(IArgumentable<?> one, IArgumentable<?> other) { final int arity = one.getArity(); Comparison comparison = EQUAL, temp; for (int i = 0; i < arity; i++) { temp = other.getFormalParameterAt(i).compareTo(one.getFormalParameterAt(i)); switch (temp) { // als er minstens 1 vergelijking ambigu is, is vergelijking niet mogelijk case AMBIGUOUS: return AMBIGUOUS; /*break;*/ // als er een verschil is moet... case BETTER: case WORSE: if (comparison == EQUAL) // ... na de eerste keer ... comparison = temp; else if (comparison != temp) // ... de vergelijking steeds hetzelfde zijn return AMBIGUOUS; break; } } return comparison; } public Comparison compareTo(IArgumentable<?> other) { return compare(this, other); } @Override public int hashCode() { int result = 23; final int arity = getArity(); for (int i = 0; i < arity; i++) result = 37 * result + getFormalParameterAt(i).hashCode(); return result; } @Override public abstract boolean equals(Object obj); }
hendrikvanantwerpen/jchr
src/be/kuleuven/jchr/compiler/CHRIntermediateForm/arg/argumentable/Argumentable.java
1,255
// als er een verschil is moet...
line_comment
nl
package be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.argumentable; import static be.kuleuven.jchr.util.comparing.Comparison.AMBIGUOUS; import static be.kuleuven.jchr.util.comparing.Comparison.EQUAL; import be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.argument.IArgument; import be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.argumented.IArgumented; import be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.arguments.IArguments; import be.kuleuven.jchr.compiler.CHRIntermediateForm.matching.MatchingInfo; import be.kuleuven.jchr.compiler.CHRIntermediateForm.matching.MatchingInfos; import be.kuleuven.jchr.compiler.CHRIntermediateForm.types.IType; import be.kuleuven.jchr.util.comparing.Comparison; /** * @author Peter Van Weert */ public abstract class Argumentable<T extends IArgumentable<?>> implements IArgumentable<T> { public IType[] getFormalParameters() { final IType[] result = new IType[getArity()]; for (int i = 0; i < result.length; i++) result[i] = getFormalParameterAt(i); return result; } public static MatchingInfos canHaveAsArguments(final IArgumentable<?> argumentable, final IArguments arguments) { final int arity = argumentable.getArity(); if (arity != arguments.getArity()) return MatchingInfos.NO_MATCH; MatchingInfos result = new MatchingInfos( arity, argumentable.haveToIgnoreImplicitArgument() ); MatchingInfo temp; for (int i = 0; i < arity; i++) { temp = argumentable.canHaveAsArgumentAt(i, arguments.getArgumentAt(i)); if (temp.isAmbiguous()) return temp.isInitMatch() ? MatchingInfos.AMBIGUOUS_INIT : MatchingInfos.AMBIGUOUS_NO_INIT; else if (!temp.isMatch()) return MatchingInfos.NO_MATCH; else result.setAssignmentInfoAt(temp, i); } return result; } public MatchingInfos canHaveAsArguments(IArguments arguments) { return canHaveAsArguments(this, arguments); } public MatchingInfo canHaveAsArgumentAt(int index, IArgument argument) { return argument.isAssignableTo(getFormalParameterAt(index)); } @Override public String toString() { return toString(this); } public IArgumented<T> getInstance(IArguments arguments, MatchingInfos infos) { arguments.incorporate(infos, haveToIgnoreImplicitArgument()); return getInstance(arguments); } public static String toString(IArgumentable<?> argumentable) { StringBuilder result = new StringBuilder().append('('); final int arity = argumentable.getArity(); if (arity > 0) result.append(argumentable.getFormalParameterAt(0).toTypeString()); for (int i = 1; i < arity; i++) result.append(", ").append(argumentable.getFormalParameterAt(i).toTypeString()); return result.append(')').toString(); } public static Comparison compare(IArgumentable<?> one, IArgumentable<?> other) { final int arity = one.getArity(); Comparison comparison = EQUAL, temp; for (int i = 0; i < arity; i++) { temp = other.getFormalParameterAt(i).compareTo(one.getFormalParameterAt(i)); switch (temp) { // als er minstens 1 vergelijking ambigu is, is vergelijking niet mogelijk case AMBIGUOUS: return AMBIGUOUS; /*break;*/ // als er<SUF> case BETTER: case WORSE: if (comparison == EQUAL) // ... na de eerste keer ... comparison = temp; else if (comparison != temp) // ... de vergelijking steeds hetzelfde zijn return AMBIGUOUS; break; } } return comparison; } public Comparison compareTo(IArgumentable<?> other) { return compare(this, other); } @Override public int hashCode() { int result = 23; final int arity = getArity(); for (int i = 0; i < arity; i++) result = 37 * result + getFormalParameterAt(i).hashCode(); return result; } @Override public abstract boolean equals(Object obj); }
199373_3
package be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.argumentable; import static be.kuleuven.jchr.util.comparing.Comparison.AMBIGUOUS; import static be.kuleuven.jchr.util.comparing.Comparison.EQUAL; import be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.argument.IArgument; import be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.argumented.IArgumented; import be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.arguments.IArguments; import be.kuleuven.jchr.compiler.CHRIntermediateForm.matching.MatchingInfo; import be.kuleuven.jchr.compiler.CHRIntermediateForm.matching.MatchingInfos; import be.kuleuven.jchr.compiler.CHRIntermediateForm.types.IType; import be.kuleuven.jchr.util.comparing.Comparison; /** * @author Peter Van Weert */ public abstract class Argumentable<T extends IArgumentable<?>> implements IArgumentable<T> { public IType[] getFormalParameters() { final IType[] result = new IType[getArity()]; for (int i = 0; i < result.length; i++) result[i] = getFormalParameterAt(i); return result; } public static MatchingInfos canHaveAsArguments(final IArgumentable<?> argumentable, final IArguments arguments) { final int arity = argumentable.getArity(); if (arity != arguments.getArity()) return MatchingInfos.NO_MATCH; MatchingInfos result = new MatchingInfos( arity, argumentable.haveToIgnoreImplicitArgument() ); MatchingInfo temp; for (int i = 0; i < arity; i++) { temp = argumentable.canHaveAsArgumentAt(i, arguments.getArgumentAt(i)); if (temp.isAmbiguous()) return temp.isInitMatch() ? MatchingInfos.AMBIGUOUS_INIT : MatchingInfos.AMBIGUOUS_NO_INIT; else if (!temp.isMatch()) return MatchingInfos.NO_MATCH; else result.setAssignmentInfoAt(temp, i); } return result; } public MatchingInfos canHaveAsArguments(IArguments arguments) { return canHaveAsArguments(this, arguments); } public MatchingInfo canHaveAsArgumentAt(int index, IArgument argument) { return argument.isAssignableTo(getFormalParameterAt(index)); } @Override public String toString() { return toString(this); } public IArgumented<T> getInstance(IArguments arguments, MatchingInfos infos) { arguments.incorporate(infos, haveToIgnoreImplicitArgument()); return getInstance(arguments); } public static String toString(IArgumentable<?> argumentable) { StringBuilder result = new StringBuilder().append('('); final int arity = argumentable.getArity(); if (arity > 0) result.append(argumentable.getFormalParameterAt(0).toTypeString()); for (int i = 1; i < arity; i++) result.append(", ").append(argumentable.getFormalParameterAt(i).toTypeString()); return result.append(')').toString(); } public static Comparison compare(IArgumentable<?> one, IArgumentable<?> other) { final int arity = one.getArity(); Comparison comparison = EQUAL, temp; for (int i = 0; i < arity; i++) { temp = other.getFormalParameterAt(i).compareTo(one.getFormalParameterAt(i)); switch (temp) { // als er minstens 1 vergelijking ambigu is, is vergelijking niet mogelijk case AMBIGUOUS: return AMBIGUOUS; /*break;*/ // als er een verschil is moet... case BETTER: case WORSE: if (comparison == EQUAL) // ... na de eerste keer ... comparison = temp; else if (comparison != temp) // ... de vergelijking steeds hetzelfde zijn return AMBIGUOUS; break; } } return comparison; } public Comparison compareTo(IArgumentable<?> other) { return compare(this, other); } @Override public int hashCode() { int result = 23; final int arity = getArity(); for (int i = 0; i < arity; i++) result = 37 * result + getFormalParameterAt(i).hashCode(); return result; } @Override public abstract boolean equals(Object obj); }
hendrikvanantwerpen/jchr
src/be/kuleuven/jchr/compiler/CHRIntermediateForm/arg/argumentable/Argumentable.java
1,255
// ... na de eerste keer ...
line_comment
nl
package be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.argumentable; import static be.kuleuven.jchr.util.comparing.Comparison.AMBIGUOUS; import static be.kuleuven.jchr.util.comparing.Comparison.EQUAL; import be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.argument.IArgument; import be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.argumented.IArgumented; import be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.arguments.IArguments; import be.kuleuven.jchr.compiler.CHRIntermediateForm.matching.MatchingInfo; import be.kuleuven.jchr.compiler.CHRIntermediateForm.matching.MatchingInfos; import be.kuleuven.jchr.compiler.CHRIntermediateForm.types.IType; import be.kuleuven.jchr.util.comparing.Comparison; /** * @author Peter Van Weert */ public abstract class Argumentable<T extends IArgumentable<?>> implements IArgumentable<T> { public IType[] getFormalParameters() { final IType[] result = new IType[getArity()]; for (int i = 0; i < result.length; i++) result[i] = getFormalParameterAt(i); return result; } public static MatchingInfos canHaveAsArguments(final IArgumentable<?> argumentable, final IArguments arguments) { final int arity = argumentable.getArity(); if (arity != arguments.getArity()) return MatchingInfos.NO_MATCH; MatchingInfos result = new MatchingInfos( arity, argumentable.haveToIgnoreImplicitArgument() ); MatchingInfo temp; for (int i = 0; i < arity; i++) { temp = argumentable.canHaveAsArgumentAt(i, arguments.getArgumentAt(i)); if (temp.isAmbiguous()) return temp.isInitMatch() ? MatchingInfos.AMBIGUOUS_INIT : MatchingInfos.AMBIGUOUS_NO_INIT; else if (!temp.isMatch()) return MatchingInfos.NO_MATCH; else result.setAssignmentInfoAt(temp, i); } return result; } public MatchingInfos canHaveAsArguments(IArguments arguments) { return canHaveAsArguments(this, arguments); } public MatchingInfo canHaveAsArgumentAt(int index, IArgument argument) { return argument.isAssignableTo(getFormalParameterAt(index)); } @Override public String toString() { return toString(this); } public IArgumented<T> getInstance(IArguments arguments, MatchingInfos infos) { arguments.incorporate(infos, haveToIgnoreImplicitArgument()); return getInstance(arguments); } public static String toString(IArgumentable<?> argumentable) { StringBuilder result = new StringBuilder().append('('); final int arity = argumentable.getArity(); if (arity > 0) result.append(argumentable.getFormalParameterAt(0).toTypeString()); for (int i = 1; i < arity; i++) result.append(", ").append(argumentable.getFormalParameterAt(i).toTypeString()); return result.append(')').toString(); } public static Comparison compare(IArgumentable<?> one, IArgumentable<?> other) { final int arity = one.getArity(); Comparison comparison = EQUAL, temp; for (int i = 0; i < arity; i++) { temp = other.getFormalParameterAt(i).compareTo(one.getFormalParameterAt(i)); switch (temp) { // als er minstens 1 vergelijking ambigu is, is vergelijking niet mogelijk case AMBIGUOUS: return AMBIGUOUS; /*break;*/ // als er een verschil is moet... case BETTER: case WORSE: if (comparison == EQUAL) // ... na<SUF> comparison = temp; else if (comparison != temp) // ... de vergelijking steeds hetzelfde zijn return AMBIGUOUS; break; } } return comparison; } public Comparison compareTo(IArgumentable<?> other) { return compare(this, other); } @Override public int hashCode() { int result = 23; final int arity = getArity(); for (int i = 0; i < arity; i++) result = 37 * result + getFormalParameterAt(i).hashCode(); return result; } @Override public abstract boolean equals(Object obj); }
199373_4
package be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.argumentable; import static be.kuleuven.jchr.util.comparing.Comparison.AMBIGUOUS; import static be.kuleuven.jchr.util.comparing.Comparison.EQUAL; import be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.argument.IArgument; import be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.argumented.IArgumented; import be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.arguments.IArguments; import be.kuleuven.jchr.compiler.CHRIntermediateForm.matching.MatchingInfo; import be.kuleuven.jchr.compiler.CHRIntermediateForm.matching.MatchingInfos; import be.kuleuven.jchr.compiler.CHRIntermediateForm.types.IType; import be.kuleuven.jchr.util.comparing.Comparison; /** * @author Peter Van Weert */ public abstract class Argumentable<T extends IArgumentable<?>> implements IArgumentable<T> { public IType[] getFormalParameters() { final IType[] result = new IType[getArity()]; for (int i = 0; i < result.length; i++) result[i] = getFormalParameterAt(i); return result; } public static MatchingInfos canHaveAsArguments(final IArgumentable<?> argumentable, final IArguments arguments) { final int arity = argumentable.getArity(); if (arity != arguments.getArity()) return MatchingInfos.NO_MATCH; MatchingInfos result = new MatchingInfos( arity, argumentable.haveToIgnoreImplicitArgument() ); MatchingInfo temp; for (int i = 0; i < arity; i++) { temp = argumentable.canHaveAsArgumentAt(i, arguments.getArgumentAt(i)); if (temp.isAmbiguous()) return temp.isInitMatch() ? MatchingInfos.AMBIGUOUS_INIT : MatchingInfos.AMBIGUOUS_NO_INIT; else if (!temp.isMatch()) return MatchingInfos.NO_MATCH; else result.setAssignmentInfoAt(temp, i); } return result; } public MatchingInfos canHaveAsArguments(IArguments arguments) { return canHaveAsArguments(this, arguments); } public MatchingInfo canHaveAsArgumentAt(int index, IArgument argument) { return argument.isAssignableTo(getFormalParameterAt(index)); } @Override public String toString() { return toString(this); } public IArgumented<T> getInstance(IArguments arguments, MatchingInfos infos) { arguments.incorporate(infos, haveToIgnoreImplicitArgument()); return getInstance(arguments); } public static String toString(IArgumentable<?> argumentable) { StringBuilder result = new StringBuilder().append('('); final int arity = argumentable.getArity(); if (arity > 0) result.append(argumentable.getFormalParameterAt(0).toTypeString()); for (int i = 1; i < arity; i++) result.append(", ").append(argumentable.getFormalParameterAt(i).toTypeString()); return result.append(')').toString(); } public static Comparison compare(IArgumentable<?> one, IArgumentable<?> other) { final int arity = one.getArity(); Comparison comparison = EQUAL, temp; for (int i = 0; i < arity; i++) { temp = other.getFormalParameterAt(i).compareTo(one.getFormalParameterAt(i)); switch (temp) { // als er minstens 1 vergelijking ambigu is, is vergelijking niet mogelijk case AMBIGUOUS: return AMBIGUOUS; /*break;*/ // als er een verschil is moet... case BETTER: case WORSE: if (comparison == EQUAL) // ... na de eerste keer ... comparison = temp; else if (comparison != temp) // ... de vergelijking steeds hetzelfde zijn return AMBIGUOUS; break; } } return comparison; } public Comparison compareTo(IArgumentable<?> other) { return compare(this, other); } @Override public int hashCode() { int result = 23; final int arity = getArity(); for (int i = 0; i < arity; i++) result = 37 * result + getFormalParameterAt(i).hashCode(); return result; } @Override public abstract boolean equals(Object obj); }
hendrikvanantwerpen/jchr
src/be/kuleuven/jchr/compiler/CHRIntermediateForm/arg/argumentable/Argumentable.java
1,255
// ... de vergelijking steeds hetzelfde zijn
line_comment
nl
package be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.argumentable; import static be.kuleuven.jchr.util.comparing.Comparison.AMBIGUOUS; import static be.kuleuven.jchr.util.comparing.Comparison.EQUAL; import be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.argument.IArgument; import be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.argumented.IArgumented; import be.kuleuven.jchr.compiler.CHRIntermediateForm.arg.arguments.IArguments; import be.kuleuven.jchr.compiler.CHRIntermediateForm.matching.MatchingInfo; import be.kuleuven.jchr.compiler.CHRIntermediateForm.matching.MatchingInfos; import be.kuleuven.jchr.compiler.CHRIntermediateForm.types.IType; import be.kuleuven.jchr.util.comparing.Comparison; /** * @author Peter Van Weert */ public abstract class Argumentable<T extends IArgumentable<?>> implements IArgumentable<T> { public IType[] getFormalParameters() { final IType[] result = new IType[getArity()]; for (int i = 0; i < result.length; i++) result[i] = getFormalParameterAt(i); return result; } public static MatchingInfos canHaveAsArguments(final IArgumentable<?> argumentable, final IArguments arguments) { final int arity = argumentable.getArity(); if (arity != arguments.getArity()) return MatchingInfos.NO_MATCH; MatchingInfos result = new MatchingInfos( arity, argumentable.haveToIgnoreImplicitArgument() ); MatchingInfo temp; for (int i = 0; i < arity; i++) { temp = argumentable.canHaveAsArgumentAt(i, arguments.getArgumentAt(i)); if (temp.isAmbiguous()) return temp.isInitMatch() ? MatchingInfos.AMBIGUOUS_INIT : MatchingInfos.AMBIGUOUS_NO_INIT; else if (!temp.isMatch()) return MatchingInfos.NO_MATCH; else result.setAssignmentInfoAt(temp, i); } return result; } public MatchingInfos canHaveAsArguments(IArguments arguments) { return canHaveAsArguments(this, arguments); } public MatchingInfo canHaveAsArgumentAt(int index, IArgument argument) { return argument.isAssignableTo(getFormalParameterAt(index)); } @Override public String toString() { return toString(this); } public IArgumented<T> getInstance(IArguments arguments, MatchingInfos infos) { arguments.incorporate(infos, haveToIgnoreImplicitArgument()); return getInstance(arguments); } public static String toString(IArgumentable<?> argumentable) { StringBuilder result = new StringBuilder().append('('); final int arity = argumentable.getArity(); if (arity > 0) result.append(argumentable.getFormalParameterAt(0).toTypeString()); for (int i = 1; i < arity; i++) result.append(", ").append(argumentable.getFormalParameterAt(i).toTypeString()); return result.append(')').toString(); } public static Comparison compare(IArgumentable<?> one, IArgumentable<?> other) { final int arity = one.getArity(); Comparison comparison = EQUAL, temp; for (int i = 0; i < arity; i++) { temp = other.getFormalParameterAt(i).compareTo(one.getFormalParameterAt(i)); switch (temp) { // als er minstens 1 vergelijking ambigu is, is vergelijking niet mogelijk case AMBIGUOUS: return AMBIGUOUS; /*break;*/ // als er een verschil is moet... case BETTER: case WORSE: if (comparison == EQUAL) // ... na de eerste keer ... comparison = temp; else if (comparison != temp) // ... de<SUF> return AMBIGUOUS; break; } } return comparison; } public Comparison compareTo(IArgumentable<?> other) { return compare(this, other); } @Override public int hashCode() { int result = 23; final int arity = getArity(); for (int i = 0; i < arity; i++) result = 37 * result + getFormalParameterAt(i).hashCode(); return result; } @Override public abstract boolean equals(Object obj); }
199390_1
package ui.importer; import com.google.inject.Inject; import domain.importing.Groepsinschrijving; import domain.importing.Reeks; import domain.importing.WizardData; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import persistence.Marshalling; import persistence.ReeksDefinitie; import ui.EditingCell; import java.util.ArrayList; import java.util.Comparator; import java.util.stream.Collectors; public class WizardImportReeksenController extends WizardImportController{ @FXML private TableView tblReeksen; @FXML private TableColumn tblColDiscipline, tblColAantal, tblColRing, tblColExtensie; @Inject WizardData model; @FXML public void initialize() { tblColDiscipline.setCellValueFactory(new PropertyValueFactory<Reeks,String>("naam")); tblColAantal.setCellValueFactory(new PropertyValueFactory<Reeks,Integer>("aantal")); tblColRing.setCellFactory(col -> new EditingCell<Reeks, String>() { @Override public void updateIndex(int i) { super.updateIndex(i); if (i >= 0) { this.getStyleClass().add("editable-cell"); } } @Override public void commitEditHandler(String newValue){ Reeks reeks = (Reeks) getTableRow().getItem(); reeks.setRingNaam(newValue.trim()); } }); tblColRing.setCellValueFactory(new PropertyValueFactory<Reeks,String>("ringNaam")); tblColExtensie.setCellFactory(col -> new EditingCell<Reeks, String>() { @Override public void updateIndex(int i) { super.updateIndex(i); if (i >= 0) { this.getStyleClass().add("editable-cell"); } } @Override public void commitEditHandler(String newValue){ Reeks reeks = (Reeks) getTableRow().getItem(); reeks.setExtensie(newValue.trim()); } }); tblColExtensie.setCellValueFactory(new PropertyValueFactory<Reeks,String>("extensie")); tblReeksen.setItems(model.getReeksen()); tblReeksen.getSelectionModel().setCellSelectionEnabled(true); } @Override public void activate(){ model.setTitle("Disciplines aan ringen toewijzen"); model.setSubtitle("Disciplines die in dezelfde ring moeten zitten, worden hier aangeduid, eventueel aangevuld met een extensie"); model.getReeksen().clear(); //TODO: errors in Marshalling controlleren ArrayList<Groepsinschrijving> groepsinschrijvingen = Marshalling.importGroepsinschrijvingen(model.getFilename(), Marshalling.getActiveSheet(model.getFilename()), model.getColHeaders(), model.getColSportfeest(), model.getColAfdeling(), model.getColDiscipline(), model.getColAantal()); groepsinschrijvingen.stream() .filter(groepsinschrijving -> groepsinschrijving.getSportfeest().equalsIgnoreCase(model.getSportfeest().getValue())) .collect(Collectors.groupingBy(Groepsinschrijving::getSport, Collectors.summingInt(Groepsinschrijving::getAantal))) .forEach((discipline, aantal) -> model.getReeksen().add(new Reeks(discipline, aantal))); model.getReeksen().sort(Comparator.comparing(Reeks::getNaam)); for(Reeks conf : ReeksDefinitie.unMarshall()){ model.getReeksen().stream() .filter(reeks -> reeks.getNaam().equalsIgnoreCase(conf.getNaam())) .forEach(reeks -> { reeks.setRingNaam(conf.getRingNaam()); reeks.setExtensie(conf.getExtensie()); reeks.setDuur(Math.max(reeks.getDuur(),conf.getDuur())); }); } } @Validate public boolean validate() throws Exception { //ringnamen moeten minstens 8 characters zijn if(!model.getReeksen().stream().allMatch(reeks -> reeks.getRingNaam() != null && reeks.getRingNaam().length() > 8)) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Ringen"); alert.setHeaderText( "Ringnaam te kort" ); alert.setContentText( "Alle ringnamen moeten minsten 8 characters lang zijn" ); alert.showAndWait(); return false; } return true; } @Submit public void submit() throws Exception { } }
samverstraete/klj-sf-planner
src/main/java/ui/importer/WizardImportReeksenController.java
1,164
//ringnamen moeten minstens 8 characters zijn
line_comment
nl
package ui.importer; import com.google.inject.Inject; import domain.importing.Groepsinschrijving; import domain.importing.Reeks; import domain.importing.WizardData; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import persistence.Marshalling; import persistence.ReeksDefinitie; import ui.EditingCell; import java.util.ArrayList; import java.util.Comparator; import java.util.stream.Collectors; public class WizardImportReeksenController extends WizardImportController{ @FXML private TableView tblReeksen; @FXML private TableColumn tblColDiscipline, tblColAantal, tblColRing, tblColExtensie; @Inject WizardData model; @FXML public void initialize() { tblColDiscipline.setCellValueFactory(new PropertyValueFactory<Reeks,String>("naam")); tblColAantal.setCellValueFactory(new PropertyValueFactory<Reeks,Integer>("aantal")); tblColRing.setCellFactory(col -> new EditingCell<Reeks, String>() { @Override public void updateIndex(int i) { super.updateIndex(i); if (i >= 0) { this.getStyleClass().add("editable-cell"); } } @Override public void commitEditHandler(String newValue){ Reeks reeks = (Reeks) getTableRow().getItem(); reeks.setRingNaam(newValue.trim()); } }); tblColRing.setCellValueFactory(new PropertyValueFactory<Reeks,String>("ringNaam")); tblColExtensie.setCellFactory(col -> new EditingCell<Reeks, String>() { @Override public void updateIndex(int i) { super.updateIndex(i); if (i >= 0) { this.getStyleClass().add("editable-cell"); } } @Override public void commitEditHandler(String newValue){ Reeks reeks = (Reeks) getTableRow().getItem(); reeks.setExtensie(newValue.trim()); } }); tblColExtensie.setCellValueFactory(new PropertyValueFactory<Reeks,String>("extensie")); tblReeksen.setItems(model.getReeksen()); tblReeksen.getSelectionModel().setCellSelectionEnabled(true); } @Override public void activate(){ model.setTitle("Disciplines aan ringen toewijzen"); model.setSubtitle("Disciplines die in dezelfde ring moeten zitten, worden hier aangeduid, eventueel aangevuld met een extensie"); model.getReeksen().clear(); //TODO: errors in Marshalling controlleren ArrayList<Groepsinschrijving> groepsinschrijvingen = Marshalling.importGroepsinschrijvingen(model.getFilename(), Marshalling.getActiveSheet(model.getFilename()), model.getColHeaders(), model.getColSportfeest(), model.getColAfdeling(), model.getColDiscipline(), model.getColAantal()); groepsinschrijvingen.stream() .filter(groepsinschrijving -> groepsinschrijving.getSportfeest().equalsIgnoreCase(model.getSportfeest().getValue())) .collect(Collectors.groupingBy(Groepsinschrijving::getSport, Collectors.summingInt(Groepsinschrijving::getAantal))) .forEach((discipline, aantal) -> model.getReeksen().add(new Reeks(discipline, aantal))); model.getReeksen().sort(Comparator.comparing(Reeks::getNaam)); for(Reeks conf : ReeksDefinitie.unMarshall()){ model.getReeksen().stream() .filter(reeks -> reeks.getNaam().equalsIgnoreCase(conf.getNaam())) .forEach(reeks -> { reeks.setRingNaam(conf.getRingNaam()); reeks.setExtensie(conf.getExtensie()); reeks.setDuur(Math.max(reeks.getDuur(),conf.getDuur())); }); } } @Validate public boolean validate() throws Exception { //ringnamen moeten<SUF> if(!model.getReeksen().stream().allMatch(reeks -> reeks.getRingNaam() != null && reeks.getRingNaam().length() > 8)) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Ringen"); alert.setHeaderText( "Ringnaam te kort" ); alert.setContentText( "Alle ringnamen moeten minsten 8 characters lang zijn" ); alert.showAndWait(); return false; } return true; } @Submit public void submit() throws Exception { } }
199394_1
package be.ucll.web; import be.ucll.dao.MatchRepository; import be.ucll.dao.PlayerRepository; import be.ucll.dao.TeamPlayerRepository; import be.ucll.dao.TeamRepository; import be.ucll.exceptions.NotFoundException; import be.ucll.exceptions.ParameterInvalidException; import be.ucll.models.Player; import be.ucll.models.Team; import be.ucll.models.TeamPlayer; import be.ucll.service.LiveStatsService; import be.ucll.service.MatchHistoryService; import be.ucll.service.models.CurrentGameInfo; import io.swagger.v3.oas.annotations.Operation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; import java.util.Optional; @RestController @RequestMapping("liveStats") public class LiveStatsResource { TeamRepository teamRepository; TeamPlayerRepository teamPlayerRepository; PlayerRepository playerRepository; LiveStatsService liveStatsService; @Autowired public LiveStatsResource(TeamRepository teamRepository,TeamPlayerRepository teamPlayerRepository, PlayerRepository playerRepository, LiveStatsService liveStatsService) { this.teamRepository = teamRepository; this.playerRepository = playerRepository; this.liveStatsService = liveStatsService; this.teamPlayerRepository = teamPlayerRepository; } @Operation( summary = "Get live stats", description = "Get live stats from players in a team" ) @GetMapping("/{teamId}") public ResponseEntity<List<CurrentGameInfo>> getLiveStats(@PathVariable("teamId") Long teamId) throws NotFoundException, ParameterInvalidException { if (teamId <= 0) throw new ParameterInvalidException(teamId.toString()); //1. vraag team op Optional<Team> team = teamRepository.findTeamById(teamId); if(team.isEmpty()){ throw new NotFoundException(teamId.toString()); } System.out.println("found team "+team.get().getName()); //debug //2. vraag teamplayers op van het team List<TeamPlayer> teamPlayers = teamPlayerRepository.findPlayersByTeam(team.get()); if(teamPlayers.isEmpty()){ throw new NotFoundException("teamPlayers of "+teamId.toString()); } System.out.println("found teamplayers "+teamPlayers.toString()); //debug System.out.println(teamPlayers.size()+" size"); //debug //3. Maak request voor alle players active games List<CurrentGameInfo> liveStats = new ArrayList<>(); teamPlayers.forEach(((teamPlayer) -> { Player player = teamPlayer.getPlayer(); System.out.println("found player "+player.getSummonerID()); //debug Optional<CurrentGameInfo> currentGameInfo = Optional.empty(); try { currentGameInfo= liveStatsService.getActiveGames(player.getSummonerID()); }catch(Exception e){ } System.out.println("currentGameInfo "+currentGameInfo.toString()); //debug if(currentGameInfo.isPresent()){ System.out.println("currentGameInfo "+currentGameInfo.get().toString()); //debug liveStats.add(currentGameInfo.get()); }else{ System.out.println("no currentGameInfo "); //debug } })); //4. Check of liveStats minstens 2 heeft if(liveStats.isEmpty()){ throw new NotFoundException("live stats of players in team "+teamId); } if(liveStats.size()<2){ throw new NotFoundException("Too few players active in team "+teamId); } return ResponseEntity.status(HttpStatus.OK).body(liveStats); } }
kdssoftware/UCLL-projects
Java/UCLL-gip4/src/main/java/be/ucll/web/LiveStatsResource.java
968
//2. vraag teamplayers op van het team
line_comment
nl
package be.ucll.web; import be.ucll.dao.MatchRepository; import be.ucll.dao.PlayerRepository; import be.ucll.dao.TeamPlayerRepository; import be.ucll.dao.TeamRepository; import be.ucll.exceptions.NotFoundException; import be.ucll.exceptions.ParameterInvalidException; import be.ucll.models.Player; import be.ucll.models.Team; import be.ucll.models.TeamPlayer; import be.ucll.service.LiveStatsService; import be.ucll.service.MatchHistoryService; import be.ucll.service.models.CurrentGameInfo; import io.swagger.v3.oas.annotations.Operation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; import java.util.Optional; @RestController @RequestMapping("liveStats") public class LiveStatsResource { TeamRepository teamRepository; TeamPlayerRepository teamPlayerRepository; PlayerRepository playerRepository; LiveStatsService liveStatsService; @Autowired public LiveStatsResource(TeamRepository teamRepository,TeamPlayerRepository teamPlayerRepository, PlayerRepository playerRepository, LiveStatsService liveStatsService) { this.teamRepository = teamRepository; this.playerRepository = playerRepository; this.liveStatsService = liveStatsService; this.teamPlayerRepository = teamPlayerRepository; } @Operation( summary = "Get live stats", description = "Get live stats from players in a team" ) @GetMapping("/{teamId}") public ResponseEntity<List<CurrentGameInfo>> getLiveStats(@PathVariable("teamId") Long teamId) throws NotFoundException, ParameterInvalidException { if (teamId <= 0) throw new ParameterInvalidException(teamId.toString()); //1. vraag team op Optional<Team> team = teamRepository.findTeamById(teamId); if(team.isEmpty()){ throw new NotFoundException(teamId.toString()); } System.out.println("found team "+team.get().getName()); //debug //2. vraag<SUF> List<TeamPlayer> teamPlayers = teamPlayerRepository.findPlayersByTeam(team.get()); if(teamPlayers.isEmpty()){ throw new NotFoundException("teamPlayers of "+teamId.toString()); } System.out.println("found teamplayers "+teamPlayers.toString()); //debug System.out.println(teamPlayers.size()+" size"); //debug //3. Maak request voor alle players active games List<CurrentGameInfo> liveStats = new ArrayList<>(); teamPlayers.forEach(((teamPlayer) -> { Player player = teamPlayer.getPlayer(); System.out.println("found player "+player.getSummonerID()); //debug Optional<CurrentGameInfo> currentGameInfo = Optional.empty(); try { currentGameInfo= liveStatsService.getActiveGames(player.getSummonerID()); }catch(Exception e){ } System.out.println("currentGameInfo "+currentGameInfo.toString()); //debug if(currentGameInfo.isPresent()){ System.out.println("currentGameInfo "+currentGameInfo.get().toString()); //debug liveStats.add(currentGameInfo.get()); }else{ System.out.println("no currentGameInfo "); //debug } })); //4. Check of liveStats minstens 2 heeft if(liveStats.isEmpty()){ throw new NotFoundException("live stats of players in team "+teamId); } if(liveStats.size()<2){ throw new NotFoundException("Too few players active in team "+teamId); } return ResponseEntity.status(HttpStatus.OK).body(liveStats); } }
199394_3
package be.ucll.web; import be.ucll.dao.MatchRepository; import be.ucll.dao.PlayerRepository; import be.ucll.dao.TeamPlayerRepository; import be.ucll.dao.TeamRepository; import be.ucll.exceptions.NotFoundException; import be.ucll.exceptions.ParameterInvalidException; import be.ucll.models.Player; import be.ucll.models.Team; import be.ucll.models.TeamPlayer; import be.ucll.service.LiveStatsService; import be.ucll.service.MatchHistoryService; import be.ucll.service.models.CurrentGameInfo; import io.swagger.v3.oas.annotations.Operation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; import java.util.Optional; @RestController @RequestMapping("liveStats") public class LiveStatsResource { TeamRepository teamRepository; TeamPlayerRepository teamPlayerRepository; PlayerRepository playerRepository; LiveStatsService liveStatsService; @Autowired public LiveStatsResource(TeamRepository teamRepository,TeamPlayerRepository teamPlayerRepository, PlayerRepository playerRepository, LiveStatsService liveStatsService) { this.teamRepository = teamRepository; this.playerRepository = playerRepository; this.liveStatsService = liveStatsService; this.teamPlayerRepository = teamPlayerRepository; } @Operation( summary = "Get live stats", description = "Get live stats from players in a team" ) @GetMapping("/{teamId}") public ResponseEntity<List<CurrentGameInfo>> getLiveStats(@PathVariable("teamId") Long teamId) throws NotFoundException, ParameterInvalidException { if (teamId <= 0) throw new ParameterInvalidException(teamId.toString()); //1. vraag team op Optional<Team> team = teamRepository.findTeamById(teamId); if(team.isEmpty()){ throw new NotFoundException(teamId.toString()); } System.out.println("found team "+team.get().getName()); //debug //2. vraag teamplayers op van het team List<TeamPlayer> teamPlayers = teamPlayerRepository.findPlayersByTeam(team.get()); if(teamPlayers.isEmpty()){ throw new NotFoundException("teamPlayers of "+teamId.toString()); } System.out.println("found teamplayers "+teamPlayers.toString()); //debug System.out.println(teamPlayers.size()+" size"); //debug //3. Maak request voor alle players active games List<CurrentGameInfo> liveStats = new ArrayList<>(); teamPlayers.forEach(((teamPlayer) -> { Player player = teamPlayer.getPlayer(); System.out.println("found player "+player.getSummonerID()); //debug Optional<CurrentGameInfo> currentGameInfo = Optional.empty(); try { currentGameInfo= liveStatsService.getActiveGames(player.getSummonerID()); }catch(Exception e){ } System.out.println("currentGameInfo "+currentGameInfo.toString()); //debug if(currentGameInfo.isPresent()){ System.out.println("currentGameInfo "+currentGameInfo.get().toString()); //debug liveStats.add(currentGameInfo.get()); }else{ System.out.println("no currentGameInfo "); //debug } })); //4. Check of liveStats minstens 2 heeft if(liveStats.isEmpty()){ throw new NotFoundException("live stats of players in team "+teamId); } if(liveStats.size()<2){ throw new NotFoundException("Too few players active in team "+teamId); } return ResponseEntity.status(HttpStatus.OK).body(liveStats); } }
kdssoftware/UCLL-projects
Java/UCLL-gip4/src/main/java/be/ucll/web/LiveStatsResource.java
968
//4. Check of liveStats minstens 2 heeft
line_comment
nl
package be.ucll.web; import be.ucll.dao.MatchRepository; import be.ucll.dao.PlayerRepository; import be.ucll.dao.TeamPlayerRepository; import be.ucll.dao.TeamRepository; import be.ucll.exceptions.NotFoundException; import be.ucll.exceptions.ParameterInvalidException; import be.ucll.models.Player; import be.ucll.models.Team; import be.ucll.models.TeamPlayer; import be.ucll.service.LiveStatsService; import be.ucll.service.MatchHistoryService; import be.ucll.service.models.CurrentGameInfo; import io.swagger.v3.oas.annotations.Operation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; import java.util.Optional; @RestController @RequestMapping("liveStats") public class LiveStatsResource { TeamRepository teamRepository; TeamPlayerRepository teamPlayerRepository; PlayerRepository playerRepository; LiveStatsService liveStatsService; @Autowired public LiveStatsResource(TeamRepository teamRepository,TeamPlayerRepository teamPlayerRepository, PlayerRepository playerRepository, LiveStatsService liveStatsService) { this.teamRepository = teamRepository; this.playerRepository = playerRepository; this.liveStatsService = liveStatsService; this.teamPlayerRepository = teamPlayerRepository; } @Operation( summary = "Get live stats", description = "Get live stats from players in a team" ) @GetMapping("/{teamId}") public ResponseEntity<List<CurrentGameInfo>> getLiveStats(@PathVariable("teamId") Long teamId) throws NotFoundException, ParameterInvalidException { if (teamId <= 0) throw new ParameterInvalidException(teamId.toString()); //1. vraag team op Optional<Team> team = teamRepository.findTeamById(teamId); if(team.isEmpty()){ throw new NotFoundException(teamId.toString()); } System.out.println("found team "+team.get().getName()); //debug //2. vraag teamplayers op van het team List<TeamPlayer> teamPlayers = teamPlayerRepository.findPlayersByTeam(team.get()); if(teamPlayers.isEmpty()){ throw new NotFoundException("teamPlayers of "+teamId.toString()); } System.out.println("found teamplayers "+teamPlayers.toString()); //debug System.out.println(teamPlayers.size()+" size"); //debug //3. Maak request voor alle players active games List<CurrentGameInfo> liveStats = new ArrayList<>(); teamPlayers.forEach(((teamPlayer) -> { Player player = teamPlayer.getPlayer(); System.out.println("found player "+player.getSummonerID()); //debug Optional<CurrentGameInfo> currentGameInfo = Optional.empty(); try { currentGameInfo= liveStatsService.getActiveGames(player.getSummonerID()); }catch(Exception e){ } System.out.println("currentGameInfo "+currentGameInfo.toString()); //debug if(currentGameInfo.isPresent()){ System.out.println("currentGameInfo "+currentGameInfo.get().toString()); //debug liveStats.add(currentGameInfo.get()); }else{ System.out.println("no currentGameInfo "); //debug } })); //4. Check<SUF> if(liveStats.isEmpty()){ throw new NotFoundException("live stats of players in team "+teamId); } if(liveStats.size()<2){ throw new NotFoundException("Too few players active in team "+teamId); } return ResponseEntity.status(HttpStatus.OK).body(liveStats); } }
199399_1
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at www.github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.domain.expressie.functie; import java.util.List; import nl.bzk.brp.domain.expressie.Context; import nl.bzk.brp.domain.expressie.Expressie; import nl.bzk.brp.domain.expressie.ExpressieType; import nl.bzk.brp.domain.expressie.signatuur.ExistentieleFunctieSignatuur; import org.springframework.stereotype.Component; /** * Representeert de functie ER_IS(L,V,C). De functie geeft true terug als minstens één element uit lijst L voldoet aan * conditie C, waarbij variabele V steeds de waarde van een element uit L aanneemt. */ @Component @FunctieKeyword("ER_IS") final class ErIsFunctie extends AbstractFunctie { /** * Constructor voor de functie. */ ErIsFunctie() { super(new ExistentieleFunctieSignatuur()); } @Override public Expressie evalueer(final List<Expressie> argumenten, final Context context) { return evalueerLijst(argumenten, context, false); } @Override public ExpressieType getType(final List<Expressie> argumenten, final Context context) { return ExpressieType.BOOLEAN; } @Override public boolean evalueerArgumenten() { return false; } }
DDDNL/OperatieBRP
Broncode/operatiebrp-code-145.3/brp/brp-leveren/brp-leveren-domain/brp-domain-expressie/src/main/java/nl/bzk/brp/domain/expressie/functie/ErIsFunctie.java
448
/** * Representeert de functie ER_IS(L,V,C). De functie geeft true terug als minstens één element uit lijst L voldoet aan * conditie C, waarbij variabele V steeds de waarde van een element uit L aanneemt. */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at www.github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.domain.expressie.functie; import java.util.List; import nl.bzk.brp.domain.expressie.Context; import nl.bzk.brp.domain.expressie.Expressie; import nl.bzk.brp.domain.expressie.ExpressieType; import nl.bzk.brp.domain.expressie.signatuur.ExistentieleFunctieSignatuur; import org.springframework.stereotype.Component; /** * Representeert de functie<SUF>*/ @Component @FunctieKeyword("ER_IS") final class ErIsFunctie extends AbstractFunctie { /** * Constructor voor de functie. */ ErIsFunctie() { super(new ExistentieleFunctieSignatuur()); } @Override public Expressie evalueer(final List<Expressie> argumenten, final Context context) { return evalueerLijst(argumenten, context, false); } @Override public ExpressieType getType(final List<Expressie> argumenten, final Context context) { return ExpressieType.BOOLEAN; } @Override public boolean evalueerArgumenten() { return false; } }
199426_12
package ru.m210projects.Tekwar; import static ru.m210projects.Build.Engine.*; import static ru.m210projects.Tekwar.Globals.*; import static ru.m210projects.Tekwar.View.*; import java.io.FileNotFoundException; import static ru.m210projects.Tekwar.Animate.*; import static ru.m210projects.Tekwar.Main.*; import static ru.m210projects.Tekwar.Names.*; import static ru.m210projects.Tekwar.Tekchng.*; import static ru.m210projects.Tekwar.Tekgun.*; import static ru.m210projects.Tekwar.Tekmap.*; import static ru.m210projects.Tekwar.Tekstat.*; import static ru.m210projects.Tekwar.Tektag.*; import static ru.m210projects.Tekwar.Player.*; import ru.m210projects.Build.Architecture.BuildGdx; import ru.m210projects.Build.FileHandle.Resource; import ru.m210projects.Build.Types.BuildPos; import ru.m210projects.Build.Types.InvalidVersionException; import ru.m210projects.Build.Types.SECTOR; import ru.m210projects.Tekwar.Types.SpriteXT; import ru.m210projects.Tekwar.Types.Startspottype; public class Tekprep { public static final int MAXSTARTSPOTS = 16; public static SpriteXT[] spriteXT = new SpriteXT[MAXSPRITES]; public static int startx, starty, startz, starta, starts; static int firsttimethru = 1; static int coopmode, switchlevelsflag; public static int[] subwaysound = new int[4]; static int startspotcnt; static Startspottype[] startspot = new Startspottype[MAXSTARTSPOTS]; public static void setup3dscreen(int w, int h) { if (!engine.setgamemode(tekcfg.fullscreen, w, h)) tekcfg.fullscreen = 0; tekcfg.ScreenWidth = BuildGdx.graphics.getWidth(); tekcfg.ScreenHeight = BuildGdx.graphics.getHeight(); } public static int tekpreinit() { int j, k, l; byte[] tempbuf = new byte[256]; Resource fp; if ((fp = BuildGdx.cache.open("lookup.dat", 0)) != null) { l = fp.readByte() & 0xFF; for (j = 0; j < l; j++) { k = fp.readByte() & 0xFF; fp.read(tempbuf, 0, 256); engine.makepalookup(k, tempbuf, 0, 0, 0, 1); } fp.close(); } if ((game.nNetMode == NetMode.Multiplayer) && ((fp = BuildGdx.cache.open("nlookup.dat", 0)) != null)) { l = fp.readByte() & 0xFF; for (j = 0; j < l; j++) { k = fp.readByte() & 0xFF; fp.read(tempbuf, 9, 256); engine.makepalookup(k + 15, tempbuf, 0, 0, 0, 1); } fp.close(); } engine.makepalookup(255, tempbuf, 60, 60, 60, 1); pskyoff[0] = 0; // 2 tiles pskyoff[1] = 1; pskyoff[2] = 2; pskyoff[3] = 3; pskybits = 2; // tile 4 times, every 90 deg. parallaxtype = 1; parallaxyoffs = 112; if (game.nNetMode == NetMode.Multiplayer) gDifficulty = 2; return 0; } public static void initplayersprite(short snum) { int i; if (gPlayer[snum].playersprite >= 0) return; i = jsinsertsprite(gPlayer[snum].cursectnum, (short) 8); if (i == -1) { System.err.println("initplayersprite: jsinsertsprite on player " + snum + " failed"); } gPlayer[snum].playersprite = (short) i; sprite[i].x = gPlayer[snum].posx; sprite[i].y = gPlayer[snum].posy; sprite[i].z = gPlayer[snum].posz + (KENSPLAYERHEIGHT << 8); sprite[i].cstat = 0x101; sprite[i].shade = 0; if (game.nNetMode != NetMode.Multiplayer) { sprite[i].pal = 0; } else { sprite[i].pal = (byte) (snum + 16); } sprite[i].clipdist = 32; sprite[i].xrepeat = 24; sprite[i].yrepeat = 24; sprite[i].xoffset = 0; sprite[i].yoffset = 0; sprite[i].picnum = DOOMGUY; sprite[i].ang = (short) gPlayer[snum].ang; sprite[i].xvel = 0; sprite[i].yvel = 0; sprite[i].zvel = 0; sprite[i].owner = (short) (snum + 4096); sprite[i].sectnum = gPlayer[snum].cursectnum; sprite[i].statnum = 8; sprite[i].lotag = 0; sprite[i].hitag = 0; // important to set extra = -1 sprite[i].extra = -1; gPlayer[snum].pInput.Reset(); tekrestoreplayer(snum); } static short[] dieframe = new short[MAXPLAYERS]; public static void tekrestoreplayer(short snum) { resetEffects(); engine.setsprite(gPlayer[snum].playersprite, gPlayer[snum].posx, gPlayer[snum].posy, gPlayer[snum].posz + (KENSPLAYERHEIGHT << 8)); sprite[gPlayer[snum].playersprite].ang = (short) gPlayer[snum].ang; sprite[gPlayer[snum].playersprite].xrepeat = 24; sprite[gPlayer[snum].playersprite].yrepeat = 24; gPlayer[snum].horiz = 100; gPlayer[snum].health = MAXHEALTH; gPlayer[snum].fireseq = 0; restockammo(snum); stun[snum] = MAXSTUN; fallz[snum] = 0; gPlayer[snum].drawweap = 0; gPlayer[snum].invredcards = 0; gPlayer[snum].invbluecards = 0; gPlayer[snum].invaccutrak = 0; dieframe[snum] = 0; if (game.nNetMode == NetMode.Multiplayer) { gPlayer[snum].weapons = 0; gPlayer[snum].weapons = flags32[GUN2FLAG] | flags32[GUN3FLAG]; } else { gPlayer[snum].weapons = 0; if (TEKDEMO) gPlayer[snum].weapons = flags32[GUN1FLAG] | flags32[GUN2FLAG]; else gPlayer[snum].weapons = flags32[GUN1FLAG] | flags32[GUN2FLAG] | flags32[GUN3FLAG]; } } static boolean RESETSCORE = false; public static boolean prepareboard(String daboardfilename) { short startwall, endwall, dasector; int i, j, k = 0, s, dax, day, dax2, day2; int l; boardfilename = daboardfilename; initsprites(); if (firsttimethru != 0) { // getmessageleng = 0; engine.srand(17); } gAnimationCount = 0; BuildPos out = null; try { out = engine.loadboard(daboardfilename); } catch (FileNotFoundException | InvalidVersionException | RuntimeException e) { game.GameMessage(e.getMessage()); return false; } startx = out.x; starty = out.y; startz = out.z; starta = out.ang; starts = out.sectnum; gViewMode = kView3D; zoom = 768; for (i = 0; i < MAXPLAYERS; i++) { gPlayer[i].posx = startx; gPlayer[i].posy = starty; gPlayer[i].posz = startz; gPlayer[i].ang = starta; gPlayer[i].cursectnum = (short) starts; gPlayer[i].ocursectnum = (short) starts; gPlayer[i].horiz = 100; gPlayer[i].lastchaingun = 0; gPlayer[i].health = 100; if (RESETSCORE) gPlayer[i].score = 0; gPlayer[i].numbombs = -1; gPlayer[i].deaths = 0; gPlayer[i].playersprite = -1; gPlayer[i].saywatchit = -1; } if (firsttimethru != 0) { for (i = 0; i < MAXPLAYERS; i++) { gPlayer[i].pInput.Reset(); } } for (i = 0; i < MAXPLAYERS; i++) { waterfountainwall[i] = -1; waterfountaincnt[i] = 0; slimesoundcnt[i] = 0; } for (i = 0; i < MAXPLAYERS; i++) gPlayer[i].updategun = 1; warpsectorcnt = 0; // Make a list of warping sectors xpanningsectorcnt = 0; // Make a list of wall x-panning sectors floorpanningcnt = 0; // Make a list of slime sectors dragsectorcnt = 0; // Make a list of moving platforms swingcnt = 0; // Make a list of swinging doors revolvecnt = 0; // Make a list of revolving doors subwaytrackcnt = 0; // Make a list of subways // intitialize subwaysound[]s for (i = 0; i < 4; i++) { subwaysound[i] = -1; } // scan sector tags for (i = 0; i < numsectors; i++) { switch (sector[i].lotag) { case 4: if (floorpanningcnt < 64) floorpanninglist[floorpanningcnt++] = (short) i; break; case 5060: if (game.nNetMode == NetMode.Multiplayer) { sector[i].lotag = 0; } break; case 25: if ((singlemapmode != 0) || (generalplay != 0) || (game.nNetMode == NetMode.Multiplayer)) { sector[i].lotag = 0; } break; case 10: if ((generalplay == 0) && (game.nNetMode != NetMode.Multiplayer) && (warpsectorcnt < 64)) { warpsectorlist[warpsectorcnt++] = (short) i; } break; case 11: xpanningsectorlist[xpanningsectorcnt++] = (short) i; break; case 12: dasector = (short) i; dax = 0x7fffffff; day = 0x7fffffff; dax2 = 0x80000000; day2 = 0x80000000; startwall = sector[i].wallptr; endwall = (short) (startwall + sector[i].wallnum - 1); for (j = startwall; j <= endwall; j++) { if (wall[j].x < dax) dax = wall[j].x; if (wall[j].y < day) day = wall[j].y; if (wall[j].x > dax2) dax2 = wall[j].x; if (wall[j].y > day2) day2 = wall[j].y; if (wall[j].lotag == 3) k = j; } if (wall[k].x == dax) dragxdir[dragsectorcnt] = -16; if (wall[k].y == day) dragydir[dragsectorcnt] = -16; if (wall[k].x == dax2) dragxdir[dragsectorcnt] = 16; if (wall[k].y == day2) dragydir[dragsectorcnt] = 16; dasector = wall[startwall].nextsector; dragx1[dragsectorcnt] = 0x7fffffff; dragy1[dragsectorcnt] = 0x7fffffff; dragx2[dragsectorcnt] = 0x80000000; dragy2[dragsectorcnt] = 0x80000000; startwall = sector[dasector].wallptr; endwall = (short) (startwall + sector[dasector].wallnum - 1); for (j = startwall; j <= endwall; j++) { if (wall[j].x < dragx1[dragsectorcnt]) dragx1[dragsectorcnt] = wall[j].x; if (wall[j].y < dragy1[dragsectorcnt]) dragy1[dragsectorcnt] = wall[j].y; if (wall[j].x > dragx2[dragsectorcnt]) dragx2[dragsectorcnt] = wall[j].x; if (wall[j].y > dragy2[dragsectorcnt]) dragy2[dragsectorcnt] = wall[j].y; } dragx1[dragsectorcnt] += (wall[sector[i].wallptr].x - dax); dragy1[dragsectorcnt] += (wall[sector[i].wallptr].y - day); dragx2[dragsectorcnt] -= (dax2 - wall[sector[i].wallptr].x); dragy2[dragsectorcnt] -= (day2 - wall[sector[i].wallptr].y); dragfloorz[dragsectorcnt] = sector[i].floorz; dragsectorlist[dragsectorcnt++] = (short) i; break; case 13: startwall = sector[i].wallptr; endwall = (short) (startwall + sector[i].wallnum - 1); for (j = startwall; j <= endwall; j++) { if (wall[j].lotag == 4) { k = wall[wall[wall[wall[j].point2].point2].point2].point2; if ((wall[j].x == wall[k].x) && (wall[j].y == wall[k].y)) { // Door opens counterclockwise swingwall[swingcnt][0] = (short) j; swingwall[swingcnt][1] = wall[j].point2; swingwall[swingcnt][2] = wall[wall[j].point2].point2; swingwall[swingcnt][3] = wall[wall[wall[j].point2].point2].point2; swingangopen[swingcnt] = 1536; swingangclosed[swingcnt] = 0; swingangopendir[swingcnt] = -1; } else { // Door opens clockwise swingwall[swingcnt][0] = wall[j].point2; swingwall[swingcnt][1] = (short) j; swingwall[swingcnt][2] = (short) engine.lastwall(j); swingwall[swingcnt][3] = (short) engine.lastwall(swingwall[swingcnt][2]); swingwall[swingcnt][4] = (short) engine.lastwall(swingwall[swingcnt][3]); swingangopen[swingcnt] = 512; swingangclosed[swingcnt] = 0; swingangopendir[swingcnt] = 1; } for (k = 0; k < 4; k++) { swingx[swingcnt][k] = wall[swingwall[swingcnt][k]].x; swingy[swingcnt][k] = wall[swingwall[swingcnt][k]].y; } swingsector[swingcnt] = (short) i; swingang[swingcnt] = swingangclosed[swingcnt]; swinganginc[swingcnt] = 0; swingcnt++; } } break; case 14: startwall = sector[i].wallptr; endwall = (short) (startwall + sector[i].wallnum - 1); dax = 0; day = 0; for (j = startwall; j <= endwall; j++) { dax += wall[j].x; day += wall[j].y; } revolvepivotx[revolvecnt] = dax / (endwall - startwall + 1); revolvepivoty[revolvecnt] = day / (endwall - startwall + 1); k = 0; for (j = startwall; j <= endwall; j++) { revolvex[revolvecnt][k] = wall[j].x; revolvey[revolvecnt][k] = wall[j].y; k++; } revolvesector[revolvecnt] = (short) i; revolveang[revolvecnt] = 0; revolvecnt++; break; case 15: subwaytracksector[subwaytrackcnt][0] = (short) i; subwaystopcnt[subwaytrackcnt] = 0; dax = 0x7fffffff; day = 0x7fffffff; dax2 = 0x80000000; day2 = 0x80000000; startwall = sector[i].wallptr; endwall = (short) (startwall + sector[i].wallnum - 1); for (j = startwall; j <= endwall; j++) { if (wall[j].x < dax) dax = wall[j].x; if (wall[j].y < day) day = wall[j].y; if (wall[j].x > dax2) dax2 = wall[j].x; if (wall[j].y > day2) day2 = wall[j].y; } for (j = startwall; j <= endwall; j++) { if (wall[j].lotag == 5) { if ((wall[j].x > dax) && (wall[j].y > day) && (wall[j].x < dax2) && (wall[j].y < day2)) { subwayx[subwaytrackcnt] = wall[j].x; } else { subwaystop[subwaytrackcnt][subwaystopcnt[subwaytrackcnt]] = wall[j].x; if (accessiblemap(wall[j].hitag) == 0) { subwaystop[subwaytrackcnt][subwaystopcnt[subwaytrackcnt]] = 0; } subwaystopcnt[subwaytrackcnt]++; } } } // de-sparse stoplist but keep increasing x order for (j = 0; j < subwaystopcnt[subwaytrackcnt]; j++) { if (subwaystop[subwaytrackcnt][j] == 0) { for (l = j + 1; l < subwaystopcnt[subwaytrackcnt]; l++) { if (subwaystop[subwaytrackcnt][l] != 0) { subwaystop[subwaytrackcnt][j] = subwaystop[subwaytrackcnt][l]; subwaystop[subwaytrackcnt][l] = 0; l = subwaystopcnt[subwaytrackcnt]; } } } } // recount stopcnt subwaystopcnt[subwaytrackcnt] = 0; while (subwaystop[subwaytrackcnt][subwaystopcnt[subwaytrackcnt]] != 0) { subwaystopcnt[subwaytrackcnt]++; } for (j = 1; j < subwaystopcnt[subwaytrackcnt]; j++) for (k = 0; k < j; k++) if (subwaystop[subwaytrackcnt][j] < subwaystop[subwaytrackcnt][k]) { s = subwaystop[subwaytrackcnt][j]; subwaystop[subwaytrackcnt][j] = subwaystop[subwaytrackcnt][k]; subwaystop[subwaytrackcnt][k] = s; } subwaygoalstop[subwaytrackcnt] = 0; for (j = 0; j < subwaystopcnt[subwaytrackcnt]; j++) if (Math.abs(subwaystop[subwaytrackcnt][j] - subwayx[subwaytrackcnt]) < Math .abs(subwaystop[subwaytrackcnt][subwaygoalstop[subwaytrackcnt]] - subwayx[subwaytrackcnt])) subwaygoalstop[subwaytrackcnt] = j; subwaytrackx1[subwaytrackcnt] = dax; subwaytracky1[subwaytrackcnt] = day; subwaytrackx2[subwaytrackcnt] = dax2; subwaytracky2[subwaytrackcnt] = day2; subwaynumsectors[subwaytrackcnt] = 1; for (j = 0; j < numsectors; j++) if (j != i) { startwall = sector[j].wallptr; if (wall[startwall].x > subwaytrackx1[subwaytrackcnt]) if (wall[startwall].y > subwaytracky1[subwaytrackcnt]) if (wall[startwall].x < subwaytrackx2[subwaytrackcnt]) if (wall[startwall].y < subwaytracky2[subwaytrackcnt]) { if (sector[j].lotag == 16) sector[j].lotag = 17; // Make special subway door if (sector[j].floorz != sector[i].floorz) { sector[j].ceilingstat |= 64; sector[j].floorstat |= 64; } subwaytracksector[subwaytrackcnt][subwaynumsectors[subwaytrackcnt]] = (short) j; subwaynumsectors[subwaytrackcnt]++; } } subwayvel[subwaytrackcnt] = 32; // orig 64 subwaypausetime[subwaytrackcnt] = 720; subwaytrackcnt++; break; } } // scan wall tags ypanningwallcnt = 0; for (i = 0; i < numwalls; i++) { if (wall[i].lotag == 1) ypanningwalllist[ypanningwallcnt++] = (short) i; } // scan sprite tags&picnum's rotatespritecnt = 0; startspotcnt = 0; for (i = 0; i < MAXSPRITES; i++) { if (sprite[i].picnum == STARTPOS) { if (startspotcnt < MAXSTARTSPOTS) { if (startspot[startspotcnt] == null) startspot[startspotcnt] = new Startspottype(); startspot[startspotcnt].x = sprite[i].x; startspot[startspotcnt].y = sprite[i].y; startspot[startspotcnt].z = sprite[i].z; startspot[startspotcnt].sectnum = sprite[i].sectnum; startspotcnt++; } jsdeletesprite((short) i); } else if (sprite[i].lotag == 3) { rotatespritelist[rotatespritecnt++] = (short) i; } else if (game.nNetMode == NetMode.Multiplayer) { if (sprite[i].lotag == 1009) { jsdeletesprite((short) i); } } } if ((startspotcnt == 0) && (game.nNetMode == NetMode.Multiplayer)) { System.err.println("no net startspots"); } for (i = 0; i < (MAXSECTORS >> 3); i++) show2dsector[i] = (byte) 0xff; for (i = 0; i < (MAXWALLS >> 3); i++) show2dwall[i] = (byte) 0xff; automapping = 0; // tags that make wall/sector not show up on 2D map for (i = 0; i < MAXSECTORS; i++) { if (sector[i] != null && sector[i].lotag == 9901) { show2dsector[i >> 3] &= ~(1 << (i & 7)); startwall = sector[i].wallptr; endwall = (short) (startwall + sector[i].wallnum - 1); for (j = startwall; j <= endwall; j++) { show2dwall[j >> 3] &= ~(1 << (j & 7)); if (wall[j].nextwall != -1) show2dwall[(wall[j].nextwall) >> 3] &= ~(1 << ((wall[j].nextwall) & 7)); } } } for (i = 0; i < MAXWALLS; i++) { if (wall[i] != null && wall[i].lotag == 9900) { show2dwall[i >> 3] &= ~(1 << (i & 7)); } } if (firsttimethru != 0) { lockclock = 0; } if (game.nNetMode == NetMode.Multiplayer) { firsttimethru = 0; } tekpreptags(); initspriteXTs(); if (currentmapno == 0) { SECTOR sec = sector[333]; if (sec != null && sec.lotag == 5020 && sec.hitag == 901) { sec.lotag = sec.hitag = 0; } } // put guns somewhere on map return true; } }
atsb/NuBuildGDX
src/ru/m210projects/Tekwar/Tekprep.java
6,848
// Door opens clockwise
line_comment
nl
package ru.m210projects.Tekwar; import static ru.m210projects.Build.Engine.*; import static ru.m210projects.Tekwar.Globals.*; import static ru.m210projects.Tekwar.View.*; import java.io.FileNotFoundException; import static ru.m210projects.Tekwar.Animate.*; import static ru.m210projects.Tekwar.Main.*; import static ru.m210projects.Tekwar.Names.*; import static ru.m210projects.Tekwar.Tekchng.*; import static ru.m210projects.Tekwar.Tekgun.*; import static ru.m210projects.Tekwar.Tekmap.*; import static ru.m210projects.Tekwar.Tekstat.*; import static ru.m210projects.Tekwar.Tektag.*; import static ru.m210projects.Tekwar.Player.*; import ru.m210projects.Build.Architecture.BuildGdx; import ru.m210projects.Build.FileHandle.Resource; import ru.m210projects.Build.Types.BuildPos; import ru.m210projects.Build.Types.InvalidVersionException; import ru.m210projects.Build.Types.SECTOR; import ru.m210projects.Tekwar.Types.SpriteXT; import ru.m210projects.Tekwar.Types.Startspottype; public class Tekprep { public static final int MAXSTARTSPOTS = 16; public static SpriteXT[] spriteXT = new SpriteXT[MAXSPRITES]; public static int startx, starty, startz, starta, starts; static int firsttimethru = 1; static int coopmode, switchlevelsflag; public static int[] subwaysound = new int[4]; static int startspotcnt; static Startspottype[] startspot = new Startspottype[MAXSTARTSPOTS]; public static void setup3dscreen(int w, int h) { if (!engine.setgamemode(tekcfg.fullscreen, w, h)) tekcfg.fullscreen = 0; tekcfg.ScreenWidth = BuildGdx.graphics.getWidth(); tekcfg.ScreenHeight = BuildGdx.graphics.getHeight(); } public static int tekpreinit() { int j, k, l; byte[] tempbuf = new byte[256]; Resource fp; if ((fp = BuildGdx.cache.open("lookup.dat", 0)) != null) { l = fp.readByte() & 0xFF; for (j = 0; j < l; j++) { k = fp.readByte() & 0xFF; fp.read(tempbuf, 0, 256); engine.makepalookup(k, tempbuf, 0, 0, 0, 1); } fp.close(); } if ((game.nNetMode == NetMode.Multiplayer) && ((fp = BuildGdx.cache.open("nlookup.dat", 0)) != null)) { l = fp.readByte() & 0xFF; for (j = 0; j < l; j++) { k = fp.readByte() & 0xFF; fp.read(tempbuf, 9, 256); engine.makepalookup(k + 15, tempbuf, 0, 0, 0, 1); } fp.close(); } engine.makepalookup(255, tempbuf, 60, 60, 60, 1); pskyoff[0] = 0; // 2 tiles pskyoff[1] = 1; pskyoff[2] = 2; pskyoff[3] = 3; pskybits = 2; // tile 4 times, every 90 deg. parallaxtype = 1; parallaxyoffs = 112; if (game.nNetMode == NetMode.Multiplayer) gDifficulty = 2; return 0; } public static void initplayersprite(short snum) { int i; if (gPlayer[snum].playersprite >= 0) return; i = jsinsertsprite(gPlayer[snum].cursectnum, (short) 8); if (i == -1) { System.err.println("initplayersprite: jsinsertsprite on player " + snum + " failed"); } gPlayer[snum].playersprite = (short) i; sprite[i].x = gPlayer[snum].posx; sprite[i].y = gPlayer[snum].posy; sprite[i].z = gPlayer[snum].posz + (KENSPLAYERHEIGHT << 8); sprite[i].cstat = 0x101; sprite[i].shade = 0; if (game.nNetMode != NetMode.Multiplayer) { sprite[i].pal = 0; } else { sprite[i].pal = (byte) (snum + 16); } sprite[i].clipdist = 32; sprite[i].xrepeat = 24; sprite[i].yrepeat = 24; sprite[i].xoffset = 0; sprite[i].yoffset = 0; sprite[i].picnum = DOOMGUY; sprite[i].ang = (short) gPlayer[snum].ang; sprite[i].xvel = 0; sprite[i].yvel = 0; sprite[i].zvel = 0; sprite[i].owner = (short) (snum + 4096); sprite[i].sectnum = gPlayer[snum].cursectnum; sprite[i].statnum = 8; sprite[i].lotag = 0; sprite[i].hitag = 0; // important to set extra = -1 sprite[i].extra = -1; gPlayer[snum].pInput.Reset(); tekrestoreplayer(snum); } static short[] dieframe = new short[MAXPLAYERS]; public static void tekrestoreplayer(short snum) { resetEffects(); engine.setsprite(gPlayer[snum].playersprite, gPlayer[snum].posx, gPlayer[snum].posy, gPlayer[snum].posz + (KENSPLAYERHEIGHT << 8)); sprite[gPlayer[snum].playersprite].ang = (short) gPlayer[snum].ang; sprite[gPlayer[snum].playersprite].xrepeat = 24; sprite[gPlayer[snum].playersprite].yrepeat = 24; gPlayer[snum].horiz = 100; gPlayer[snum].health = MAXHEALTH; gPlayer[snum].fireseq = 0; restockammo(snum); stun[snum] = MAXSTUN; fallz[snum] = 0; gPlayer[snum].drawweap = 0; gPlayer[snum].invredcards = 0; gPlayer[snum].invbluecards = 0; gPlayer[snum].invaccutrak = 0; dieframe[snum] = 0; if (game.nNetMode == NetMode.Multiplayer) { gPlayer[snum].weapons = 0; gPlayer[snum].weapons = flags32[GUN2FLAG] | flags32[GUN3FLAG]; } else { gPlayer[snum].weapons = 0; if (TEKDEMO) gPlayer[snum].weapons = flags32[GUN1FLAG] | flags32[GUN2FLAG]; else gPlayer[snum].weapons = flags32[GUN1FLAG] | flags32[GUN2FLAG] | flags32[GUN3FLAG]; } } static boolean RESETSCORE = false; public static boolean prepareboard(String daboardfilename) { short startwall, endwall, dasector; int i, j, k = 0, s, dax, day, dax2, day2; int l; boardfilename = daboardfilename; initsprites(); if (firsttimethru != 0) { // getmessageleng = 0; engine.srand(17); } gAnimationCount = 0; BuildPos out = null; try { out = engine.loadboard(daboardfilename); } catch (FileNotFoundException | InvalidVersionException | RuntimeException e) { game.GameMessage(e.getMessage()); return false; } startx = out.x; starty = out.y; startz = out.z; starta = out.ang; starts = out.sectnum; gViewMode = kView3D; zoom = 768; for (i = 0; i < MAXPLAYERS; i++) { gPlayer[i].posx = startx; gPlayer[i].posy = starty; gPlayer[i].posz = startz; gPlayer[i].ang = starta; gPlayer[i].cursectnum = (short) starts; gPlayer[i].ocursectnum = (short) starts; gPlayer[i].horiz = 100; gPlayer[i].lastchaingun = 0; gPlayer[i].health = 100; if (RESETSCORE) gPlayer[i].score = 0; gPlayer[i].numbombs = -1; gPlayer[i].deaths = 0; gPlayer[i].playersprite = -1; gPlayer[i].saywatchit = -1; } if (firsttimethru != 0) { for (i = 0; i < MAXPLAYERS; i++) { gPlayer[i].pInput.Reset(); } } for (i = 0; i < MAXPLAYERS; i++) { waterfountainwall[i] = -1; waterfountaincnt[i] = 0; slimesoundcnt[i] = 0; } for (i = 0; i < MAXPLAYERS; i++) gPlayer[i].updategun = 1; warpsectorcnt = 0; // Make a list of warping sectors xpanningsectorcnt = 0; // Make a list of wall x-panning sectors floorpanningcnt = 0; // Make a list of slime sectors dragsectorcnt = 0; // Make a list of moving platforms swingcnt = 0; // Make a list of swinging doors revolvecnt = 0; // Make a list of revolving doors subwaytrackcnt = 0; // Make a list of subways // intitialize subwaysound[]s for (i = 0; i < 4; i++) { subwaysound[i] = -1; } // scan sector tags for (i = 0; i < numsectors; i++) { switch (sector[i].lotag) { case 4: if (floorpanningcnt < 64) floorpanninglist[floorpanningcnt++] = (short) i; break; case 5060: if (game.nNetMode == NetMode.Multiplayer) { sector[i].lotag = 0; } break; case 25: if ((singlemapmode != 0) || (generalplay != 0) || (game.nNetMode == NetMode.Multiplayer)) { sector[i].lotag = 0; } break; case 10: if ((generalplay == 0) && (game.nNetMode != NetMode.Multiplayer) && (warpsectorcnt < 64)) { warpsectorlist[warpsectorcnt++] = (short) i; } break; case 11: xpanningsectorlist[xpanningsectorcnt++] = (short) i; break; case 12: dasector = (short) i; dax = 0x7fffffff; day = 0x7fffffff; dax2 = 0x80000000; day2 = 0x80000000; startwall = sector[i].wallptr; endwall = (short) (startwall + sector[i].wallnum - 1); for (j = startwall; j <= endwall; j++) { if (wall[j].x < dax) dax = wall[j].x; if (wall[j].y < day) day = wall[j].y; if (wall[j].x > dax2) dax2 = wall[j].x; if (wall[j].y > day2) day2 = wall[j].y; if (wall[j].lotag == 3) k = j; } if (wall[k].x == dax) dragxdir[dragsectorcnt] = -16; if (wall[k].y == day) dragydir[dragsectorcnt] = -16; if (wall[k].x == dax2) dragxdir[dragsectorcnt] = 16; if (wall[k].y == day2) dragydir[dragsectorcnt] = 16; dasector = wall[startwall].nextsector; dragx1[dragsectorcnt] = 0x7fffffff; dragy1[dragsectorcnt] = 0x7fffffff; dragx2[dragsectorcnt] = 0x80000000; dragy2[dragsectorcnt] = 0x80000000; startwall = sector[dasector].wallptr; endwall = (short) (startwall + sector[dasector].wallnum - 1); for (j = startwall; j <= endwall; j++) { if (wall[j].x < dragx1[dragsectorcnt]) dragx1[dragsectorcnt] = wall[j].x; if (wall[j].y < dragy1[dragsectorcnt]) dragy1[dragsectorcnt] = wall[j].y; if (wall[j].x > dragx2[dragsectorcnt]) dragx2[dragsectorcnt] = wall[j].x; if (wall[j].y > dragy2[dragsectorcnt]) dragy2[dragsectorcnt] = wall[j].y; } dragx1[dragsectorcnt] += (wall[sector[i].wallptr].x - dax); dragy1[dragsectorcnt] += (wall[sector[i].wallptr].y - day); dragx2[dragsectorcnt] -= (dax2 - wall[sector[i].wallptr].x); dragy2[dragsectorcnt] -= (day2 - wall[sector[i].wallptr].y); dragfloorz[dragsectorcnt] = sector[i].floorz; dragsectorlist[dragsectorcnt++] = (short) i; break; case 13: startwall = sector[i].wallptr; endwall = (short) (startwall + sector[i].wallnum - 1); for (j = startwall; j <= endwall; j++) { if (wall[j].lotag == 4) { k = wall[wall[wall[wall[j].point2].point2].point2].point2; if ((wall[j].x == wall[k].x) && (wall[j].y == wall[k].y)) { // Door opens counterclockwise swingwall[swingcnt][0] = (short) j; swingwall[swingcnt][1] = wall[j].point2; swingwall[swingcnt][2] = wall[wall[j].point2].point2; swingwall[swingcnt][3] = wall[wall[wall[j].point2].point2].point2; swingangopen[swingcnt] = 1536; swingangclosed[swingcnt] = 0; swingangopendir[swingcnt] = -1; } else { // Door opens<SUF> swingwall[swingcnt][0] = wall[j].point2; swingwall[swingcnt][1] = (short) j; swingwall[swingcnt][2] = (short) engine.lastwall(j); swingwall[swingcnt][3] = (short) engine.lastwall(swingwall[swingcnt][2]); swingwall[swingcnt][4] = (short) engine.lastwall(swingwall[swingcnt][3]); swingangopen[swingcnt] = 512; swingangclosed[swingcnt] = 0; swingangopendir[swingcnt] = 1; } for (k = 0; k < 4; k++) { swingx[swingcnt][k] = wall[swingwall[swingcnt][k]].x; swingy[swingcnt][k] = wall[swingwall[swingcnt][k]].y; } swingsector[swingcnt] = (short) i; swingang[swingcnt] = swingangclosed[swingcnt]; swinganginc[swingcnt] = 0; swingcnt++; } } break; case 14: startwall = sector[i].wallptr; endwall = (short) (startwall + sector[i].wallnum - 1); dax = 0; day = 0; for (j = startwall; j <= endwall; j++) { dax += wall[j].x; day += wall[j].y; } revolvepivotx[revolvecnt] = dax / (endwall - startwall + 1); revolvepivoty[revolvecnt] = day / (endwall - startwall + 1); k = 0; for (j = startwall; j <= endwall; j++) { revolvex[revolvecnt][k] = wall[j].x; revolvey[revolvecnt][k] = wall[j].y; k++; } revolvesector[revolvecnt] = (short) i; revolveang[revolvecnt] = 0; revolvecnt++; break; case 15: subwaytracksector[subwaytrackcnt][0] = (short) i; subwaystopcnt[subwaytrackcnt] = 0; dax = 0x7fffffff; day = 0x7fffffff; dax2 = 0x80000000; day2 = 0x80000000; startwall = sector[i].wallptr; endwall = (short) (startwall + sector[i].wallnum - 1); for (j = startwall; j <= endwall; j++) { if (wall[j].x < dax) dax = wall[j].x; if (wall[j].y < day) day = wall[j].y; if (wall[j].x > dax2) dax2 = wall[j].x; if (wall[j].y > day2) day2 = wall[j].y; } for (j = startwall; j <= endwall; j++) { if (wall[j].lotag == 5) { if ((wall[j].x > dax) && (wall[j].y > day) && (wall[j].x < dax2) && (wall[j].y < day2)) { subwayx[subwaytrackcnt] = wall[j].x; } else { subwaystop[subwaytrackcnt][subwaystopcnt[subwaytrackcnt]] = wall[j].x; if (accessiblemap(wall[j].hitag) == 0) { subwaystop[subwaytrackcnt][subwaystopcnt[subwaytrackcnt]] = 0; } subwaystopcnt[subwaytrackcnt]++; } } } // de-sparse stoplist but keep increasing x order for (j = 0; j < subwaystopcnt[subwaytrackcnt]; j++) { if (subwaystop[subwaytrackcnt][j] == 0) { for (l = j + 1; l < subwaystopcnt[subwaytrackcnt]; l++) { if (subwaystop[subwaytrackcnt][l] != 0) { subwaystop[subwaytrackcnt][j] = subwaystop[subwaytrackcnt][l]; subwaystop[subwaytrackcnt][l] = 0; l = subwaystopcnt[subwaytrackcnt]; } } } } // recount stopcnt subwaystopcnt[subwaytrackcnt] = 0; while (subwaystop[subwaytrackcnt][subwaystopcnt[subwaytrackcnt]] != 0) { subwaystopcnt[subwaytrackcnt]++; } for (j = 1; j < subwaystopcnt[subwaytrackcnt]; j++) for (k = 0; k < j; k++) if (subwaystop[subwaytrackcnt][j] < subwaystop[subwaytrackcnt][k]) { s = subwaystop[subwaytrackcnt][j]; subwaystop[subwaytrackcnt][j] = subwaystop[subwaytrackcnt][k]; subwaystop[subwaytrackcnt][k] = s; } subwaygoalstop[subwaytrackcnt] = 0; for (j = 0; j < subwaystopcnt[subwaytrackcnt]; j++) if (Math.abs(subwaystop[subwaytrackcnt][j] - subwayx[subwaytrackcnt]) < Math .abs(subwaystop[subwaytrackcnt][subwaygoalstop[subwaytrackcnt]] - subwayx[subwaytrackcnt])) subwaygoalstop[subwaytrackcnt] = j; subwaytrackx1[subwaytrackcnt] = dax; subwaytracky1[subwaytrackcnt] = day; subwaytrackx2[subwaytrackcnt] = dax2; subwaytracky2[subwaytrackcnt] = day2; subwaynumsectors[subwaytrackcnt] = 1; for (j = 0; j < numsectors; j++) if (j != i) { startwall = sector[j].wallptr; if (wall[startwall].x > subwaytrackx1[subwaytrackcnt]) if (wall[startwall].y > subwaytracky1[subwaytrackcnt]) if (wall[startwall].x < subwaytrackx2[subwaytrackcnt]) if (wall[startwall].y < subwaytracky2[subwaytrackcnt]) { if (sector[j].lotag == 16) sector[j].lotag = 17; // Make special subway door if (sector[j].floorz != sector[i].floorz) { sector[j].ceilingstat |= 64; sector[j].floorstat |= 64; } subwaytracksector[subwaytrackcnt][subwaynumsectors[subwaytrackcnt]] = (short) j; subwaynumsectors[subwaytrackcnt]++; } } subwayvel[subwaytrackcnt] = 32; // orig 64 subwaypausetime[subwaytrackcnt] = 720; subwaytrackcnt++; break; } } // scan wall tags ypanningwallcnt = 0; for (i = 0; i < numwalls; i++) { if (wall[i].lotag == 1) ypanningwalllist[ypanningwallcnt++] = (short) i; } // scan sprite tags&picnum's rotatespritecnt = 0; startspotcnt = 0; for (i = 0; i < MAXSPRITES; i++) { if (sprite[i].picnum == STARTPOS) { if (startspotcnt < MAXSTARTSPOTS) { if (startspot[startspotcnt] == null) startspot[startspotcnt] = new Startspottype(); startspot[startspotcnt].x = sprite[i].x; startspot[startspotcnt].y = sprite[i].y; startspot[startspotcnt].z = sprite[i].z; startspot[startspotcnt].sectnum = sprite[i].sectnum; startspotcnt++; } jsdeletesprite((short) i); } else if (sprite[i].lotag == 3) { rotatespritelist[rotatespritecnt++] = (short) i; } else if (game.nNetMode == NetMode.Multiplayer) { if (sprite[i].lotag == 1009) { jsdeletesprite((short) i); } } } if ((startspotcnt == 0) && (game.nNetMode == NetMode.Multiplayer)) { System.err.println("no net startspots"); } for (i = 0; i < (MAXSECTORS >> 3); i++) show2dsector[i] = (byte) 0xff; for (i = 0; i < (MAXWALLS >> 3); i++) show2dwall[i] = (byte) 0xff; automapping = 0; // tags that make wall/sector not show up on 2D map for (i = 0; i < MAXSECTORS; i++) { if (sector[i] != null && sector[i].lotag == 9901) { show2dsector[i >> 3] &= ~(1 << (i & 7)); startwall = sector[i].wallptr; endwall = (short) (startwall + sector[i].wallnum - 1); for (j = startwall; j <= endwall; j++) { show2dwall[j >> 3] &= ~(1 << (j & 7)); if (wall[j].nextwall != -1) show2dwall[(wall[j].nextwall) >> 3] &= ~(1 << ((wall[j].nextwall) & 7)); } } } for (i = 0; i < MAXWALLS; i++) { if (wall[i] != null && wall[i].lotag == 9900) { show2dwall[i >> 3] &= ~(1 << (i & 7)); } } if (firsttimethru != 0) { lockclock = 0; } if (game.nNetMode == NetMode.Multiplayer) { firsttimethru = 0; } tekpreptags(); initspriteXTs(); if (currentmapno == 0) { SECTOR sec = sector[333]; if (sec != null && sec.lotag == 5020 && sec.hitag == 901) { sec.lotag = sec.hitag = 0; } } // put guns somewhere on map return true; } }