List of usage examples for java.util LinkedList toArray
@SuppressWarnings("unchecked") public <T> T[] toArray(T[] a)
From source file:com.erudika.para.validation.ValidationUtils.java
/** * Validates objects.//from ww w . j a v a 2 s .com * @param content an object to be validated * @param app the current app * @return a list of error messages or empty if object is valid */ public static String[] validateObject(App app, ParaObject content) { if (content == null || app == null) { return new String[] { "Object cannot be null." }; } try { String type = content.getType(); boolean isCustomType = (content instanceof Sysprop) && !type.equals(Utils.type(Sysprop.class)); // Validate custom types and user-defined properties if (!app.getValidationConstraints().isEmpty() && isCustomType) { Map<String, Map<String, Map<String, ?>>> fieldsMap = app.getValidationConstraints().get(type); if (fieldsMap != null && !fieldsMap.isEmpty()) { LinkedList<String> errors = new LinkedList<String>(); for (Map.Entry<String, Map<String, Map<String, ?>>> e : fieldsMap.entrySet()) { String field = e.getKey(); Object actualValue = ((Sysprop) content).getProperty(field); // overriding core property validation rules is allowed if (actualValue == null && PropertyUtils.isReadable(content, field)) { actualValue = PropertyUtils.getProperty(content, field); } Map<String, Map<String, ?>> consMap = e.getValue(); for (Map.Entry<String, Map<String, ?>> constraint : consMap.entrySet()) { String consName = constraint.getKey(); Map<String, ?> vals = constraint.getValue(); if (vals == null) { vals = Collections.emptyMap(); } Object val = vals.get("value"); Object min = vals.get("min"); Object max = vals.get("max"); Object in = vals.get("integer"); Object fr = vals.get("fraction"); if ("required".equals(consName) && !required().isValid(actualValue)) { errors.add(Utils.formatMessage("{0} is required.", field)); } else if (matches(Min.class, consName) && !min(val).isValid(actualValue)) { errors.add( Utils.formatMessage("{0} must be a number larger than {1}.", field, val)); } else if (matches(Max.class, consName) && !max(val).isValid(actualValue)) { errors.add( Utils.formatMessage("{0} must be a number smaller than {1}.", field, val)); } else if (matches(Size.class, consName) && !size(min, max).isValid(actualValue)) { errors.add( Utils.formatMessage("{0} must be between {1} and {2}.", field, min, max)); } else if (matches(Email.class, consName) && !email().isValid(actualValue)) { errors.add(Utils.formatMessage("{0} is not a valid email.", field)); } else if (matches(Digits.class, consName) && !digits(in, fr).isValid(actualValue)) { errors.add( Utils.formatMessage("{0} is not a valid number or within range.", field)); } else if (matches(Pattern.class, consName) && !pattern(val).isValid(actualValue)) { errors.add(Utils.formatMessage("{0} doesn't match the pattern {1}.", field, val)); } else if (matches(AssertFalse.class, consName) && !falsy().isValid(actualValue)) { errors.add(Utils.formatMessage("{0} must be false.", field)); } else if (matches(AssertTrue.class, consName) && !truthy().isValid(actualValue)) { errors.add(Utils.formatMessage("{0} must be true.", field)); } else if (matches(Future.class, consName) && !future().isValid(actualValue)) { errors.add(Utils.formatMessage("{0} must be in the future.", field)); } else if (matches(Past.class, consName) && !past().isValid(actualValue)) { errors.add(Utils.formatMessage("{0} must be in the past.", field)); } else if (matches(URL.class, consName) && !url().isValid(actualValue)) { errors.add(Utils.formatMessage("{0} is not a valid URL.", field)); } } } if (!errors.isEmpty()) { return errors.toArray(new String[0]); } } } } catch (Exception ex) { logger.error(null, ex); } return validateObject(content); }
From source file:org.pdfsam.plugin.vpagereorder.listeners.RunButtonActionListener.java
public void actionPerformed(ActionEvent e) { File inputFile = panel.getSelectionPanel().getSelectedPdfDocument(); if (inputFile == null || !panel.getSelectionPanel().hasValidElements()) { JOptionPane.showMessageDialog(panel, GettextResource.gettext(Configuration.getInstance().getI18nResourceBundle(), "Please select a pdf document or undelete some page"), GettextResource.gettext(Configuration.getInstance().getI18nResourceBundle(), "Warning"), JOptionPane.WARNING_MESSAGE); return;// ww w. j av a 2s .c om } if (!panel.getSameAsSourceRadio().isSelected() && StringUtils.isEmpty(panel.getDestinationFileText().getText())) { DialogUtility.showWarningNoDestinationSelected(panel, DialogUtility.FILE_DESTINATION); return; } // overwrite confirmation if (panel.getOverwriteCheckbox().isSelected() && Configuration.getInstance().isAskOverwriteConfirmation()) { int dialogRet = DialogUtility.askForOverwriteConfirmation(panel); if (JOptionPane.NO_OPTION == dialogRet) { panel.getOverwriteCheckbox().setSelected(false); } else if (JOptionPane.CANCEL_OPTION == dialogRet) { return; } } LinkedList<String> args = new LinkedList<String>(); try { args.addAll(panel.getSelectionPanel().getValidConsoleParameters()); // rotation String rotation = panel.getSelectionPanel().getRotatedElementsString(); if (rotation != null && rotation.length() > 0) { args.add("-" + ConcatParsedCommand.R_ARG); args.add(rotation); } String destination = ""; // check radio for output options if (panel.getSameAsSourceRadio().isSelected()) { if (inputFile != null) { destination = inputFile.getAbsolutePath(); } } else { // if no extension given ensurePdfExtensionOnTextField(panel.getDestinationFileText()); File destinationDir = new File(panel.getDestinationFileText().getText()); File parent = destinationDir.getParentFile(); if (!(parent != null && parent.exists())) { String suggestedDir = null; if (Configuration.getInstance().getDefaultWorkingDirectory() != null && Configuration.getInstance().getDefaultWorkingDirectory().length() > 0) { suggestedDir = new File(Configuration.getInstance().getDefaultWorkingDirectory(), destinationDir.getName()).getAbsolutePath(); } else { suggestedDir = new File(inputFile.getParent(), destinationDir.getName()).getAbsolutePath(); } if (suggestedDir != null) { int chosenOpt = DialogUtility.showConfirmOuputLocationDialog(panel, suggestedDir); if (JOptionPane.YES_OPTION == chosenOpt) { panel.getDestinationFileText().setText(suggestedDir); } else if (JOptionPane.CANCEL_OPTION == chosenOpt) { return; } } } destination = panel.getDestinationFileText().getText(); } // check if the file already exists and the user didn't select to overwrite File destFile = (destination != null) ? new File(destination) : null; if (destFile != null && destFile.exists() && !panel.getOverwriteCheckbox().isSelected()) { int chosenOpt = DialogUtility.askForOverwriteOutputFileDialog(panel, destFile.getName()); if (JOptionPane.YES_OPTION == chosenOpt) { panel.getOverwriteCheckbox().setSelected(true); } else if (JOptionPane.CANCEL_OPTION == chosenOpt) { return; } } args.add("-" + ConcatParsedCommand.O_ARG); args.add(destination); if (panel.getOverwriteCheckbox().isSelected()) args.add("-" + ConcatParsedCommand.OVERWRITE_ARG); if (panel.getOutputCompressedCheck().isSelected()) args.add("-" + ConcatParsedCommand.COMPRESSED_ARG); args.add("-" + ConcatParsedCommand.PDFVERSION_ARG); args.add(((StringItem) panel.getVersionCombo().getSelectedItem()).getId()); args.add(AbstractParsedCommand.COMMAND_CONCAT); String[] myStringArray = args.toArray(new String[args.size()]); WorkExecutor.getInstance().execute(new WorkThread(myStringArray)); } catch (Exception ex) { log.error(GettextResource.gettext(Configuration.getInstance().getI18nResourceBundle(), "Error: "), ex); SoundPlayer.getInstance().playErrorSound(); } }
From source file:org.pdfsam.plugin.mix.listeners.RunButtonActionListener.java
public void actionPerformed(ActionEvent arg0) { if (WorkExecutor.getInstance().getRunningThreads() > 0 || panel.getSelectionPanel().isAdding()) { DialogUtility.showWarningAddingDocument(panel); return;/*from ww w.j a v a 2s . c o m*/ } PdfSelectionTableItem[] items = panel.getSelectionPanel().getTableRows(); if (items == null || items.length != 2) { DialogUtility.showWarningNoDocsSelected(panel, DialogUtility.TWO_DOC); return; } if (StringUtils.isEmpty(panel.getDestinationTextField().getText())) { DialogUtility.showWarningNoDestinationSelected(panel, DialogUtility.FILE_DESTINATION); return; } LinkedList<String> args = new LinkedList<String>(); try { // overwrite confirmation if (panel.getOverwriteCheckbox().isSelected() && Configuration.getInstance().isAskOverwriteConfirmation()) { int dialogRet = DialogUtility.askForOverwriteConfirmation(panel); if (JOptionPane.NO_OPTION == dialogRet) { panel.getOverwriteCheckbox().setSelected(false); } else if (JOptionPane.CANCEL_OPTION == dialogRet) { return; } } args.addAll(getInputFilesArguments(items)); String destination = ""; // if no extension given ensurePdfExtensionOnTextField(panel.getDestinationTextField()); File destinationDir = new File(panel.getDestinationTextField().getText()); File parent = destinationDir.getParentFile(); if (!(parent != null && parent.exists())) { String suggestedDir = getSuggestedOutputFile(items[items.length - 1], destinationDir.getName()); int chosenOpt = DialogUtility.showConfirmOuputLocationDialog(panel, suggestedDir); if (JOptionPane.YES_OPTION == chosenOpt) { panel.getDestinationTextField().setText(suggestedDir); } else if (JOptionPane.CANCEL_OPTION == chosenOpt) { return; } } destination = panel.getDestinationTextField().getText(); // check if the file already exists and the user didn't select to overwrite File destFile = (destination != null) ? new File(destination) : null; if (destFile != null && destFile.exists() && !panel.getOverwriteCheckbox().isSelected()) { int chosenOpt = DialogUtility.askForOverwriteOutputFileDialog(panel, destFile.getName()); if (JOptionPane.YES_OPTION == chosenOpt) { panel.getOverwriteCheckbox().setSelected(true); } else if (JOptionPane.CANCEL_OPTION == chosenOpt) { return; } } args.add("-" + MixParsedCommand.O_ARG); args.add(destination); String step = panel.getStepTextField().getText(); if (StringUtils.isNotEmpty(step)) { args.add("-" + MixParsedCommand.STEP_ARG); args.add(step); } String secondStep = panel.getSecondStepTextField().getText(); if (StringUtils.isNotEmpty(secondStep)) { args.add("-" + MixParsedCommand.SECOND_STEP_ARG); args.add(secondStep); } if (panel.getOverwriteCheckbox().isSelected()) args.add("-" + MixParsedCommand.OVERWRITE_ARG); if (panel.getOutputCompressedCheck().isSelected()) args.add("-" + MixParsedCommand.COMPRESSED_ARG); if (panel.getReverseFirstCheckbox().isSelected()) args.add("-" + MixParsedCommand.REVERSE_FIRST_ARG); if (panel.getReverseSecondCheckbox().isSelected()) args.add("-" + MixParsedCommand.REVERSE_SECOND_ARG); args.add("-" + MixParsedCommand.PDFVERSION_ARG); args.add(((StringItem) panel.getVersionCombo().getSelectedItem()).getId()); args.add(MixParsedCommand.COMMAND_MIX); String[] myStringArray = args.toArray(new String[args.size()]); WorkExecutor.getInstance().execute(new WorkThread(myStringArray)); } catch (Exception ex) { log.error(GettextResource.gettext(Configuration.getInstance().getI18nResourceBundle(), "Error: "), ex); SoundPlayer.getInstance().playErrorSound(); } }
From source file:org.pdfsam.plugin.setviewer.listeners.RunButtonActionListener.java
public void actionPerformed(ActionEvent arg0) { if (WorkExecutor.getInstance().getRunningThreads() > 0 || panel.getSelectionPanel().isAdding()) { DialogUtility.showWarningAddingDocument(panel); return;//from w ww .java 2 s . c o m } PdfSelectionTableItem[] items = panel.getSelectionPanel().getTableRows(); if (ArrayUtils.isEmpty(items)) { DialogUtility.showWarningNoDocsSelected(panel, DialogUtility.AT_LEAST_ONE_DOC); return; } LinkedList<String> args = new LinkedList<String>(); // validation and permission check are demanded to the CmdParser object try { // overwrite confirmation if (panel.getOverwriteCheckbox().isSelected() && Configuration.getInstance().isAskOverwriteConfirmation()) { int dialogRet = DialogUtility.askForOverwriteConfirmation(panel); if (JOptionPane.NO_OPTION == dialogRet) { panel.getOverwriteCheckbox().setSelected(false); } else if (JOptionPane.CANCEL_OPTION == dialogRet) { return; } } args.addAll(getInputFilesArguments(items)); args.add("-" + SetViewerParsedCommand.P_ARG); args.add(panel.getOutPrefixTextField().getText()); args.add("-" + SetViewerParsedCommand.O_ARG); if (StringUtils.isEmpty(panel.getDestFolderText().getText())) { String suggestedDir = getSuggestedDestinationDirectory(items[items.length - 1]); int chosenOpt = DialogUtility.showConfirmOuputLocationDialog(panel, suggestedDir); if (JOptionPane.YES_OPTION == chosenOpt) { panel.getDestFolderText().setText(suggestedDir); } else if (JOptionPane.CANCEL_OPTION == chosenOpt) { return; } } args.add(panel.getDestFolderText().getText()); args.add("-" + SetViewerParsedCommand.L_ARG); args.add(((StringItem) panel.getViewerLayout().getSelectedItem()).getId()); args.add("-" + SetViewerParsedCommand.M_ARG); args.add(((StringItem) panel.getViewerOpenMode().getSelectedItem()).getId()); if (panel.getNonFullScreenMode().isEnabled()) { args.add("-" + SetViewerParsedCommand.NFSM_ARG); args.add(((StringItem) panel.getNonFullScreenMode().getSelectedItem()).getId()); } if (((StringItem) panel.getDirectionCombo().getSelectedItem()).getId().length() > 0) { args.add("-" + SetViewerParsedCommand.DIRECTION_ARG); args.add(((StringItem) panel.getDirectionCombo().getSelectedItem()).getId()); } if (panel.getHideMenuBar().isSelected()) { args.add("-" + SetViewerParsedCommand.HIDEMENU_ARG); } if (panel.getHideToolBar().isSelected()) { args.add("-" + SetViewerParsedCommand.HIDETOOLBAR_ARG); } if (panel.getHideUIElements().isSelected()) { args.add("-" + SetViewerParsedCommand.HIDEWINDOWUI_ARG); } if (panel.getResizeToFit().isSelected()) { args.add("-" + SetViewerParsedCommand.FITWINDOW_ARG); } if (panel.getCenterScreen().isSelected()) { args.add("-" + SetViewerParsedCommand.CENTERWINDOW_ARG); } if (panel.getDisplayTitle().isSelected()) { args.add("-" + SetViewerParsedCommand.DOCTITLE_ARG); } if (panel.getNoPageScaling().isSelected()) { args.add("-" + SetViewerParsedCommand.NOPRINTSCALING_ARG); } if (panel.getOverwriteCheckbox().isSelected()) { args.add("-" + SetViewerParsedCommand.OVERWRITE_ARG); } if (panel.getOutputCompressedCheck().isSelected()) { args.add("-" + SetViewerParsedCommand.COMPRESSED_ARG); } args.add("-" + SetViewerParsedCommand.PDFVERSION_ARG); args.add(((StringItem) panel.getVersionCombo().getSelectedItem()).getId()); args.add(SetViewerParsedCommand.COMMAND_SETVIEWER); String[] myStringArray = (String[]) args.toArray(new String[args.size()]); WorkExecutor.getInstance().execute(new WorkThread(myStringArray)); } catch (Exception ex) { log.error(GettextResource.gettext(Configuration.getInstance().getI18nResourceBundle(), "Error: "), ex); SoundPlayer.getInstance().playErrorSound(); } }
From source file:org.pdfsam.plugin.merge.listeners.RunButtonActionListener.java
public void actionPerformed(ActionEvent arg0) { if (WorkExecutor.getInstance().getRunningThreads() > 0 || panel.getSelectionPanel().isAdding()) { DialogUtility.showWarningAddingDocument(panel); return;//from ww w . ja v a 2 s . co m } PdfSelectionTableItem[] items = panel.getSelectionPanel().getTableRows(); if (ArrayUtils.isEmpty(items)) { DialogUtility.showWarningNoDocsSelected(panel, DialogUtility.AT_LEAST_ONE_DOC); return; } if (StringUtils.isEmpty(panel.getDestinationTextField().getText())) { DialogUtility.showWarningNoDestinationSelected(panel, DialogUtility.FILE_DESTINATION); return; } LinkedList<String> args = new LinkedList<String>(); try { // overwrite confirmation if (panel.getOverwriteCheckbox().isSelected() && Configuration.getInstance().isAskOverwriteConfirmation()) { int dialogRet = DialogUtility.askForOverwriteConfirmation(panel); if (JOptionPane.NO_OPTION == dialogRet) { panel.getOverwriteCheckbox().setSelected(false); } else if (JOptionPane.CANCEL_OPTION == dialogRet) { return; } } // if no extension given ensurePdfExtensionOnTextField(panel.getDestinationTextField()); File destinationDir = new File(panel.getDestinationTextField().getText()); File parent = destinationDir.getParentFile(); // only filename no dir if (!(parent != null && parent.exists())) { String suggestedDir = getSuggestedOutputFile(items[items.length - 1], destinationDir.getName()); int chosenOpt = DialogUtility.showConfirmOuputLocationDialog(panel, suggestedDir); if (JOptionPane.YES_OPTION == chosenOpt) { panel.getDestinationTextField().setText(suggestedDir); } else if (JOptionPane.CANCEL_OPTION == chosenOpt) { return; } } String destination = panel.getDestinationTextField().getText(); // check if the file already exists and the user didn't select to overwrite File destFile = (destination != null) ? new File(destination) : null; if (destFile != null && destFile.exists() && !panel.getOverwriteCheckbox().isSelected()) { int chosenOpt = DialogUtility.askForOverwriteOutputFileDialog(panel, destFile.getName()); if (JOptionPane.YES_OPTION == chosenOpt) { panel.getOverwriteCheckbox().setSelected(true); } else if (JOptionPane.CANCEL_OPTION == chosenOpt) { return; } } args.add("-" + ConcatParsedCommand.O_ARG); args.add(destination); StringBuilder psStringBuilder = new StringBuilder(); for (PdfSelectionTableItem item : items) { String pageSelection = (!StringUtils.isEmpty(item.getPageSelection())) ? item.getPageSelection() : MergeMainGUI.ALL_STRING; String[] selections = StringUtils.split(pageSelection, ","); if (!ValidationUtility.isValidPageSelectionsArray(selections)) { DialogUtility.errorValidatingBounds(panel, pageSelection); return; } else { args.add("-" + ConcatParsedCommand.F_ARG); String f = item.getInputFile().getAbsolutePath(); if (!StringUtils.isEmpty(item.getPassword())) { log.debug(GettextResource.gettext(Configuration.getInstance().getI18nResourceBundle(), "Found a password for input file.")); f += ":" + item.getPassword(); } args.add(f); psStringBuilder.append(pageSelection).append(":"); } } args.add("-" + ConcatParsedCommand.U_ARG); args.add(psStringBuilder.toString()); if (panel.getOverwriteCheckbox().isSelected()) args.add("-" + ConcatParsedCommand.OVERWRITE_ARG); if (panel.getOutputCompressedCheck().isSelected()) args.add("-" + ConcatParsedCommand.COMPRESSED_ARG); if (panel.getMergeTypeCheck().isSelected()) args.add("-" + ConcatParsedCommand.COPYFIELDS_ARG); args.add("-" + ConcatParsedCommand.PDFVERSION_ARG); args.add(((StringItem) panel.getVersionCombo().getSelectedItem()).getId()); args.add(AbstractParsedCommand.COMMAND_CONCAT); String[] myStringArray = args.toArray(new String[args.size()]); WorkExecutor.getInstance().execute(new WorkThread(myStringArray)); } catch (Exception ex) { log.error(GettextResource.gettext(Configuration.getInstance().getI18nResourceBundle(), "Error: "), ex); SoundPlayer.getInstance().playErrorSound(); } }
From source file:org.jsweet.transpiler.JSweetTranspiler.java
private void ts2js(ErrorCountTranspilationHandler transpilationHandler, SourceFile[] files) throws IOException { if (tsCompilationProcess != null && isTscWatchMode()) { return;/*from w w w.j a v a2 s.c o m*/ } if (isTscWatchMode()) { watchedFiles = files; } logger.debug("ts2js: " + Arrays.asList(files)); LinkedList<String> args = new LinkedList<>(); if (System.getProperty("os.name").startsWith("Windows")) { args.addAll(asList("--target", ecmaTargetVersion.name())); } else { args.addAll(asList("--target", ecmaTargetVersion.name())); } if (isUsingModules()) { if (ecmaTargetVersion.higherThan(EcmaScriptComplianceLevel.ES5)) { logger.warn("cannot use old fashionned modules with ES>5 target"); } else { args.add("--module"); args.add(moduleKind.toString()); } } if (ecmaTargetVersion.ordinal() >= EcmaScriptComplianceLevel.ES5.ordinal()) { args.add("--experimentalDecorators"); } if (isTscWatchMode()) { args.add("--watch"); } if (isPreserveSourceLineNumbers()) { args.add("--sourceMap"); } if (isGenerateDeclarations()) { args.add("--declaration"); } args.addAll(asList("--rootDir", tsOutputDir.getAbsolutePath())); // args.addAll(asList("--sourceRoot", tsOutputDir.toString())); if (jsOutputDir != null) { args.addAll(asList("--outDir", jsOutputDir.getAbsolutePath())); } File tscRootFile = getOrCreateTscRootFile(); if (tscRootFile.exists()) { args.add(relativizeTsFile(tscRootFile).toString()); } for (SourceFile sourceFile : files) { String filePath = relativizeTsFile(sourceFile.getTsFile()).toString(); if (!args.contains(filePath)) { args.add(filePath); } } // this may not be necessary because tsc seems to add required modules // automatically for (File f : auxiliaryTsModuleFiles) { String filePath = relativizeTsFile(f).toString(); if (!args.contains(filePath)) { args.add(filePath); } } for (File dir : tsDefDirs) { LinkedList<File> tsDefFiles = new LinkedList<>(); Util.addFiles(".d.ts", dir, tsDefFiles); for (File f : tsDefFiles) { args.add(relativizeTsFile(f).toString()); } } LinkedList<File> tsDefFiles = new LinkedList<>(); Util.addFiles(".d.ts", tsOutputDir, tsDefFiles); for (File f : tsDefFiles) { args.add(relativizeTsFile(f).toString()); } try { logger.info("launching tsc..."); runTSC(transpilationHandler, files, args.toArray(new String[0])); } catch (Exception e) { e.printStackTrace(); } }
From source file:de._13ducks.cor.game.server.movement.SectorPathfinder.java
/** * Der Start und Zielknoten sind von weit mehr als nur den Knoten ihres Polygons erreichbar. * Dies muss bereits whrend der Basic-Berechnung beachtet werden, das kann die Pfadoptimierung nachtrglich nichtmehr leisten. * Also alle Nodes suchen, die ohne Hinderniss direkt erreichbar sind * @param from alle vollstndig im Mesh liegenden Kanten von hier zu Nachbarknoten suchen * @param basicPolygon Der Polygon, in dem der Node drinliegt. * @return alle direkt erreichbaren Knoten (natrlich sind die des basicPolygons auch dabei) *///from w w w .j av a 2 s . co m private static Node[] computeDirectReachable(Node from, FreePolygon basicPolygon) { // Das ist eine modifizierte Breitensuche: LinkedList<FreePolygon> open = new LinkedList<FreePolygon>(); // Queue fr zu untersuchende Polygone LinkedHashSet<FreePolygon> openContains = new LinkedHashSet<FreePolygon>(); // Welche Elemente die open enthlt (schnellerer Test) LinkedHashSet<FreePolygon> closed = new LinkedHashSet<FreePolygon>(); LinkedHashSet<Node> testedNodes = new LinkedHashSet<Node>(); LinkedList<Node> result = new LinkedList<Node>(); open.offer(basicPolygon); // Start-Polygon openContains.add(basicPolygon); while (!open.isEmpty()) { // Diesen hier bearbeiten wir jetzt FreePolygon poly = open.poll(); openContains.remove(poly); closed.add(poly); boolean containsreachableNodes = false; // Alle Nodes dieses Knotens untersuchen for (Node node : poly.getNodes()) { // Schon bekannt? if (result.contains(node)) { // Bekannt und ok containsreachableNodes = true; } else { if (testedNodes.contains(node)) { // Der geht nicht } else { // Testen! FreePolygon currentPoly = basicPolygon; // Testweise Kante zwischen from und node erstellen Edge edge = new Edge(from, node); // Im Folgenden wird untersucht, ob der neue Weg "edge" passierbar ist. // Damit wir beim Dreieckwechsel nicht wieder zurck gehen: Node lastNode = null; boolean routeAllowed = true; // Jetzt so lange weiter laufen, bis wir im Ziel-Polygon sind while (!node.getPolygons().contains(currentPoly)) { // Untersuchen, ob es eine Seite des currentPolygons gibt, die sich mit der alternativRoute schneidet List<Edge> edges = currentPoly.calcEdges(); Edge intersecting = null; SimplePosition intersection = null; for (Edge testedge : edges) { // Gibts da einen Schnitt? intersection = edge.intersectionWithEndsNotAllowed(testedge); if (intersection != null && !intersection.equals(lastNode)) { intersecting = testedge; break; } } // Kandidat fr den nchsten Polygon FreePolygon nextPoly = null; // Kante gefunden if (intersecting != null) { // Von dieser Kante die Enden suchen nextPoly = getOtherPoly(intersecting.getStart(), intersecting.getEnd(), currentPoly); } if (intersecting != null && nextPoly != null) { // Wir haben einen Schnittpunkt und eine Kante gefunden, sind jetzt also in einem neuen Polygon // Extra Node bentigt Node extraNode = intersection.toNode(); extraNode.addPolygon(nextPoly); extraNode.addPolygon(currentPoly); lastNode = extraNode; currentPoly = nextPoly; // Der nchste Schleifendurchlauf wird den nchsten Polygon untersuchen } else { // Es gab leider keinen betretbaren Polygon hier. // Das bedeutet, dass wir die Suche abbrechen knnen, es gibt hier keinen direkten Weg routeAllowed = false; break; } } // Wenn der neue Weg gltig war, einbauen. Sonst weiter mit dem nchsten Knoten if (routeAllowed) { // In die erlaubt-Liste: result.add(node); testedNodes.add(node); containsreachableNodes = true; } else { testedNodes.add(node); } } } } // Nur weiter in die Tiefe gehen, wenn mindestens einer erreichbar war if (containsreachableNodes) { // Alle Nachbarn untersuchen: for (FreePolygon n : poly.getNeighbors()) { // Schon bekannt/bearbeitet? if (!openContains.contains(n) && !closed.contains(n)) { // Nein, also auch zur Bearbeitung vorsehen open.add(n); openContains.add(n); } } } } return result.toArray(new Node[0]); }
From source file:org.gcaldaemon.core.ldap.ContactLoader.java
private final void loadContacts() throws Exception { // Loading contact list log.debug("Loading Gmail contact list..."); GmailPool pool = configurator.getGmailPool(); LinkedList contactList = new LinkedList(); HashSet processedEntries = new HashSet(); String rev = new DateTime().toString(); HashSet cardFiles = new HashSet(); GmailEntry entry = null;//from w w w . j a v a2 s. c o m GmailContact contact; String key, csv; boolean found; char[] chars; int i, m, n; char c; // Loop on accounts QuickWriter buffer = new QuickWriter(); for (n = 0; n < usernames.length; n++) { try { // Download CSV from Gmail entry = pool.borrow(usernames[n], passwords[n]); csv = entry.downloadCSV(); if (csv == null) { continue; } // Remove header chars = csv.toCharArray(); found = false; i = -1; for (m = 0; m < chars.length; m++) { c = chars[m]; if (c == '\r' || c == '\n') { found = true; continue; } if (found) { i = m; break; } } if (i != -1) { buffer.write(chars, i, chars.length - i); } } finally { pool.recycle(entry); } if (n < usernames.length - 1) { Thread.sleep(1000); } } // Parse CSV to GmailContact array csv = buffer.toString(); GmailContact[] contactArray = parseCSV(csv); // Save 'contacts.csv' in UTF8 into the 'work/vcard' dir File file = new File(vcardDirectory, "contacts.csv"); byte[] bytes = StringUtils.encodeString(csv, StringUtils.UTF_8); saveFile(file, bytes); // Process contacts if (contactArray == null) { contactArray = new GmailContact[0]; } for (i = 0; i < contactArray.length; i++) { // Verify email address and name field contact = contactArray[i]; if (contact.email.length() == 0) { // Use the secondary email address contact.email = contact.mail; } if (contact.name.length() == 0) { // Create name from the email address contact.name = contact.email; m = contact.name.indexOf('@'); if (m != -1) { contact.name = contact.name.substring(0, m); } } // Fix MS Address Book bug if (contact.email.indexOf('@') == -1) { continue; } key = contact.email + '\t' + contact.name; if (processedEntries.contains(key)) { continue; } processedEntries.add(key); if (contact.email.length() != 0) { // Save vcard with name and email address contactList.addLast(contact); } else { if (contact.name.length() != 0) { // Save vcard without email address cardFiles.add(saveVCard(contact, rev)); } } } GmailContact[] array = new GmailContact[contactList.size()]; contactList.toArray(array); // Save contacts withall email addresses for (i = 0; i < array.length; i++) { cardFiles.add(saveVCard(array[i], rev)); } // Save contact in other formats (eg. HTML) saveContacts(vcardDirectory, array, buffer); // Remove deleted contacts String[] currentFiles = vcardDirectory.list(); String fileName; for (i = 0; i < currentFiles.length; i++) { fileName = currentFiles[i]; if (fileName.endsWith(VCARD_EXTENSION) && !cardFiles.contains(fileName)) { (new File(vcardDirectory, fileName)).delete(); } } // Contact list loaded synchronized (this) { contacts = array; } log.debug(array.length + " contacts loaded successfully."); }
From source file:com.buaa.cfs.conf.Configuration.java
private Resource loadResource(Properties properties, Resource wrapper, boolean quiet) { String name = UNKNOWN_RESOURCE; try {//from ww w . j a va 2s . c o m Object resource = wrapper.getResource(); name = wrapper.getName(); DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); //ignore all comments inside the xml file docBuilderFactory.setIgnoringComments(true); //allow includes in the xml file docBuilderFactory.setNamespaceAware(true); try { docBuilderFactory.setXIncludeAware(true); } catch (UnsupportedOperationException e) { LOG.error("Failed to set setXIncludeAware(true) for parser " + docBuilderFactory + ":" + e, e); } DocumentBuilder builder = docBuilderFactory.newDocumentBuilder(); Document doc = null; Element root = null; boolean returnCachedProperties = false; if (resource instanceof URL) { // an URL resource doc = parse(builder, (URL) resource); } else if (resource instanceof String) { // a CLASSPATH resource URL url = getResource((String) resource); doc = parse(builder, url); } else if (resource instanceof Path) { // a file resource // Can't use FileSystem API or we get an infinite loop // since FileSystem uses Configuration API. Use java.io.File instead. File file = new File(((Path) resource).toUri().getPath()).getAbsoluteFile(); if (file.exists()) { if (!quiet) { LOG.debug("parsing File " + file); } doc = parse(builder, new BufferedInputStream(new FileInputStream(file)), ((Path) resource).toString()); } } else if (resource instanceof InputStream) { doc = parse(builder, (InputStream) resource, null); returnCachedProperties = true; } else if (resource instanceof Properties) { overlay(properties, (Properties) resource); } else if (resource instanceof Element) { root = (Element) resource; } if (root == null) { if (doc == null) { if (quiet) { return null; } throw new RuntimeException(resource + " not found"); } root = doc.getDocumentElement(); } Properties toAddTo = properties; if (returnCachedProperties) { toAddTo = new Properties(); } if (!"configuration".equals(root.getTagName())) LOG.fatal("bad conf file: top-level element not <configuration>"); NodeList props = root.getChildNodes(); DeprecationContext deprecations = deprecationContext.get(); for (int i = 0; i < props.getLength(); i++) { Node propNode = props.item(i); if (!(propNode instanceof Element)) continue; Element prop = (Element) propNode; if ("configuration".equals(prop.getTagName())) { loadResource(toAddTo, new Resource(prop, name), quiet); continue; } if (!"property".equals(prop.getTagName())) LOG.warn("bad conf file: element not <property>"); NodeList fields = prop.getChildNodes(); String attr = null; String value = null; boolean finalParameter = false; LinkedList<String> source = new LinkedList<String>(); for (int j = 0; j < fields.getLength(); j++) { Node fieldNode = fields.item(j); if (!(fieldNode instanceof Element)) continue; Element field = (Element) fieldNode; if ("name".equals(field.getTagName()) && field.hasChildNodes()) attr = StringInterner.weakIntern(((Text) field.getFirstChild()).getData().trim()); if ("value".equals(field.getTagName()) && field.hasChildNodes()) value = StringInterner.weakIntern(((Text) field.getFirstChild()).getData()); if ("final".equals(field.getTagName()) && field.hasChildNodes()) finalParameter = "true".equals(((Text) field.getFirstChild()).getData()); if ("source".equals(field.getTagName()) && field.hasChildNodes()) source.add(StringInterner.weakIntern(((Text) field.getFirstChild()).getData())); } source.add(name); // Ignore this parameter if it has already been marked as 'final' if (attr != null) { if (deprecations.getDeprecatedKeyMap().containsKey(attr)) { DeprecatedKeyInfo keyInfo = deprecations.getDeprecatedKeyMap().get(attr); keyInfo.clearAccessed(); for (String key : keyInfo.newKeys) { // update new keys with deprecated key's value loadProperty(toAddTo, name, key, value, finalParameter, source.toArray(new String[source.size()])); } } else { loadProperty(toAddTo, name, attr, value, finalParameter, source.toArray(new String[source.size()])); } } } if (returnCachedProperties) { overlay(properties, toAddTo); return new Resource(toAddTo, name); } return null; } catch (IOException e) { LOG.fatal("error parsing conf " + name, e); throw new RuntimeException(e); } catch (DOMException e) { LOG.fatal("error parsing conf " + name, e); throw new RuntimeException(e); } catch (SAXException e) { LOG.fatal("error parsing conf " + name, e); throw new RuntimeException(e); } catch (ParserConfigurationException e) { LOG.fatal("error parsing conf " + name, e); throw new RuntimeException(e); } }
From source file:oscar.oscarRx.data.RxPrescriptionData.java
public Favorite[] getFavorites(String providerNo) { Favorite[] arr = {};// ww w . ja v a 2 s . c o m LinkedList lst = new LinkedList(); try { ResultSet rs; Favorite favorite; rs = DBHandler.GetSQL( "SELECT * FROM favorites WHERE provider_no = '" + providerNo + "' ORDER BY favoritename"); while (rs.next()) { favorite = new Favorite(rs.getInt("favoriteid"), oscar.Misc.getString(rs, "provider_no"), oscar.Misc.getString(rs, "favoritename"), oscar.Misc.getString(rs, "BN"), rs.getInt("GCN_SEQNO"), oscar.Misc.getString(rs, "customName"), rs.getFloat("takemin"), rs.getFloat("takemax"), oscar.Misc.getString(rs, "freqcode"), oscar.Misc.getString(rs, "duration"), oscar.Misc.getString(rs, "durunit"), oscar.Misc.getString(rs, "quantity"), rs.getInt("repeat"), rs.getInt("nosubs"), rs.getInt("prn"), oscar.Misc.getString(rs, "special"), oscar.Misc.getString(rs, "GN"), oscar.Misc.getString(rs, "ATC"), oscar.Misc.getString(rs, "regional_identifier"), oscar.Misc.getString(rs, "unit"), oscar.Misc.getString(rs, "unitName"), oscar.Misc.getString(rs, "method"), oscar.Misc.getString(rs, "route"), oscar.Misc.getString(rs, "drug_form"), rs.getBoolean("custom_instructions"), oscar.Misc.getString(rs, "dosage")); lst.add(favorite); } rs.close(); arr = (Favorite[]) lst.toArray(arr); } catch (SQLException e) { logger.error("unexpected error", e); } finally { DbConnectionFilter.releaseThreadLocalDbConnection(); } return arr; }