List of usage examples for org.apache.commons.lang3 StringUtils split
public static String[] split(final String str, final String separatorChars)
Splits the provided text into an array, separators specified.
From source file:com.inkubator.hrm.service.impl.NotificationApproverSmsMessagesListener.java
@Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, timeout = 50, rollbackFor = Exception.class) public void onMessage(Message message) { String approverNumber = StringUtils.EMPTY; String notifMessage = StringUtils.EMPTY; try {//from w ww . j a v a 2 s .c o m TextMessage textMessage = (TextMessage) message; String json = textMessage.getText(); approverNumber = jsonConverter.getValueByKey(json, "senderNumber"); HrmUser approver = hrmUserDao.getEntityByPhoneNumber("+" + approverNumber); String content = jsonConverter.getValueByKey(json, "smsContent"); String[] arrContent = StringUtils.split(content, "#"); notifMessage = StringUtils.EMPTY; ApprovalActivity approvalActivity = StringUtils.isNumeric(arrContent[0]) ? approvalActivityDao.getEntiyByPK(Long.parseLong(arrContent[0])) : null; /** validation */ if (approver == null) { notifMessage = "Maaf, No Telepon tidak terdaftar "; } else if (arrContent.length != 3) { notifMessage = "Maaf, format tidak sesuai dengan standard : ApprovalActivityID#YES/NO/REVISI#COMMENT "; } else if (!(StringUtils.equalsIgnoreCase(arrContent[1], "YES") || StringUtils.equalsIgnoreCase(arrContent[1], "NO") || StringUtils.equalsIgnoreCase(arrContent[1], "REVISI"))) { notifMessage = "Maaf, format tidak sesuai dengan standard : ApprovalActivityID#YES/NO/REVISI#COMMENT "; } else if (!StringUtils.isNumeric(arrContent[0])) { notifMessage = "Maaf, Approval Activity ID tidak terdaftar"; } else if (approvalActivity == null) { notifMessage = "Maaf, approval activity ID tidak terdaftar"; } else if (!StringUtils.equals(approvalActivity.getApprovedBy(), approver.getUserId())) { notifMessage = "Maaf, No Telpon ini tidak berhak untuk melakukan approval"; } else if (approvalActivity.getApprovalStatus() != HRMConstant.APPROVAL_STATUS_WAITING_APPROVAL) { notifMessage = "Maaf, permintaan tidak dapat di proses karena status Approval sudah berubah"; } /** proses approval, jika memenuhi validasi */ if (StringUtils.isEmpty(notifMessage)) { if (StringUtils.equalsIgnoreCase(arrContent[1], "YES")) { /** do Approved */ switch (approvalActivity.getApprovalDefinition().getName()) { case HRMConstant.BUSINESS_TRAVEL: businessTravelService.approved(approvalActivity.getId(), null, arrContent[2]); break; case HRMConstant.LOAN: loanNewApplicationService.approved(approvalActivity.getId(), null, arrContent[2]); break; case HRMConstant.REIMBURSEMENT: rmbsApplicationService.approved(approvalActivity.getId(), null, arrContent[2]); break; case HRMConstant.REIMBURSEMENT_DISBURSEMENT: rmbsDisbursementService.approved(approvalActivity.getId(), null, arrContent[2]); break; case HRMConstant.SHIFT_SCHEDULE: tempJadwalKaryawanService.approved(approvalActivity.getId(), null, arrContent[2]); break; case HRMConstant.LEAVE: leaveImplementationService.approved(approvalActivity.getId(), null, arrContent[2]); break; case HRMConstant.LEAVE_CANCELLATION: leaveImplementationService.approved(approvalActivity.getId(), null, arrContent[2]); break; case HRMConstant.ANNOUNCEMENT: announcementService.approved(approvalActivity.getId(), null, arrContent[2]); break; case HRMConstant.EMP_CORRECTION_ATTENDANCE: wtEmpCorrectionAttendanceService.approved(approvalActivity.getId(), null, arrContent[2]); break; case HRMConstant.VACANCY_ADVERTISEMENT: recruitVacancyAdvertisementService.approved(approvalActivity.getId(), null, arrContent[2]); break; case HRMConstant.EMPLOYEE_CAREER_TRANSITION: empCareerHistoryService.approved(approvalActivity.getId(), null, arrContent[2]); break; default: break; } notifMessage = "Terima kasih, permintaan untuk disetujui telah di proses"; } else if (StringUtils.equalsIgnoreCase(arrContent[1], "NO")) { /** do Rejected */ switch (approvalActivity.getApprovalDefinition().getName()) { case HRMConstant.BUSINESS_TRAVEL: businessTravelService.rejected(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.LOAN: loanNewApplicationService.rejected(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.REIMBURSEMENT: rmbsApplicationService.rejected(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.REIMBURSEMENT_DISBURSEMENT: rmbsDisbursementService.rejected(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.SHIFT_SCHEDULE: tempJadwalKaryawanService.rejected(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.LEAVE: leaveImplementationService.rejected(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.LEAVE_CANCELLATION: leaveImplementationService.rejected(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.ANNOUNCEMENT: announcementService.rejected(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.EMP_CORRECTION_ATTENDANCE: wtEmpCorrectionAttendanceService.rejected(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.VACANCY_ADVERTISEMENT: recruitVacancyAdvertisementService.rejected(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.EMPLOYEE_CAREER_TRANSITION: empCareerHistoryService.rejected(approvalActivity.getId(), arrContent[2]); break; default: break; } notifMessage = "Terima kasih, permintaan untuk ditolak telah di proses"; } else if (StringUtils.equalsIgnoreCase(arrContent[1], "REVISI")) { /** do Asking Revised */ switch (approvalActivity.getApprovalDefinition().getName()) { case HRMConstant.LOAN: loanNewApplicationService.askingRevised(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.REIMBURSEMENT: rmbsApplicationService.askingRevised(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.REIMBURSEMENT_DISBURSEMENT: rmbsDisbursementService.askingRevised(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.ANNOUNCEMENT: announcementService.askingRevised(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.EMP_CORRECTION_ATTENDANCE: wtEmpCorrectionAttendanceService.askingRevised(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.VACANCY_ADVERTISEMENT: recruitVacancyAdvertisementService.askingRevised(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.EMPLOYEE_CAREER_TRANSITION: empCareerHistoryService.askingRevised(approvalActivity.getId(), arrContent[2]); break; default: /** Tidak semua module implement asking revised, jika belum/tidak implement maka kirim sms balik ke sender untuk notifikasi */ notifMessage = "Maaf, permintaan untuk \"REVISI\" tidak dapat diproses. Hanya bisa melakukan proses \"YES\" atau \"NO\""; break; } if (StringUtils.isEmpty(notifMessage)) { notifMessage = "Terima kasih, permintaan untuk direvisi telah di proses"; } } } } catch (Exception ex) { notifMessage = "Maaf, permintaan tidak dapat di proses, ada kegagalan di sistem. Mohon ulangi proses via aplikasi web atau hubungi Administrator"; LOGGER.error("Error", ex); } /** kirim sms balik ke sender untuk notifikasi messagenya */ final SMSSend mSSend = new SMSSend(); LOGGER.error("Info SMS " + notifMessage); mSSend.setFrom(HRMConstant.SYSTEM_ADMIN); mSSend.setDestination("+" + approverNumber); mSSend.setContent(notifMessage); //Send notificatin SMS this.jmsTemplateSMS.send(new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { return session.createTextMessage(jsonConverter.getJson(mSSend)); } }); }
From source file:com.precioustech.fxtrading.tradingbot.social.twitter.tweethandler.ThirdBrainFx2TweetHandler.java
@Override protected CloseFXTradeTweet<String> parseCloseTrade(String[] tokens) { String ccyPair = this.deriveCcyPair(tokens); String strPrice = tokens[9];/* w w w .j av a 2s . c o m*/ String profitStr = tokens[11]; if (profitStr.contains(TradingConstants.COLON)) { String[] tokens2 = StringUtils.split((String) profitStr, TradingConstants.COLON); return new CloseFXTradeTweet<>(new TradeableInstrument<>(ccyPair), Double.parseDouble(tokens2[1]), Double.parseDouble(strPrice)); } return null; }
From source file:com.wini.octal.pipe.HttpServerHandler.java
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { // Transfer-Encoding: chunked == N if (!readingChunks) { HttpRequest request = (HttpRequest) e.getMessage(); // Http?? ? ? ? ?? request body ? // Expect: 100-continue // cli Header serv? allow? ? request body ? if (is100ContinueExpected(request)) { send100Continue(e);/*from w ww . ja v a 2 s . c om*/ } if (request.isChunked()) { readingChunks = true; } else { String method = request.getMethod().getName(); String uri = request.getUri(); String[] uriTokens; int lenTokens; // only NGAVL if (uri.startsWith("NGAVL", 1)) { if (method.equalsIgnoreCase("POST")) { // requst uri : /NGAVL/ws/SQL.CONFIG.NGAVL_VL00001.service uriTokens = StringUtils.split(uri, "[/.]"); lenTokens = uriTokens.length; /*String svcExt = uriTokens[lenTokens - 1];*/ String svcNm = uriTokens[lenTokens - 2]; // proxy service if (svcNm.equalsIgnoreCase("service")) { ChannelBuffer buffer = (ChannelBuffer) request.getContent(); String param = buffer.toString(CharsetUtil.UTF_8); param = param.substring(param.indexOf("=") + 1); @SuppressWarnings("unchecked") HashMap<String, String> map = gson.fromJson(param, java.util.HashMap.class); svcNm = map.get("ServiceNm"); svcNm = svcNm.substring(svcNm.lastIndexOf(".") + 1); buffer.clear(); buffer.writeBytes(param.getBytes()); request.setContent(buffer); } try { Runnable task = CONFIG_INSTNACE.getService(svcNm, e, request); CONFIG_INSTNACE.getThreadPool().execute(task); } catch (BeansException excp) { throw new HttpFileNotFound(e); } } else if (method.equalsIgnoreCase("GET")) { // request uri : /NGAVL/[AAA]/[BBB.CCC] URL url = getClass().getResource(uri); if (url == null) throw new HttpFileNotFound(e); File file = new File(url.getPath()); if (file.exists()) { Runnable task = CONFIG_INSTNACE.getService(NGAVL_StaticSVC.class.getName(), e, request, file); CONFIG_INSTNACE.getThreadPool().execute(task); } else { throw new HttpFileNotFound(e); } } // else request Not Found else { throw new HttpFileNotFound(e); } } } } // Transfer-Encoding: chunked == Y else { HttpChunk chunk = (HttpChunk) e.getMessage(); if (chunk.isLast()) { readingChunks = false; buf.append("END OF CONTENT\r\n"); HttpChunkTrailer trailer = (HttpChunkTrailer) chunk; if (!trailer.getHeaderNames().isEmpty()) { buf.append("\r\n"); for (String name : trailer.getHeaderNames()) { for (String value : trailer.getHeaders(name)) { buf.append("TRAILING HEADER: " + name + " = " + value + "\r\n"); } } buf.append("\r\n"); } //writeResponse(e); } else { buf.append("CHUNK: " + chunk.getContent().toString(CharsetUtil.UTF_8) + "\r\n"); } } }
From source file:eqtlmappingpipeline.util.ModuleEqtlGeuvadisReplication.java
/** * @param args the command line arguments *//*from w w w .j a va2s . c o m*/ public static void main(String[] args) throws IOException, LdCalculatorException { System.out.println(HEADER); System.out.println(); System.out.flush(); //flush to make sure header is before errors try { Thread.sleep(25); //Allows flush to complete } catch (InterruptedException ex) { } CommandLineParser parser = new PosixParser(); final CommandLine commandLine; try { commandLine = parser.parse(OPTIONS, args, true); } catch (ParseException ex) { System.err.println("Invalid command line arguments: " + ex.getMessage()); System.err.println(); new HelpFormatter().printHelp(" ", OPTIONS); System.exit(1); return; } final String[] genotypesBasePaths = commandLine.getOptionValues("g"); final RandomAccessGenotypeDataReaderFormats genotypeDataType; final String replicationQtlFilePath = commandLine.getOptionValue("e"); final String interactionQtlFilePath = commandLine.getOptionValue("i"); final String outputFilePath = commandLine.getOptionValue("o"); final double ldCutoff = Double.parseDouble(commandLine.getOptionValue("ld")); final int window = Integer.parseInt(commandLine.getOptionValue("w")); System.out.println("Genotype: " + Arrays.toString(genotypesBasePaths)); System.out.println("Interaction file: " + interactionQtlFilePath); System.out.println("Replication file: " + replicationQtlFilePath); System.out.println("Output: " + outputFilePath); System.out.println("LD: " + ldCutoff); System.out.println("Window: " + window); try { if (commandLine.hasOption("G")) { genotypeDataType = RandomAccessGenotypeDataReaderFormats .valueOf(commandLine.getOptionValue("G").toUpperCase()); } else { if (genotypesBasePaths[0].endsWith(".vcf")) { System.err.println( "Only vcf.gz is supported. Please see manual on how to do create a vcf.gz file."); System.exit(1); return; } try { genotypeDataType = RandomAccessGenotypeDataReaderFormats .matchFormatToPath(genotypesBasePaths[0]); } catch (GenotypeDataException e) { System.err .println("Unable to determine input 1 type based on specified path. Please specify -G"); System.exit(1); return; } } } catch (IllegalArgumentException e) { System.err.println("Error parsing --genotypesFormat \"" + commandLine.getOptionValue("G") + "\" is not a valid input data format"); System.exit(1); return; } final RandomAccessGenotypeData genotypeData; try { genotypeData = genotypeDataType.createFilteredGenotypeData(genotypesBasePaths, 100, null, null, null, 0.8); } catch (TabixFileNotFoundException e) { LOGGER.fatal("Tabix file not found for input data at: " + e.getPath() + "\n" + "Please see README on how to create a tabix file"); System.exit(1); return; } catch (IOException e) { LOGGER.fatal("Error reading input data: " + e.getMessage(), e); System.exit(1); return; } catch (IncompatibleMultiPartGenotypeDataException e) { LOGGER.fatal("Error combining the impute genotype data files: " + e.getMessage(), e); System.exit(1); return; } catch (GenotypeDataException e) { LOGGER.fatal("Error reading input data: " + e.getMessage(), e); System.exit(1); return; } ChrPosTreeMap<ArrayList<EQTL>> replicationQtls = new QTLTextFile(replicationQtlFilePath, false) .readQtlsAsTreeMap(); int interactionSnpNotInGenotypeData = 0; int noReplicationQtlsInWindow = 0; int noReplicationQtlsInLd = 0; int multipleReplicationQtlsInLd = 0; int replicationTopSnpNotInGenotypeData = 0; final CSVWriter outputWriter = new CSVWriter(new FileWriter(new File(outputFilePath)), '\t', '\0'); final String[] outputLine = new String[14]; int c = 0; outputLine[c++] = "Chr"; outputLine[c++] = "Pos"; outputLine[c++] = "SNP"; outputLine[c++] = "Gene"; outputLine[c++] = "Module"; outputLine[c++] = "DiscoveryZ"; outputLine[c++] = "ReplicationZ"; outputLine[c++] = "DiscoveryZCorrected"; outputLine[c++] = "ReplicationZCorrected"; outputLine[c++] = "DiscoveryAlleleAssessed"; outputLine[c++] = "ReplicationAlleleAssessed"; outputLine[c++] = "bestLd"; outputLine[c++] = "bestLd_dist"; outputLine[c++] = "nextLd"; outputWriter.writeNext(outputLine); HashSet<String> notFound = new HashSet<>(); CSVReader interactionQtlReader = new CSVReader(new FileReader(interactionQtlFilePath), '\t'); interactionQtlReader.readNext();//skip header String[] interactionQtlLine; while ((interactionQtlLine = interactionQtlReader.readNext()) != null) { String snp = interactionQtlLine[1]; String chr = interactionQtlLine[2]; int pos = Integer.parseInt(interactionQtlLine[3]); String gene = interactionQtlLine[4]; String alleleAssessed = interactionQtlLine[9]; String module = interactionQtlLine[12]; double discoveryZ = Double.parseDouble(interactionQtlLine[10]); GeneticVariant interactionQtlVariant = genotypeData.getSnpVariantByPos(chr, pos); if (interactionQtlVariant == null) { System.err.println("Interaction QTL SNP not found in genotype data: " + chr + ":" + pos); ++interactionSnpNotInGenotypeData; continue; } EQTL bestMatch = null; double bestMatchR2 = Double.NaN; Ld bestMatchLd = null; double nextBestR2 = Double.NaN; ArrayList<EQTL> sameSnpQtls = replicationQtls.get(chr, pos); if (sameSnpQtls != null) { for (EQTL sameSnpQtl : sameSnpQtls) { if (sameSnpQtl.getProbe().equals(gene)) { bestMatch = sameSnpQtl; bestMatchR2 = 1; } } } NavigableMap<Integer, ArrayList<EQTL>> potentionalReplicationQtls = replicationQtls.getChrRange(chr, pos - window, true, pos + window, true); for (ArrayList<EQTL> potentialReplicationQtls : potentionalReplicationQtls.values()) { for (EQTL potentialReplicationQtl : potentialReplicationQtls) { if (!potentialReplicationQtl.getProbe().equals(gene)) { continue; } GeneticVariant potentialReplicationQtlVariant = genotypeData.getSnpVariantByPos( potentialReplicationQtl.getRsChr().toString(), potentialReplicationQtl.getRsChrPos()); if (potentialReplicationQtlVariant == null) { notFound.add(potentialReplicationQtl.getRsChr().toString() + ":" + potentialReplicationQtl.getRsChrPos()); ++replicationTopSnpNotInGenotypeData; continue; } Ld ld = interactionQtlVariant.calculateLd(potentialReplicationQtlVariant); double r2 = ld.getR2(); if (r2 > 1) { r2 = 1; } if (bestMatch == null) { bestMatch = potentialReplicationQtl; bestMatchR2 = r2; bestMatchLd = ld; } else if (r2 > bestMatchR2) { bestMatch = potentialReplicationQtl; nextBestR2 = bestMatchR2; bestMatchR2 = r2; bestMatchLd = ld; } } } double replicationZ = Double.NaN; double replicationZCorrected = Double.NaN; double discoveryZCorrected = Double.NaN; String replicationAlleleAssessed = null; if (bestMatch != null) { replicationZ = bestMatch.getZscore(); replicationAlleleAssessed = bestMatch.getAlleleAssessed(); if (pos != bestMatch.getRsChrPos()) { String commonHap = null; double commonHapFreq = -1; for (Map.Entry<String, Double> hapFreq : bestMatchLd.getHaplotypesFreq().entrySet()) { double f = hapFreq.getValue(); if (f > commonHapFreq) { commonHapFreq = f; commonHap = hapFreq.getKey(); } } String[] commonHapAlleles = StringUtils.split(commonHap, '/'); discoveryZCorrected = commonHapAlleles[0].equals(alleleAssessed) ? discoveryZ : discoveryZ * -1; replicationZCorrected = commonHapAlleles[1].equals(replicationAlleleAssessed) ? replicationZ : replicationZ * -1; } else { discoveryZCorrected = discoveryZ; replicationZCorrected = alleleAssessed.equals(replicationAlleleAssessed) ? replicationZ : replicationZ * -1; } } c = 0; outputLine[c++] = chr; outputLine[c++] = String.valueOf(pos); outputLine[c++] = snp; outputLine[c++] = gene; outputLine[c++] = module; outputLine[c++] = String.valueOf(discoveryZ); outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(replicationZ); outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(discoveryZCorrected); outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(replicationZCorrected); outputLine[c++] = alleleAssessed; outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(bestMatch.getAlleleAssessed()); outputLine[c++] = String.valueOf(bestMatchR2); outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(Math.abs(pos - bestMatch.getRsChrPos())); outputLine[c++] = String.valueOf(nextBestR2); outputWriter.writeNext(outputLine); } outputWriter.close(); for (String e : notFound) { System.err.println("Not found: " + e); } System.out.println("interactionSnpNotInGenotypeData: " + interactionSnpNotInGenotypeData); System.out.println("noReplicationQtlsInWindow: " + noReplicationQtlsInWindow); System.out.println("noReplicationQtlsInLd: " + noReplicationQtlsInLd); System.out.println("multipleReplicationQtlsInLd: " + multipleReplicationQtlsInLd); System.out.println("replicationTopSnpNotInGenotypeData: " + replicationTopSnpNotInGenotypeData); }
From source file:com.google.mr4c.config.category.CategoryBuilder.java
/** * Comma delimited files in order of precedence *///from w ww. j a v a 2 s . c om public void addPropertiesFromFileList(String source, String propFiles) throws IOException { if (StringUtils.isEmpty(propFiles)) { return; } s_log.info("Trying to load {} config properties from files specified by {}: [{}]", m_category.getCategoryName(), source, propFiles); List<URI> uris = new ArrayList<URI>(); for (String file : StringUtils.split(propFiles, ",")) { file = file.trim(); uris.add(URI.create(file)); } addProperties(uris); }
From source file:com.thinkbiganalytics.nifi.v2.thrift.ExecuteHQLStatement.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws RuntimeException { FlowFile flowFile = session.get();//from w ww . ja v a 2 s. c o m if (flowFile == null) { return; } final String ddlQuery = context.getProperty(SQL_DDL_STATEMENT).evaluateAttributeExpressions(flowFile) .getValue(); String[] hiveStatements = StringUtils.split(ddlQuery, ';'); final ThriftService thriftService = context.getProperty(THRIFT_SERVICE) .asControllerService(ThriftService.class); executeStatements(session, flowFile, hiveStatements, thriftService); }
From source file:com.thinkbiganalytics.validation.TestValidationTransformation.java
@Test public void testLookupValidator() { String lookupList = "one,two,three"; LookupValidator validator = new LookupValidator(lookupList); FieldValidationRule uiModel = ValidatorAnnotationTransformer.instance().toUIModel(validator); LookupValidator convertedValidator = fromUI(uiModel, LookupValidator.class); Assert.assertEquals(lookupList, convertedValidator.getLookupList()); for (String value : StringUtils.split(lookupList, ",")) { Assert.assertTrue(value, convertedValidator.getLookupValues().contains(value)); }/*from w ww. j a va2s .com*/ }
From source file:com.opentable.config.ConfigFactory.java
private CombinedConfiguration loadNessStrategy() { // Allow foo/bar/baz and foo:bar:baz final String[] configNames = StringUtils.stripAll(StringUtils.split(configName, "/:")); final CombinedConfiguration cc = new CombinedConfiguration(new OverrideCombiner()); // All properties can be overridden by the System properties. cc.addConfiguration(new SystemConfiguration(), "systemProperties"); LOG.info("Configuration source: SYSTEM"); boolean loadedConfig = false; for (int i = 0; i < configNames.length; i++) { final String configFileName = configNames[configNames.length - i - 1]; final String configFilePath = StringUtils.join(configNames, "/", 0, configNames.length - i); try {/*from w w w . j a v a 2 s .c om*/ final AbstractConfiguration subConfig = configStrategy.load(configFileName, configFilePath); if (subConfig == null) { throw new IllegalStateException( String.format("Configuration '%s' does not exist!", configFileName)); } else { cc.addConfiguration(subConfig, configFileName); LOG.info("Configuration source: {}", configFileName); loadedConfig = true; } } catch (ConfigurationException ce) { LOG.error(String.format("While loading configuration '%s'", configFileName), ce); } } if (!loadedConfig && configNames.length > 0) { throw new IllegalStateException(String.format( "Config name '%s' was given but no config file could be found, this looks fishy!", configName)); } return cc; }
From source file:com.sinnerschrader.s2b.accounttool.logic.component.licences.LicenseSummary.java
private List<Dependency> loadFromJSON(Resource licenseFile) throws Exception { List<Dependency> deps = new LinkedList<>(); ObjectMapper om = new ObjectMapper(); JsonNode licenseRoot = om.readTree(licenseFile.getInputStream()); Iterator<String> entryNames = licenseRoot.fieldNames(); while (entryNames.hasNext()) { String entryName = entryNames.next(); JsonNode licenceNode = licenseRoot.get(entryName); String[] npmNameFragments = StringUtils.split(entryName, '@'); final String groupId = "npm"; final String artifactId = npmNameFragments[0]; final String version = npmNameFragments[1]; final String lName = getFieldValue(licenceNode, "licenses"); final String lUrl = getFieldValue(licenceNode, "repository"); final String lDistro = "repo"; String comments = ""; deps.add(new Dependency(groupId, artifactId, version, new License(lName, lUrl, lDistro, comments))); }//w w w. ja v a2 s .c o m Collections.sort(deps); return deps; }
From source file:com.github.jknack.amd4j.DependencyCollector.java
/** * Collect all the dependencies for the given module. * * @param config A configuration options. * @param module An AMD module./* ww w.j av a2 s.co m*/ * @return A dependency set. */ public static Set<String> collect(final Config config, final Module module) { // empty module? if (module.content.length() == 0) { return Collections.emptySet(); } // just parse *.js files if (!"js".equals(getExtension(module.uri.getPath()))) { return Collections.emptySet(); } return new NodeVisitor() { private Set<String> dependencies = new LinkedHashSet<String>(); /** * Collect all the dependencies. * * @return A dependency set. */ public Set<String> collect() { Parser parser = new Parser(); AstRoot node = parser.parse(module.content.toString(), module.name, 1); node.visit(this); // check shim configuration Shim shim = config.getShim(module.name); if (shim != null) { // add dependencies if (shim.dependencies() != null) { dependencies.addAll(shim.dependencies()); } } return dependencies; } @Override public boolean visit(final AstNode node) { int type = node.getType(); switch (type) { case Token.CALL: return visit((FunctionCall) node); default: return true; } } /** * Find out "define" and "require" function calls. * * @param node The function call node. * @return True, to keep walking. */ public boolean visit(final FunctionCall node) { AstNode target = node.getTarget(); if (target instanceof Name) { String name = ((Name) target).getIdentifier(); if ("define".equals(name)) { visitDependencies(node); } else if ("require".equals(name)) { int depth = node.getParent().depth() - 1; if (config.isFindNestedDependencies() || depth == 0) { visitDependencies(node); } } } return true; } /** * Report module's dependencies. * * @param node The function's call. */ private void visitDependencies(final FunctionCall node) { List<AstNode> arguments = node.getArguments(); for (AstNode arg : arguments) { if (arg instanceof ArrayLiteral) { // found! ArrayLiteral array = (ArrayLiteral) arg; List<AstNode> dependencyList = array.getElements(); for (AstNode dependencyNode : dependencyList) { String dependency = ((StringLiteral) dependencyNode).getValue(); String[] dependencies = StringUtils.split(dependency, "!"); if (dependencies.length > 1) { this.dependencies.add(dependencies[0]); } this.dependencies.add(dependency); } break; } } } }.collect(); }