List of usage examples for org.apache.commons.lang3.tuple Triple of
public static <L, M, R> Triple<L, M, R> of(final L left, final M middle, final R right)
Obtains an immutable triple of from three objects inferring the generic types.
This factory allows the triple to be created using inference to obtain the generic types.
From source file:com.microsoft.azure.keyvault.extensions.cryptography.algorithms.AesCbcHmacSha2.java
private static Triple<byte[], byte[], Mac> GetAlgorithmParameters(String algorithm, byte[] key) throws InvalidKeyException, NoSuchAlgorithmException { byte[] aes_key; byte[] hmac_key; Mac hmac;/*w w w. j av a2 s .c o m*/ if (algorithm.equalsIgnoreCase(Aes128CbcHmacSha256.AlgorithmName)) { if ((key.length << 3) < 256) { throw new IllegalArgumentException( String.format("%s key length in bits %d < 256", algorithm, key.length << 3)); } hmac_key = new byte[128 >> 3]; aes_key = new byte[128 >> 3]; // The HMAC key precedes the AES key System.arraycopy(key, 0, hmac_key, 0, 128 >> 3); System.arraycopy(key, 128 >> 3, aes_key, 0, 128 >> 3); hmac = Mac.getInstance("HmacSHA256"); hmac.init(new SecretKeySpec(hmac_key, "HmacSHA256")); } else if (algorithm.equalsIgnoreCase(Aes192CbcHmacSha384.AlgorithmName)) { if ((key.length << 3) < 384) { throw new IllegalArgumentException( String.format("%s key length in bits %d < 384", algorithm, key.length << 3)); } hmac_key = new byte[192 >> 3]; aes_key = new byte[192 >> 3]; // The HMAC key precedes the AES key System.arraycopy(key, 0, hmac_key, 0, 192 >> 3); System.arraycopy(key, 192 >> 3, aes_key, 0, 192 >> 3); hmac = Mac.getInstance("HmacSHA384"); hmac.init(new SecretKeySpec(hmac_key, "HmacSHA384")); } else if (algorithm.equalsIgnoreCase(Aes256CbcHmacSha512.AlgorithmName)) { if ((key.length << 3) < 512) { throw new IllegalArgumentException( String.format("%s key length in bits %d < 512", algorithm, key.length << 3)); } hmac_key = new byte[256 >> 3]; aes_key = new byte[256 >> 3]; // The HMAC key precedes the AES key System.arraycopy(key, 0, hmac_key, 0, 256 >> 3); System.arraycopy(key, 256 >> 3, aes_key, 0, 256 >> 3); hmac = Mac.getInstance("HmacSHA512"); hmac.init(new SecretKeySpec(hmac_key, "HmacSHA512")); } else { throw new IllegalArgumentException(String.format("Unsupported algorithm: %s", algorithm)); } return Triple.of(aes_key, hmac_key, hmac); }
From source file:com.twentyn.patentSearch.Searcher.java
private List<Triple<Float, String, String>> executeQuery(Pair<IndexReader, IndexSearcher> readerSearcher, BooleanQuery query) throws UncheckedIOException { TopDocs topDocs;//from w w w . j a v a 2s .com try { topDocs = readerSearcher.getRight().search(query, MAX_RESULTS_PER_QUERY); } catch (IOException e) { LOGGER.error("Caught IO exception when trying to run search for %s: %s", query, e.getMessage()); /* Wrap `e` in an unchecked exception to allow it to escape our call stack. The top level function with catch * and rethrow it as a normal IOException. */ throw new UncheckedIOException(e); } ScoreDoc[] scoreDocs = topDocs.scoreDocs; if (scoreDocs.length == 0) { LOGGER.debug("Search returned no results."); return Collections.emptyList(); } // ScoreDoc just contains a score and an id. We need to retrieve the documents' content using that id. /* Crux of the next bit: * Filter by score and convert from scoreDocs to document features. * No need to use `limit` here since we already had Lucene cap the result set size. */ return Arrays.stream(scoreDocs).filter(scoreDoc -> scoreDoc.score >= scoreThreshold).map(scoreDoc -> { // try { Pair<String, String> features = this .extractDocFeatures(readerSearcher.getLeft().document(scoreDoc.doc)); // Put the score first so the natural sort order is based on score. return Triple.of(scoreDoc.score, features.getLeft(), features.getRight()); } catch (IOException e) { // Yikes, this is v. bad. LOGGER.error("Caught IO exception when trying to read doc id %d: %s", scoreDoc.doc, e.getMessage()); throw new UncheckedIOException(e); // Same as above. } }).collect(Collectors.toList()); }
From source file:alfio.controller.api.AdminApiController.java
@RequestMapping(value = "/events/{eventName}/pending-payments/bulk-confirmation", method = POST) public List<Triple<Boolean, String, String>> bulkConfirmation(@PathVariable("eventName") String eventName, Principal principal, @RequestParam("file") MultipartFile file) throws IOException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()))) { String username = principal.getName(); return reader.lines().map(line -> { String reservationID = null; try (Scanner scanner = new Scanner(line)) { scanner.findInLine("([a-zA-Z0-9\\-]+);(\\d+(\\.\\d+)?)"); MatchResult match = scanner.match(); reservationID = match.group(1); eventManager.confirmPayment(eventName, reservationID, new BigDecimal(match.group(2)), username); return Triple.of(Boolean.TRUE, reservationID, ""); } catch (Exception e) { return Triple.of(Boolean.FALSE, Optional.ofNullable(reservationID).orElse(""), e.getMessage()); }//from w ww. j av a2 s. c om }).collect(Collectors.toList()); } }
From source file:hu.bme.mit.sette.common.tasks.TestSuiteRunner.java
private void analyzeOne(Snippet snippet, File[] binaryDirectories) throws Exception { String snippetClassName = snippet.getContainer().getJavaClass().getName(); String snippetMethodName = snippet.getMethod().getName(); String testClassName = snippet.getContainer().getJavaClass().getName() + "_" + snippet.getMethod().getName() + "_Tests"; logger.debug("Snippet: {}#{}()", snippetClassName, snippetMethodName); logger.debug("Tests: {}", testClassName); // create JaCoCo runtime and instrumenter IRuntime runtime = new LoggerRuntime(); Instrumenter instrumenter = new Instrumenter(runtime); // start runtime RuntimeData data = new RuntimeData(); runtime.startup(data);/*from ww w . ja v a2 s . c om*/ // create class loader JaCoCoClassLoader classLoader = new JaCoCoClassLoader(binaryDirectories, instrumenter, getSnippetProject().getClassLoader()); // load test class // snippet class and other dependencies will be loaded and instrumented // on the fly Class<?> testClass = classLoader.loadClass(testClassName); TestCase testClassInstance = (TestCase) testClass.newInstance(); // invoke test methods // TODO separate collect and invoke for (Method m : testClass.getDeclaredMethods()) { if (m.isSynthetic()) { // skip synthetic method continue; } if (m.getName().startsWith("test")) { logger.trace("Invoking: " + m.getName()); try { m.invoke(testClassInstance); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof NullPointerException || cause instanceof ArrayIndexOutOfBoundsException || cause instanceof AssertionFailedError) { logger.warn(cause.getClass().getName() + ": " + m.getDeclaringClass().getName() + "." + m.getName()); } else { logger.error("Exception: " + m.getDeclaringClass().getName() + "." + m.getName()); } logger.debug(e.getMessage(), e); } } else { logger.warn("Not test method: {}", m.getName()); } } // collect data ExecutionDataStore executionData = new ExecutionDataStore(); SessionInfoStore sessionInfos = new SessionInfoStore(); data.collect(executionData, sessionInfos, false); runtime.shutdown(); // get classes to analyse // store string to avoid the mess up between the different class loaders Set<String> javaClasses = new HashSet<>(); javaClasses.add(snippetClassName); for (Constructor<?> inclConstructor : snippet.getIncludedConstructors()) { javaClasses.add(inclConstructor.getDeclaringClass().getName()); } for (Method inclMethod : snippet.getIncludedMethods()) { javaClasses.add(inclMethod.getDeclaringClass().getName()); } // TODO inner classes are not handled well enough // TODO anonymous classes can also have anonymous classes -> recursion Set<String> toAdd = new HashSet<>(); for (String javaClass : javaClasses) { int i = 1; while (true) { // guess anonymous classes, like ClassName$1, ClassName$2 etc. try { classLoader.loadClass(javaClass + "$" + i); toAdd.add(javaClass + "$" + i); i++; } catch (ClassNotFoundException e) { // bad guess, no more anonymous classes on this level break; } } } javaClasses.addAll(toAdd); // analyse classes CoverageBuilder coverageBuilder = new CoverageBuilder(); Analyzer analyzer = new Analyzer(executionData, coverageBuilder); for (String javaClassName : javaClasses) { logger.trace("Analysing: {}", javaClassName); analyzer.analyzeClass(classLoader.readBytes(javaClassName), javaClassName); } // TODO remove debug // new File("D:/SETTE/!DUMP/" + getTool().getName()).mkdirs(); // PrintStream out = new PrintStream("D:/SETTE/!DUMP/" // + getTool().getName() + "/" + testClassName + ".out"); Map<String, Triple<TreeSet<Integer>, TreeSet<Integer>, TreeSet<Integer>>> coverageInfo = new HashMap<>(); for (final IClassCoverage cc : coverageBuilder.getClasses()) { String file = cc.getPackageName() + '/' + cc.getSourceFileName(); file = file.replace('\\', '/'); if (!coverageInfo.containsKey(file)) { coverageInfo.put(file, Triple.of(new TreeSet<Integer>(), new TreeSet<Integer>(), new TreeSet<Integer>())); } // out.printf("Coverage of class %s%n", cc.getName()); // // printCounter(out, "instructions", // cc.getInstructionCounter()); // printCounter(out, "branches", cc.getBranchCounter()); // printCounter(out, "lines", cc.getLineCounter()); // printCounter(out, "methods", cc.getMethodCounter()); // printCounter(out, "complexity", cc.getComplexityCounter()); for (int l = cc.getFirstLine(); l <= cc.getLastLine(); l++) { switch (cc.getLine(l).getStatus()) { case ICounter.FULLY_COVERED: coverageInfo.get(file).getLeft().add(l); break; case ICounter.PARTLY_COVERED: coverageInfo.get(file).getMiddle().add(l); break; case ICounter.NOT_COVERED: coverageInfo.get(file).getRight().add(l); break; } } } // create coverage XML SnippetCoverageXml coverageXml = new SnippetCoverageXml(); coverageXml.setToolName(getTool().getName()); coverageXml.setSnippetProjectElement( new SnippetProjectElement(getSnippetProjectSettings().getBaseDirectory().getCanonicalPath())); coverageXml.setSnippetElement( new SnippetElement(snippet.getContainer().getJavaClass().getName(), snippet.getMethod().getName())); coverageXml.setResultType(ResultType.S); for (Entry<String, Triple<TreeSet<Integer>, TreeSet<Integer>, TreeSet<Integer>>> entry : coverageInfo .entrySet()) { TreeSet<Integer> full = entry.getValue().getLeft(); TreeSet<Integer> partial = entry.getValue().getMiddle(); TreeSet<Integer> not = entry.getValue().getRight(); FileCoverageElement fce = new FileCoverageElement(); fce.setName(entry.getKey()); fce.setFullyCoveredLines(StringUtils.join(full, ' ')); fce.setPartiallyCoveredLines(StringUtils.join(partial, ' ')); fce.setNotCoveredLines(StringUtils.join(not, ' ')); coverageXml.getCoverage().add(fce); } coverageXml.validate(); // TODO needs more documentation File coverageFile = RunnerProjectUtils.getSnippetCoverageFile(getRunnerProjectSettings(), snippet); Serializer serializer = new Persister(new AnnotationStrategy(), new Format("<?xml version=\"1.0\" encoding= \"UTF-8\" ?>")); serializer.write(coverageXml, coverageFile); // TODO move HTML generation to another file/phase File htmlFile = RunnerProjectUtils.getSnippetHtmlFile(getRunnerProjectSettings(), snippet); String htmlTitle = getTool().getName() + " - " + snippetClassName + '.' + snippetMethodName + "()"; StringBuilder htmlData = new StringBuilder(); htmlData.append("<!DOCTYPE html>\n"); htmlData.append("<html lang=\"hu\">\n"); htmlData.append("<head>\n"); htmlData.append(" <meta charset=\"utf-8\" />\n"); htmlData.append(" <title>" + htmlTitle + "</title>\n"); htmlData.append(" <style type=\"text/css\">\n"); htmlData.append(" .code { font-family: 'Consolas', monospace; }\n"); htmlData.append(" .code .line { border-bottom: 1px dotted #aaa; white-space: pre; }\n"); htmlData.append(" .code .green { background-color: #CCFFCC; }\n"); htmlData.append(" .code .yellow { background-color: #FFFF99; }\n"); htmlData.append(" .code .red { background-color: #FFCCCC; }\n"); htmlData.append(" .code .line .number {\n"); htmlData.append(" display: inline-block;\n"); htmlData.append(" width:50px;\n"); htmlData.append(" text-align:right;\n"); htmlData.append(" margin-right:5px;\n"); htmlData.append(" }\n"); htmlData.append(" </style>\n"); htmlData.append("</head>\n"); htmlData.append("\n"); htmlData.append("<body>\n"); htmlData.append(" <h1>" + htmlTitle + "</h1>\n"); for (FileCoverageElement fce : coverageXml.getCoverage()) { htmlData.append(" <h2>" + fce.getName() + "</h2>\n"); htmlData.append(" \n"); File src = new File(getSnippetProject().getSettings().getSnippetSourceDirectory(), fce.getName()); List<String> srcLines = FileUtils.readLines(src); SortedSet<Integer> full = linesToSortedSet(fce.getFullyCoveredLines()); SortedSet<Integer> partial = linesToSortedSet(fce.getPartiallyCoveredLines()); SortedSet<Integer> not = linesToSortedSet(fce.getNotCoveredLines()); htmlData.append(" <div class=\"code\">\n"); int i = 1; for (String srcLine : srcLines) { String divClass = getLineDivClass(i, full, partial, not); htmlData.append(" <div class=\"" + divClass + "\"><div class=\"number\">" + i + "</div> " + srcLine + "</div>\n"); i++; } htmlData.append(" </div>\n\n"); } // htmlData.append(" <div class=\"line\"><div class=\"number\">1</div> package samplesnippets;</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">2</div> </div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">3</div> import hu.bme.mit.sette.annotations.SetteIncludeCoverage;</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">4</div> import hu.bme.mit.sette.annotations.SetteNotSnippet;</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">5</div> import hu.bme.mit.sette.annotations.SetteRequiredStatementCoverage;</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">6</div> import hu.bme.mit.sette.annotations.SetteSnippetContainer;</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">7</div> import samplesnippets.inputs.SampleContainer_Inputs;</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">8</div> </div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">9</div> @SetteSnippetContainer(category = "X1",</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">10</div> goal = "Sample // snippet container",</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">11</div> inputFactoryContainer = SampleContainer_Inputs.class)</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">12</div> public final class SampleContainer {</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">13</div> private SampleContainer() {</div>\n"); // htmlData.append(" <div class=\"line red\"><div class=\"number\">14</div> throw new UnsupportedOperationException("Static // class");</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">15</div> }</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">16</div> </div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">17</div> @SetteRequiredStatementCoverage(value = 100)</div>\n"); // htmlData.append(" <div class=\"line green\"><div class=\"number\">18</div> public static boolean snippet(int x) {</div>\n"); // htmlData.append(" <div class=\"line yellow\"><div class=\"number\">19</div> if (20 * x + 2 == 42) {</div>\n"); // htmlData.append(" <div class=\"line green\"><div class=\"number\">20</div> return true;</div>\n"); // htmlData.append(" <div class=\"line green\"><div class=\"number\">21</div> } else {</div>\n"); // htmlData.append(" <div class=\"line green\"><div class=\"number\">22</div> return false;</div>\n"); // htmlData.append(" <div class=\"line green\"><div class=\"number\">23</div> }</div>\n"); // htmlData.append(" <div class=\"line green\"><div class=\"number\">24</div> }</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">25</div> }</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">26</div> </div>\n"); htmlData.append("</body>\n"); htmlData.append("</html>\n"); FileUtils.write(htmlFile, htmlData); }
From source file:com.nttec.everychan.ui.gallery.GalleryActivity.java
@Override protected void onCreate(final Bundle savedInstanceState) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) requestWindowFeature(Window.FEATURE_PROGRESS); settings = getIntent().getParcelableExtra(EXTRA_SETTINGS); if (settings == null) settings = GallerySettings.fromSettings(new ApplicationSettings( PreferenceManager.getDefaultSharedPreferences(getApplication()), getResources())); settings.getTheme().setTo(this, R.style.Transparent); super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) CompatibilityImpl.setActionBarNoIcon(this); inflater = getLayoutInflater();/*from w ww . jav a2s. c o m*/ instantiatedViews = new SparseArray<View>(); tnDownloadingExecutor = Executors.newFixedThreadPool(4, Async.LOW_PRIORITY_FACTORY); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH && settings.fullscreenGallery()) { setContentView(R.layout.gallery_layout_fullscreen); GalleryFullscreen.initFullscreen(this); } else { setContentView(R.layout.gallery_layout); } progressBar = (ProgressBar) findViewById(android.R.id.progress); progressBar.setMax(Window.PROGRESS_END); viewPager = (ViewPager) findViewById(R.id.gallery_viewpager); navigationInfo = (TextView) findViewById(R.id.gallery_navigation_info); for (int id : new int[] { R.id.gallery_navigation_previous, R.id.gallery_navigation_next }) findViewById(id).setOnClickListener(this); bindService(new Intent(this, GalleryBackend.class), new ServiceConnection() { { serviceConnection = this; } @Override public void onServiceConnected(ComponentName name, IBinder service) { GalleryBinder galleryBinder = GalleryBinder.Stub.asInterface(service); try { GalleryInitData initData = new GalleryInitData(getIntent(), savedInstanceState); boardModel = initData.boardModel; chan = boardModel.chan; remote = new GalleryRemote(galleryBinder, galleryBinder.initContext(initData)); GalleryInitResult initResult = remote.getInitResult(); if (initResult != null) { attachments = initResult.attachments; currentPosition = initResult.initPosition; if (initResult.shouldWaitForPageLoaded) waitForPageLoaded(savedInstanceState); } else { attachments = Collections.singletonList( Triple.of(initData.attachment, initData.attachmentHash, (String) null)); currentPosition = 0; } viewPager.setAdapter(new GalleryAdapter()); viewPager.setCurrentItem(currentPosition); viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { currentPosition = position; updateItem(); } }); } catch (Exception e) { Logger.e(TAG, e); finish(); } } @Override public void onServiceDisconnected(ComponentName name) { Logger.e(TAG, "backend service disconnected"); remote = null; System.exit(0); } }, BINDING_FLAGS); GalleryExceptionHandler.init(); }
From source file:de.pixida.logtest.designer.logreader.LogReaderEditor.java
private List<Triple<String, Node, String>> createConfigurationForm() { final List<Triple<String, Node, String>> formItems = new ArrayList<>(); // Headline pattern final TextField textInput = new TextField(this.logReader.getHeadlinePattern()); textInput.textProperty().addListener((ChangeListener<String>) (observable, oldValue, newValue) -> { this.logReader.setHeadlinePattern(newValue); this.setChanged(true); });//w w w .ja v a 2 s. com textInput.setStyle("-fx-font-family: monospace"); formItems.add(Triple.of("Headline Pattern", textInput, "The perl style regular expression is used to spot the beginning of" + " log entries in the log file. If a log entry consists of multiple lines, this pattern must only match the first" + " line, called \"head line\". Groups can intentionally be matched to spot values like timestamp or channel name." + " All matching groups are removed from the payload before they are processed by an automaton.")); // Index of timestamp Supplier<Integer> getter = () -> this.logReader.getHeadlinePatternIndexOfTimestamp(); Consumer<Integer> setter = value -> this.logReader.setHeadlinePatternIndexOfTimestamp(value); final TextField indexOfTimestampInput = this.createIntegerInputField(textInput, getter, setter); formItems.add(Triple.of("Timestamp Group", indexOfTimestampInput, "Denotes which matching group in the headline pattern contains" + " the timestamp. Index 0 references the whole pattern match, index 1 is the first matching group etc. The timestamp must" + " always be a valid integer. Currently, this integer is always interpreted as milliseconds. If no value is set, no" + " timestamp will be extracted and timing conditions cannot be used. If the referenced matching group is optional" + " and does not match for a specific head line, the last recent timestamp will be used for the extracted log entry.")); // Index of channel getter = () -> this.logReader.getHeadlinePatternIndexOfChannel(); setter = value -> this.logReader.setHeadlinePatternIndexOfChannel(value); final TextField indexOfChannelInput = this.createIntegerInputField(textInput, getter, setter); formItems.add(Triple.of("Channel Group", indexOfChannelInput, "Denotes which matching group in the headline pattern contains" + " the channel. If the value is empty or the matching group is optional and it did not match, the default channel is used" + " for the extracted log entry.")); // Trim payload CheckBox cb = new CheckBox(); cb.setSelected(this.logReader.getTrimPayload()); cb.selectedProperty().addListener((ChangeListener<Boolean>) (observable, oldValue, newValue) -> { this.logReader.setTrimPayload(BooleanUtils.toBoolean(newValue)); this.setChanged(true); }); formItems.add(Triple.of("Trim Payload", cb, "Only has effect on multiline payloads." + " If enabled, all leading and trailing whitespaces are removed from the payload" + " after the matching groups are removed. This allows for regular expressions in the automaton that match the beginning" + " and the end of the payload, without having to take care too much for whitespaces in the source log file.")); // Handling of non headline lines this.createInputForHandlingOfNonHeadlineLines(formItems); // Trim payload cb = new CheckBox(); cb.setSelected(this.logReader.getRemoveEmptyPayloadLinesFromMultilineEntry()); cb.selectedProperty().addListener((ChangeListener<Boolean>) (observable, oldValue, newValue) -> { this.logReader.setRemoveEmptyPayloadLinesFromMultilineEntry(BooleanUtils.toBoolean(newValue)); this.setChanged(true); }); formItems.add(Triple.of("Remove Empty Lines", cb, "If enabled, empty lines will be removed from multiline payload entries.")); // Charset final SortedMap<String, Charset> charsets = Charset.availableCharsets(); final ChoiceBox<String> encodingInput = new ChoiceBox<>( FXCollections.observableArrayList(charsets.keySet())); encodingInput.getSelectionModel().select(this.logReader.getLogFileCharset().name()); encodingInput.getSelectionModel().selectedItemProperty() .addListener((ChangeListener<String>) (observable, oldValue, newValue) -> { this.logReader.setLogFileCharset(charsets.get(newValue)); this.setChanged(true); }); formItems.add(Triple.of("Log File Encoding", encodingInput, "Encoding of the log file. Note that some of the encodings are" + " platform specific such that reading the log on a different platform might fail. Usually, log files are written" + " using UTF-8, UTF-16, ISO-8859-1 or ASCII.")); return formItems; }
From source file:com.etsy.arbiter.workflow.WorkflowGraphBuilder.java
/** * Processes all connected subcomponents of a given graph * * @param parentGraph The graph for which to process subcomponents * @return A Triple with these elements - A new graph with fork/join pairs inserted, the "first" node in this graph, and the "last" node in this graph * @throws WorkflowGraphException//from ww w .ja va2 s. com * @throws DirectedAcyclicGraph.CycleFoundException */ private static Triple<DirectedAcyclicGraph<Action, DefaultEdge>, Action, Action> processSubcomponents( DirectedAcyclicGraph<Action, DefaultEdge> parentGraph) throws WorkflowGraphException, DirectedAcyclicGraph.CycleFoundException { ConnectivityInspector<Action, DefaultEdge> inspector = new ConnectivityInspector<>(parentGraph); List<Set<Action>> connectedComponents = inspector.connectedSets(); // Recursively process each connected subcomponent of the graph List<DirectedAcyclicGraph<Action, DefaultEdge>> componentGraphs = new ArrayList<>( connectedComponents.size()); for (Set<Action> subComponent : connectedComponents) { componentGraphs.add(buildComponentGraph(subComponent, parentGraph)); } DirectedAcyclicGraph<Action, DefaultEdge> result = new DirectedAcyclicGraph<>(DefaultEdge.class); for (DirectedAcyclicGraph<Action, DefaultEdge> subSubgraph : componentGraphs) { Graphs.addGraph(result, subSubgraph); } // If we have more than one subcomponent, we must insert a fork/join to run them in parallel if (componentGraphs.size() > 1) { Pair<Action, Action> forkJoin = addForkJoin(result); Action fork = forkJoin.getLeft(); Action join = forkJoin.getRight(); for (DirectedAcyclicGraph<Action, DefaultEdge> subSubgraph : componentGraphs) { for (Action vertex : subSubgraph.vertexSet()) { // Vertices with no incoming edges attach directly to the fork if (subSubgraph.inDegreeOf(vertex) == 0) { result.addDagEdge(fork, vertex); } // Vertices with no outgoing edges attach directly to the join if (subSubgraph.outDegreeOf(vertex) == 0) { result.addDagEdge(vertex, join); } } } } // The graph will now have one node with no outgoing edges and one node with no incoming edges // The node with no outgoing edges is the "last" node in the resulting graph // The node with no incoming edges is the "first" node in the resulting graph // These are pulled out specifically to make it easier to attach the resulting graph into another one Action noOutgoing = null; Action noIncoming = null; for (Action vertex : result.vertexSet()) { if (noIncoming == null && result.inDegreeOf(vertex) == 0) { noIncoming = vertex; } } for (Action vertex : result.vertexSet()) { if (noOutgoing == null && result.outDegreeOf(vertex) == 0) { noOutgoing = vertex; } } return Triple.of(result, noIncoming, noOutgoing); }
From source file:io.lavagna.service.EventEmitter.java
private static Triple<Set<Integer>, Set<Integer>, Set<String>> extractFrom(List<CardFull> l) { Set<Integer> cardIds = new HashSet<>(); Set<Integer> columnIds = new HashSet<>(); Set<String> projectShortNames = new HashSet<>(); for (CardFull cf : l) { cardIds.add(cf.getId());/* w ww.j a va 2 s . c om*/ columnIds.add(cf.getColumnId()); projectShortNames.add(cf.getProjectShortName()); } return Triple.of(cardIds, columnIds, projectShortNames); }
From source file:com.yahoo.elide.security.executors.ActivePermissionExecutor.java
@Override public boolean shouldShortCircuitPermissionChecks(Class<? extends Annotation> annotationClass, Class resourceClass, String field) { return expressionResultShortCircuit.contains(Triple.of(annotationClass, resourceClass, field)); }
From source file:de.tu_dortmund.ub.data.dswarm.TaskProcessingUnit.java
private static void executeTPUPartsOnDemand(final Optional<Boolean> optionalDoInit, final Optional<Boolean> optionalAllowMultipleDataModels, String[] watchFolderFiles, final String resourceWatchFolder, final Optional<String> optionalOutputDataModelID, final String serviceName, final Integer engineThreads, final Optional<Boolean> optionalDoTransformations, final Optional<Boolean> optionalDoIngestOnTheFly, final Optional<Boolean> optionalDoExportOnTheFly, final Optional<String> optionalExportMimeType, final Optional<String> optionalExportFileExtension, final Properties config) throws Exception { // keys = input data models; values = related data resources final Map<String, Triple<String, String, String>> inputDataModelsAndResources = new HashMap<>(); // init// w w w . ja v a2 s .c o m if (optionalDoInit.isPresent() && optionalDoInit.get()) { if (optionalAllowMultipleDataModels.isPresent() && optionalAllowMultipleDataModels.get()) { for (int i = 0; i < watchFolderFiles.length; i++) { final String initResourceFileName = watchFolderFiles[i]; doInit(resourceWatchFolder, initResourceFileName, serviceName, engineThreads, config, inputDataModelsAndResources); // remove the file already processed during init from the files list to avoid duplicates watchFolderFiles = ArrayUtils.removeElement(watchFolderFiles, initResourceFileName); } } else { // use the first file in the folder for init final String initResourceFileName = watchFolderFiles[0]; doInit(resourceWatchFolder, initResourceFileName, serviceName, engineThreads, config, inputDataModelsAndResources); // remove the file already processed during init from the files list to avoid duplicates watchFolderFiles = ArrayUtils.removeElement(watchFolderFiles, initResourceFileName); } } else { final String inputDataModelID = config.getProperty(TPUStatics.PROTOTYPE_INPUT_DATA_MODEL_ID_IDENTIFIER); final String resourceID = config.getProperty(TPUStatics.PROTOTYPE_RESOURCE_ID_INDENTIFIER); inputDataModelsAndResources.put(inputDataModelID, Triple.of(inputDataModelID, resourceID, null)); LOG.info("skip init part"); } final Optional<Boolean> optionalDoIngest = TPUUtil.getBooleanConfigValue(TPUStatics.DO_INGEST_IDENTIFIER, config); // ingest if (optionalDoIngest.isPresent() && optionalDoIngest.get()) { final String projectName = config.getProperty(TPUStatics.PROJECT_NAME_IDENTIFIER); if (!optionalAllowMultipleDataModels.isPresent() || !optionalAllowMultipleDataModels.get()) { final Set<Map.Entry<String, Triple<String, String, String>>> entries = inputDataModelsAndResources .entrySet(); final Iterator<Map.Entry<String, Triple<String, String, String>>> iterator = entries.iterator(); final Map.Entry<String, Triple<String, String, String>> entry = iterator.next(); final String inputDataModelID = entry.getKey(); final Triple<String, String, String> triple = entry.getValue(); final String resourceID = triple.getMiddle(); executeIngests(watchFolderFiles, inputDataModelID, resourceID, projectName, serviceName, engineThreads, config); } } else { LOG.info("skip ingest"); } if (!optionalOutputDataModelID.isPresent()) { throw new Exception( "please set an output data model ('prototype.outputDataModelID') for this TPU task"); } final String outputDataModelID = optionalOutputDataModelID.get(); // task execution if (optionalDoTransformations.isPresent() && optionalDoTransformations.get()) { if (optionalAllowMultipleDataModels.isPresent() && optionalAllowMultipleDataModels.get()) { final Set<Map.Entry<String, Triple<String, String, String>>> entries = inputDataModelsAndResources .entrySet(); for (final Map.Entry<String, Triple<String, String, String>> entry : entries) { final String inputDataModelID = entry.getKey(); executeTransform(inputDataModelID, outputDataModelID, optionalDoIngestOnTheFly, optionalDoExportOnTheFly, optionalExportMimeType, optionalExportFileExtension, engineThreads, serviceName, config); } } else { final Set<Map.Entry<String, Triple<String, String, String>>> entries = inputDataModelsAndResources .entrySet(); final Iterator<Map.Entry<String, Triple<String, String, String>>> iterator = entries.iterator(); final Map.Entry<String, Triple<String, String, String>> entry = iterator.next(); final String inputDataModelID = entry.getKey(); executeTransform(inputDataModelID, outputDataModelID, optionalDoIngestOnTheFly, optionalDoExportOnTheFly, optionalExportMimeType, optionalExportFileExtension, engineThreads, serviceName, config); } } else { LOG.info("skip transformations"); } final Optional<Boolean> optionalDoExport = TPUUtil.getBooleanConfigValue(TPUStatics.DO_EXPORT_IDENTIFIER, config); // export if (optionalDoExport.isPresent() && optionalDoExport.get()) { if (!optionalAllowMultipleDataModels.isPresent() || !optionalAllowMultipleDataModels.get()) { final String exportDataModelID; if (outputDataModelID != null && !outputDataModelID.trim().isEmpty()) { exportDataModelID = outputDataModelID; } else { final Set<Map.Entry<String, Triple<String, String, String>>> entries = inputDataModelsAndResources .entrySet(); final Iterator<Map.Entry<String, Triple<String, String, String>>> iterator = entries.iterator(); final Map.Entry<String, Triple<String, String, String>> entry = iterator.next(); exportDataModelID = entry.getKey(); } executeExport(exportDataModelID, optionalExportMimeType, optionalExportFileExtension, engineThreads, serviceName, config); } } else { LOG.info("skip export"); } // clean-up int cnt = 0; final String engineDswarmAPI = config.getProperty(TPUStatics.ENGINE_DSWARM_API_IDENTIFIER); final Set<Map.Entry<String, Triple<String, String, String>>> entries = inputDataModelsAndResources .entrySet(); for (final Map.Entry<String, Triple<String, String, String>> entry : entries) { final Triple<String, String, String> triple = entry.getValue(); final String inputDataModelId = triple.getLeft(); final String resourceId = triple.getMiddle(); final String configurationId = triple.getRight(); TPUUtil.deleteObject(inputDataModelId, DswarmBackendStatics.DATAMODELS_ENDPOINT, serviceName, engineDswarmAPI, cnt); TPUUtil.deleteObject(resourceId, DswarmBackendStatics.RESOURCES_ENDPOINT, serviceName, engineDswarmAPI, cnt); TPUUtil.deleteObject(configurationId, DswarmBackendStatics.CONFIGURATIONS_ENDPOINT, serviceName, engineDswarmAPI, cnt); cnt++; } }