List of usage examples for java.util Collections addAll
@SafeVarargs public static <T> boolean addAll(Collection<? super T> c, T... elements)
From source file:io.cloudsoft.marklogic.nodes.MarkLogicNodeSshDriver.java
@Override public Set<String> scanDatabases() { LOG.debug("Scanning databases"); DefaultHttpClient httpClient = new DefaultHttpClient(); try {/* w w w.j a v a2 s . c om*/ httpClient.getCredentialsProvider().setCredentials(new AuthScope(null, AuthScope.ANY_PORT), new UsernamePasswordCredentials(getEntity().getUser(), getEntity().getPassword())); String adminUrl = getEntity().getAdminConnectUrl(); String uri = adminUrl + "/database_list.xqy"; HttpGet httpget = new HttpGet(uri); HttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); String result = IOUtils.toString(entity.getContent()); EntityUtils.consume(entity); Set<String> forests = Sets.newHashSet(); String[] split = result.split("\n"); Collections.addAll(forests, split); return forests; } catch (IOException e) { throw new RuntimeException(e); } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:edu.emory.library.tast.images.admin.ImagesBean.java
public String saveImage() { Session sess = null;/*from w w w. java2 s . c om*/ Transaction transaction = null; try { // open db sess = HibernateConn.getSession(); transaction = sess.beginTransaction(); // load image Image image = null; if (selectedImageId != null) { image = Image.loadById(Integer.parseInt(selectedImageId), sess); } else { image = new Image(); } // basic image metadata image.setTitle(imageTitle); image.setSource(imageSource); image.setCreator(imageCreator); image.setReferences(imageReferences); image.setEmoryLocation(imageEmoryLocation); image.setExternalId(imageExternalId); // we will use it often Configuration appConf = AppConfig.getConfiguration(); // image properties image.setWidth(imageWidth); image.setHeight(imageHeight); image.setSize(imageSize); image.setFileName(imageFileName); image.setMimeType(imageMimeType); // title String titleLocal = checkTextField(image.getTitle(), "title", appConf.getInt(AppConfig.IMAGES_TITLE_MAXLEN), false); image.setTitle(titleLocal); // description image.setDescription(imageDescription); // category ImageCategory cat = ImageCategory.loadById(sess, imageCategoryId); image.setCategory(cat); // check source String sourceLocal = checkTextField(image.getSource(), "source", appConf.getInt(AppConfig.IMAGES_SOURCE_MAXLEN), true); image.setSource(sourceLocal); // date image.setDate(imageDate); // check creator String creatorLocal = checkTextField(image.getCreator(), "creator", appConf.getInt(AppConfig.IMAGES_CREATOR_MAXLEN), true); image.setCreator(creatorLocal); // language image.setLanguage(imageLanguage); // comments image.setComments(imageComments); // check references String referencesLocal = checkTextField(image.getReferences(), "references", appConf.getInt(AppConfig.IMAGES_REFERENCES_MAXLEN), true); image.setReferences(referencesLocal); // is at Emory image.setEmory(imageEmory); // check emory location String emoryLocationLocal = checkTextField(image.getEmoryLocation(), "Emory location", appConf.getInt(AppConfig.IMAGES_EMORYLOCATION_MAXLEN), true); image.setEmoryLocation(emoryLocationLocal); // authorization status image.setAuthorizationStatus(imageAuthorizationStatus); // image status image.setImageStatus(imageImageStatus); // image ready to go image.setReadyToGo(imageReadyToGo); // links to regions (not shown now) Set imageRegions = new HashSet(); image.setRegions(imageRegions); for (int i = 0; i < selectedRegionsIds.length; i++) { int regionId = Integer.parseInt(selectedRegionsIds[i]); Region dbRegion = Region.loadById(sess, regionId); imageRegions.add(dbRegion); } // links to ports (not shown now) Set imagePorts = new HashSet(); image.setPorts(imagePorts); for (int i = 0; i < selectedPortsIds.length; i++) { int portId = Integer.parseInt(selectedPortsIds[i]); Port dbPort = Port.loadById(sess, portId); imagePorts.add(dbPort); } // links to voyages Integer[] newVoyageIds; try { newVoyageIds = StringUtils .parseIntegerArray(StringUtils.splitByLinesAndRemoveEmpty(imageVoyageIds)); } catch (NumberFormatException nfe) { throw new SaveImageException("All linked voyage IDs have to be integers."); } Set voyageIds = image.getVoyageIds(); voyageIds.clear(); Collections.addAll(voyageIds, newVoyageIds); // save sess.saveOrUpdate(image); // commit transaction.commit(); sess.close(); return "list"; } catch (SaveImageException se) { if (transaction != null) transaction.rollback(); if (sess != null) sess.close(); setErrorText(se.getMessage()); return null; } catch (DataException de) { if (transaction != null) transaction.rollback(); if (sess != null) sess.close(); setErrorText("Internal problem with database. Sorry for the inconvenience."); return null; } }
From source file:net.sf.logsaw.dialect.pattern.APatternDialect.java
@Override public void parse(ILogResource log, InputStream input, ILogEntryCollector collector) throws CoreException { Assert.isNotNull(log, "log"); //$NON-NLS-1$ Assert.isNotNull(input, "input"); //$NON-NLS-1$ Assert.isNotNull(collector, "collector"); //$NON-NLS-1$ Assert.isTrue(isConfigured(), "Dialect should be configured by now"); //$NON-NLS-1$ try {/*from w w w . j a v a 2 s .c o m*/ LogEntry currentEntry = null; IHasEncoding enc = (IHasEncoding) log.getAdapter(IHasEncoding.class); IHasLocale loc = (IHasLocale) log.getAdapter(IHasLocale.class); if (loc != null) { // Apply the locale getPatternTranslator().applyLocale(loc.getLocale(), rules); } IHasTimeZone tz = (IHasTimeZone) log.getAdapter(IHasTimeZone.class); if (tz != null) { // Apply the timezone getPatternTranslator().applyTimeZone(tz.getTimeZone(), rules); } LineIterator iter = IOUtils.lineIterator(input, enc.getEncoding()); int minLinesPerEntry = getPatternTranslator().getMinLinesPerEntry(); int lineNo = 0; int moreLinesToCome = 0; try { String line = null; while (iter.hasNext()) { lineNo++; if (minLinesPerEntry == 1) { // Simple case line = iter.nextLine(); } else { String s = iter.nextLine(); if (moreLinesToCome == 0) { Matcher m = getInternalPatternFirstLine().matcher(s); if (m.find()) { // First line line = s; moreLinesToCome = minLinesPerEntry - 1; continue; } else { // Some crazy stuff line = s; } } else if (iter.hasNext() && (moreLinesToCome > 1)) { // Some middle line line += IOUtils.LINE_SEPARATOR + s; moreLinesToCome--; continue; } else { // Last line line += IOUtils.LINE_SEPARATOR + s; if (!iter.hasNext()) { line += IOUtils.LINE_SEPARATOR; } moreLinesToCome = 0; } } // Error handling List<IStatus> statuses = null; boolean fatal = false; // determines whether to interrupt parsing Matcher m = getInternalPatternFull().matcher(line); if (m.find()) { // The next line matches, so flush the previous entry and continue if (currentEntry != null) { collector.collect(currentEntry); currentEntry = null; } currentEntry = new LogEntry(); for (int i = 0; i < m.groupCount(); i++) { try { getPatternTranslator().extractField(currentEntry, getRules().get(i), m.group(i + 1)); } catch (CoreException e) { // Mark for interruption fatal = fatal || e.getStatus().matches(IStatus.ERROR); // Messages will be displayed later if (statuses == null) { statuses = new ArrayList<IStatus>(); } if (e.getStatus().isMultiStatus()) { Collections.addAll(statuses, e.getStatus().getChildren()); } else { statuses.add(e.getStatus()); } } } // We encountered errors or warnings if (statuses != null && !statuses.isEmpty()) { currentEntry = null; // Stop propagation IStatus status = new MultiStatus(PatternDialectPlugin.PLUGIN_ID, 0, statuses.toArray(new IStatus[statuses.size()]), NLS.bind(Messages.APatternDialect_error_failedToParseLine, lineNo), null); if (fatal) { // Interrupt parsing in case of error throw new CoreException(status); } else { collector.addMessage(status); } } } else if (currentEntry != null) { // Append to message String msg = currentEntry.get(getFieldProvider().getMessageField()); currentEntry.put(getFieldProvider().getMessageField(), msg + IOUtils.LINE_SEPARATOR + line); } if (collector.isCanceled()) { // Cancel parsing break; } } if (currentEntry != null) { // Collect left over entry collector.collect(currentEntry); } } finally { LineIterator.closeQuietly(iter); } } catch (Exception e) { throw new CoreException(new Status(IStatus.ERROR, PatternDialectPlugin.PLUGIN_ID, NLS.bind(Messages.APatternDialect_error_failedToParseFile, new Object[] { log.getName(), e.getLocalizedMessage() }), e)); } }
From source file:net.reichholf.dreamdroid.fragment.TimerEditFragment.java
/** * Set the GUI-Content from <code>mTimer</code> *//*from w w w .j a va 2s . c om*/ protected void reload() { // Name mName.setText(mTimer.getString(Timer.KEY_NAME)); mName.setHint(R.string.title); // Description mDescription.setText(mTimer.getString(Timer.KEY_DESCRIPTION)); mDescription.setHint(R.string.description); // Enabled int disabled = DateTime.parseTimestamp(mTimer.getString(Timer.KEY_DISABLED)); if (disabled == 0) { mEnabled.setChecked(true); } else { mEnabled.setChecked(false); } int zap = DateTime.parseTimestamp(mTimer.getString(Timer.KEY_JUST_PLAY)); if (zap == 1) { mZap.setChecked(true); } else { mZap.setChecked(false); } mService.setText(mTimer.getString(Timer.KEY_SERVICE_NAME)); // Afterevents ArrayAdapter<CharSequence> aaAfterevent = ArrayAdapter.createFromResource(getAppCompatActivity(), R.array.afterevents, android.R.layout.simple_spinner_item); aaAfterevent.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mAfterevent.setAdapter(aaAfterevent); int aeValue = DateTime.parseTimestamp(mTimer.getString(Timer.KEY_AFTER_EVENT)); mAfterevent.setSelection(aeValue); // Locations ArrayAdapter<String> aaLocations = new ArrayAdapter<>(getAppCompatActivity(), android.R.layout.simple_spinner_item, DreamDroid.getLocations()); aaLocations.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mLocation.setAdapter(aaLocations); String timerLoc = mTimer.getString(Timer.KEY_LOCATION); for (int i = 0; i < DreamDroid.getLocations().size(); i++) { String loc = DreamDroid.getLocations().get(i); if (timerLoc != null) { if (timerLoc.equals(loc)) { mLocation.setSelection(i); } } } // Start and Endtime mBegin = DateTime.parseTimestamp(mTimer.getString(Timer.KEY_BEGIN)); mEnd = DateTime.parseTimestamp(mTimer.getString(Timer.KEY_END)); Date dateBegin = new Date(((long) mBegin) * 1000); Date dateEnd = new Date(((long) mEnd) * 1000); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm"); mStartDate.setText(dateFormat.format(dateBegin)); mStartTime.setText(timeFormat.format(dateBegin)); mEndDate.setText(dateFormat.format(dateEnd)); mEndTime.setText(timeFormat.format(dateEnd)); // Repeatings int repeatedValue = 0; try { repeatedValue = DateTime.parseTimestamp(mTimer.getString(Timer.KEY_REPEATED)); } catch (NumberFormatException ex) { } String repeatedText = getRepeated(repeatedValue); mRepeatings.setText(repeatedText); String text = mTimer.getString(Timer.KEY_TAGS); if (text == null) { text = ""; } mTags.setText(text); String[] tags = text.split(" "); Collections.addAll(mSelectedTags, tags); }
From source file:net.sf.keystore_explorer.crypto.x509.X509CertUtil.java
/** * PKI Path encode a number of certificates. * * @return The encoding/* w w w . j a va2 s . co m*/ * @param certs * The certificates * @throws CryptoException * If there was a problem encoding the certificates */ public static byte[] getCertsEncodedPkiPath(X509Certificate[] certs) throws CryptoException { try { ArrayList<Certificate> encodedCerts = new ArrayList<Certificate>(); Collections.addAll(encodedCerts, certs); CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE, BOUNCY_CASTLE.jce()); CertPath cp = cf.generateCertPath(encodedCerts); return cp.getEncoded(PKI_PATH_ENCODING); } catch (CertificateException e) { throw new CryptoException(res.getString("NoPkcs7Encode.exception.message"), e); } catch (NoSuchProviderException e) { throw new CryptoException(res.getString("NoPkcs7Encode.exception.message"), e); } }
From source file:com.jayway.restassured.RestAssured.java
/** * Add default filters to apply to each request. * * @param filter The filter to add * @param additionalFilters An optional array of additional filters to add *//*w w w . jav a 2 s .co m*/ public static void filters(Filter filter, Filter... additionalFilters) { Validate.notNull(filter, "Filter cannot be null"); RestAssured.filters.add(filter); if (additionalFilters != null) { Collections.addAll(RestAssured.filters, additionalFilters); } }
From source file:org.dasein.cloud.tier3.APIHandler.java
private @Nonnull String getEndpoint(@Nonnull String resource, @Nullable String id, @Nullable NameValuePair... parameters) throws ConfigurationException, InternalException { ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new NoContextException(); }/* w ww. j a va2 s. co m*/ String endpoint = ctx.getEndpoint(); if (endpoint == null) { logger.error("Null endpoint for the CenturyLink cloud"); throw new ConfigurationException("Null endpoint for CenturyLink cloud"); } while (endpoint.endsWith("/") && !endpoint.equals("/")) { endpoint = endpoint.substring(0, endpoint.length() - 1); } // TODO special V1 logic, replace when v2 is released endpoint += "/REST"; if (resource.startsWith("/")) { endpoint = endpoint + resource; } else { endpoint = endpoint + "/" + resource; } if (id != null) { if (endpoint.endsWith("/")) { endpoint = endpoint + id; } else { endpoint = endpoint + "/" + id; } } if (parameters != null && parameters.length > 0) { while (endpoint.endsWith("/")) { endpoint = endpoint.substring(0, endpoint.length() - 1); } endpoint = endpoint + "?"; ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); Collections.addAll(params, parameters); endpoint = endpoint + URLEncodedUtils.format(params, "utf-8"); } logger.trace("Returning endpoint: " + endpoint); return endpoint; }
From source file:io.cloudsoft.marklogic.nodes.MarkLogicNodeSshDriver.java
@Override public Set<String> scanForests() { LOG.debug("Scanning forests"); DefaultHttpClient httpClient = new DefaultHttpClient(); try {//from w ww. ja v a 2 s . c om httpClient.getCredentialsProvider().setCredentials(new AuthScope(null, AuthScope.ANY_PORT), new UsernamePasswordCredentials(getEntity().getUser(), getEntity().getPassword())); String adminUrl = getEntity().getAdminConnectUrl(); String uri = adminUrl + "/forest_list.xqy"; HttpGet httpget = new HttpGet(uri); HttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); String result = IOUtils.toString(entity.getContent()); EntityUtils.consume(entity); Set<String> forests = new HashSet<String>(); String[] split = result.split("\n"); Collections.addAll(forests, split); return forests; } catch (IOException e) { throw new RuntimeException(e); } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:io.neba.core.resourcemodels.mapping.FieldValueMappingCallback.java
/** * The fieldType is a collection. However, the component type of * the collection is a property type, e.g. List<String>. We must * fetch the property with the array-type of the component type (e.g. String[]) * and add the values to a new instance of Collection<T>. * * @return a collection of the resolved values, or <code>null</code> if no value could be resolved. *//*from ww w.j a va 2s .c o m*/ private Collection<?> getArrayPropertyAsCollection(FieldData field) { Class<?> arrayType = field.metaData.getArrayTypeOfTypeParameter(); Object[] elements = (Object[]) resolvePropertyTypedValue(field, arrayType); if (elements != null) { @SuppressWarnings("unchecked") Collection<Object> collection = ReflectionUtil .instantiateCollectionType((Class<Collection<Object>>) field.metaData.getType()); Collections.addAll(collection, elements); return collection; } return null; }
From source file:com.vmware.photon.controller.deployer.dcp.task.ProvisionHostTaskService.java
private void processProvisionAgentSubStage(State currentState, DeploymentService.State deploymentState, HostService.State hostState) { List<String> datastores = null; if (hostState.metadata != null && hostState.metadata.containsKey(HostService.State.METADATA_KEY_NAME_ALLOWED_DATASTORES)) { String[] allowedDatastores = hostState.metadata .get(HostService.State.METADATA_KEY_NAME_ALLOWED_DATASTORES).trim() .split(COMMA_DELIMITED_REGEX); datastores = new ArrayList<>(allowedDatastores.length); Collections.addAll(datastores, allowedDatastores); }/*from w w w .ja v a 2 s .c om*/ List<String> networks = null; if (hostState.metadata != null && hostState.metadata.containsKey(HostService.State.METADATA_KEY_NAME_ALLOWED_NETWORKS)) { String[] allowedNetworks = hostState.metadata.get(HostService.State.METADATA_KEY_NAME_ALLOWED_NETWORKS) .trim().split(COMMA_DELIMITED_REGEX); networks = new ArrayList<>(allowedNetworks.length); Collections.addAll(networks, allowedNetworks); } StatsPluginConfig statsPluginConfig = new StatsPluginConfig(deploymentState.statsEnabled); if (deploymentState.statsStoreEndpoint != null) { statsPluginConfig.setStats_store_endpoint(deploymentState.statsStoreEndpoint); } if (deploymentState.statsStorePort != null) { statsPluginConfig.setStats_store_port(deploymentState.statsStorePort); } if (deploymentState.statsStoreType != null) { statsPluginConfig .setStats_store_type(StatsStoreType.findByValue(deploymentState.statsStoreType.ordinal())); } if (hostState.usageTags != null) { // Agent accepts stats' tags as comma separated string. // Concatenate usageTags as one tag for stats so that they could be // queried easily. For example, user can query all metrics // having tag equal to 'MGMT-CLOUD' or '*MGMT*'. List<String> usageTagList = new ArrayList<>(hostState.usageTags); Collections.sort(usageTagList); statsPluginConfig.setStats_host_tags(Joiner.on("-").skipNulls().join(usageTagList)); } try { AgentControlClient agentControlClient = HostUtils.getAgentControlClient(this); agentControlClient.setIpAndPort(hostState.hostAddress, hostState.agentPort); agentControlClient.provision(datastores, deploymentState.imageDataStoreNames, deploymentState.imageDataStoreUsedForVMs, networks, hostState.hostAddress, hostState.agentPort, 0, // Overcommit ratio is not implemented, deploymentState.syslogEndpoint, DEFAULT_AGENT_LOG_LEVEL, statsPluginConfig, (hostState.usageTags != null && hostState.usageTags.contains(UsageTag.MGMT.name()) && !hostState.usageTags.contains(UsageTag.CLOUD.name())), ServiceUtils.getIDFromDocumentSelfLink(currentState.hostServiceLink), ServiceUtils.getIDFromDocumentSelfLink(currentState.deploymentServiceLink), deploymentState.ntpEndpoint, new AsyncMethodCallback<AgentControl.AsyncClient.provision_call>() { @Override public void onComplete(AgentControl.AsyncClient.provision_call provisionCall) { try { AgentControlClient.ResponseValidator .checkProvisionResponse(provisionCall.getResult()); sendStageProgressPatch(currentState, TaskState.TaskStage.STARTED, TaskState.SubStage.WAIT_FOR_PROVISION); } catch (Throwable t) { logProvisioningErrorAndFail(hostState, t); } } @Override public void onError(Exception e) { logProvisioningErrorAndFail(hostState, e); } }); } catch (Throwable t) { logProvisioningErrorAndFail(hostState, t); } }