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

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

Introduction

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

Prototype

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

Source Link

Document

Gets the substring before the first occurrence of a separator.

Usage

From source file:io.cloudslang.lang.compiler.modeller.ExecutableBuilder.java

private String resolveDoReferenceId(String rawReferenceId, Map<String, String> imports, String namespace) {

    int numberOfDelimiters = StringUtils.countMatches(rawReferenceId, NAMESPACE_DELIMITER);
    String resolvedReferenceId;/*from w w  w.j  a v a2s . c  o  m*/

    if (numberOfDelimiters == 0) {
        // implicit namespace
        resolvedReferenceId = namespace + NAMESPACE_DELIMITER + rawReferenceId;
    } else {
        String prefix = StringUtils.substringBefore(rawReferenceId, NAMESPACE_DELIMITER);
        String suffix = StringUtils.substringAfter(rawReferenceId, NAMESPACE_DELIMITER);
        if (MapUtils.isNotEmpty(imports) && imports.containsKey(prefix)) {
            // expand alias
            resolvedReferenceId = imports.get(prefix) + NAMESPACE_DELIMITER + suffix;
        } else {
            // full path without alias expanding
            resolvedReferenceId = rawReferenceId;
        }
    }

    return resolvedReferenceId;
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.html.HTMLFormElementTest.java

private void enctypeTest(final String enctype, final String method, final String expectedCntType)
        throws Exception {
    final String html = "<html><head><script>\n" + "function test() {\n" + "  var f = document.forms[0];\n"
            + "  f.submit();\n" + "}\n" + "</script></head><body onload='test()'>\n"
            + "<form action='foo.html' enctype='" + enctype + "' method='" + method + "'>\n"
            + "  <input name='myField' value='some value'>\n" + "</form></body></html>";

    getMockWebConnection().setDefaultResponse("");
    loadPageWithAlerts2(html);/*from   w  w  w  .  j  a  va  2 s  . co  m*/
    String headerValue = getMockWebConnection().getLastWebRequest().getAdditionalHeaders().get("Content-Type");
    // Can't test equality for multipart/form-data as it will have the form:
    // multipart/form-data; boundary=---------------------------42937861433140731107235900
    headerValue = StringUtils.substringBefore(headerValue, ";");
    assertEquals(expectedCntType, headerValue);
}

From source file:com.google.dart.java2dart.engine.MainEngine.java

private static CompilationUnit buildResolverLibrary() throws Exception {
    CompilationUnit unit = new CompilationUnit(null, null, null, null, null);
    unit.getDirectives().add(libraryDirective("engine", "resolver"));
    unit.getDirectives().add(importDirective("dart:collection", null));
    unit.getDirectives().add(importDirective("dart:uri", null, importShowCombinator("Uri")));
    unit.getDirectives().add(importDirective("java_core.dart", null));
    unit.getDirectives().add(importDirective("java_engine.dart", null));
    unit.getDirectives().add(importDirective("instrumentation.dart", null));
    unit.getDirectives().add(importDirective("source.dart", null));
    unit.getDirectives().add(importDirective("error.dart", null));
    unit.getDirectives().add(importDirective("scanner.dart", "sc"));
    unit.getDirectives().add(importDirective("utilities_dart.dart", null));
    unit.getDirectives().add(importDirective("ast.dart", null));
    unit.getDirectives()/*from  w w w  .  ja  va 2 s .  c o m*/
            .add(importDirective("parser.dart", null, importShowCombinator("Parser", "ParserErrorCode")));
    unit.getDirectives().add(importDirective("sdk.dart", null, importShowCombinator("DartSdk")));
    unit.getDirectives().add(
            importDirective("element.dart", null, importHideCombinator("HideCombinator", "ShowCombinator")));
    unit.getDirectives().add(importDirective("html.dart", "ht"));
    unit.getDirectives().add(importDirective("engine.dart", null));
    unit.getDirectives().add(importDirective("constant.dart", null));
    for (CompilationUnitMember member : dartUnit.getDeclarations()) {
        File file = context.getMemberToFile().get(member);
        if (isEnginePath(file, "resolver/") || isEnginePath(file, "internal/resolver/")
                || isEnginePath(file, "internal/builder/") || isEnginePath(file, "internal/scope/")
                || isEnginePath(file, "internal/verifier/")) {
            unit.getDeclarations().add(member);
        }
    }
    // there is conflict between Hide/ShowCombinator classes in AST and Element, so tweak them
    unit.getDirectives().add(importDirective("element.dart", "__imp_combi",
            importShowCombinator("HideCombinator", "ShowCombinator")));
    unit.accept(new RecursiveASTVisitor<Void>() {
        @Override
        public Void visitTypeName(TypeName node) {
            ITypeBinding binding = context.getNodeTypeBinding(node);
            if (binding != null) {
                String shortName = binding.getName();
                shortName = StringUtils.substringBefore(shortName, "<");
                if (JavaUtils.isTypeNamed(binding, "com.google.dart.engine.element.HideCombinator")
                        || JavaUtils.isTypeNamed(binding, "com.google.dart.engine.element.ShowCombinator")) {
                    ((SimpleIdentifier) node.getName()).setToken(token("__imp_combi." + shortName));
                }
            }
            return super.visitTypeName(node);
        }
    });
    EngineSemanticProcessor.useImportPrefix(context, unit, "sc",
            new String[] { "com.google.dart.engine.scanner." });
    EngineSemanticProcessor.useImportPrefix(context, unit, "ht",
            new String[] { "com.google.dart.engine.html." });
    // done
    return unit;
}

From source file:com.gp.cong.logisoft.bc.fcl.SedFilingBC.java

public void readRespResponseFile(InputStream is, String aesFilesFolder, String aesResponseFileName)
        throws Exception {
    List<String> contents = FileUtils.readLines(new File(aesFilesFolder + aesResponseFileName));
    // Iterate the result to print each line of the file.
    String itn = "";
    String shipmentNumber = "";
    String status = "";
    String exception = "";
    if (null != contents && contents.size() > 0) {
        contents.remove(0);/*from  w w w.  j  ava  2  s.  c  o  m*/
    }
    for (String line : contents) {
        if (null != line && line.length() > 0) {
            String key = StringUtils.substringBefore(line, " ");
            shipmentNumber = StringUtils.substringBefore(key, "-") + "-"
                    + (StringUtils.substringAfterLast(key, "-").substring(0, 2));
            status += StringUtils.substringAfterLast(line, key).trim() + " ";
        }
    }
    status = StringUtils.removeEnd(status, " ");
    if (CommonUtils.isNotEmpty(shipmentNumber)) {
        FclBlDAO fclBlDAO = new FclBlDAO();
        String fileNo = shipmentNumber.contains("-") ? shipmentNumber.substring(0, shipmentNumber.indexOf("-"))
                : shipmentNumber;
        if (fileNo.length() > 6) {
            fileNo = fileNo.substring(2);
        }
        //String fileNo = shipmentNumber.contains("-") && shipmentNumber.length() > 2 ? shipmentNumber.substring(2, shipmentNumber.indexOf("-")) : shipmentNumber;
        FclBl fclBl = fclBlDAO.getFileNoObject(fileNo);
        LclFileNumber lclFileNumber = null;
        if (null == fclBl) {
            lclFileNumber = new LclFileNumberDAO().getByProperty("fileNumber", fileNo);
        }
        FclAESDetails fclAESDetails = new FclAESDetails();
        SedFilingsDAO sedFilingsDAO = new SedFilingsDAO();
        boolean hasAes = false;
        SedFilings sedFilings = sedFilingsDAO.findByTrnref(shipmentNumber.trim());
        if (null != sedFilings) {
            sedFilings.setItn(itn);
            if (status.contains("SUCCESSFULLY PROCESSED")) {
                sedFilings.setStatus("P");
            } else {
                sedFilings.setStatus("E");
            }
            AesHistory aesHistory = new AesHistory();
            if (null != fclBl) {
                aesHistory.setBolId(fclBl.getBol());
                aesHistory.setFclBlNo(fclBl.getBolId());
                for (Object object : fclBl.getFclAesDetails()) {
                    FclAESDetails aes = (FclAESDetails) object;
                    if (null != aes.getAesDetails() && aes.getAesDetails().equalsIgnoreCase(itn)) {
                        hasAes = true;
                        break;
                    }
                }
                if (!hasAes && CommonUtils.isNotEmpty(itn)) {
                    fclAESDetails.setAesDetails(itn);
                    fclAESDetails.setFileNo(fileNo);
                    fclAESDetails.setTrailerNoId(fclBl.getBol());
                    fclBl.getFclAesDetails().add(fclAESDetails);
                    fclBlDAO.update(fclBl);
                }
            } else if (null != lclFileNumber) {
                //aesHistory.setBolId(lclFileNumber.getId());
                aesHistory.setFclBlNo(lclFileNumber.getFileNumber());
            }
            aesHistory.setFileNumber(shipmentNumber);
            aesHistory.setAesException(exception);
            aesHistory.setFileNo(fileNo);
            aesHistory.setItn(itn);
            aesHistory.setStatus(status);
            aesHistory.setProcessedDate(new Date());
            byte[] bs = IOUtils.toByteArray(is);
            Blob blob = fclBlDAO.getSession().getLobHelper().createBlob(bs);
            aesHistory.setResponseFile(blob);
            new AesHistoryDAO().save(aesHistory);
            sedFilingsDAO.update(sedFilings);
        }
    }
}

From source file:Interface.FoodCollectionSupervisor.FoodCollectionWorkArea.java

private void btnFindingDriversActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFindingDriversActionPerformed
    // TODO add your handling code here:
    int selectedRow = tblNewRequest.getSelectedRow();
    int nearestMiles = 0;
    if (selectedRow < 0) {
        JOptionPane.showMessageDialog(null, "Please select the row from the table.");
        return;/* w  w w  .j a v a 2s  . c  o m*/
    }

    btnAssignRequest.setEnabled(false);
    btnFindingDrivers.setName("Finding closest drivers...");

    btnFindingDrivers.setEnabled(false);

    jScrollPane6.setVisible(true);
    FoodCollectionWorkRequest request = (FoodCollectionWorkRequest) tblNewRequest.getValueAt(selectedRow, 0);
    String pickupAddress = request.getSender().getEmployee().getAddress();
    DefaultTableModel model = (DefaultTableModel) tblRecommendationDriver.getModel();
    model.setRowCount(0);
    for (UserAccount ua : organization.getUserAccountDirectory().getUserAccountList()) {
        Employee ee = ua.getEmployee();
        if (ee instanceof FoodCollectionDriverEmployee) {
            try {
                if (nearestMiles == 3) {
                    break;
                }

                String driverCurrentLocation = ((FoodCollectionDriverEmployee) (ee)).getDriverCurrentAddress();
                String sourceAddress = pickupAddress;
                String myKey = "AIzaSyDxQT-LVz0VhlZN_4FZ4NaKoa63zeGIge0";

                driverCurrentLocation = driverCurrentLocation.replace(" ", "+");
                sourceAddress = sourceAddress.replace(" ", "+");

                String url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=#ORIGIN&destinations=#DESTINATION&mode=driving&units=imperial&language=fr-FR&key=#KEY";
                url = url.replace("#ORIGIN", driverCurrentLocation);
                url = url.replace("#DESTINATION", sourceAddress);
                url = url.replace("#KEY", myKey);

                // HttpURLConnectionExample http = new HttpURLConnectionExample();

                // System.out.println("Testing 1 - Send Http GET request");
                String json = sendGet(url);

                String a = StringUtils.substringBefore(json, "miles");
                String b = StringUtils.substringAfterLast(a, "\"");
                b = b.replace(",", ".");
                String distance = b + "miles";
                //System.out.println("Distance : " + b +" miles.");

                Double bInMiles = Double.parseDouble(b);
                if (bInMiles < 2.0) {
                    nearestMiles++;
                }

                Object[] row = new Object[3];
                row[0] = ua.getEmployee().getName();
                row[1] = ((FoodCollectionDriverEmployee) (ee)).getDriverCurrentAddress();
                row[2] = distance;

                model.addRow(row);

            } catch (Exception e) {
                System.out.println("Message :" + e.getMessage());
            }
        }

    }

    btnAssignRequest.setEnabled(true);
    btnFindingDrivers.setName("Recommendation for closest driver >>");
    btnFindingDrivers.setEnabled(true);

}

From source file:gov.anl.cue.arcane.engine.matrix.MatrixModel.java

/**
 * Export image render graph./*from  w  w  w .  j  a  v a 2 s.  c om*/
 *
 * @param graph the graph
 * @return the j frame
 * @throws HeadlessException the headless exception
 */
public JFrame exportImageRenderGraph(Graph<String, String> graph) throws HeadlessException {

    // Define the layout routine.
    Layout<String, String> layout = new CircleLayout<String, String>(graph);
    layout.setSize(new Dimension(700, 700));

    // Create the visualization server.
    BasicVisualizationServer<String, String> visualizationServer = new BasicVisualizationServer<String, String>(
            layout);
    visualizationServer.setPreferredSize(layout.getSize());

    // Setup the vertex labeler.
    visualizationServer.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<String>());

    // Setup the edge labeler.
    visualizationServer.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller<String>());
    visualizationServer.getRenderContext().setEdgeLabelTransformer(new Transformer<String, String>() {
        public String transform(String string) {
            return StringUtils.substringBefore(string, "(");
        }
    });

    // Setup the rendering frame.
    JFrame frame = new JFrame("ARCANE Graph");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(visualizationServer);
    frame.pack();

    // Return the results.
    return frame;

}

From source file:com.gargoylesoftware.htmlunit.WebClient.java

private WebResponse makeWebResponseForAboutUrl(final URL url) {
    final String urlWithoutQuery = StringUtils.substringBefore(url.toExternalForm(), "?");
    if (!"blank".equalsIgnoreCase(StringUtils.substringAfter(urlWithoutQuery, "about:"))) {
        throw new IllegalArgumentException(url + " is not supported, only about:blank is supported now.");
    }/*ww w .  j  a v  a2s . c  o m*/
    return new StringWebResponse("", URL_ABOUT_BLANK);
}

From source file:me.ryanhamshire.griefprevention.DataStore.java

public Text parseMessage(Messages messageID, TextColor color, String... args) {
    String message = GriefPreventionPlugin.instance.dataStore.getMessage(messageID, args);
    Text textMessage = Text.of(color, message);
    List<String> urls = extractUrls(message);
    if (urls.isEmpty()) {
        return textMessage;
    }//from  ww w.  j  av a  2  s .  c om

    Iterator<String> iterator = urls.iterator();
    while (iterator.hasNext()) {
        String url = iterator.next();
        String msgPart = StringUtils.substringBefore(message, url);

        if (msgPart != null && !msgPart.equals("")) {
            try {
                textMessage = Text.of(color, msgPart, TextColors.GREEN, TextActions.openUrl(new URL(url)), url);
            } catch (MalformedURLException e) {
                e.printStackTrace();
                return Text.of(message);
            }
        }

        iterator.remove();
        message = StringUtils.substringAfter(message, url);
    }

    if (message != null && !message.equals("")) {
        textMessage = Text.of(textMessage, " ", color, message);
    }

    return textMessage;
}

From source file:com.google.dart.java2dart.SyntaxTranslator.java

private TypeName translateTypeName(ITypeBinding binding) {
    if (binding != null) {
        if (binding.isArray()) {
            return typeName(identifier("List"), translateTypeName(binding.getComponentType()));
        }//from  ww w. j  a  va2  s. co  m
        String name = binding.getName();
        name = StringUtils.substringBefore(name, "<");
        if (JavaUtils.isTypeNamed(binding, "java.util.ArrayList")) {
            name = "List";
        }
        if (JavaUtils.isTypeNamed(binding, "java.lang.Void")) {
            name = "Object";
        }
        if ("boolean".equals(name)) {
            return typeName("bool");
        }
        List<TypeName> arguments = Lists.newArrayList();
        for (ITypeBinding typeArgument : binding.getTypeArguments()) {
            arguments.add(translateTypeName(typeArgument));
        }
        TypeName result = typeName(identifier(name), arguments);
        context.putNodeTypeBinding(result, binding);
        context.putNodeTypeBinding(result.getName(), binding);
        putReference(binding, (SimpleIdentifier) result.getName());
        return result;
    }
    throw new IllegalArgumentException("" + binding);
}

From source file:com.sonicle.webtop.mail.Service.java

public SharedPrincipal getSharedPrincipal(String domainId, String mailUserId) {
    SharedPrincipal p = null;// w w  w. j  ava 2s  .  c  om
    Connection con = null;
    try {
        con = getConnection();
        logger.debug("looking for shared folder map on {}@{}", mailUserId, domainId);
        OUserMap omap = UserMapDAO.getInstance().selectFirstByMailUser(con, domainId, mailUserId);
        OUser ouser;
        if (omap != null) {
            logger.debug("found mapping : {}", omap.getUserId());
            //get mapped webtop user
            ouser = UserDAO.getInstance().selectByDomainUser(con, domainId, omap.getUserId());
        } else {
            //remove @domain if present
            mailUserId = StringUtils.substringBefore(mailUserId, "@");
            logger.debug("mapping not found, looking for a webtop user with id = {}", mailUserId);
            //try looking for a webtop user with userId=mailUserId
            ouser = UserDAO.getInstance().selectByDomainUser(con, domainId, mailUserId);
        }

        String desc = null;
        if (ouser != null) {
            desc = LangUtils.value(ouser.getDisplayName(), "");
        } else {
            String email = mailUserId;
            if (email.indexOf("@") < 0)
                email += "@" + WT.getDomainInternetName(domainId);
            UserProfile.Data udata = WT.guessUserData(email);
            if (udata != null)
                desc = LangUtils.value(udata.getDisplayName(), "");
        }

        if (desc != null) {
            logger.debug("webtop user found, desc={}", desc);
            p = new SharedPrincipal(mailUserId, desc.trim());
        } else {
            logger.debug("webtop user not found, creating unmapped principal");
            p = new SharedPrincipal(mailUserId, mailUserId);
        }

    } catch (SQLException exc) {
        logger.error("Error finding principal for {}@{}", mailUserId, domainId, exc);
    } finally {
        DbUtils.closeQuietly(con);
    }
    return p;
}