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

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

Introduction

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

Prototype

public static String removeEnd(final String str, final String remove) 

Source Link

Document

Removes a substring only if it is at the end of a source string, otherwise returns the source string.

A null source string will return null .

Usage

From source file:io.wcm.maven.plugins.contentpackage.DownloadMojo.java

/**
 * Download content package from CRX instance
 *///  ww  w .  j  a  v a 2s . c o m
private File downloadFile(File file, String ouputFilePath) throws MojoExecutionException {
    try (CloseableHttpClient httpClient = getHttpClient()) {
        getLog().info("Download " + file.getName() + " from " + getCrxPackageManagerUrl());

        // 1st: try upload to get path of package - or otherwise make sure package def exists (no install!)
        HttpPost post = new HttpPost(getCrxPackageManagerUrl() + "/.json?cmd=upload");
        MultipartEntityBuilder entity = MultipartEntityBuilder.create().addBinaryBody("package", file)
                .addTextBody("force", "true");
        post.setEntity(entity.build());
        JSONObject jsonResponse = executePackageManagerMethodJson(httpClient, post);
        boolean success = jsonResponse.optBoolean("success", false);
        String msg = jsonResponse.optString("msg", null);
        String path = jsonResponse.optString("path", null);

        // package already exists - get path from error message and continue
        if (!success && StringUtils.startsWith(msg, CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX)
                && StringUtils.isEmpty(path)) {
            path = StringUtils.substringAfter(msg, CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX);
            success = true;
        }
        if (!success) {
            throw new MojoExecutionException("Package path detection failed: " + msg);
        }

        getLog().info("Package path is: " + path + " - now rebuilding package...");

        // 2nd: build package
        HttpPost buildMethod = new HttpPost(getCrxPackageManagerUrl() + "/console.html" + path + "?cmd=build");
        executePackageManagerMethodHtml(httpClient, buildMethod, 0);

        // 3rd: download package
        String crxUrl = StringUtils.removeEnd(getCrxPackageManagerUrl(), "/crx/packmgr/service");
        HttpGet downloadMethod = new HttpGet(crxUrl + path);

        // execute download
        CloseableHttpResponse response = httpClient.execute(downloadMethod);
        try {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                // get response stream
                InputStream responseStream = response.getEntity().getContent();

                // delete existing file
                File outputFileObject = new File(ouputFilePath);
                if (outputFileObject.exists()) {
                    outputFileObject.delete();
                }

                // write response file
                FileOutputStream fos = new FileOutputStream(outputFileObject);
                IOUtil.copy(responseStream, fos);
                fos.flush();
                responseStream.close();
                fos.close();

                getLog().info("Package downloaded to " + outputFileObject.getAbsolutePath());

                return outputFileObject;
            } else {
                throw new MojoExecutionException(
                        "Package download failed:\n" + EntityUtils.toString(response.getEntity()));
            }
        } finally {
            if (response != null) {
                EntityUtils.consumeQuietly(response.getEntity());
                try {
                    response.close();
                } catch (IOException ex) {
                    // ignore
                }
            }
        }
    } catch (FileNotFoundException ex) {
        throw new MojoExecutionException("File not found: " + file.getAbsolutePath(), ex);
    } catch (IOException ex) {
        throw new MojoExecutionException("Download operation failed.", ex);
    }
}

From source file:io.wcm.maven.plugins.contentpackage.AbstractContentPackageMojo.java

protected final String getCrxPackageManagerUrl() {
    String serviceUrl = this.serviceURL;
    // convert "legacy interface URL" with service.jsp to new CRX interface (since CRX 2.1)
    serviceUrl = StringUtils.replace(serviceUrl, "/crx/packmgr/service.jsp", "/crx/packmgr/service");
    // remove /.json suffix if present
    serviceUrl = StringUtils.removeEnd(serviceUrl, "/.json");
    return serviceUrl;
}

From source file:info.magnolia.security.app.dialog.field.AccessControlList.java

private Entry doGetEntryFromNode(Node entryNode) throws RepositoryException {
    long permissions = entryNode.getProperty(PERMISSIONS_PROPERTY_NAME).getLong();
    String path = entryNode.getProperty(PATH_PROPERTY_NAME).getString();

    long accessType;

    if (path.endsWith("/*")) {
        accessType = ACCESS_TYPE_CHILDREN;
        path = path.equals("/*") ? "/" : StringUtils.substringBeforeLast(path, "/*");
    } else {//from  w  w  w  . j a  v a 2s  . co m
        accessType = ACCESS_TYPE_NODE;
        path = path.equals("/") ? path : StringUtils.removeEnd(path, "/");
    }

    return new Entry(permissions, accessType, path);
}

From source file:info.magnolia.security.setup.migration.MoveAclPermissionsBetweenWorkspaces.java

/**
 * Rename the ACL node and check the related permission path.
 *///w w w  .  j  av a2  s . c o  m
private void handleAclNode(Session targetSession, Node aclNode, String newAclNodeName,
        InstallContext installContext) throws RepositoryException {
    // If node already exist, return
    final Node parent = aclNode.getParent();
    final String newAclPath = NodeUtil.combinePathAndName(parent.getPath(), newAclNodeName);
    if (aclNode.getSession().nodeExists(newAclPath)) {
        log.warn("{} already exist. No migration will be performed.", newAclPath);
        return;
    }

    // Rename node
    String oldAclNodePath = aclNode.getPath();
    NodeUtil.renameNode(aclNode, newAclNodeName);
    log.info("The following ACL node '{}' was succesfully renamed to '{}'", oldAclNodePath, aclNode.getPath());
    // Check the permission path
    Iterator<Node> childNodeIterator = NodeUtil
            .collectAllChildren(aclNode, new NodePropertyNamePredicate("path")).iterator();
    // Iterate child and check if the path is still valid
    while (childNodeIterator.hasNext()) {
        Property pathProperty = childNodeIterator.next().getProperty("path");
        String originalPath = pathProperty.getString();
        String extraParameter = getExtraAclParameter(originalPath);
        String pathToHandle = StringUtils.removeEnd(originalPath, extraParameter);
        // If the path is blank, handle the next one.
        if (StringUtils.isBlank(pathToHandle)) {
            continue;
        }

        // Check if the path is well-formed
        if (!isPathWellFormed(targetSession, pathToHandle)) {
            log.info("Following ACL link is not a well-formed path '{}'. ", originalPath);
        } else if (!targetSession.itemExists(pathToHandle)) {
            // Path is well-formed but not valid
            handleNoNoValidACLPath(targetSession, pathToHandle, extraParameter, pathProperty, installContext);
        } else {
            log.info("Following ACL link is valid '{}'. ", originalPath);
        }
    }
}

From source file:com.opensymphony.xwork2.util.finder.UrlSet.java

/**
 * Try to find a classes directory inside a war file add its normalized url to this set
 *//*from  w  w  w  . j  a va 2s .  c  o m*/
public UrlSet includeClassesUrl(ClassLoaderInterface classLoaderInterface, FileProtocolNormalizer normalizer)
        throws IOException {
    Enumeration<URL> rootUrlEnumeration = classLoaderInterface.getResources("");
    while (rootUrlEnumeration.hasMoreElements()) {
        URL url = rootUrlEnumeration.nextElement();
        String externalForm = StringUtils.removeEnd(url.toExternalForm(), "/");
        if (externalForm.endsWith(".war/WEB-INF/classes")) {
            //if it is inside a war file, get the url to the file
            externalForm = StringUtils.substringBefore(externalForm, "/WEB-INF/classes");
            URL warUrl = new URL(externalForm);
            URL normalizedUrl = normalizer.normalizeToFileProtocol(warUrl);
            URL finalUrl = ObjectUtils.defaultIfNull(normalizedUrl, warUrl);

            Map<String, URL> newUrls = new HashMap<String, URL>(this.urls);
            if ("jar".equals(finalUrl.getProtocol()) || "file".equals(finalUrl.getProtocol())) {
                newUrls.put(finalUrl.toExternalForm(), finalUrl);
            }
            return new UrlSet(newUrls);
        }
    }

    return this;
}

From source file:com.nesscomputing.httpserver.jetty.TestClasspathResourceHandler.java

@Test
public void testIfModified() throws Exception {
    final AtomicReference<String> holder = new AtomicReference<String>(null);
    final HttpClientResponseHandler<String> responseHandler = new ContentResponseHandler<String>(
            new StringContentConverter() {
                @Override//from  w  w w  .j  av  a  2  s.com
                public String convert(final HttpClientResponse response, final InputStream inputStream)
                        throws IOException {
                    holder.set(response.getHeader("Last-Modified"));
                    return super.convert(response, inputStream);
                }
            });

    final String uri = baseUri + "/simple-content.txt";
    final String content = httpClient.get(uri, responseHandler).perform();

    Assert.assertNotNull(holder.get());
    Assert.assertEquals("this is simple content for a simple test\n", content);

    final HttpClientResponseHandler<String> responseHandler2 = new ContentResponseHandler<String>(
            new StringContentConverter() {
                @Override
                public String convert(final HttpClientResponse response, final InputStream inputStream)
                        throws IOException {
                    Assert.assertEquals(304, response.getStatusCode());
                    return null;
                }
            });

    final String content2 = httpClient.get(uri, responseHandler2).addHeader("If-Modified-Since", holder.get())
            .perform();

    Assert.assertNull(content2);

    // "Time zone names ('z') cannot be parsed."  so we hack it by hand, assuming GMT  >:(
    final DateTimeFormatter httpFormat = DateTimeFormat.forPattern("EEE, dd MMM YYYY HH:mm:ss");
    final long newModified = httpFormat.parseMillis(StringUtils.removeEnd(holder.get(), " GMT")) - 600000;
    httpClient.get(uri, Valid2xxContentConverter.DEFAULT_FAILING_RESPONSE_HANDLER)
            .addHeader("If-Modified-Since", httpFormat.print(newModified) + " GMT").perform();
}

From source file:de.tuberlin.uebb.jbop.access.ClassAccessor.java

/**
 * Rename the given Class./*from ww  w . j  a v  a2  s .c om*/
 * 
 * Exactly the suffix <code>suffix</code> is added to the Classname
 * and every internal reference is updated to the new name.
 * 
 * @param classDescriptor
 *          the classDescriptor
 * @param suffix
 *          the suffix
 * @return the new ClassDescriptor with the renamed class
 */
public static ClassDescriptor rename(final ClassDescriptor classDescriptor, final String suffix) {
    final String newName = classDescriptor.getName() + suffix;
    final ClassReader classReader = new ClassReader(classDescriptor.getClassData());
    final ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
    final ClassRenamer renamer = new ClassRenamer(writer, newName.replace(".", "/"));
    classReader.accept(renamer, 0);
    final byte[] renamedClassBytes = renamer.toByteArray();

    final ClassDescriptor out = new ClassDescriptor(newName, renamedClassBytes,
            StringUtils.removeEnd(classDescriptor.getFile(), ".class") + suffix + ".class");
    return out;
}

From source file:de.tuberlin.uebb.jbop.optimizer.utils.ClassNodeBuilderTextifier.java

/**
 * Prints a disassembled view of the given annotation.
 * /* ww w. j av a  2 s . co m*/
 * @param desc
 *          the class descriptor of the annotation class.
 * @param visible
 *          <tt>true</tt> if the annotation is visible at runtime.
 * @return a visitor to visit the annotation values.
 */
@Override
public Textifier visitAnnotation(final String desc, final boolean visible) {
    buf.setLength(0);
    buf.append("withAnnotation(");
    buf.append(StringUtils.replace(StringUtils.removeEnd(StringUtils.removeStart(desc, "L"), ";"), "/", "."));
    buf.append(".class");
    text.add(buf.toString());
    text.add(").//\n");
    return createTextifier();
}

From source file:ke.co.tawi.babblesms.server.sendsms.tawismsgw.PostSMS.java

/**
 * //from   w ww.j a v a  2 s . c  om
 */
@Override
public void run() {
    HttpEntity responseEntity = null;
    Map<String, String> params;

    if (urlValidator.isValid(smsGateway.getUrl())) {

        // Prepare the parameters to send
        params = new HashMap<>();

        params.put("username", smsGateway.getUsername());
        params.put("password", smsGateway.getPasswd());
        params.put("source", smsSource.getSource());
        params.put("message", message);

        switch (smsSource.getNetworkuuid()) {
        case Network.SAFARICOM_KE:
            params.put("network", "safaricom_ke");
            break;

        case Network.AIRTEL_KE:
            params.put("network", "safaricom_ke"); // TODO: change to airtel_ke
            break;
        }

        // When setting the destination, numbers beginning with '07' are edited
        // to begin with '254'
        phoneMap = new HashMap<>();
        StringBuffer phoneBuff = new StringBuffer();
        String phoneNum;

        for (Phone phone : phoneList) {
            phoneNum = phone.getPhonenumber();

            if (StringUtils.startsWith(phoneNum, "07")) {
                phoneNum = "254" + StringUtils.substring(phoneNum, 1);
            }

            phoneMap.put(phoneNum, phone);
            phoneBuff.append(phoneNum).append(";");
        }

        params.put("destination", StringUtils.removeEnd(phoneBuff.toString(), ";"));

        // Push to the URL
        try {
            URL url = new URL(smsGateway.getUrl());

            if (StringUtils.equalsIgnoreCase(url.getProtocol(), "http")) {
                responseEntity = doPost(smsGateway.getUrl(), params, retry);

            }
            //            else if(StringUtils.equalsIgnoreCase(url.getProtocol(), "https")) {
            //               doPostSecure(smsGateway.getUrl(), params, retry);
            //            }

        } catch (MalformedURLException e) {
            logger.error("MalformedURLException for URL: '" + smsGateway.getUrl() + "'");
            logger.error(ExceptionUtils.getStackTrace(e));
        }
    } // end 'if(urlValidator.isValid(urlStr))'

    // Process the response from the SMS Gateway
    // Assuming all is ok, it would have the following pattern:
    // requestStatus=ACCEPTED&messageIds=254726176878:b265ce23;254728932844:367941a36d2e4ef195;254724300863:11fca3c5966d4d
    if (responseEntity != null) {

        OutgoingLog outgoingLog;

        try {
            String response = EntityUtils.toString(responseEntity);
            GatewayDAO.getInstance().logResponse(account, response, new Date());

            String[] strTokens = StringUtils.split(response, '&');
            String tmpStr = "", dateStr = "";
            for (String str : strTokens) {
                if (StringUtils.startsWith(str, "messageIds")) {
                    tmpStr = StringUtils.removeStart(str, "messageIds=");
                } else if (StringUtils.startsWith(str, "datetime")) {
                    dateStr = StringUtils.removeStart(str, "datetime=");
                }
            }

            strTokens = StringUtils.split(tmpStr, ';');
            String phoneStr, uuid;
            Phone phone;
            DateTimeFormatter timeFormatter = ISODateTimeFormat.dateTimeNoMillis();

            for (String str : strTokens) {
                phoneStr = StringUtils.split(str, ':')[0];
                uuid = StringUtils.split(str, ':')[1];
                phone = phoneMap.get(phoneStr);

                outgoingLog = new OutgoingLog();
                outgoingLog.setUuid(uuid);
                outgoingLog.setOrigin(smsSource.getSource());
                outgoingLog.setMessage(message);
                outgoingLog.setDestination(phone.getPhonenumber());
                outgoingLog.setNetworkUuid(phone.getNetworkuuid());
                outgoingLog.setMessagestatusuuid(MsgStatus.SENT);
                outgoingLog.setSender(account.getUuid());
                outgoingLog.setPhoneUuid(phone.getUuid());

                // Set the date of the OutgoingLog to match the SMS Gateway time

                LocalDateTime datetime = timeFormatter.parseLocalDateTime(dateStr);
                outgoingLog.setLogTime(datetime.toDate());

                outgoingLogDAO.put(outgoingLog);
            }

        } catch (ParseException e) {
            logger.error("ParseException when reading responseEntity");
            logger.error(ExceptionUtils.getStackTrace(e));

        } catch (IOException e) {
            logger.error("IOException when reading responseEntity");
            logger.error(ExceptionUtils.getStackTrace(e));
        }
    }
}

From source file:alfio.manager.PaypalManager.java

public String createCheckoutRequest(Event event, String reservationId, OrderSummary orderSummary,
        CustomerName customerName, String email, String billingAddress, Locale locale,
        boolean postponeAssignment) throws Exception {

    APIContext apiContext = getApiContext(event);

    Optional<String> experienceProfileId = getOrCreateWebProfile(event, locale, apiContext);

    List<Transaction> transactions = buildPaymentDetails(event, orderSummary, reservationId, locale);
    String eventName = event.getShortName();

    Payer payer = new Payer();
    payer.setPaymentMethod("paypal");

    Payment payment = new Payment();
    payment.setIntent("sale");
    payment.setPayer(payer);/*from   w  w  w .  j a  va 2s.  c om*/
    payment.setTransactions(transactions);
    RedirectUrls redirectUrls = new RedirectUrls();

    String baseUrl = StringUtils.removeEnd(
            configurationManager.getRequiredValue(
                    Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.BASE_URL)),
            "/");
    String bookUrl = baseUrl + "/event/" + eventName + "/reservation/" + reservationId + "/book";

    UriComponentsBuilder bookUrlBuilder = UriComponentsBuilder.fromUriString(bookUrl)
            .queryParam("fullName", customerName.getFullName())
            .queryParam("firstName", customerName.getFirstName())
            .queryParam("lastName", customerName.getLastName()).queryParam("email", email)
            .queryParam("billingAddress", billingAddress).queryParam("postponeAssignment", postponeAssignment)
            .queryParam("hmac", computeHMAC(customerName, email, billingAddress, event));
    String finalUrl = bookUrlBuilder.toUriString();

    redirectUrls.setCancelUrl(finalUrl + "&paypal-cancel=true");
    redirectUrls.setReturnUrl(finalUrl + "&paypal-success=true");
    payment.setRedirectUrls(redirectUrls);

    experienceProfileId.ifPresent(payment::setExperienceProfileId);

    Payment createdPayment = payment.create(apiContext);

    TicketReservation reservation = ticketReservationRepository.findReservationById(reservationId);
    //add 15 minutes of validity in case the paypal flow is slow
    ticketReservationRepository.updateValidity(reservationId,
            DateUtils.addMinutes(reservation.getValidity(), 15));

    if (!"created".equals(createdPayment.getState())) {
        throw new Exception(createdPayment.getFailureReason());
    }

    //extract url for approval
    return createdPayment.getLinks().stream().filter(l -> "approval_url".equals(l.getRel())).findFirst()
            .map(Links::getHref).orElseThrow(IllegalStateException::new);

}