List of usage examples for java.lang String join
public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
From source file:edu.usu.sdl.openstorefront.doc.JaxrsProcessor.java
public static APIResourceModel processRestClass(Class resource, String rootPath) { APIResourceModel resourceModel = new APIResourceModel(); resourceModel.setClassName(resource.getName()); resourceModel.setResourceName(/*from ww w . j a v a2s . c o m*/ String.join(" ", StringUtils.splitByCharacterTypeCamelCase(resource.getSimpleName()))); APIDescription aPIDescription = (APIDescription) resource.getAnnotation(APIDescription.class); if (aPIDescription != null) { resourceModel.setResourceDescription(aPIDescription.value()); } Path path = (Path) resource.getAnnotation(Path.class); if (path != null) { resourceModel.setResourcePath(rootPath + "/" + path.value()); } RequireAdmin requireAdmin = (RequireAdmin) resource.getAnnotation(RequireAdmin.class); if (requireAdmin != null) { resourceModel.setRequireAdmin(true); } //class parameters mapParameters(resourceModel.getResourceParams(), resource.getDeclaredFields()); //methods ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); int methodId = 0; for (Method method : resource.getDeclaredMethods()) { APIMethodModel methodModel = new APIMethodModel(); methodModel.setId(methodId++); //rest method List<String> restMethods = new ArrayList<>(); GET getMethod = (GET) method.getAnnotation(GET.class); POST postMethod = (POST) method.getAnnotation(POST.class); PUT putMethod = (PUT) method.getAnnotation(PUT.class); DELETE deleteMethod = (DELETE) method.getAnnotation(DELETE.class); if (getMethod != null) { restMethods.add("GET"); } if (postMethod != null) { restMethods.add("POST"); } if (putMethod != null) { restMethods.add("PUT"); } if (deleteMethod != null) { restMethods.add("DELETE"); } methodModel.setRestMethod(String.join(",", restMethods)); if (restMethods.isEmpty()) { //skip non-rest methods continue; } //produces Produces produces = (Produces) method.getAnnotation(Produces.class); if (produces != null) { methodModel.setProducesTypes(String.join(",", produces.value())); } //consumes Consumes consumes = (Consumes) method.getAnnotation(Consumes.class); if (consumes != null) { methodModel.setConsumesTypes(String.join(",", consumes.value())); } aPIDescription = (APIDescription) method.getAnnotation(APIDescription.class); if (aPIDescription != null) { methodModel.setDescription(aPIDescription.value()); } path = (Path) method.getAnnotation(Path.class); if (path != null) { methodModel.setMethodPath(path.value()); } requireAdmin = (RequireAdmin) method.getAnnotation(RequireAdmin.class); if (requireAdmin != null) { methodModel.setRequireAdmin(true); } try { if (!(method.getReturnType().getSimpleName().equalsIgnoreCase(Void.class.getSimpleName()))) { APIValueModel valueModel = new APIValueModel(); DataType dataType = (DataType) method.getAnnotation(DataType.class); boolean addResponseObject = true; if ("javax.ws.rs.core.Response".equals(method.getReturnType().getName()) && dataType == null) { addResponseObject = false; } if (addResponseObject) { valueModel.setValueObjectName(method.getReturnType().getSimpleName()); ReturnType returnType = (ReturnType) method.getAnnotation(ReturnType.class); Class returnTypeClass; if (returnType != null) { returnTypeClass = returnType.value(); } else { returnTypeClass = method.getReturnType(); } if (!"javax.ws.rs.core.Response".equals(method.getReturnType().getName())) { if (ReflectionUtil.isCollectionClass(method.getReturnType()) == false) { try { valueModel.setValueObject( objectMapper.writeValueAsString(returnTypeClass.newInstance())); mapValueField(valueModel.getValueFields(), ReflectionUtil.getAllFields(returnTypeClass).toArray(new Field[0])); mapComplexTypes(valueModel.getAllComplexTypes(), ReflectionUtil.getAllFields(returnTypeClass).toArray(new Field[0]), false); aPIDescription = (APIDescription) returnTypeClass .getAnnotation(APIDescription.class); if (aPIDescription != null) { valueModel.setValueDescription(aPIDescription.value()); } } catch (InstantiationException iex) { log.log(Level.WARNING, MessageFormat.format( "Unable to instantiated type: {0} make sure the type is not abstract.", returnTypeClass)); } } } if (dataType != null) { String typeName = dataType.value().getSimpleName(); if (StringUtils.isNotBlank(dataType.actualClassName())) { typeName = dataType.actualClassName(); } valueModel.setTypeObjectName(typeName); try { valueModel.setTypeObject( objectMapper.writeValueAsString(dataType.value().newInstance())); mapValueField(valueModel.getTypeFields(), ReflectionUtil.getAllFields(dataType.value()).toArray(new Field[0])); mapComplexTypes(valueModel.getAllComplexTypes(), ReflectionUtil.getAllFields(dataType.value()).toArray(new Field[0]), false); aPIDescription = (APIDescription) dataType.value() .getAnnotation(APIDescription.class); if (aPIDescription != null) { valueModel.setTypeDescription(aPIDescription.value()); } } catch (InstantiationException iex) { log.log(Level.WARNING, MessageFormat.format( "Unable to instantiated type: {0} make sure the type is not abstract.", dataType.value())); } } methodModel.setResponseObject(valueModel); } } } catch (IllegalAccessException | JsonProcessingException ex) { log.log(Level.WARNING, null, ex); } //method parameters mapMethodParameters(methodModel.getMethodParams(), method.getParameters()); //Handle Consumed Objects mapConsumedObjects(methodModel, method.getParameters()); resourceModel.getMethods().add(methodModel); } Collections.sort(resourceModel.getMethods(), new ApiMethodComparator<>()); return resourceModel; }
From source file:com.coinblesk.server.service.ForexService.java
public Map<String, BigDecimal> getExchangeRates(final String... pairs) throws Exception { // mark as used Map<String, BigDecimal> exchangeRates = new HashMap<>(pairs.length); // this empty most of the times: List<String> unknowRates = new ArrayList<>(1); for (String pair : pairs) { exchangeRatesSymbolCache.put(pair, Boolean.TRUE); BigDecimal exchangeRate = exchangeRatesCache.getIfPresent(pair); if (exchangeRate == null) { unknowRates.add(pair);/*from ww w.j a va 2 s . c o m*/ } else { exchangeRates.put(pair, exchangeRate); } } if (!unknowRates.isEmpty()) { String values = String.join("\",\"", unknowRates); String rates = '"' + values + '"'; final String url = YAHOO_API.replace(PLACEHOLDER, rates); final StringBuffer response = ServiceUtils.doHttpRequest(url); // gets actual exchange rate out of Json Object and saves it to last. final Gson gson = new Gson(); if (unknowRates.size() > 1) { final RootMulti root = gson.fromJson(response.toString(), RootMulti.class); for (RootMulti.Query.Results.Rate rate : root.query.results.rate) { BigDecimal exchangeRate = new BigDecimal(rate.Rate); exchangeRatesCache.put(rate.id, exchangeRate); exchangeRates.put(rate.id, exchangeRate); } } else { final RootSingle root = gson.fromJson(response.toString(), RootSingle.class); BigDecimal exchangeRate = new BigDecimal(root.query.results.rate.Rate); exchangeRatesCache.put(root.query.results.rate.id, exchangeRate); exchangeRates.put(root.query.results.rate.id, exchangeRate); } } return exchangeRates; }
From source file:org.apache.calcite.adapter.elasticsearch.ElasticSearchAdapterTest.java
/** * Used to create {@code zips} index and insert zip data in bulk. * @throws Exception when instance setup failed */// www .j av a 2 s . c o m @BeforeClass public static void setupInstance() throws Exception { // hardcoded mapping definition final String mapping = String.format(Locale.ROOT, "{'mappings':{'%s':{'properties':" + "{'city':{'type':'keyword'},'state':{'type':'keyword'},'pop':{'type':'long'}}" + "}}}", ZIPS).replace('\'', '"'); // create index and mapping final HttpEntity entity = new StringEntity(mapping, ContentType.APPLICATION_JSON); NODE.restClient().performRequest("PUT", "/" + ZIPS, Collections.emptyMap(), entity); // load records from file final List<String> bulk = new ArrayList<>(); Resources.readLines(ElasticSearchAdapterTest.class.getResource("/zips-mini.json"), StandardCharsets.UTF_8, new LineProcessor<Void>() { @Override public boolean processLine(String line) throws IOException { bulk.add("{\"index\": {} }"); // index/type will be derived from _bulk URI line = line.replaceAll("_id", "id"); // _id is a reserved attribute in ES bulk.add(line); return true; } @Override public Void getResult() { return null; } }); if (bulk.isEmpty()) { throw new IllegalStateException("No records to index. Empty file ?"); } final String uri = String.format(Locale.ROOT, "/%s/%s/_bulk?refresh", ZIPS, ZIPS); Response response = NODE.restClient().performRequest("POST", uri, Collections.emptyMap(), new StringEntity(String.join("\n", bulk) + "\n", ContentType.APPLICATION_JSON)); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { final String error = EntityUtils.toString(response.getEntity()); final String message = String.format(Locale.ROOT, "Couldn't bulk insert %d elements into %s (%s/%s). Error was %s\n%s\n", bulk.size(), ZIPS, response.getHost(), response.getRequestLine(), response.getStatusLine(), error); throw new IllegalStateException(message); } }
From source file:com.sisrni.managedbean.ProyectoReportMB.java
public String obtenerOrganismos(List<Organismo> listOrganismos) { List<String> nombreOrganismo = new ArrayList<String>(); for (Organismo organismo : listOrganismos) { nombreOrganismo.add(organismo.getNombreOrganismo()); }//from w ww. j a v a2 s . c o m return String.join(",", nombreOrganismo); }
From source file:org.twilmes.sql.gremlin.plugin.SqlRemoteAcceptor.java
@Override public Object submit(final List<String> args) throws RemoteException { try {//ww w.j av a 2 s. c o m final String query = RemoteAcceptor.getScript(String.join(" ", args), this.shell); // if the query starts with 'explain', return the plan instead of the results if (query.toLowerCase().startsWith("explain")) { int explainIndex = query.toLowerCase().indexOf("explain"); return compiler.explain(query.substring(explainIndex + 7, query.length())); } return compiler.execute(query); } catch (final Exception e) { throw new RemoteException(e); } }
From source file:it.iit.genomics.cru.simsearch.bundle.utils.PantherBridge.java
public static Collection<String[]> getEnrichment(String organism, String fileName, double threshold) { ArrayList<String[]> results = new ArrayList<>(); ArrayListMultimap<String, String> genes = ArrayListMultimap.create(); ArrayListMultimap<Double, String> pvalues = ArrayListMultimap.create(); HashSet<String> uniqueGenes = new HashSet<>(); try {/*from w w w . j a va 2 s. co m*/ String[] enrichmentTypes = { "process", "pathway" }; for (String enrichmentType : enrichmentTypes) { HttpClient client = new HttpClient(); MultipartPostMethod method = new MultipartPostMethod( "http://pantherdb.org/webservices/garuda/tools/enrichment/VER_2/enrichment.jsp?"); // Define name-value pairs to set into the QueryString method.addParameter("organism", organism); method.addParameter("type", "enrichment"); method.addParameter("enrichmentType", enrichmentType); // "function", // "process", // "cellular_location", // "protein_class", // "pathway" File inputFile = new File(fileName); method.addPart(new FilePart("geneList", inputFile, "text/plain", "ISO-8859-1")); // PANTHER does not use the ID type // method.addParameter("IdType", "UniProt"); // Execute and print response client.executeMethod(method); String response = method.getResponseBodyAsString(); for (String line : response.split("\n")) { if (false == "".equals(line.trim())) { String[] row = line.split("\t"); // Id Name GeneId P-value if ("Id".equals(row[0])) { // header continue; } // if (row.length > 1) { String name = row[1]; String gene = row[2]; Double pvalue = Double.valueOf(row[3]); uniqueGenes.add(gene); if (pvalue < threshold) { if (false == genes.containsKey(name)) { pvalues.put(pvalue, name); } genes.put(name, gene); } // } else { // System.out.println("oups: " + row[0]); // } } } method.releaseConnection(); } ArrayList<Double> pvalueList = new ArrayList<>(); Collections.sort(pvalueList); pvalueList.addAll(pvalues.keySet()); Collections.sort(pvalueList); int numGenes = uniqueGenes.size(); for (Double pvalue : pvalueList) { for (String name : pvalues.get(pvalue)) { String geneList = String.join(",", genes.get(name)); String result[] = { name, "" + pvalue, genes.get(name).size() + "/" + numGenes, geneList }; results.add(result); } } } catch (IOException e) { e.printStackTrace(); } return results; }
From source file:net.sf.jabref.model.entry.CustomEntryType.java
/** * Get a String describing the required field set for this entry type. * * @return Description of required field set for storage in preferences or bib file. *//* www . ja va 2 s . c o m*/ public String getRequiredFieldsString() { return String.join(";", required); }
From source file:it.uniud.ailab.dcore.annotation.annotators.RawTdidfAnnotator.java
@Override public void annotate(Blackboard blackboard, DocumentComponent component) { initIndex(component.getLanguage());/* www .ja va 2 s . c o m*/ List<Sentence> sentences = DocumentUtils.getSentences(component); for (Sentence s : sentences) { for (Gram g : s.getGrams()) { if (!g.hasAnnotation(TFIDF)) { String stemmedSurface = g.getSurface(); String[] tokenizedSurface = OpenNlpBootstrapperAnnotator.tokenizeText(stemmedSurface, component.getLanguage().getLanguage()); SnowballStemmer stemmer = SnowballStemmerSelector .getStemmerForLanguage(component.getLanguage()); for (int i = 0; i < tokenizedSurface.length; i++) { stemmer.setCurrent(tokenizedSurface[i]); if (stemmer.stem()) { tokenizedSurface[i] = stemmer.getCurrent(); } } stemmedSurface = String.join(" ", markTokens(tokenizedSurface)).trim(); ((Keyphrase) g).putFeature(TFIDF, tfIdf(IOBlackboard.getCurrentDocument(), stemmedSurface)); } } } }
From source file:com.streamsets.pipeline.lib.salesforce.ChangeDataCaptureRecordCreator.java
@Override @SuppressWarnings("unchecked") public Record createRecord(String sourceId, Object source) throws StageException { Pair<PartnerConnection, Map<String, Object>> pair = (Pair<PartnerConnection, Map<String, Object>>) source; PartnerConnection partnerConnection = pair.getLeft(); Map<String, Object> data = pair.getRight(); Map<String, Object> payload = (Map<String, Object>) data.get("payload"); Record rec = context.createRecord(sourceId); // Process ChangeEventHeader since we need the object type String objectType = null;// ww w. ja va2 s .c om Record.Header recordHeader = rec.getHeader(); Map<String, Object> headers = (Map<String, Object>) payload.get(CHANGE_EVENT_HEADER); if (headers == null) { throw new StageException(Errors.FORCE_40); } // event data becomes header attributes // of the form salesforce.cdc.createdDate, // salesforce.cdc.type for (Map.Entry<String, Object> header : headers.entrySet()) { if ("recordIds".equals(header.getKey())) { // Turn list of record IDs into a comma-separated list recordHeader.setAttribute(HEADER_ATTRIBUTE_PREFIX + header.getKey(), String.join(",", (List<String>) header.getValue())); } else { recordHeader.setAttribute(HEADER_ATTRIBUTE_PREFIX + header.getKey(), header.getValue().toString()); if ("changeType".equals(header.getKey())) { int operationCode = SFDC_TO_SDC_OPERATION.get(header.getValue().toString()); recordHeader.setAttribute(OperationType.SDC_OPERATION_TYPE, String.valueOf(operationCode)); } else if ("entityName".equals(header.getKey())) { objectType = header.getValue().toString(); recordHeader.setAttribute(SOBJECT_TYPE_ATTRIBUTE, objectType); } } } payload.remove(CHANGE_EVENT_HEADER); // payload data becomes fields LinkedHashMap<String, Field> map = new LinkedHashMap<>(); for (Map.Entry<String, Object> entry : payload.entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); if (!objectTypeIsCached(objectType)) { try { addObjectTypeToCache(partnerConnection, objectType); } catch (ConnectionException e) { throw new StageException(Errors.FORCE_21, objectType, e); } } com.sforce.soap.partner.Field sfdcField = getFieldMetadata(objectType, key); Field field = createField(val, sfdcField); if (conf.createSalesforceNsHeaders) { setHeadersOnField(field, getFieldMetadata(objectType, key)); } map.put(key, field); } rec.set(Field.createListMap(map)); return rec; }
From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.local.debian.LocalDebianServiceProvider.java
@Override public String getInstallCommand(GenerateService.ResolvedConfiguration resolvedConfiguration, Map<String, String> installCommands) { Map<String, String> bindings = new HashMap<>(); List<String> serviceNames = new ArrayList<>(installCommands.keySet()); List<String> upstartNames = getLocalServices(serviceNames).stream() .filter(i -> resolvedConfiguration.getServiceSettings(i.getService()).getEnabled()) .map(i -> ((LocalDebianService) i).getUpstartServiceName()).filter(Objects::nonNull) .collect(Collectors.toList()); List<String> serviceInstalls = serviceNames.stream().map(installCommands::get).collect(Collectors.toList()); TemplatedResource resource = new JarResource("/debian/init.sh"); bindings.put("services", Strings.join(upstartNames, " ")); String upstartInit = resource.setBindings(bindings).toString(); resource = new JarResource("/debian/install.sh"); bindings = new HashMap<>(); bindings.put("prepare-environment", "true"); bindings.put("install-redis", "true"); bindings.put("debian-repository", artifactSources.getDebianRepository()); bindings.put("install-commands", String.join("\n", serviceInstalls)); bindings.put("service-action", "restart"); bindings.put("upstart-init", upstartInit); return resource.setBindings(bindings).toString(); }