List of usage examples for java.util Collections addAll
@SafeVarargs public static <T> boolean addAll(Collection<? super T> c, T... elements)
From source file:com.asakusafw.runtime.directio.hadoop.HadoopDataSourceUtil.java
private static List<FileStatus> recursiveStep(FileSystem fs, List<FileStatus> current) throws IOException { assert fs != null; assert current != null; Set<Path> paths = new HashSet<>(); List<FileStatus> results = new ArrayList<>(); LinkedList<FileStatus> work = new LinkedList<>(current); while (work.isEmpty() == false) { FileStatus next = work.removeFirst(); Path path = next.getPath(); if (paths.contains(path) == false) { paths.add(path);// w ww. ja v a 2s . com results.add(next); if (next.isDirectory()) { FileStatus[] children; try { children = fs.listStatus(path); } catch (FileNotFoundException e) { children = null; if (LOG.isDebugEnabled()) { LOG.debug(MessageFormat.format("Target file is not found: {0}", path), e); //$NON-NLS-1$ } } if (children != null) { Collections.addAll(work, children); } } } } return results; }
From source file:com.example.app.config.ProjectShellCommands.java
/** * Convert the AddressData into an Address * * @param cmdUtil the shell commands util * * @return an Address/*w w w . java 2 s.c om*/ * * @throws IOException if the shell screws up */ @Nonnull public Address toAddress(@Nonnull ShellCommandsUtil cmdUtil) throws IOException { cmdUtil.printLine("Creating Address..."); Address address = new Address(); category = cmdUtil.getCategory(category, "for this Address"); address.setCategory(cmdUtil.convertCategory(category, ContactDataCategory.BUSINESS)); if (addressLines == null) { List<String> addressLineList = new ArrayList<>(); boolean cont = true; while (cont) { cmdUtil.getShell().printNewline(); String line = cmdUtil.getShell() .readLine("Address Line(To stop adding address lines, just hit ENTER):"); if (!isEmptyString(line)) { addressLineList.add(line); } else { cont = false; } } addressLines = addressLineList.toArray(new String[addressLineList.size()]); } Collections.addAll(address.getAddressLineList(), addressLines); if (isEmptyString(city)) { city = cmdUtil.getInteractiveArg("What is the city for this Address?", result -> !isEmptyString(result)); } if (isEmptyString(state)) { state = cmdUtil.getInteractiveArg("What is the state for this Address?", result -> !isEmptyString(result)); } if (isEmptyString(zip)) { zip = cmdUtil.getInteractiveArg("What is the postal code for this Address?", result -> !isEmptyString(result)); } address.setCity(city); address.setState(state); address.setPostalCode(zip); return address; }
From source file:com.haulmont.cuba.gui.data.impl.AbstractCollectionDatasource.java
protected void setSortDirection(LoadContext.Query q) { boolean asc = Sortable.Order.ASC.equals(sortInfos[0].getOrder()); MetaPropertyPath propertyPath = sortInfos[0].getPropertyPath(); String[] sortProperties = null; if (metadata.getTools().isPersistent(propertyPath)) { sortProperties = getSortPropertiesForPersistentAttribute(propertyPath); } else {//from w w w. j a v a 2 s.c o m // a non-persistent attribute List<String> relProperties = metadata.getTools().getRelatedProperties(propertyPath.getMetaProperty()); if (!relProperties.isEmpty()) { List<String> sortPropertiesList = new ArrayList<>(relProperties.size()); for (String relProp : relProperties) { String[] ppCopy = Arrays.copyOf(propertyPath.getPath(), propertyPath.getPath().length); ppCopy[ppCopy.length - 1] = relProp; MetaPropertyPath relPropertyPath = propertyPath.getMetaProperties()[0].getDomain() .getPropertyPath(Joiner.on(".").join(ppCopy)); String[] sortPropertiesForRelProperty = getSortPropertiesForPersistentAttribute( relPropertyPath); if (sortPropertiesForRelProperty != null) Collections.addAll(sortPropertiesList, sortPropertiesForRelProperty); } if (!sortPropertiesList.isEmpty()) sortProperties = sortPropertiesList.toArray(new String[sortPropertiesList.size()]); } } if (sortProperties != null) { QueryTransformer transformer = QueryTransformerFactory.createTransformer(q.getQueryString()); transformer.replaceOrderBy(!asc, sortProperties); String jpqlQuery = transformer.getResult(); q.setQueryString(jpqlQuery); } }
From source file:com.m4rc310.cb.builders.ComponentBuilder.java
@Override public void clear(Object... targetsA) { if (targetsA.length == 0) { Collections.addAll(targets, targetsA); }//from w w w. j a v a2s . c om for (Object tar : targetsA) { adapters.entrySet().stream().forEach((entrySet) -> { Field field = entrySet.getKey(); AbstractComponetAdapter adapter = entrySet.getValue(); if (getTargetForField(field) == tar) { try { adapter.clear(); } catch (Exception e) { infoError(e); } } }); } }
From source file:edu.unc.lib.dl.services.BatchIngestTask.java
/** * *///from www. j av a2 s . c o m private void sendIngestMessages() { // load reordered existing children File reorderedFile = new File(this.getBaseDir(), REORDERED_LOG); if (reorderedFile.exists()) { List<PID> reordered = new ArrayList<PID>(); BufferedReader r = null; try { r = new BufferedReader(new FileReader(reorderedFile)); for (String line = r.readLine(); line != null; line = r.readLine()) { reordered.add(new PID(line)); } } catch (IOException e) { throw new Error("Unexpected IO error.", e); } finally { try { if (r != null) r.close(); } catch (IOException ignored) { } } Set<PID> containerSet = new HashSet<PID>(); Collections.addAll(containerSet, this.containers); if (this.sendJmsMessages) { this.getOperationsMessageSender().sendAddOperation(ingestProperties.getSubmitter(), containerSet, ingestProperties.getContainerPlacements().keySet(), reordered, ingestProperties.getOriginalDepositId()); } } // send successful ingest email if (this.sendEmailMessages && this.mailNotifier != null && ingestProperties.getEmailRecipients() != null) this.mailNotifier.sendIngestSuccessNotice(ingestProperties, this.foxmlFiles.length); this.state = STATE.CLEANUP; }
From source file:literarytermsquestionbank.RomeoAndJuliet.java
private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened // Set custom icon this.setIconImage( Toolkit.getDefaultToolkit().getImage(getClass().getResource("/Resources/Images/book-icon_rj.png"))); // Set custom fonts try {/*www. j a v a 2 s . c om*/ GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); // Load Old English from resources Font englishFontFace = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("/Resources/Fonts/OLDENGL.TTF")); ge.registerFont(englishFontFace); actLabel.setFont(englishFontFace.deriveFont(Font.PLAIN, 30f)); sceneLabel.setFont(englishFontFace.deriveFont(Font.PLAIN, 16f)); lineNumberLabel.setFont(englishFontFace.deriveFont(Font.PLAIN, 16f)); // Load Matura Script font from resources Font maturaFontFace = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("/Resources/Fonts/MATURASC.TTF")); ge.registerFont(maturaFontFace); tabbedPane.setFont(maturaFontFace.deriveFont(Font.PLAIN, 18f)); questionLabel.setFont(maturaFontFace.deriveFont(Font.PLAIN, 18f)); checkButton.setFont(maturaFontFace.deriveFont(Font.PLAIN, 14f)); stuckLabel.setFont(maturaFontFace.deriveFont(Font.PLAIN, 14f)); rescueButton.setFont(maturaFontFace.deriveFont(Font.PLAIN, 14f)); answerLabel.setFont(maturaFontFace.deriveFont(Font.PLAIN, 14f)); youAreViewingLabel.setFont(maturaFontFace.deriveFont(Font.PLAIN, 18f)); quoteIndexTextField.setFont(maturaFontFace.deriveFont(Font.PLAIN, 24f)); totalNumberLabel.setFont(maturaFontFace.deriveFont(Font.PLAIN, 36f)); goButton.setFont(maturaFontFace.deriveFont(Font.PLAIN, 24f)); randomButton.setFont(maturaFontFace.deriveFont(Font.PLAIN, 18f)); previousButton.setFont(maturaFontFace.deriveFont(Font.PLAIN, 14f)); nextButton.setFont(maturaFontFace.deriveFont(Font.PLAIN, 14f)); backButton.setFont(maturaFontFace.deriveFont(Font.PLAIN, 14f)); // Load Corsova font from resources Font corsovaFontFace = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("/Resources/Fonts/MTCORSVA.TTF")); ge.registerFont(corsovaFontFace); clueLabel.setFont(corsovaFontFace.deriveFont(Font.PLAIN, 18f)); passageLabel.setFont(corsovaFontFace.deriveFont(Font.PLAIN, 18f)); examplesLabel.setFont(corsovaFontFace.deriveFont(Font.PLAIN, 18f)); commentsLabel.setFont(corsovaFontFace.deriveFont(Font.PLAIN, 14f)); // Load Imprint font from resources Font imprintFontFace = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("/Resources/Fonts/IMPRISHA.TTF")); ge.registerFont(imprintFontFace); quoteTopLabel.setFont(imprintFontFace.deriveFont(Font.PLAIN, 48f)); quoteBottomLabel.setFont(imprintFontFace.deriveFont(Font.PLAIN, 48f)); } catch (FontFormatException ex) { Logger.getLogger(RomeoAndJuliet.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(RomeoAndJuliet.class.getName()).log(Level.SEVERE, null, ex); } JSONParser parser = new JSONParser(); try { // This object is the result of parsing the JSON file at the relative filepath as defined above; the JSON file is in the Resources source package. Object quoteObj = parser .parse(new InputStreamReader(getClass().getResourceAsStream("/Resources/Files/db.json"))); // This casts the object to a JSONObject for future manipulation JSONObject jsonObject = (JSONObject) quoteObj; // This array holds all the quotes JSONArray quotesArray = (JSONArray) jsonObject.get("Romeo and Juliet"); Iterator<JSONObject> iterator = quotesArray.iterator(); // Using the iterator as declared above, add each JSONObject in the Romeo and Juliet array to the ArrayList while (iterator.hasNext()) { Collections.addAll(quotesList, iterator.next()); totalNumberOfQuotes++; } // Init randomizer Random rand = new Random(); // Generate a random integer between 1 and size of the ArrayList quoteIndex = rand.nextInt(quotesList.size()) + 1; generateQuote(quoteIndex); // This calls a method to generate a quote and display it } catch (Exception e) { // This means something went very wrong when starting the program System.out.println("Uh oh, something bad happened. Possible database corruption."); JOptionPane.showMessageDialog(null, "Something went wrong while starting the app! Please tell Aaron with code 129.", "Uh-oh!", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } }
From source file:com.diversityarrays.kdxplore.heatmap.HeatMapPanel.java
private Set<PlotOrSpecimen> getSelectedPlotIds() { Set<Point> selectedPoints = heatMap.getSelectedPoints(); Map<Point, PlotOrSpecimen> plotSpecimensByPoint = heatMap.getModel().getCellContentByPoint(); List<PlotOrSpecimen> list = plotSpecimensByPoint.keySet().stream().filter(pt -> selectedPoints.contains(pt)) .map(pt -> plotSpecimensByPoint.get(pt)).collect(Collectors.toList()); Set<PlotOrSpecimen> result = new HashSet<>(); for (PlotOrSpecimen posArray : list) { Collections.addAll(result, posArray); }//from w w w .java 2 s .c o m return result; }
From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java
private static byte[] createSignatureBlock(byte[] toSign, PrivateKey privateKey, X509Certificate[] certificateChain, SignatureType signatureType, String tsaUrl, Provider provider) throws CryptoException { try {//from w w w.j av a2s .c om List<X509Certificate> certList = new ArrayList<X509Certificate>(); Collections.addAll(certList, certificateChain); DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider("BC") .build(); JcaContentSignerBuilder csb = new JcaContentSignerBuilder(signatureType.jce()) .setSecureRandom(SecureRandom.getInstance("SHA1PRNG")); if (provider != null) { csb.setProvider(provider); } JcaSignerInfoGeneratorBuilder siGeneratorBuilder = new JcaSignerInfoGeneratorBuilder(digCalcProv); // remove cmsAlgorithmProtect for compatibility reasons SignerInfoGenerator sigGen = siGeneratorBuilder.build(csb.build(privateKey), certificateChain[0]); final CMSAttributeTableGenerator sAttrGen = sigGen.getSignedAttributeTableGenerator(); sigGen = new SignerInfoGenerator(sigGen, new DefaultSignedAttributeTableGenerator() { @Override public AttributeTable getAttributes(@SuppressWarnings("rawtypes") Map parameters) { AttributeTable ret = sAttrGen.getAttributes(parameters); return ret.remove(CMSAttributes.cmsAlgorithmProtect); } }, sigGen.getUnsignedAttributeTableGenerator()); CMSSignedDataGenerator dataGen = new CMSSignedDataGenerator(); dataGen.addSignerInfoGenerator(sigGen); dataGen.addCertificates(new JcaCertStore(certList)); CMSSignedData signedData = dataGen.generate(new CMSProcessableByteArray(toSign), true); // now let TSA time-stamp the signature if (tsaUrl != null && !tsaUrl.isEmpty()) { signedData = addTimestamp(tsaUrl, signedData); } return signedData.getEncoded(); } catch (Exception ex) { throw new CryptoException(res.getString("SignatureBlockCreationFailed.exception.message"), ex); } }
From source file:io.smartspaces.launcher.bootstrap.SmartSpacesFrameworkBootstrap.java
/** * Create, configure, and start the OSGi framework instance. * * @param extensionsReader/*from w ww . j a v a2s . c om*/ * the reader for extensions files * * @throws Exception * unable to create and/or start the framework */ private void createFramework(ExtensionsReader extensionsReader) throws Exception { Map<String, String> frameworkConfig = new HashMap<String, String>(); frameworkConfig.put(Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT); // The bootloader delegation loads all classes in the java install. This // covers things like the javax classes which // are not automatically exposed through the OSGi bundle classloaders. List<String> bootDelegationPackages = new ArrayList<String>(); // Extra system packages are not found in the boot classloader but need // to // be exported by the system bundle // classloader. List<String> extraSystemPackages = new ArrayList<String>(); bootDelegationPackages.addAll(extensionsReader.getBootPackages()); processDelegationsFile(bootDelegationPackages, extraSystemPackages); configureBootDelegationPackages(frameworkConfig, bootDelegationPackages); // Get the initial packages into the extra system packages. Collections.addAll(extraSystemPackages, PACKAGES_SYSTEM_EXTERNAL); Collections.addAll(extraSystemPackages, PACKAGES_SYSTEM_SMARTSPACES); extraSystemPackages.addAll(extensionsReader.getPackages()); configureExtraSystemPackages(frameworkConfig, extraSystemPackages); frameworkConfig.put(CoreConfiguration.CONFIGURATION_NAME_SMARTSPACES_BASE_INSTALL_DIR, baseInstallFolder.getAbsolutePath()); frameworkConfig.put(CoreConfiguration.CONFIGURATION_NAME_SMARTSPACES_RUNTIME_DIR, runtimeFolder.getAbsolutePath()); frameworkConfig.put(CoreConfiguration.CONFIGURATION_NAME_SMARTSPACES_VERSION, getSmartSpacesVersion()); frameworkConfig.putAll(configurationProvider.getInitialConfiguration()); File pluginsCacheFolder = new File( new File(runtimeFolder, ContainerFilesystemLayout.FOLDER_SMARTSPACES_RUN), FOLDER_PLUGINS_CACHE); frameworkConfig.put(Constants.FRAMEWORK_STORAGE, pluginsCacheFolder.getCanonicalPath()); framework = getFrameworkFactory().newFramework(frameworkConfig); frameworkStartLevel = framework.adapt(FrameworkStartLevel.class); framework.init(); rootBundleContext = framework.getBundleContext(); if (CONFIG_PROPERTY_VALUE_STARTUP_LOGGING.equals(frameworkConfig.get(CONFIG_PROPERTY_STARTUP_LOGGING))) { rootBundleContext.addBundleListener(new SynchronousBundleListener() { @Override public void bundleChanged(BundleEvent event) { try { if (event.getType() == BundleEvent.STARTED) { Bundle bundle = event.getBundle(); loggingProvider.getLog() .info(String.format("Bundle %s:%s started with start level %d", bundle.getSymbolicName(), bundle.getVersion(), bundle.adapt(BundleStartLevel.class).getStartLevel())); } } catch (Exception e) { loggingProvider.getLog().error("Exception while responding to bundle change events", e); } } }); } }
From source file:com.amalto.core.server.DefaultItem.java
/** * Search ordered Items through a view in a cluster and specifying a condition * * @param dataClusterPOJOPK The Data Cluster where to run the query * @param viewPOJOPK The View//from w w w . j av a 2 s . c om * @param searchValue The value searched. If empty, null or equals to "*", this method is equivalent to a view search * with no filter. * @param matchWholeSentence If <code>false</code>, the searchValue is separated into keywords using " " (white space) as * separator. Match will be done with a OR condition on each field. If <code>true</code>, the keyword is considered * as a whole sentence and matching is done on the whole sentence (not each word). * @param spellThreshold The condition spell checking threshold. A negative value de-activates spell * @param orderBy An optional full path of the item used to order results. * @param direction One of {@link com.amalto.xmlserver.interfaces.IXmlServerSLWrapper#ORDER_ASCENDING} or * {@link com.amalto.xmlserver.interfaces.IXmlServerSLWrapper#ORDER_DESCENDING} * @param start The first item index (starts at zero) * @param limit The maximum number of items to return * @return The ordered list of results * @throws com.amalto.core.util.XtentisException In case of error in MDM code. */ @Override public ArrayList<String> quickSearch(DataClusterPOJOPK dataClusterPOJOPK, ViewPOJOPK viewPOJOPK, String searchValue, boolean matchWholeSentence, int spellThreshold, String orderBy, String direction, int start, int limit) throws XtentisException { try { // check if there actually is a search value if ((searchValue == null) || "".equals(searchValue) || "*".equals(searchValue)) { // $NON-NLS-1$ // $NON-NLS-2$ return viewSearch(dataClusterPOJOPK, viewPOJOPK, null, spellThreshold, orderBy, direction, start, limit); } else { ViewPOJO view = Util.getViewCtrlLocal().getView(viewPOJOPK); ArrayList<String> searchableFields = view.getSearchableBusinessElements().getList(); Iterator<String> iterator = searchableFields.iterator(); while (iterator.hasNext()) { String searchableField = iterator.next(); // Exclude searchable elements that don't include a '/' since we are generating XPath expressions // (exclude 'Entity' elements but keep 'Entity/Id'). if (!searchableField.contains("/")) { iterator.remove(); } } List<String> keywords; if (!matchWholeSentence) { // Match on each word. keywords = new ArrayList<String>(); String[] allKeywords = searchValue.split("\\p{Space}+"); Collections.addAll(keywords, allKeywords); } else { // Match on whole sentence keywords = Collections.singletonList(searchValue); } IWhereItem searchItem; if (searchableFields.isEmpty()) { return new ArrayList<String>(0); } else { WhereOr whereOr = new WhereOr(); for (String fieldName : searchableFields) { WhereOr nestedOr = new WhereOr(); for (String keyword : keywords) { WhereCondition nestedCondition = new WhereCondition(fieldName, WhereCondition.CONTAINS, keyword.trim(), WhereCondition.PRE_OR, false); nestedOr.add(nestedCondition); } whereOr.add(nestedOr); } searchItem = whereOr; } return viewSearch(dataClusterPOJOPK, viewPOJOPK, searchItem, spellThreshold, orderBy, direction, start, limit); } } catch (XtentisException e) { throw (e); } catch (Exception e) { String err = "Unable to quick search " + searchValue + ": " + e.getClass().getName() + ": " + e.getLocalizedMessage(); LOGGER.error(err, e); throw new XtentisException(err, e); } }