List of usage examples for java.util LinkedList contains
public boolean contains(Object o)
From source file:com.redsqirl.workflow.server.Workflow.java
/** * Get all elements needed for this element * /*from www. j a v a 2s .c o m*/ * @param el * @return List if elements * @throws RemoteException */ protected LinkedList<DataFlowElement> getItAndAllElementsNeeded(DataFlowElement el) throws RemoteException { LinkedList<DataFlowElement> ans = new LinkedList<DataFlowElement>(); ans.add(el); Map<String, List<DFEOutput>> ins = el.getDependencies(); Iterator<String> it = ins.keySet().iterator(); while (it.hasNext()) { String cur = it.next(); boolean needed = false; Iterator<DFEOutput> itOut = ins.get(cur).iterator(); while (itOut.hasNext() && !needed) { DFEOutput outCur = itOut.next(); needed = !outCur.isPathExist(); } if (needed) { Iterator<DataFlowElement> itCur = getItAndAllElementsNeeded(getElement(cur)).iterator(); while (itCur.hasNext()) { DataFlowElement cans = itCur.next(); if (!ans.contains(cans)) { ans.add(cans); } } } } return ans; }
From source file:com.sshtools.common.ui.SshToolsApplicationClientPanel.java
/** * * * @param newProfile//from w w w. j av a2 s.com * * @return * * @throws IOException */ protected boolean authenticateUser(boolean newProfile) throws IOException { try { // We should now authenticate int result = AuthenticationProtocolState.READY; // Our authenticated flag boolean authenticated = false; // Get the supported authentication methods java.util.List auths = SshAuthenticationClientFactory.getSupportedMethods(); // Get the available methods java.util.List supported = null; supported = ssh.getAvailableAuthMethods(getCurrentConnectionProfile().getUsername()); if (supported == null) throw new IOException( "There are no authentication methods which both the server and client understand.\n Cannot connect."); // If the server supports external key exchange then we SHOULD use it if (supported.contains("external-keyx")) { EKEYXAuthenticationClient aa = new EKEYXAuthenticationClient(); aa.setProperties(getCurrentConnectionProfile()); aa.setUsername(getCurrentConnectionProfile().getUsername()); result = ssh.authenticate(aa, getCurrentConnectionProfile().getHost()); if (result == AuthenticationProtocolState.COMPLETE) { authenticationComplete(newProfile); return true; } } // If the server supports public key lets look for an agent and try // some of his keys if (supported.contains("publickey")) { if (System.getProperty("sshtools.agent") != null) { try { SshAgentClient agent = SshAgentClient.connectLocalAgent("SSHTerm", System.getProperty("sshtools.agent") /*, 5*/); AgentAuthenticationClient aac = new AgentAuthenticationClient(); aac.setAgent(agent); aac.setUsername(getCurrentConnectionProfile().getUsername()); result = ssh.authenticate(aac, getCurrentConnectionProfile().getHost()); agent.close(); } catch (AgentNotAvailableException ex) { log.info("No agent was available for authentication"); // Just continue } if (result == AuthenticationProtocolState.COMPLETE) { authenticationComplete(newProfile); return true; } } } // Create a list for display that will contain only the // supported and available methods java.util.List display = new java.util.ArrayList(); // Did we receive a banner from the remote computer final String banner = ssh.getAuthenticationBanner(BANNER_TIMEOUT); if (banner != null) { if (!banner.trim().equals("")) { try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { BannerDialog.showBannerDialog(SshToolsApplicationClientPanel.this, banner); } }); } catch (Exception e) { log.error("Failed to invoke and wait on BannerDialog", e); } } } // Are there any authentication methods within the properties file? // Iterate through selecting only the supported and available Iterator it = supported.iterator(); LinkedList allowed = new LinkedList(); while (it.hasNext() && !authenticated) { Object obj = it.next(); if (auths.contains(obj)) { display.add(obj); allowed.add(obj); //System.out.println(obj); } } // First look to see if we have any authenticaiton methods available // in the profile properties object as this will overide a manual selection java.util.Map authMethods = (Map) ((HashMap) getCurrentConnectionProfile().getAuthenticationMethods()) .clone(); it = authMethods.entrySet().iterator(); //Iterator it2 = null; java.util.List selected; // Loop until the user either cancels or completes boolean completed = false; SshAuthenticationClient auth; Map.Entry entry; String msg = null; while (!completed && (ssh.getConnectionState().getValue() != TransportProtocolState.DISCONNECTED)) { auth = null; // Select an authentication method from the properties file or // prompt the user to choose if (it.hasNext()) { Object obj = it.next(); if (obj instanceof Map.Entry) { entry = (Map.Entry) obj; auth = (SshAuthenticationClient) entry.getValue(); } else if (obj instanceof String) { auth = SshAuthenticationClientFactory.newInstance((String) obj, getCurrentConnectionProfile()); auth.setUsername(getCurrentConnectionProfile().getUsername()); } else { closeConnection(true); throw new IOException("Iterator of Map or List of String expected"); } } else { selected = AuthenticationDialog.showAuthenticationDialog(this, display, ((msg == null) ? "" : msg)); if (selected.size() > 0) { it = selected.iterator(); } else { closeConnection(true); return false; } } if (auth != null && !allowed.contains(auth.getMethodName())) auth = null; if (auth != null) { // The password authentication client can act upon requests to change the password /* if (auth instanceof PasswordAuthenticationClient) { PasswordAuthenticationDialog dialog = new PasswordAuthenticationDialog(SshTerminalPanel.this); ((PasswordAuthenticationClient) auth).setAuthenticationPrompt(dialog); ( (PasswordAuthenticationClient) auth) .setPasswordChangePrompt(PasswordChange.getInstance()); PasswordChange.getInstance().setParentComponent( SshTerminalPanel.this); }*/ // Show the implementations dialog // if(auth.showAuthenticationDialog()) { // Authentication with the details supplied try { result = showAuthenticationPrompt(auth); //ssh.authenticate(auth); } catch (IllegalArgumentException e) {// Do not use this authentication method! allowed.remove(auth); } if (result == AuthenticationProtocolState.FAILED) { msg = auth.getMethodName() + " authentication failed, try again?"; } // If the result returned partial success then continue if (result == AuthenticationProtocolState.PARTIAL) { // We succeeded so add to the connections authenticaiton // list and continue on to the next one getCurrentConnectionProfile().addAuthenticationMethod(auth); msg = auth.getMethodName() + " authentication succeeded but another is required"; } if (result == AuthenticationProtocolState.COMPLETE) { authenticated = true; //If successfull add to the connections list so we can save later getCurrentConnectionProfile().addAuthenticationMethod(auth); // Set the completed flag completed = true; authenticationComplete(newProfile); } if (result == AuthenticationProtocolState.CANCELLED) { ssh.disconnect(); return false; } // } // else { // User has cancelled the authenticaiton // closeConnection(true); // return false; // } } // end of if } // end of while return authenticated; } catch (EOFException e) { throw new IOException( "The remote host has closed the connection.\n\nAs you are authenticating this probably means the server has given up authenticating you."); } catch (MessageStoreEOFException e) { throw new IOException( "The remote host has closed the connection.\n\nAs you are authenticating this probably means the server has given up authenticating you."); } }
From source file:net.lightbody.bmp.proxy.jetty.http.HttpContext.java
/** Get the file classpath of the context. * This method makes a best effort to return a complete file * classpath for the context./*www .java 2 s.c o m*/ * It is obtained by walking the classloader hierarchy and looking for * URLClassLoaders. The system property java.class.path is also checked for * file elements not already found in the loader hierarchy. * @return Path of files and directories for loading classes. * @exception IllegalStateException HttpContext.initClassLoader * has not been called. */ public String getFileClassPath() throws IllegalStateException { ClassLoader loader = getClassLoader(); if (loader == null) throw new IllegalStateException("Context classloader not initialized"); LinkedList paths = new LinkedList(); LinkedList loaders = new LinkedList(); // Walk the loader hierarchy while (loader != null) { loaders.add(0, loader); loader = loader.getParent(); } // Try to handle java2compliant modes loader = getClassLoader(); if (loader instanceof ContextLoader && !((ContextLoader) loader).isJava2Compliant()) { loaders.remove(loader); loaders.add(0, loader); } for (int i = 0; i < loaders.size(); i++) { loader = (ClassLoader) loaders.get(i); if (log.isDebugEnabled()) log.debug("extract paths from " + loader); if (loader instanceof URLClassLoader) { URL[] urls = ((URLClassLoader) loader).getURLs(); for (int j = 0; urls != null && j < urls.length; j++) { try { Resource path = Resource.newResource(urls[j]); if (log.isTraceEnabled()) log.trace("path " + path); File file = path.getFile(); if (file != null) paths.add(file.getAbsolutePath()); } catch (Exception e) { LogSupport.ignore(log, e); } } } } // Add the system classpath elements from property. String jcp = System.getProperty("java.class.path"); if (jcp != null) { StringTokenizer tok = new StringTokenizer(jcp, File.pathSeparator); while (tok.hasMoreTokens()) { String path = tok.nextToken(); if (!paths.contains(path)) { if (log.isTraceEnabled()) log.trace("PATH=" + path); paths.add(path); } else if (log.isTraceEnabled()) log.trace("done=" + path); } } StringBuffer buf = new StringBuffer(); Iterator iter = paths.iterator(); while (iter.hasNext()) { if (buf.length() > 0) buf.append(File.pathSeparator); buf.append(iter.next().toString()); } if (log.isDebugEnabled()) log.debug("fileClassPath=" + buf); return buf.toString(); }
From source file:com.sun.portal.rssportlet.RssPortlet.java
private void processEditAction(ActionRequest request, ActionResponse response, AlertHandler alertHandler, Resources resources, SettingsBean readBean, SettingsBean writeBean) throws PortletModeException { String[] checkedFeeds = request.getParameterValues(INPUT_FEEDS); LinkedList feeds = null; if (checkedFeeds != null) { feeds = new LinkedList(Arrays.asList(checkedFeeds)); PortletSession psession = request.getPortletSession(); String[] mandate_feeds = (String[]) psession.getAttribute(MANDATE_FEEDS); String[] role_feeds = (String[]) psession.getAttribute(ROLE_FEEDS); //add role based feeds if (null != role_feeds) { for (int i = 0; i < role_feeds.length; i++) { feeds.add(i, role_feeds[i]); }//from www . j av a 2 s . c o m } //add mandatory feeds if (null != mandate_feeds) { for (int i = 0; i < mandate_feeds.length; i++) { feeds.add(i, mandate_feeds[i]); } } String[] sessionDefaultFeeds = (String[]) psession.getAttribute(SettingsHandler.SESSION_DEFAULT_FEEDS); if (null != sessionDefaultFeeds && sessionDefaultFeeds.length != 0) { for (int i = 0; i < sessionDefaultFeeds.length; i++) { feeds.add(i, sessionDefaultFeeds[i]); } } } else if (request.getParameter(FormNames.WINDOW_CUSTOM) != null) { //mandataoy + role based feeds are already included feeds = readBean.getFeeds(); } else { //none of the feeds are checked PortletSession psession = request.getPortletSession(); String[] mandate_feeds = (String[]) psession.getAttribute(MANDATE_FEEDS); String[] role_feeds = (String[]) psession.getAttribute(ROLE_FEEDS); //add role based feeds feeds = new LinkedList(); if (null != role_feeds) { for (int i = 0; i < role_feeds.length; i++) { feeds.add(i, role_feeds[i]); } } //add mandatory feeds if (null != mandate_feeds) { for (int i = 0; i < mandate_feeds.length; i++) { feeds.add(i, mandate_feeds[i]); } } } if (log.isDebugEnabled()) { Iterator it = feeds.listIterator(); it = feeds.listIterator(); while (it.hasNext()) { log.debug("RssPortlet feeds ***********" + (String) it.next()); } } if (feeds == null) { // // no feeds // empty the feeds list // writeBean.setFeeds(new LinkedList()); } else { // // entries selected, reset feed list to // the selected entries. // writeBean.setFeeds(feeds); // // start feed // only set the start feed if the feeds list in non-null // (that's the only way we get here) // make sure the start feed is in the new feeds list // catch the case where the user deletes the start feed // String startFeed = request.getParameter(INPUT_START_FEED); if (log.isDebugEnabled()) { log.debug("RssPortlet INPUT_START_FEED***********" + startFeed); } if (startFeed != null && feeds.contains(startFeed)) { writeBean.setStartFeed(startFeed); } // // case where we delete the selected feed // set to the start feed // if (readBean.getSelectedFeed() != null && !feeds.contains(readBean.getSelectedFeed())) { String selectedFeed = writeBean.getStartFeed(); writeBean.setSelectedFeed(selectedFeed); } // // case where selected feed is null, because feed // list was previously null // set the selected feed to the start feed // if (readBean.getFeeds().size() == 0) { writeBean.setSelectedFeed(writeBean.getStartFeed()); } } //handle custom page- could be done in a separate method? if (request.getParameter(FormNames.WINDOW_CUSTOM) != null) { String s = request.getParameter(INPUT_MAX_AGE); if (s != null && s.length() > 0) { // // test to make sure it's an int // try { int n = Integer.parseInt(s); if (n < 1) { alertHandler.setError(resources.get("enter_a_whole_number_greater_than_zero")); } else { writeBean.setMaxAge(n); } } catch (NumberFormatException nfe) { alertHandler.setError(resources.get("enter_a_whole_number_greater_than_zero")); } } String maxEntries = request.getParameter(INPUT_MAX_ENTRIES); if (maxEntries != null && maxEntries.length() > 0) { // // test to make sure it's an int // try { int n = Integer.parseInt(maxEntries); if (n < 1) { alertHandler.setError(resources.get("enter_a_whole_number_greater_than_zero")); } else { writeBean.setMaxEntries(n); } } catch (NumberFormatException nfe) { alertHandler.setError(resources.get("enter_a_whole_number_greater_than_zero")); } } String[] disableMaxAge = request.getParameterValues(INPUT_DISABLE_MAX_AGE); if (disableMaxAge != null && disableMaxAge.length > 0) { writeBean.setDisableMaxAge(true); } else { writeBean.setDisableMaxAge(false); } String[] newWindow = request.getParameterValues(INPUT_NEWWIN); if (newWindow != null && newWindow.length > 0) { writeBean.setNewWindow(true); } else { writeBean.setNewWindow(false); } } if (!alertHandler.isErrorExists()) { // if there were no errors, then go back to // view mode response.setPortletMode(PortletMode.VIEW); } else { response.setRenderParameter(FormNames.SUBMIT_CUSTOM, FormNames.SUBMIT_CUSTOM); } }
From source file:org.nuxeo.ecm.platform.routing.core.impl.GraphRunner.java
/** * Runs the graph starting with the given node. * * @param graph the graph//from ww w . j a va2 s. co m * @param initialNode the initial node to run */ protected void runGraph(CoreSession session, DocumentRouteElement element, GraphNode initialNode) throws DocumentRouteException { GraphRoute graph = (GraphRoute) element; List<GraphNode> pendingSubRoutes = new LinkedList<GraphNode>(); LinkedList<GraphNode> pendingNodes = new LinkedList<GraphNode>(); pendingNodes.add(initialNode); boolean done = false; int count = 0; while (!pendingNodes.isEmpty()) { GraphNode node = pendingNodes.pop(); count++; if (count > MAX_LOOPS) { throw new DocumentRouteException("Execution is looping, node: " + node); } State jump = null; switch (node.getState()) { case READY: log.debug("Doing node " + node); if (node.isMerge()) { jump = State.WAITING; } else { jump = State.RUNNING_INPUT; } break; case WAITING: if (node.canMerge()) { recursiveCancelInput(graph, node, pendingNodes); jump = State.RUNNING_INPUT; } // else leave state to WAITING break; case RUNNING_INPUT: node.starting(); node.executeChain(node.getInputChain()); if (node.hasTask() || node.hasMultipleTasks()) { createTask(session, graph, node); // may create several node.setState(State.SUSPENDED); } if (node.hasSubRoute()) { if (!pendingSubRoutes.contains(node)) { pendingSubRoutes.add(node); } node.setState(State.SUSPENDED); } if (node.getState() != State.SUSPENDED) { jump = State.RUNNING_OUTPUT; } // else this node is suspended, // remove it from queue of nodes to process break; case SUSPENDED: if (node != initialNode) { throw new DocumentRouteException("Executing unexpected SUSPENDED state"); } // actor NuxeoPrincipal principal = (NuxeoPrincipal) session.getPrincipal(); String actor = principal.getActingUser(); node.setLastActor(actor); // resuming, variables have been set by resumeGraph jump = State.RUNNING_OUTPUT; break; case RUNNING_OUTPUT: node.executeChain(node.getOutputChain()); List<Transition> trueTrans = node.evaluateTransitions(); node.ending(); node.setState(State.READY); if (node.isStop()) { if (!pendingNodes.isEmpty()) { throw new DocumentRouteException(String .format("Route %s stopped with still pending nodes: %s", graph, pendingNodes)); } done = true; } else { if (trueTrans.isEmpty()) { throw new DocumentRouteException("No transition evaluated to true from node " + node); } for (Transition t : trueTrans) { node.executeTransitionChain(t); GraphNode target = graph.getNode(t.target); if (!pendingNodes.contains(target)) { pendingNodes.add(target); } } } break; } if (jump != null) { node.setState(jump); // loop again on this node count--; pendingNodes.addFirst(node); } } if (done) { element.setDone(session); /* * Resume the parent route if this is a sub-route. */ if (graph.hasParentRoute()) { graph.resumeParentRoute(session); } } /* * Now run the sub-routes. If they are done, they'll call back into the routing service to resume the parent * node (above code). */ for (GraphNode node : pendingSubRoutes) { DocumentRoute subRoute = node.startSubRoute(); } session.save(); }
From source file:org.eclipse.birt.report.model.writer.ModuleWriterImpl.java
/** * Writes the contents of a slot. The order is not the order in the slot * while we first write the ancestor and then the derived ones. The contents * are enclosed in an optional list tag. * /* w ww . ja v a 2s . c om*/ * @param obj * the container element * @param slot * the slot to write * @param tag * the optional list tag that encloses the list of contents */ protected void writeArrangedContents(DesignElement obj, int slot, String tag) { List<DesignElement> list = obj.getSlot(slot).getContents(); if (list.isEmpty()) return; LinkedList<DesignElement> newList = new LinkedList<DesignElement>(); Iterator<DesignElement> iter = list.iterator(); while (iter.hasNext()) { DesignElement element = iter.next(); DesignElement parent = element.getExtendsElement(); if (!newList.contains(element)) { newList.add(element); } if (parent != null && list.contains(parent)) { if (!newList.contains(parent)) { int index = newList.indexOf(element); newList.add(index, parent); } else if (newList.indexOf(element) < newList.indexOf(parent)) { newList.remove(parent); int index = newList.indexOf(element); newList.add(index, parent); } } } if (tag != null) writer.conditionalStartElement(tag); // Iterate over the contents using this visitor to write each one. // Note that this may result in a recursive call back into this // method as we do a depth-first traversal of the design tree. iter = newList.iterator(); while (iter.hasNext()) { (iter.next()).apply(this); } if (tag != null) writer.endElement(); }
From source file:com.redsqirl.workflow.server.Workflow.java
protected List<DataFlowElement> subsetElementToRun(List<String> dataFlowElements) throws Exception { LinkedList<DataFlowElement> elsIn = new LinkedList<DataFlowElement>(); if (!isSchedule() && dataFlowElements.size() < element.size()) { Iterator<DataFlowElement> itIn = getEls(dataFlowElements).iterator(); while (itIn.hasNext()) { DataFlowElement cur = itIn.next(); elsIn = getAllWithoutDuplicate(elsIn, getItAndAllElementsNeeded(cur)); }//w w w. j a v a 2 s . c o m } else { elsIn.addAll(getEls(dataFlowElements)); } // Run only what have not been calculated in the workflow. List<DataFlowElement> toRun = new LinkedList<DataFlowElement>(); Iterator<DataFlowElement> itE = elsIn.iterator(); while (itE.hasNext()) { DataFlowElement cur = itE.next(); // Never run an element that have no action if (cur.getOozieAction() != null && !toRun.contains(cur)) { boolean haveTobeRun = false; List<DataFlowElement> outAllComp = cur.getAllOutputComponent(); Collection<DFEOutput> outData = cur.getDFEOutput().values(); Map<String, List<DataFlowElement>> outComp = cur.getOutputComponent(); boolean lastElement = outAllComp.size() == 0; // If the current element has output, check if those has to run Iterator<DataFlowElement> itE2 = outAllComp.iterator(); while (itE2.hasNext() && !lastElement) { lastElement = !elsIn.contains(itE2.next()); } if (lastElement) { // Element at the end of what need to run // Check if one element buffered/recorded exist or not // if all elements are temporary and not exist calculate the // element Iterator<DFEOutput> itOutData = outData.iterator(); int nbTemporary = 0; while (itOutData.hasNext() && !haveTobeRun) { DFEOutput outC = itOutData.next(); if ((!SavingState.TEMPORARY.equals(outC.getSavingState())) && !outC.isPathExist()) { haveTobeRun = true; } else if (SavingState.TEMPORARY.equals(outC.getSavingState()) && !outC.isPathExist()) { ++nbTemporary; } } if (nbTemporary == outData.size()) { haveTobeRun = true; } } else { // Check if among the output several elements some are // recorded/buffered and does not exist Iterator<DFEOutput> itOutData = outData.iterator(); while (itOutData.hasNext() && !haveTobeRun) { DFEOutput outC = itOutData.next(); if ((!SavingState.TEMPORARY.equals(outC.getSavingState())) && !outC.isPathExist()) { haveTobeRun = true; } } if (!haveTobeRun) { // Check if among the output several elements to run are // in the list // Check if it is true the corresponded outputs is saved // or not Iterator<String> searchOutIt = outComp.keySet().iterator(); while (searchOutIt.hasNext() && !haveTobeRun) { boolean foundOne = false; String searchOut = searchOutIt.next(); Iterator<DataFlowElement> outCIt = outComp.get(searchOut).iterator(); while (outCIt.hasNext() && !foundOne) { foundOne = elsIn.contains(outCIt.next()); } if (foundOne) { haveTobeRun = !cur.getDFEOutput().get(searchOut).isPathExist(); } } } } if (haveTobeRun) { // If this element have to be run // if one element exist and one recorded/buffered does not // send an error cur.cleanDataOut(); toRun.add(cur); } } } List<DataFlowElement> toRunSort = null; if (toRun != null) { toRunSort = new LinkedList<DataFlowElement>(); Iterator<DataFlowElement> it = element.iterator(); while (it.hasNext()) { DataFlowElement cur = it.next(); if (toRun.contains(cur)) { toRunSort.add(cur); } } } return toRunSort; }
From source file:oct.analysis.application.comp.EZWorker.java
@Override protected EZEdgeCoord doInBackground() throws Exception { int foveaCenterXPosition = analysisManager.getFoveaCenterXPosition(); /*// w w w.java2 s . co m first get a sharpened version of the OCT and use that to obtain the segmentation of the Bruch's membrane. Use a Loess interpolation algorithm to smooth out imperfetions in the segmentation line. */ UnivariateInterpolator interpolator = new LoessInterpolator(0.1, 0); ArrayList<Point> rawBrmPoints = new ArrayList<>(analysisManager .getSegmentation(new SharpenOperation(15, 0.5F)).getSegment(Segmentation.BrM_SEGMENT)); double[][] brmSeg = Util.getXYArraysFromPoints(rawBrmPoints); UnivariateFunction brmInterp = interpolator.interpolate(brmSeg[0], brmSeg[1]); BufferedImage sharpOCT = analysisManager.getSharpenedOctImage(8.5D, 1.0F); setProgress(10); /* Starting from the identified location of the fovea search northward in the image until the most northern pixels northward (in a 3x3 matrix of pixels arround the the search point (X,Y) ) are black (ie. the search matrix is has found that the search point isn't totally surrounded by white pixels). Then a recursive search algorithm determines if the black area signifies the seperation between bands or simply represents a closed (a black blob entirely surrounded by white pixels) black band. It will continue searching northward in the image until it can find an open region of all blak pixels. Once this is found it will find the contour of the edge between the black and white pixels along the width of the image. */ int searchY = (int) Math.round(brmInterp.value(foveaCenterXPosition)) + 1; do { searchY--; } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) > 0 || !isContrastPoint(foveaCenterXPosition, searchY, sharpOCT)); LinkedList<Point> contour = new LinkedList<>(); Point startPoint = new Point(foveaCenterXPosition, searchY); //find contour by searching for white pixel boundary to te right of the fovea contour.add(findContourRight(startPoint, Cardinality.SOUTH, startPoint, Cardinality.SOUTH, contour, sharpOCT, 0)); //search until open black area found (ie. if the search algorithm arrives back at //the starting pixel keep moving north to next black area to search) while (contour.get(0).equals(startPoint)) { contour = new LinkedList<>(); do { searchY--; } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) == 0); do { searchY--; } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) > 0 || isSurroundedByWhite(foveaCenterXPosition, searchY, sharpOCT)); startPoint = new Point(foveaCenterXPosition, searchY); contour.add(findContourRight(startPoint, Cardinality.SOUTH, startPoint, Cardinality.SOUTH, contour, sharpOCT, 0)); } setProgress(20); //open balck space found, complete contour to left of fovea contour.add( findContourLeft(startPoint, Cardinality.SOUTH, startPoint, Cardinality.SOUTH, contour, sharpOCT)); analysisManager.getImgPanel().setDrawPoint(new Point(foveaCenterXPosition, searchY)); setProgress(30); /* since the contour can snake around due to aberations and low image density we need to create a single line (represented by points) from left to right to represent the countour. This is easily done by building a line of points consisting of the point with the largest Y value (furthest from the top of the image) at each X value. This eliminates overhangs from the contour line. */ Map<Double, List<Point>> grouped = contour.stream().collect(Collectors.groupingBy(Point::getX)); List<Point> refinedEZContour = grouped.values().stream().map((List<Point> points) -> { int maxY = points.stream().mapToInt((Point p) -> p.y).min().getAsInt(); return new Point(points.get(0).x, maxY); }).sorted((Point p1, Point p2) -> Integer.compare(p1.x, p2.x)).collect(Collectors.toList()); setProgress(35); /* Starting from the identified location of the fovea search southward in the image until the most southern pixels (in a 3x3 matrix of pixels arround the the search point (X,Y) ) are black (ie. the search matrix has found that the search point isn't totally surrounded by white pixels). Then a recursive search algorithm determines if the black area signifies the bottom of the Bruch's membrane or simply represents a closed (a black blob entirely surrounded by white pixels) black band. It will continue searching southward in the image until it can find an open region of all black pixels. Once this is found it will find the contour of the edge between the black and white pixels, along the width of the image, of the bottom of the Bruch's membrane. */ // sharpOCT = getSharpenedOctImage(5D, 1.0F); searchY = (int) Math.round(brmInterp.value(foveaCenterXPosition)); do { searchY++; } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) > 0 || isSurroundedByWhite(foveaCenterXPosition, searchY, sharpOCT)); contour = new LinkedList<>(); startPoint = new Point(foveaCenterXPosition, searchY); /* Find contour by searching for white pixel boundary to te right of the fovea. Sometimes the crap below the Bruchs membrane causes too much interferance for the algorithm to work properly so we must tweak some of the parameters of the sharpening performed on the image until the algorithm succedes or we can no longer tweak parameters. In the case of the later event we can use the raw segmented Bruchs membrane as a substitute to keep the method from failing. */ contour.add(findContourRight(startPoint, Cardinality.NORTH, startPoint, Cardinality.NORTH, contour, sharpOCT, 0)); double filtValue = 8.5D; boolean tweakFailed = false; while (contour.contains(null)) { contour = new LinkedList<>(); filtValue -= 0.5D; System.out.println("Reducing sigma to " + filtValue); if (filtValue <= 0D) { tweakFailed = true; break; } sharpOCT = analysisManager.getSharpenedOctImage(8.5D, 1.0F); contour.add(findContourRight(startPoint, Cardinality.NORTH, startPoint, Cardinality.NORTH, contour, sharpOCT, 0)); } if (tweakFailed) { contour = new LinkedList<>(rawBrmPoints); } else { //search until open black area found (ie. if the search algorithm arrives back at //the starting pixel keep moving south to next black area to search) while (contour.get(0).equals(startPoint)) { contour = new LinkedList<>(); do { searchY++; } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) == 0); do { searchY++; } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) > 0 || isSurroundedByWhite(foveaCenterXPosition, searchY, sharpOCT)); startPoint = new Point(foveaCenterXPosition, searchY); contour.add(findContourRight(startPoint, Cardinality.NORTH, startPoint, Cardinality.NORTH, contour, sharpOCT, 0)); } setProgress(45); //open balck space found, complete contour to left of fovea contour.add(findContourLeft(startPoint, Cardinality.NORTH, startPoint, Cardinality.NORTH, contour, sharpOCT)); } setProgress(55); /* since the contour can snake around due to aberations and low image density we need to create a single line (represented by points) from left to right to represent the countour. This is easily done by building a line of points consisting of the point with the smallest Y value (closest to the top of the image) at each X value. This eliminates overhangs from the contour line. */ grouped = contour.stream().collect(Collectors.groupingBy(Point::getX)); List<Point> refinedBruchsMembraneContour = grouped.values().stream().map((List<Point> points) -> { int minY = points.stream().mapToInt((Point p) -> p.y).min().getAsInt(); return new Point(points.get(0).x, minY); }).sorted((Point p1, Point p2) -> Integer.compare(p1.x, p2.x)).collect(Collectors.toList()); setProgress(70); /* use a Loess interpolator again to smooth the new contours of the EZ and Bruch's Membrane */ double[][] refinedContourPoints = Util.getXYArraysFromPoints(refinedEZContour); UnivariateFunction interpEZContour = interpolator.interpolate(refinedContourPoints[0], refinedContourPoints[1]); refinedContourPoints = Util.getXYArraysFromPoints(refinedBruchsMembraneContour); UnivariateFunction interpBruchsContour = interpolator.interpolate(refinedContourPoints[0], refinedContourPoints[1]); /* find the average difference in the distance in the Y between the 10 pixels at each end of the Bruch's Membrane contour and the contour created along the top of the EZ. */ //since the lines are sorted on X position it is easy to align the lines //based on the tails of each line int minX = refinedEZContour.get(0).x; int maxX; //the interpolator can shorten the range of the X values from the original supplied //so we need to test where the end of the range occurs since it isn't directly accessible for (maxX = refinedEZContour.get(refinedEZContour.size() - 1).x; maxX > minX; maxX--) { try { double tmp = interpEZContour.value(maxX) - interpBruchsContour.value(maxX); //if this break is reached we have found the max value the interpolators will allow break; } catch (OutOfRangeException oe) { //do nothing but let loop continue } } double avgDif = Stream .concat(IntStream.range(minX + 30, minX + 50).boxed(), IntStream.range(maxX - 49, maxX - 28).boxed()) .mapToDouble(x -> interpBruchsContour.value(x) - interpEZContour.value(x)).average().getAsDouble(); int height = sharpOCT.getHeight();//make to use in lambda expression List<LinePoint> ezLine = IntStream.rangeClosed(minX, maxX) .mapToObj(x -> new LinePoint(x, height - interpEZContour.value(x) - avgDif)) .collect(Collectors.toList()); List<LinePoint> bmLine = IntStream.rangeClosed(minX, maxX) .mapToObj(x -> new LinePoint(x, height - interpBruchsContour.value(x))) .collect(Collectors.toList()); List<LinePoint> bmUnfiltLine = refinedBruchsMembraneContour.stream() .map((Point p) -> new LinePoint(p.x, height - p.getY())).collect(Collectors.toList()); Util.graphPoints(ezLine, bmLine, bmUnfiltLine); analysisManager.getImgPanel().setDrawnLines( IntStream.rangeClosed(minX, maxX).mapToObj(x -> new LinePoint(x, interpEZContour.value(x))) .collect(Collectors.toList()), IntStream.rangeClosed(minX, maxX).mapToObj(x -> new LinePoint(x, interpBruchsContour.value(x))) .collect(Collectors.toList())); /* Find the difference between the two contours (Bruch's membrane and the EZ + Bruch's membrane) and use this to determine where the edge of the EZ is */ List<LinePoint> diffLine = findDiffWithAdjustment(interpBruchsContour, 0D, interpEZContour, avgDif, minX, maxX); setProgress(90); // List<LinePoint> peaks = Util.findPeaksAndVallies(diffLine); // Util.graphPoints(diffLine, peaks); /* Find the first zero crossings of the difference line on both sides of the fovea. If a zero crossing can't be found then search for the first crossing of a value of 1, then 2, then 3, etc. until an X coordinate of a crossing is found on each side of the fovea. */ OptionalInt ezLeftEdge; double crossingThreshold = 0.25D; do { double filtThresh = crossingThreshold; System.out.println("Crossing threshold = " + crossingThreshold); ezLeftEdge = diffLine.stream().filter(lp -> lp.getY() <= filtThresh && lp.getX() < foveaCenterXPosition) .mapToInt(LinePoint::getX).max(); crossingThreshold += 0.25D; } while (!ezLeftEdge.isPresent()); OptionalInt ezRightEdge; crossingThreshold = 0.25D; do { double filtThresh = crossingThreshold; System.out.println("Crossing threshold = " + crossingThreshold); ezRightEdge = diffLine.stream() .filter(lp -> lp.getY() <= filtThresh && lp.getX() > foveaCenterXPosition) .mapToInt(LinePoint::getX).min(); crossingThreshold += 0.25D; } while (!ezRightEdge.isPresent()); //return findings return new EZEdgeCoord(ezLeftEdge.getAsInt(), ezRightEdge.getAsInt()); }
From source file:net.spfbl.spf.SPF.java
/** * Consulta o registro SPF nos registros DNS do domnio. Se houver mais de * dois registros diferentes, realiza o merge do forma a retornar um nico * registro./*from w ww. jav a2 s .co m*/ * * @param hostname o nome do hostname para consulta do SPF. * @param bgWhenUnavailable usar best-guess quando houver erro temporrio * para alcanar o registro. * @return o registro SPF consertado, padronuzado e mergeado. * @throws ProcessException */ private static LinkedList<String> getRegistrySPF(String hostname, boolean bgWhenUnavailable) throws ProcessException { LinkedList<String> registryList = new LinkedList<String>(); try { // if (CacheGuess.containsExact(hostname)) { // // Sempre que houver registro de // // chute, sobrepor registro atual. // registryList.add(CacheGuess.get(hostname)); // } else { // // Caso contrrio procurar nos // // registros oficiais do domnio. try { Attributes attributes = Server.getAttributesDNS(hostname, new String[] { "SPF" }); Attribute attribute = attributes.get("SPF"); if (attribute != null) { for (int index = 0; index < attribute.size(); index++) { String registry = (String) attribute.get(index); if (registry.contains("v=spf1 ")) { registry = fixRegistry(registry); if (!registryList.contains(registry)) { registryList.add(registry); } } } } } catch (InvalidAttributeIdentifierException ex) { // No encontrou registro SPF. } if (registryList.isEmpty()) { try { Attributes attributes = Server.getAttributesDNS(hostname, new String[] { "TXT" }); Attribute attribute = attributes.get("TXT"); if (attribute != null) { for (int index = 0; index < attribute.size(); index++) { String registry = (String) attribute.get(index); if (registry.contains("v=spf1 ")) { registry = fixRegistry(registry); if (!registryList.contains(registry)) { registryList.add(registry); } } } } } catch (InvalidAttributeIdentifierException ex2) { // No encontrou registro TXT. } } // } if (registryList.isEmpty()) { // hostname = "." + hostname; // if (CacheGuess.containsExact(hostname)) { // // Significa que um palpite SPF // // foi registrado para este hostname. // // Neste caso utilizar o paltpite especfico. // registryList.add(CacheGuess.get(hostname)); // } else { // // Se no hoouver palpite especfico para o hostname, // // utilizar o palpite padro, porm adaptado para IPv6. // // http://www.openspf.org/FAQ/Best_guess_record // registryList.add(CacheGuess.BEST_GUESS); // } // Como o domnio no tem registro SPF, // utilizar um registro SPF de chute do sistema. String guess = CacheGuess.get(hostname); registryList.add(guess); } return registryList; } catch (NameNotFoundException ex) { return null; } catch (NamingException ex) { if (bgWhenUnavailable) { // Na indisponibilidade do DNS // utilizar um registro SPF de chute do sistema. String guess = CacheGuess.get(hostname); registryList.add(guess); return registryList; } else if (ex instanceof CommunicationException) { throw new ProcessException("ERROR: DNS UNAVAILABLE"); } else { throw new ProcessException("ERROR: DNS UNAVAILABLE", ex); } } catch (Exception ex) { throw new ProcessException("ERROR: FATAL", ex); } }
From source file:net.spfbl.spf.SPF.java
/** * Algoritmo para consertar e padronizar o registro SPF. * * @param registry o registro SPF original. * @return o registro SPF consertado e padronizado. */// w ww . j a v a 2s .c om private static String fixRegistry(String registry) { String vesion = "v=spf1"; String all = null; String redirect = null; String explanation = null; LinkedList<String> midleList = new LinkedList<String>(); LinkedList<String> errorList = new LinkedList<String>(); registry = registry.replace("\\\"", "\""); registry = registry.replace("\" \"", ""); registry = registry.replace("\"", ""); registry = registry.toLowerCase(); StringTokenizer tokenizer = new StringTokenizer(registry, " "); while (tokenizer.hasMoreTokens()) { Boolean valid; String token = tokenizer.nextToken(); if (token.equals("v=spf1")) { vesion = token; valid = null; } else if (token.startsWith("redirect=")) { redirect = token; valid = null; } else if (token.startsWith("exp=")) { explanation = token; valid = null; } else if (token.equals("v=msv1")) { valid = true; } else if (token.startsWith("t=") && token.length() == 32) { valid = true; } else if (isMechanismMiddle(token)) { valid = true; } else if (isMechanismAll(token)) { all = token; valid = null; } else { valid = false; } if (valid == null) { mergeMechanism(midleList, errorList); } else if (valid == true) { mergeMechanism(midleList, errorList); if (!midleList.contains(token)) { // No considera tokens repetidos. midleList.add(token); } } else if (valid == false) { errorList.add(token); } } registry = vesion; if (redirect == null) { for (String token : midleList) { registry += ' ' + token; } if (all != null) { registry += ' ' + all; } } else { registry += ' ' + redirect; } if (explanation != null) { registry += ' ' + explanation; } return registry; }