Example usage for org.apache.commons.lang3 StringUtils substringAfter

List of usage examples for org.apache.commons.lang3 StringUtils substringAfter

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils substringAfter.

Prototype

public static String substringAfter(final String str, final String separator) 

Source Link

Document

Gets the substring after the first occurrence of a separator.

Usage

From source file:com.thinkmore.framework.orm.hibernate.HibernateDao.java

public String getCountSQL(String sql) {
    String fromHql = sql;/*from ww w .jav  a  2 s .  c o  m*/
    // 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.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
 *//*from  www.j av a2s.  c  om*/
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:de.blizzy.documentr.access.UserStore.java

private List<RoleGrantedAuthority> getUserAuthorities(String loginName, ILockedRepository repo) {
    String json = BlobUtils.getHeadContent(repo.r(), loginName + AUTHORITIES_SUFFIX);
    if (json == null) {
        throw new UserNotFoundException(loginName);
    }//from  ww w.j a v  a 2  s . co  m

    Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
    Map<String, Set<String>> authoritiesMap = gson.fromJson(json, new TypeToken<Map<String, Set<String>>>() {
    }.getType());
    List<RoleGrantedAuthority> authorities = Lists.newArrayList();
    for (Map.Entry<String, Set<String>> entry : authoritiesMap.entrySet()) {
        String targetStr = entry.getKey();
        Type type = Type.valueOf(StringUtils.substringBefore(targetStr, ":")); //$NON-NLS-1$
        String targetId = StringUtils.substringAfter(targetStr, ":"); //$NON-NLS-1$
        for (String roleName : entry.getValue()) {
            authorities.add(new RoleGrantedAuthority(new GrantedAuthorityTarget(targetId, type), roleName));
        }
    }

    Collections.sort(authorities, new RoleGrantedAuthorityComparator());

    return authorities;
}

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 ww  .  ja  v a2s . c o  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);
}

From source file:com.norconex.collector.http.url.impl.GenericLinkExtractor.java

private String toCleanAbsoluteURL(final Referer urlParts, final String newURL) {
    String url = StringUtils.trimToNull(newURL);
    if (!isValidNewURL(url)) {
        return null;
    }// ww w .  j  a  v  a2  s  .  c  o  m

    // Decode HTML entities.
    url = StringEscapeUtils.unescapeHtml4(url);

    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;
        }
    }

    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:ching.icecreaming.action.ViewAction.java

@Action(value = "view", results = { @Result(name = "login", location = "edit.jsp"),
        @Result(name = "input", location = "view.jsp"), @Result(name = "success", location = "view.jsp"),
        @Result(name = "error", location = "error.jsp") })
public String execute() throws Exception {
    Enumeration enumerator = null;
    String[] array1 = null, array2 = null;
    int int1 = -1, int2 = -1, int3 = -1;
    InputStream inputStream1 = null;
    OutputStream outputStream1 = null;
    java.io.File file1 = null, file2 = null, dir1 = null;
    List<File> files = null;
    HttpHost httpHost1 = null;/* ww  w.  jav a 2 s .c om*/
    HttpGet httpGet1 = null, httpGet2 = null;
    HttpPut httpPut1 = null;
    URI uri1 = null;
    URL url1 = null;
    DefaultHttpClient httpClient1 = null;
    URIBuilder uriBuilder1 = null, uriBuilder2 = null;
    HttpResponse httpResponse1 = null, httpResponse2 = null;
    HttpEntity httpEntity1 = null, httpEntity2 = null;
    List<NameValuePair> nameValuePair1 = null;
    String string1 = null, string2 = null, string3 = null, string4 = null, return1 = LOGIN;
    XMLConfiguration xmlConfiguration = null;
    List<HierarchicalConfiguration> list1 = null, list2 = null;
    HierarchicalConfiguration hierarchicalConfiguration2 = null;
    DataModel1 dataModel1 = null;
    DataModel2 dataModel2 = null;
    List<DataModel1> listObject1 = null, listObject3 = null;
    org.joda.time.DateTime dateTime1 = null, dateTime2 = null;
    org.joda.time.Period period1 = null;
    PeriodFormatter periodFormatter1 = new PeriodFormatterBuilder().appendYears()
            .appendSuffix(String.format(" %s", getText("year")), String.format(" %s", getText("years")))
            .appendSeparator(" ").appendMonths()
            .appendSuffix(String.format(" %s", getText("month")), String.format(" %s", getText("months")))
            .appendSeparator(" ").appendWeeks()
            .appendSuffix(String.format(" %s", getText("week")), String.format(" %s", getText("weeks")))
            .appendSeparator(" ").appendDays()
            .appendSuffix(String.format(" %s", getText("day")), String.format(" %s", getText("days")))
            .appendSeparator(" ").appendHours()
            .appendSuffix(String.format(" %s", getText("hour")), String.format(" %s", getText("hours")))
            .appendSeparator(" ").appendMinutes()
            .appendSuffix(String.format(" %s", getText("minute")), String.format(" %s", getText("minutes")))
            .appendSeparator(" ").appendSeconds().minimumPrintedDigits(2)
            .appendSuffix(String.format(" %s", getText("second")), String.format(" %s", getText("seconds")))
            .printZeroNever().toFormatter();
    if (StringUtils.isBlank(urlString) || StringUtils.isBlank(wsType)) {
        urlString = portletPreferences.getValue("urlString", "/");
        wsType = portletPreferences.getValue("wsType", "folder");
    }
    Configuration propertiesConfiguration1 = new PropertiesConfiguration("system.properties");
    timeZone1 = portletPreferences.getValue("timeZone", TimeZone.getDefault().getID());
    enumerator = portletPreferences.getNames();
    if (enumerator.hasMoreElements()) {
        array1 = portletPreferences.getValues("server", null);
        if (array1 != null) {
            if (ArrayUtils.isNotEmpty(array1)) {
                for (int1 = 0; int1 < array1.length; int1++) {
                    switch (int1) {
                    case 0:
                        sid = array1[int1];
                        break;
                    case 1:
                        uid = array1[int1];
                        break;
                    case 2:
                        pid = array1[int1];
                        break;
                    case 3:
                        alias1 = array1[int1];
                        break;
                    default:
                        break;
                    }
                }
                sid = new String(Base64.decodeBase64(sid.getBytes()));
                uid = new String(Base64.decodeBase64(uid.getBytes()));
                pid = new String(Base64.decodeBase64(pid.getBytes()));
            }
            return1 = INPUT;
        } else {
            return1 = LOGIN;
        }
    } else {
        return1 = LOGIN;
    }

    if (StringUtils.equals(urlString, "/")) {

        if (listObject1 != null) {
            listObject1.clear();
        }
        if (session.containsKey("breadcrumbs")) {
            session.remove("breadcrumbs");
        }
    } else {
        array2 = StringUtils.split(urlString, "/");
        listObject1 = (session.containsKey("breadcrumbs")) ? (List<DataModel1>) session.get("breadcrumbs")
                : new ArrayList<DataModel1>();
        int2 = array2.length - listObject1.size();
        if (int2 > 0) {
            listObject1.add(new DataModel1(urlString, label1));
        } else {
            int2 += listObject1.size();
            for (int1 = listObject1.size() - 1; int1 >= int2; int1--) {
                listObject1.remove(int1);
            }
        }
        session.put("breadcrumbs", listObject1);
    }
    switch (wsType) {
    case "folder":
        break;
    case "reportUnit":
        try {
            dateTime1 = new org.joda.time.DateTime();
            return1 = INPUT;
            httpClient1 = new DefaultHttpClient();
            if (StringUtils.equals(button1, getText("Print"))) {
                nameValuePair1 = new ArrayList<NameValuePair>();
                if (listObject2 != null) {
                    if (listObject2.size() > 0) {
                        for (DataModel2 dataObject2 : listObject2) {
                            listObject3 = dataObject2.getOptions();
                            if (listObject3 == null) {
                                string2 = dataObject2.getValue1();
                                if (StringUtils.isNotBlank(string2))
                                    nameValuePair1.add(new BasicNameValuePair(dataObject2.getId(), string2));
                            } else {
                                for (int1 = listObject3.size() - 1; int1 >= 0; int1--) {
                                    dataModel1 = (DataModel1) listObject3.get(int1);
                                    string2 = dataModel1.getString2();
                                    if (StringUtils.isNotBlank(string2))
                                        nameValuePair1
                                                .add(new BasicNameValuePair(dataObject2.getId(), string2));
                                }
                            }
                        }
                    }
                }
                url1 = new URL(sid);
                uriBuilder1 = new URIBuilder(sid);
                uriBuilder1.setUserInfo(uid, pid);
                if (StringUtils.isBlank(format1))
                    format1 = "pdf";
                uriBuilder1.setPath(url1.getPath() + "/rest_v2/reports" + urlString + "." + format1);
                if (StringUtils.isNotBlank(locale2)) {
                    nameValuePair1.add(new BasicNameValuePair("userLocale", locale2));
                }
                if (StringUtils.isNotBlank(page1)) {
                    if (NumberUtils.isNumber(page1)) {
                        nameValuePair1.add(new BasicNameValuePair("page", page1));
                    }
                }
                if (nameValuePair1.size() > 0) {
                    uriBuilder1.setQuery(URLEncodedUtils.format(nameValuePair1, "UTF-8"));
                }
                uri1 = uriBuilder1.build();
                httpGet1 = new HttpGet(uri1);
                httpResponse1 = httpClient1.execute(httpGet1);
                int1 = httpResponse1.getStatusLine().getStatusCode();
                if (int1 == HttpStatus.SC_OK) {
                    string3 = System.getProperty("java.io.tmpdir") + File.separator
                            + httpServletRequest.getSession().getId();
                    dir1 = new File(string3);
                    if (!dir1.exists()) {
                        dir1.mkdir();
                    }
                    httpEntity1 = httpResponse1.getEntity();
                    file1 = new File(string3, StringUtils.substringAfterLast(urlString, "/") + "." + format1);
                    if (StringUtils.equalsIgnoreCase(format1, "html")) {
                        result1 = EntityUtils.toString(httpEntity1);
                        FileUtils.writeStringToFile(file1, result1);
                        array1 = StringUtils.substringsBetween(result1, "<img src=\"", "\"");
                        if (ArrayUtils.isNotEmpty(array1)) {
                            dir1 = new File(
                                    string3 + File.separator + FilenameUtils.getBaseName(file1.getName()));
                            if (dir1.exists()) {
                                FileUtils.deleteDirectory(dir1);
                            }
                            file2 = new File(FilenameUtils.getFullPath(file1.getAbsolutePath())
                                    + FilenameUtils.getBaseName(file1.getName()) + ".zip");
                            if (file2.exists()) {
                                if (FileUtils.deleteQuietly(file2)) {
                                }
                            }
                            for (int2 = 0; int2 < array1.length; int2++) {
                                try {
                                    string2 = url1.getPath() + "/rest_v2/reports" + urlString + "/"
                                            + StringUtils.substringAfter(array1[int2], "/");
                                    uriBuilder1.setPath(string2);
                                    uri1 = uriBuilder1.build();
                                    httpGet1 = new HttpGet(uri1);
                                    httpResponse1 = httpClient1.execute(httpGet1);
                                    int1 = httpResponse1.getStatusLine().getStatusCode();
                                } finally {
                                    if (int1 == HttpStatus.SC_OK) {
                                        try {
                                            string2 = StringUtils.substringBeforeLast(array1[int2], "/");
                                            dir1 = new File(string3 + File.separator + string2);
                                            if (!dir1.exists()) {
                                                dir1.mkdirs();
                                            }
                                            httpEntity1 = httpResponse1.getEntity();
                                            inputStream1 = httpEntity1.getContent();
                                        } finally {
                                            string1 = StringUtils.substringAfterLast(array1[int2], "/");
                                            file2 = new File(string3 + File.separator + string2, string1);
                                            outputStream1 = new FileOutputStream(file2);
                                            IOUtils.copy(inputStream1, outputStream1);
                                        }
                                    }
                                }
                            }
                            outputStream1 = new FileOutputStream(
                                    FilenameUtils.getFullPath(file1.getAbsolutePath())
                                            + FilenameUtils.getBaseName(file1.getName()) + ".zip");
                            ArchiveOutputStream archiveOutputStream1 = new ArchiveStreamFactory()
                                    .createArchiveOutputStream(ArchiveStreamFactory.ZIP, outputStream1);
                            archiveOutputStream1.putArchiveEntry(new ZipArchiveEntry(file1, file1.getName()));
                            IOUtils.copy(new FileInputStream(file1), archiveOutputStream1);
                            archiveOutputStream1.closeArchiveEntry();
                            dir1 = new File(FilenameUtils.getFullPath(file1.getAbsolutePath())
                                    + FilenameUtils.getBaseName(file1.getName()));
                            files = (List<File>) FileUtils.listFiles(dir1, TrueFileFilter.INSTANCE,
                                    TrueFileFilter.INSTANCE);
                            for (File file3 : files) {
                                archiveOutputStream1.putArchiveEntry(new ZipArchiveEntry(file3, StringUtils
                                        .substringAfter(file3.getCanonicalPath(), string3 + File.separator)));
                                IOUtils.copy(new FileInputStream(file3), archiveOutputStream1);
                                archiveOutputStream1.closeArchiveEntry();
                            }
                            archiveOutputStream1.close();
                        }
                        bugfixGateIn = propertiesConfiguration1.getBoolean("bugfixGateIn", false);
                        string4 = bugfixGateIn
                                ? String.format("<img src=\"%s/namespace1/file-link?sessionId=%s&fileName=",
                                        portletRequest.getContextPath(),
                                        httpServletRequest.getSession().getId())
                                : String.format("<img src=\"%s/namespace1/file-link?fileName=",
                                        portletRequest.getContextPath());
                        result1 = StringUtils.replace(result1, "<img src=\"", string4);
                    } else {
                        inputStream1 = httpEntity1.getContent();
                        outputStream1 = new FileOutputStream(file1);
                        IOUtils.copy(inputStream1, outputStream1);
                        result1 = file1.getAbsolutePath();
                    }
                    return1 = SUCCESS;
                } else {
                    addActionError(String.format("%s %d: %s", getText("Error"), int1,
                            getText(Integer.toString(int1))));
                }
                dateTime2 = new org.joda.time.DateTime();
                period1 = new Period(dateTime1, dateTime2.plusSeconds(1));
                message1 = getText("Execution.time") + ": " + periodFormatter1.print(period1);
            } else {
                url1 = new URL(sid);
                uriBuilder1 = new URIBuilder(sid);
                uriBuilder1.setUserInfo(uid, pid);
                uriBuilder1.setPath(url1.getPath() + "/rest_v2/reports" + urlString + "/inputControls");
                uri1 = uriBuilder1.build();
                httpGet1 = new HttpGet(uri1);
                httpResponse1 = httpClient1.execute(httpGet1);
                int1 = httpResponse1.getStatusLine().getStatusCode();
                switch (int1) {
                case HttpStatus.SC_NO_CONTENT:
                    break;
                case HttpStatus.SC_OK:
                    httpEntity1 = httpResponse1.getEntity();
                    if (httpEntity1 != null) {
                        inputStream1 = httpEntity1.getContent();
                        if (inputStream1 != null) {
                            xmlConfiguration = new XMLConfiguration();
                            xmlConfiguration.load(inputStream1);
                            list1 = xmlConfiguration.configurationsAt("inputControl");
                            if (list1.size() > 0) {
                                listObject2 = new ArrayList<DataModel2>();
                                for (HierarchicalConfiguration hierarchicalConfiguration1 : list1) {
                                    string2 = hierarchicalConfiguration1.getString("type");
                                    dataModel2 = new DataModel2();
                                    dataModel2.setId(hierarchicalConfiguration1.getString("id"));
                                    dataModel2.setLabel1(hierarchicalConfiguration1.getString("label"));
                                    dataModel2.setType1(string2);
                                    dataModel2.setMandatory(hierarchicalConfiguration1.getBoolean("mandatory"));
                                    dataModel2.setReadOnly(hierarchicalConfiguration1.getBoolean("readOnly"));
                                    dataModel2.setVisible(hierarchicalConfiguration1.getBoolean("visible"));
                                    switch (string2) {
                                    case "bool":
                                    case "singleValueText":
                                    case "singleValueNumber":
                                    case "singleValueDate":
                                    case "singleValueDatetime":
                                        hierarchicalConfiguration2 = hierarchicalConfiguration1
                                                .configurationAt("state");
                                        dataModel2.setValue1(hierarchicalConfiguration2.getString("value"));
                                        break;
                                    case "singleSelect":
                                    case "singleSelectRadio":
                                    case "multiSelect":
                                    case "multiSelectCheckbox":
                                        hierarchicalConfiguration2 = hierarchicalConfiguration1
                                                .configurationAt("state");
                                        list2 = hierarchicalConfiguration2.configurationsAt("options.option");
                                        if (list2.size() > 0) {
                                            listObject3 = new ArrayList<DataModel1>();
                                            for (HierarchicalConfiguration hierarchicalConfiguration3 : list2) {
                                                dataModel1 = new DataModel1(
                                                        hierarchicalConfiguration3.getString("label"),
                                                        hierarchicalConfiguration3.getString("value"));
                                                if (hierarchicalConfiguration3.getBoolean("selected")) {
                                                    dataModel2.setValue1(
                                                            hierarchicalConfiguration3.getString("value"));
                                                }
                                                listObject3.add(dataModel1);
                                            }
                                            dataModel2.setOptions(listObject3);
                                        }
                                        break;
                                    default:
                                        break;
                                    }
                                    listObject2.add(dataModel2);
                                }
                            }
                        }
                    }
                    break;
                default:
                    addActionError(String.format("%s %d: %s", getText("Error"), int1,
                            getText(Integer.toString(int1))));
                    break;
                }
                if (httpEntity1 != null) {
                    EntityUtils.consume(httpEntity1);
                }
                uriBuilder1.setPath(url1.getPath() + "/rest/resource" + urlString);
                uri1 = uriBuilder1.build();
                httpGet1 = new HttpGet(uri1);
                httpResponse1 = httpClient1.execute(httpGet1);
                int2 = httpResponse1.getStatusLine().getStatusCode();
                if (int2 == HttpStatus.SC_OK) {
                    httpEntity1 = httpResponse1.getEntity();
                    inputStream1 = httpEntity1.getContent();
                    xmlConfiguration = new XMLConfiguration();
                    xmlConfiguration.load(inputStream1);
                    list1 = xmlConfiguration.configurationsAt("resourceDescriptor");
                    for (HierarchicalConfiguration hierarchicalConfiguration4 : list1) {
                        if (StringUtils.equalsIgnoreCase(
                                StringUtils.trim(hierarchicalConfiguration4.getString("[@wsType]")), "prop")) {
                            if (map1 == null)
                                map1 = new HashMap<String, String>();
                            string2 = StringUtils.substringBetween(
                                    StringUtils.substringAfter(
                                            hierarchicalConfiguration4.getString("[@uriString]"), "_files/"),
                                    "_", ".properties");
                            map1.put(string2,
                                    StringUtils.isBlank(string2) ? getText("Default") : getText(string2));
                        }
                    }
                }
                if (httpEntity1 != null) {
                    EntityUtils.consume(httpEntity1);
                }
            }
        } catch (IOException | ConfigurationException | URISyntaxException exception1) {
            exception1.printStackTrace();
            addActionError(exception1.getLocalizedMessage());
            httpGet1.abort();
            return ERROR;
        } finally {
            httpClient1.getConnectionManager().shutdown();
            IOUtils.closeQuietly(inputStream1);
        }
        break;
    default:
        addActionError(getText("This.file.type.is.not.supported"));
        break;
    }
    if (return1 != LOGIN) {
        sid = new String(Base64.encodeBase64(sid.getBytes()));
        uid = new String(Base64.encodeBase64(uid.getBytes()));
        pid = new String(Base64.encodeBase64(pid.getBytes()));
    }
    return return1;
}

From source file:com.constellio.app.services.appManagement.AppManagementService.java

File findDeployFolder(File parent, String version) {
    File deployFolder = null;//from w  w  w . jav  a 2s .c  om
    String mostRecentVersion = "";
    for (File currentWebApp : parent.listFiles(new WebAppWithValidSubversionFilenameFilter(version))) {
        String currentVersion = StringUtils.substringAfter(currentWebApp.getName(), "webapp-");
        if (mostRecentVersion.isEmpty()) {
            deployFolder = currentWebApp;
            mostRecentVersion = currentVersion;
        } else {
            if (VersionsComparator.isFirstVersionBeforeSecond(mostRecentVersion, currentVersion)) {
                deployFolder = currentWebApp;
                mostRecentVersion = currentVersion;
            }
        }
    }

    int nextSubVersion;
    if (mostRecentVersion.isEmpty()) {
        deployFolder = new File(parent, "webapp-" + version);
        nextSubVersion = 0;
    } else if (mostRecentVersion.contains("-")) {
        nextSubVersion = Integer.valueOf(mostRecentVersion.split("-")[1]);
    } else {
        nextSubVersion = 0;
    }
    nextSubVersion++;

    while (deployFolder.exists()) {
        deployFolder = new File(parent, "webapp-" + version + "-" + nextSubVersion);
        nextSubVersion++;
    }
    return deployFolder;
}

From source file:com.norconex.commons.lang.url.URLNormalizer.java

/**
 * <p>Removes a URL-based session id.  It removes PHP (PHPSESSID),
 * ASP (ASPSESSIONID), and Java EE (jsessionid) session ids.</p>
 * <code>http://www.example.com/servlet;jsessionid=1E6FEC0D14D044541DD84D2D013D29ED?a=b
 * &rarr; http://www.example.com/servlet?a=b</code>
 * <p><b>Please Note:</b> Removing session IDs from URLs is often 
 * a good way to have the URL return an error once invoked.</p>
 * @return this instance/*from w  w  w . j a v  a 2  s .  c  o  m*/
 */
public URLNormalizer removeSessionIds() {
    if (StringUtils.containsIgnoreCase(url, ";jsessionid=")) {
        url = url.replaceFirst("(;jsessionid=[0-9a-fA-F]*)", "");
    } else {
        String u = StringUtils.substringBefore(url, "?");
        String q = StringUtils.substringAfter(url, "?");
        if (StringUtils.containsIgnoreCase(url, "PHPSESSID=")) {
            q = q.replaceFirst("(&|^)(PHPSESSID=[0-9a-zA-Z]*)", "");
        } else if (StringUtils.containsIgnoreCase(url, "ASPSESSIONID")) {
            q = q.replaceFirst("(&|^)(ASPSESSIONID[a-zA-Z]{8}=[a-zA-Z]*)", "");
        }
        if (!StringUtils.isBlank(q)) {
            u += "?" + StringUtils.removeStart(q, "&");
        }
        url = u;
    }
    return this;
}

From source file:net.canadensys.dataportal.occurrence.controller.OccurrenceController.java

/**
 * Handle the received associated sequences string and fill the list in
 * OccurrenceViewModel if any./*from   w w w  . j a v a2 s .  com*/
 * 
 * @param occModel
 * @param occViewModel
 */
private void handleAssociatedSequence(OccurrenceModel occModel, OccurrenceViewModel occViewModel) {
    if (StringUtils.isEmpty(occModel.getAssociatedsequences())) {
        return;
    }

    String[] sequences = StringUtils.split(occModel.getAssociatedsequences(), ASSOCIATED_SEQUENCES_SEPARATOR);
    List<String> associatedSequences = Lists.newArrayList();

    String seqProvider, seqId, seqProviderUrlFormat;
    boolean knownFormat = false;
    for (String currentSequence : sequences) {
        seqProvider = StringUtils.substringBefore(currentSequence, ASSOCIATED_SEQUENCES_PROVIDER_SEPARATOR)
                .trim().toLowerCase();
        seqId = StringUtils.substringAfter(currentSequence, ASSOCIATED_SEQUENCES_PROVIDER_SEPARATOR).trim();
        seqProviderUrlFormat = appConfig.getSequenceProviderUrlFormat(seqProvider);
        knownFormat = StringUtils.isNotBlank(seqProviderUrlFormat);
        if (seqProvider != null && seqId != null && knownFormat) {
            associatedSequences.add(MessageFormat.format(seqProviderUrlFormat, seqId));
        } else {
            associatedSequences.add(currentSequence);
        }
    }

    Collections.sort(associatedSequences);
    occViewModel.setAssociatedSequences(associatedSequences);
}

From source file:com.constellio.app.services.appManagement.AppManagementService.java

private String getWarVersionFromFileName(File webAppFolder) {
    String folderName = webAppFolder.getName();
    if (folderName.startsWith("webapp-")) {
        return StringUtils.substringAfter(folderName, "webapp-");

    } else {/*from w w  w . ja  v  a2 s .  c  om*/
        return getWarVersion(webAppFolder);
    }
}