List of usage examples for org.apache.commons.lang3 StringUtils substringBefore
public static String substringBefore(final String str, final String separator)
Gets the substring before the first occurrence of a separator.
From source file:com.evolveum.midpoint.web.page.admin.configuration.PageRepositoryQuery.java
private void initLayout() { Form mainForm = new com.evolveum.midpoint.web.component.form.Form(ID_MAIN_FORM); add(mainForm);// w ww. j a v a 2s. c o m List<QName> objectTypeList = WebComponentUtil.createObjectTypeList(); Collections.sort(objectTypeList, new Comparator<QName>() { @Override public int compare(QName o1, QName o2) { return String.CASE_INSENSITIVE_ORDER.compare(o1.getLocalPart(), o2.getLocalPart()); } }); DropDownChoice<QName> objectTypeChoice = new DropDownChoice<>(ID_OBJECT_TYPE, new PropertyModel<>(model, RepoQueryDto.F_OBJECT_TYPE), new ListModel<>(objectTypeList), new QNameChoiceRenderer()); objectTypeChoice.setOutputMarkupId(true); objectTypeChoice.setNullValid(true); objectTypeChoice.add(new OnChangeAjaxBehavior() { @Override protected void onUpdate(AjaxRequestTarget target) { target.add(get(ID_MAIN_FORM).get(ID_MIDPOINT_QUERY_BUTTON_BAR)); } }); mainForm.add(objectTypeChoice); AceEditor editorMidPoint = new AceEditor(ID_EDITOR_MIDPOINT, new PropertyModel<>(model, RepoQueryDto.F_MIDPOINT_QUERY)); editorMidPoint.setHeight(400); editorMidPoint.setResizeToMaxHeight(false); mainForm.add(editorMidPoint); AceEditor editorHibernate = new AceEditor(ID_EDITOR_HIBERNATE, new PropertyModel<>(model, RepoQueryDto.F_HIBERNATE_QUERY)); editorHibernate.setHeight(300); editorHibernate.setResizeToMaxHeight(false); editorHibernate.setReadonly(!isAdmin); editorHibernate.setMode(null); mainForm.add(editorHibernate); AceEditor hibernateParameters = new AceEditor(ID_HIBERNATE_PARAMETERS, new PropertyModel<>(model, RepoQueryDto.F_HIBERNATE_PARAMETERS)); hibernateParameters.setReadonly(true); hibernateParameters.setHeight(100); hibernateParameters.setResizeToMaxHeight(false); hibernateParameters.setMode(null); mainForm.add(hibernateParameters); WebMarkupContainer hibernateParametersNote = new WebMarkupContainer(ID_HIBERNATE_PARAMETERS_NOTE); hibernateParametersNote.setVisible(isAdmin); mainForm.add(hibernateParametersNote); WebMarkupContainer midPointQueryButtonBar = new WebMarkupContainer(ID_MIDPOINT_QUERY_BUTTON_BAR); midPointQueryButtonBar.setOutputMarkupId(true); mainForm.add(midPointQueryButtonBar); AjaxSubmitButton executeMidPoint = new AjaxSubmitButton(ID_EXECUTE_MIDPOINT, createStringResource("PageRepositoryQuery.button.translateAndExecute")) { @Override protected void onError(AjaxRequestTarget target, Form<?> form) { target.add(getFeedbackPanel()); } @Override protected void onSubmit(AjaxRequestTarget target, Form<?> form) { queryPerformed(Action.EXECUTE_MIDPOINT, target); } }; midPointQueryButtonBar.add(executeMidPoint); AjaxSubmitButton compileMidPoint = new AjaxSubmitButton(ID_COMPILE_MIDPOINT, createStringResource("PageRepositoryQuery.button.translate")) { @Override protected void onError(AjaxRequestTarget target, Form<?> form) { target.add(getFeedbackPanel()); } @Override protected void onSubmit(AjaxRequestTarget target, Form<?> form) { queryPerformed(Action.TRANSLATE_ONLY, target); } }; midPointQueryButtonBar.add(compileMidPoint); AjaxSubmitButton useInObjectList = new AjaxSubmitButton(ID_USE_IN_OBJECT_LIST, createStringResource("PageRepositoryQuery.button.useInObjectList")) { @Override protected void onError(AjaxRequestTarget target, Form<?> form) { target.add(getFeedbackPanel()); } @Override protected void onSubmit(AjaxRequestTarget target, Form<?> form) { useInObjectListPerformed(target); } }; useInObjectList.add(new VisibleEnableBehaviour() { @Override public boolean isVisible() { return USE_IN_OBJECT_LIST_AVAILABLE_FOR.contains(model.getObject().getObjectType()); } }); midPointQueryButtonBar.add(useInObjectList); final DropDownChoice<String> sampleChoice = new DropDownChoice<>(ID_QUERY_SAMPLE, Model.of(""), new AbstractReadOnlyModel<List<String>>() { @Override public List<String> getObject() { return SAMPLES; } }, new StringResourceChoiceRenderer("PageRepositoryQuery.sample")); sampleChoice.setNullValid(true); sampleChoice.add(new OnChangeAjaxBehavior() { @Override protected void onUpdate(AjaxRequestTarget target) { String sampleName = sampleChoice.getModelObject(); if (StringUtils.isEmpty(sampleName)) { return; } String resourceName = SAMPLES_DIR + "/" + sampleName + ".xml.data"; InputStream is = PageRepositoryQuery.class.getResourceAsStream(resourceName); if (is != null) { try { String localTypeName = StringUtils.substringBefore(sampleName, "_"); model.getObject().setObjectType(new QName(SchemaConstants.NS_C, localTypeName)); model.getObject().setMidPointQuery(IOUtils.toString(is, "UTF-8")); model.getObject().setHibernateQuery(""); model.getObject().setHibernateParameters(""); model.getObject().setQueryResultObject(null); model.getObject().resetQueryResultText(); target.add(PageRepositoryQuery.this); } catch (IOException e) { LoggingUtils.logUnexpectedException(LOGGER, "Couldn't read sample from resource {}", e, resourceName); } } else { LOGGER.warn("Resource {} containing sample couldn't be found", resourceName); } } }); mainForm.add(sampleChoice); AjaxSubmitButton executeHibernate = new AjaxSubmitButton(ID_EXECUTE_HIBERNATE, createStringResource("PageRepositoryQuery.button.execute")) { @Override protected void onError(AjaxRequestTarget target, Form<?> form) { target.add(getFeedbackPanel()); } @Override protected void onSubmit(AjaxRequestTarget target, Form<?> form) { queryPerformed(Action.EXECUTE_HIBERNATE, target); } }; executeHibernate.setVisible(isAdmin); mainForm.add(executeHibernate); Label resultLabel = new Label(ID_RESULT_LABEL, new AbstractReadOnlyModel<String>() { @Override public String getObject() { if (model.getObject().getQueryResultText() == null) { return ""; } Object queryResult = model.getObject().getQueryResultObject(); if (queryResult instanceof List) { return getString("PageRepositoryQuery.resultObjects", ((List) queryResult).size()); } else if (queryResult instanceof Throwable) { return getString("PageRepositoryQuery.resultException", queryResult.getClass().getName()); } else { // including null return getString("PageRepositoryQuery.result"); } } }); mainForm.add(resultLabel); WebMarkupContainer incompleteResultsNote = new WebMarkupContainer(ID_INCOMPLETE_RESULTS_NOTE); incompleteResultsNote.add(new VisibleEnableBehaviour() { @Override public boolean isVisible() { return !isAdmin && model.getObject().getQueryResultText() != null; } }); mainForm.add(incompleteResultsNote); AceEditor resultText = new AceEditor(ID_RESULT_TEXT, new PropertyModel<>(model, RepoQueryDto.F_QUERY_RESULT_TEXT)); resultText.setReadonly(true); resultText.setHeight(300); resultText.setResizeToMaxHeight(false); resultText.setMode(null); resultText.add(new VisibleEnableBehaviour() { @Override public boolean isVisible() { return model.getObject().getQueryResultText() != null; } }); mainForm.add(resultText); }
From source file:com.apus.hades.admin.web.controller.ad.app.PositionController.java
/** * /??./*from ww w . j av a 2 s .c om*/ */ @OperatLog(Handle = SystemHandle.EDIT, Module = SystemModule.POSITION_MODEL, Desc = "/??") public String choose() { String[] checks = Struts2Utils.getParameters("checkIds"); Long positionId = Struts2Utils.getLong("positionId"); position = positionManager.findPosition(positionId); List<AdPlatformDTO> dtos = positionService.findCheckedByPositionId(positionId); // if (null == checks || checks.length == 0) { if (null != dtos && !dtos.isEmpty()) { for (AdPlatformDTO dto : dtos) { positionManager.deletePlatformInfo(positionId, dto.getId()); } } return list(); } // ?. List<AdPlatformDTO> simples = new ArrayList<AdPlatformDTO>(); for (String check : checks) { Long id = Long.parseLong(StringUtils.substringBefore(check, "_")); simples.add(new AdPlatformDTO(id)); } // ? ?. if (null == dtos || dtos.isEmpty()) { for (AdPlatformDTO dto : simples) { positionManager.addPlatformInfo(positionId, ConfigCache.LIMIT_PARTNER_IDS.getValue(), dto.getId()); } return list(); } for (AdPlatformDTO dto : dtos) { // check ?? dto.setChecked(false); for (AdPlatformDTO sm : simples) { // ? true if (dto.equals(sm)) { dto.setChecked(true); sm.setChecked(true); break; } } // ? if (!dto.isChecked()) { positionManager.deletePlatformInfo(positionId, dto.getId()); } } // ?? for (AdPlatformDTO dto : simples) { if (!dto.isChecked()) { positionManager.addPlatformInfo(positionId, ConfigCache.LIMIT_PARTNER_IDS.getValue(), dto.getId()); } } return list(); }
From source file:in.mycp.workers.IpAddressWorker.java
@Async public void disassociateAddress(final Infra infra, final AddressInfoP addressInfoP) { String threadName = Thread.currentThread().getName(); try {/* ww w .ja va 2 s .c o m*/ logger.debug("threadName " + threadName + " started for disassociateAddress"); Jec2 ec2 = getNewJce2(infra); try { ec2.disassociateAddress(addressInfoP.getPublicIp()); } catch (Exception e) { logger.error(e);//e.printStackTrace(); if (e.getMessage().indexOf("Permission denied while") > -1) { throw new Exception("Permission denied."); } else if (e.getMessage().indexOf("Number of retries exceeded") > -1) { throw new Exception("No Connectivity to Cloud"); } } String instanceIdOrig = addressInfoP.getInstanceId(); if (StringUtils.contains(instanceIdOrig, " ")) { instanceIdOrig = StringUtils.substringBefore(instanceIdOrig, " "); } InstanceP orig_compute = null; try { orig_compute = InstanceP.findInstancePsByInstanceIdEquals(instanceIdOrig).getSingleResult(); } catch (Exception e) { logger.error(e);//e.printStackTrace(); } AddressInfoP addressInfoP4PublicIp = null; try { addressInfoP4PublicIp = AddressInfoP.findAddressInfoPsByPublicIpEquals(addressInfoP.getPublicIp()) .getSingleResult(); } catch (Exception e) { logger.error(e);//e.printStackTrace(); } String newIp = ""; boolean match = false; int START_SLEEP_TIME = 5000; int waitformaxcap = START_SLEEP_TIME * 10; long now = 0; outer: while (!match) { if (now > waitformaxcap) { throw new Exception("Got bored, Quitting."); } now = now + START_SLEEP_TIME; try { List<String> params = new ArrayList<String>(); List<ReservationDescription> instances = ec2.describeInstances(params); for (ReservationDescription res : instances) { if (res.getInstances() != null) { HashSet<InstanceP> instancesP = new HashSet<InstanceP>(); for (Instance inst : res.getInstances()) { logger.info(inst.getInstanceId() + " " + orig_compute.getInstanceId() + " " + inst.getDnsName() + " " + addressInfoP.getPublicIp()); if (inst.getInstanceId().equals(orig_compute.getInstanceId()) && !inst.getDnsName().equals(addressInfoP.getPublicIp())) { newIp = inst.getDnsName(); match = true; break outer; } } //for (Instance inst : res.getInstances()) { } //if (res.getInstances() != null) { } //for (ReservationDescription res : instances) { logger.info("Ipaddress " + addressInfoP.getPublicIp() + " getting disassociated; sleeping " + START_SLEEP_TIME + "ms"); Thread.sleep(START_SLEEP_TIME); } catch (Exception e) { logger.error(e);//e.printStackTrace(); //addressInfoLocal=null; } } AddressInfoP addressInfoP4NewPublicIp = null; try { addressInfoP4NewPublicIp = AddressInfoP.findAddressInfoPsByPublicIpEquals(newIp).getSingleResult(); } catch (Exception e) { logger.error(e);//e.printStackTrace(); } if (match == true) { try { orig_compute.setDnsName(newIp); orig_compute.merge(); } catch (Exception e) { logger.error(e);//e.printStackTrace(); } try { addressInfoP4PublicIp.setAssociated(false); addressInfoP4PublicIp.setInstanceId("available"); addressInfoP4PublicIp.setStatus(Commons.ipaddress_STATUS.available + ""); addressInfoP4PublicIp.merge(); } catch (Exception e) { logger.error(e);//e.printStackTrace(); } try { addressInfoP4NewPublicIp.setAssociated(false); addressInfoP4NewPublicIp.setInstanceId(orig_compute.getInstanceId()); addressInfoP4PublicIp.setStatus(Commons.ipaddress_STATUS.available + ""); addressInfoP4NewPublicIp.merge(); } catch (Exception e) { logger.error(e);//e.printStackTrace(); } } } catch (Exception e) { logger.error(e);//e.printStackTrace(); try { AddressInfoP a = AddressInfoP.findAddressInfoP(addressInfoP.getId()); a.setStatus(Commons.ipaddress_STATUS.failed + ""); a = a.merge(); setAssetEndTime(a.getAsset()); } catch (Exception e2) { // TODO: handle exception } } }
From source file:com.thinkbiganalytics.metadata.rest.api.DebugController.java
/** * Prints the nodes of the JCR path given, for debugging. * * @param query the jcr query// ww w.j a v a 2 s. c o m * @return a printout of the JCR tree */ @GET @Path("jcr-sql") @Produces({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON }) public JcrQueryResult queryJcr(@QueryParam("query") final String query) { this.accessController.checkPermission(AccessController.SERVICES, MetadataAccessControl.ADMIN_METADATA); return metadata.read(() -> { List<List<String>> rows = new ArrayList<>(); Long startTime = System.currentTimeMillis(); JcrQueryResult jcrQueryResult = new JcrQueryResult(); try { Session session = JcrMetadataAccess.getActiveSession(); Workspace workspace = (Workspace) session.getWorkspace(); String explainPlain = JcrQueryUtil.explainPlain(session, query); //start the timer now: startTime = System.currentTimeMillis(); QueryResult result = JcrQueryUtil.query(session, query); jcrQueryResult.setExplainPlan(explainPlain); RowIterator rowItr = result.getRows(); List<JcrQueryResultColumn> columns = new ArrayList<>(); String colsStr = StringUtils.substringAfter(query.toLowerCase(), "select"); colsStr = StringUtils.substringBefore(colsStr, "from"); if (StringUtils.isNotBlank(colsStr)) { colsStr = colsStr.trim(); columns = Arrays.asList(colsStr.split(",")).stream().map(c -> { String columnName = c; if (c.contains("as ")) { columnName = StringUtils.substringAfter(c, "as "); } else if (c.contains(" ")) { columnName = StringUtils.substringAfter(c, " "); } return new JcrQueryResultColumn(columnName); }).collect(Collectors.toList()); } jcrQueryResult.setColumns(columns); while (rowItr.hasNext()) { Row row = rowItr.nextRow(); Value[] rowValues = row.getValues(); if (rowValues != null) { if (rowValues.length != columns.size()) { columns = IntStream.range(0, rowValues.length) .mapToObj(i -> new JcrQueryResultColumn("Column " + i)) .collect(Collectors.toList()); jcrQueryResult.setColumns(columns); } JcrQueryResultRow jcrQueryResultRow = new JcrQueryResultRow(); jcrQueryResult.addRow(jcrQueryResultRow); List<JcrQueryResultColumnValue> jcrQueryResultColumnValues = Arrays.asList(rowValues) .stream().map(v -> { try { String value = v.getString(); return new JcrQueryResultColumnValue(value); } catch (Exception e) { return new JcrQueryResultColumnValue("ERROR: " + e.getMessage()); } }).collect(Collectors.toList()); jcrQueryResultRow.setColumnValues(jcrQueryResultColumnValues); } } } catch (Exception e) { throw new RuntimeException(e); } long totalTime = System.currentTimeMillis() - startTime; jcrQueryResult.setQueryTime(totalTime); return jcrQueryResult; }); }
From source file:com.norconex.collector.http.url.impl.HtmlLinkExtractor.java
private String toAbsoluteURL(final Referer urlParts, final String newURL) { if (!isValidNewURL(newURL)) { return null; }/*from ww w. j a v a2s .com*/ String url = newURL; if (url.startsWith("//")) { // this is URL relative to protocol url = urlParts.protocol + StringUtils.substringAfter(url, "//"); } else if (url.startsWith("/")) { // this is a URL relative to domain name url = urlParts.absoluteBase + url; } else if (url.startsWith("?") || url.startsWith("#")) { // this is a relative url and should have the full page base url = urlParts.documentBase + url; } else if (!url.contains("://")) { if (urlParts.relativeBase.endsWith("/")) { // This is a URL relative to the last URL segment url = urlParts.relativeBase + url; } else { url = urlParts.relativeBase + "/" + url; } } //TODO have configurable whether to strip anchors. url = StringUtils.substringBefore(url, "#"); if (url.length() > maxURLLength) { LOG.debug("URL length (" + url.length() + ") exeeding " + "maximum length allowed (" + maxURLLength + ") to be extracted. URL (showing first " + LOGGING_MAX_URL_LENGTH + " chars): " + StringUtils.substring(url, 0, LOGGING_MAX_URL_LENGTH) + "..."); return null; } return url; }
From source file:com.gargoylesoftware.htmlunit.javascript.host.html.HTMLAnchorElement.java
/** * Returns the protocol portion of the link's URL, including the trailing ':'. * @return the protocol portion of the link's URL, including the trailing ':' * @throws Exception if an error occurs// www . j ava2 s . co m * @see <a href="http://msdn.microsoft.com/en-us/library/ms534353.aspx">MSDN Documentation</a> */ @JsxGetter public String getProtocol() throws Exception { try { if (getBrowserVersion().hasFeature(JS_ANCHOR_PATHNAME_DETECT_WIN_DRIVES_URL)) { final HtmlAnchor anchor = (HtmlAnchor) getDomNodeOrDie(); final String href = anchor.getHrefAttribute().toLowerCase(Locale.ROOT); if (href.length() > 1 && Character.isLetter(href.charAt(0)) && ':' == href.charAt(1)) { return "file:"; } } return getUrl().getProtocol() + ":"; } catch (final MalformedURLException e) { final HtmlAnchor anchor = (HtmlAnchor) getDomNodeOrDie(); if (anchor.getHrefAttribute().startsWith("http") && getBrowserVersion().hasFeature(JS_ANCHOR_PROTOCOL_COLON_FOR_BROKEN_URL)) { return ":"; } return StringUtils.substringBefore(anchor.getHrefAttribute(), "/"); } }
From source file:com.wso2.code.quality.matrices.ChangesFinder.java
/** * Reading the blame received for a current selected file name and insert the parent commits of the changed lines, * relevant authors and the relevant commits hashes to look for the reviewers of those line ranges * * @param rootJsonObject JSONObject containing blame information for current selected file * @param arrayListOfRelevantChangedLinesOfSelectedFile arraylist containing the changed line ranges of the current selected file * @param gettingPr should be true if running this method for finding the authors of buggy lines which are being fixed from the patch *///w w w . j a va2 s . c o m public void readBlameReceivedForAFile(JSONObject rootJsonObject, ArrayList<String> arrayListOfRelevantChangedLinesOfSelectedFile, boolean gettingPr, String oldRange) { //running a iterator for fileName arrayList to get the location of the above saved file JSONObject dataJSONObject = (JSONObject) rootJsonObject.get(GITHUB_GRAPHQL_API_DATA_KEY_STRING); JSONObject repositoryJSONObect = (JSONObject) dataJSONObject.get(GITHUB_GRAPHQL_API_REPOSITORY_KEY_STRING); JSONObject objectJSONObject = (JSONObject) repositoryJSONObect.get(GITHUB_GRAPHQL_API_OBJECT_KEY_STRING); JSONObject blameJSONObject = (JSONObject) objectJSONObject.get(GITHUB_GRAPHQL_API_BLAME_KEY_STRING); JSONArray rangeJSONArray = (JSONArray) blameJSONObject.get(GITHUB_GRAPHQL_API_RANGES_KEY_STRING); //getting the starting line no of the range of lines that are modified from the patch // parallel streams are not used in here as the order of the arraylist is important in the process arrayListOfRelevantChangedLinesOfSelectedFile.stream().forEach(lineRanges -> { int startingLineNo = 0; int endLineNo = 0; String oldFileRange = StringUtils.substringBefore(lineRanges, "/"); String newFileRange = StringUtils.substringAfter(lineRanges, "/"); // need to skip the newly created files from taking the blame as they contain no previous commits if (!oldFileRange.equals("0,0")) { if (gettingPr && oldRange.equals(oldFileRange)) { // need to consider the line range in the old file for finding authors and reviewers startingLineNo = Integer.parseInt(StringUtils.substringBefore(oldFileRange, ",")); endLineNo = Integer.parseInt(StringUtils.substringAfter(oldFileRange, ",")); } else if (!gettingPr && oldRange == null) { // need to consider the line range in the new file resulted from applying the commit, for finding parent commits startingLineNo = Integer.parseInt(StringUtils.substringBefore(newFileRange, ",")); endLineNo = Integer.parseInt(StringUtils.substringAfter(newFileRange, ",")); } else { return; // to skip the to the next iteration if oldRange != oldFileRange when finding authornames and commits for obtaining PRs } // as a new mapForStoringAgeAndIndex map should be available for each line range to find the most recent change Map<Integer, ArrayList<Integer>> mapForStoringAgeAndIndex = new HashMap<Integer, ArrayList<Integer>>(); //checking line by line by iterating the startingLineNo while (endLineNo >= startingLineNo) { // since the index value is required for later processing, without Java 8 features "for loop" is used for iteration for (int i = 0; i < rangeJSONArray.length(); i++) { JSONObject rangeJSONObject = (JSONObject) rangeJSONArray.get(i); int tempStartingLineNo = (int) rangeJSONObject .get(GITHUB_GRAPHQL_API_STARTING_LINE_KEY_STRING); int tempEndingLineNo = (int) rangeJSONObject.get(GITHUB_GRAPHQL_API_ENDING_LINE_KEY_STRING); //checking whether the line belongs to that line range group if ((tempStartingLineNo <= startingLineNo) && (tempEndingLineNo >= startingLineNo)) { // so the relevant startingLineNo belongs in this line range in other words in this JSONObject if (!gettingPr) { int age = (int) rangeJSONObject.get(GITHUB_GRAPHQL_API_AGE_KEY_STRING); // storing the age field with relevant index of the JSONObject mapForStoringAgeAndIndex.putIfAbsent(age, new ArrayList<Integer>()); if (!mapForStoringAgeAndIndex.get(age).contains(i)) { mapForStoringAgeAndIndex.get(age).add(i); // adding if the index is not present in the array list for the relevant age } } else { //for saving the author names of commiters JSONObject commitJSONObject = (JSONObject) rangeJSONObject .get(GITHUB_GRAPHQL_API_COMMIT_KEY_STRING); JSONObject authorJSONObject = (JSONObject) commitJSONObject .get(GITHUB_GRAPHQL_API_AUTHOR_KEY_STRING); String nameOfTheAuthor = (String) authorJSONObject .get(GITHUB_GRAPHQL_API_NAME_KEY_STRING); authorNames.add(nameOfTheAuthor); // authors are added to the Set String urlOfCommit = (String) commitJSONObject .get(GITHUB_GRAPHQL_API_URL_KEY_STRING); String commitHashForPRReview = StringUtils.substringAfter(urlOfCommit, "commit/"); commitHashObtainedForPRReview.add(commitHashForPRReview); } break; } else { continue; // to skip to the next JSON Object in the rangeJSONArray } } startingLineNo++; // to check for other line numbers } //for the above line range getting the lastest commit which modified the lines if (!gettingPr) { //converting the map into a treeMap to get it ordered TreeMap<Integer, ArrayList<Integer>> treeMap = new TreeMap<>(mapForStoringAgeAndIndex); int minimumKeyOfMapForStoringAgeAndIndex = treeMap.firstKey(); // getting the minimum key //getting the relevant JSONObject indexes which consists of the recent change with in the relevant line range ArrayList<Integer> indexesOfJsonObjectForRecentCommit = mapForStoringAgeAndIndex .get(minimumKeyOfMapForStoringAgeAndIndex); // the order of the indexesOfJsonObjectForRecentCommit is not important as we only need to get the parent commit hashes indexesOfJsonObjectForRecentCommit.parallelStream().forEach(index -> { JSONObject rangeJSONObject = (JSONObject) rangeJSONArray.get(index); JSONObject commitJSONObject = (JSONObject) rangeJSONObject .get(GITHUB_GRAPHQL_API_COMMIT_KEY_STRING); JSONObject historyJSONObject = (JSONObject) commitJSONObject .get(GITHUB_GRAPHQL_API_HISTORY_KEY_STRING); JSONArray edgesJSONArray = (JSONArray) historyJSONObject .get(GITHUB_GRAPHQL_API_EDGE_KEY_STRING); //getting the second json object from the array as it contain the commit of the parent which modified the above line range JSONObject edgeJSONObject = (JSONObject) edgesJSONArray.get(1); JSONObject nodeJSONObject = (JSONObject) edgeJSONObject .get(GITHUB_GRAPHQL_API_NODE_KEY_STRING); String urlOfTheParentCommit = (String) nodeJSONObject .get(GITHUB_GRAPHQL_API_URL_KEY_STRING); // this contain the URL of the parent commit String commitHash = (String) StringUtils.substringAfter(urlOfTheParentCommit, "commit/"); // commitHashesOfTheParent.add(commitHash); // commitHashesof the parent for the selected file commitHashesMapOfTheParent.putIfAbsent(oldFileRange, new HashSet<String>()); if (!commitHashesMapOfTheParent.get(oldFileRange).contains(commitHash)) { commitHashesMapOfTheParent.get(oldFileRange).add(commitHash); } }); } } }); }
From source file:com.thinkmore.framework.orm.hibernate.HibernateDao.java
public String getCountSQL(String sql) { String fromHql = sql;//from w ww . ja v a 2 s .com // select??order by???count,?. fromHql = "from " + StringUtils.substringAfter(fromHql, "from"); fromHql = StringUtils.substringBefore(fromHql, "order by"); return "select count(*) as count " + fromHql; }
From source file:com.gargoylesoftware.htmlunit.javascript.host.html.HTMLAnchorElement.java
/** * Sets the protocol portion of the link's URL. * @param protocol the new protocol portion of the link's URL * @throws Exception if an error occurs//from w w w . ja v a 2 s.c o m * @see <a href="http://msdn.microsoft.com/en-us/library/ms534353.aspx">MSDN Documentation</a> */ @JsxSetter public void setProtocol(final String protocol) throws Exception { final String bareProtocol = StringUtils.substringBefore(protocol, ":"); setUrl(UrlUtils.getUrlWithNewProtocol(getUrl(), bareProtocol)); }
From source file:io.wcm.caravan.io.http.impl.CaravanHttpServiceConfig.java
/** * Checks if protocols are defined in the ribbon "listOfServers" properties, which is not supported by ribbon itself. * If this is the case, remove them and set our custom "http.protocol" property instead to the protocol, if * it is set to "auto"./*from w w w .ja v a 2s . co m*/ */ private void applyRibbonHostsProcotol(String serviceId) { Configuration archaiusConfig = ArchaiusConfig.getConfiguration(); String[] listOfServers = archaiusConfig.getStringArray(serviceId + RIBBON_PARAM_LISTOFSERVERS); String protocolForAllServers = archaiusConfig.getString(serviceId + HTTP_PARAM_PROTOCOL); // get protocols defined in servers Set<String> protocolsFromListOfServers = Arrays.stream(listOfServers) .filter(server -> StringUtils.contains(server, "://")) .map(server -> StringUtils.substringBefore(server, "://")).collect(Collectors.toSet()); // skip further processing of no protocols defined if (protocolsFromListOfServers.isEmpty()) { return; } // ensure that only one protocol is defined. if not use the first one and write a warning to the log files. String protocol = new TreeSet<String>(protocolsFromListOfServers).iterator().next(); if (protocolsFromListOfServers.size() > 1) { log.warn("Different protocols are defined for property {}: {}. Only protocol '{}' is used.", RIBBON_HOSTS_PROPERTY, StringUtils.join(listOfServers, LIST_SEPARATOR), protocol); } // if http protocol is not set to "auto" write a warning as well, because protocol is defined in server list as well if (!(StringUtils.equals(protocolForAllServers, RequestUtil.PROTOCOL_AUTO) || StringUtils.equals(protocolForAllServers, protocol))) { log.warn( "Protocol '{}' is defined for property {}: {}, but an other protocol is defined in the server list: {}. Only protocol '{}' is used.", protocolForAllServers, PROTOCOL_PROPERTY, StringUtils.join(listOfServers, LIST_SEPARATOR), protocol); } // remove protocol from list of servers and store default protocol List<String> listOfServersWithoutProtocol = Arrays.stream(listOfServers) .map(server -> StringUtils.substringAfter(server, "://")).collect(Collectors.toList()); archaiusConfig.setProperty(serviceId + RIBBON_PARAM_LISTOFSERVERS, StringUtils.join(listOfServersWithoutProtocol, LIST_SEPARATOR)); archaiusConfig.setProperty(serviceId + HTTP_PARAM_PROTOCOL, protocol); }