Example usage for org.apache.commons.lang StringUtils split

List of usage examples for org.apache.commons.lang StringUtils split

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils split.

Prototype

public static String[] split(String str, String separatorChars) 

Source Link

Document

Splits the provided text into an array, separators specified.

Usage

From source file:com.jaeksoft.searchlib.crawler.FieldMap.java

public FieldMap(String multilineText, char fieldSeparator, char concatSeparator) throws IOException {
    StringReader sr = null;/*from  w  w w.  j a v a 2 s .  com*/
    BufferedReader br = null;
    this.concatSeparator = concatSeparator;
    try {
        sr = new StringReader(multilineText);
        br = new BufferedReader(sr);
        String line;
        while ((line = br.readLine()) != null) {
            String[] cols = StringUtils.split(line, fieldSeparator);
            if (cols == null || cols.length < 2)
                continue;
            String source = cols[0];
            String target = cols[1];
            String analyzer = cols.length > 2 ? cols[2] : null;
            Float boost = cols.length > 3 ? Float.parseFloat(cols[3]) : null;
            add(new SourceField(source, concatSeparator), new TargetField(target, analyzer, boost, null));
        }
    } finally {
        IOUtils.close(br, sr);
    }
}

From source file:gov.nih.nci.cacis.cdw.CDWPendingLoader.java

public void loadPendingCDWDocuments(CDWLoader loader) {
    LOG.debug("Pending folder: " + cdwLoadPendingDirectory);
    LOG.info("SSSSSSS STARTED CDW LOAD SSSSSSSS");
    File pendingFolder = new File(cdwLoadPendingDirectory);
    FilenameFilter loadFileFilter = new FilenameFilter() {

        public boolean accept(File dir, String name) {
            return true;
        }// ww w  .  j a  v  a  2  s. co m
    };
    String[] loadFileNames = pendingFolder.list(loadFileFilter);
    LOG.info("Total Files to Load: " + loadFileNames.length);
    int filesLoaded = 0;
    int fileNumber = 0;
    for (String fileName : loadFileNames) {
        fileNumber++;
        LOG.info("Processing File [" + fileNumber + "] " + fileName);
        File loadFile = new File(cdwLoadPendingDirectory + "/" + fileName);
        try {
            final String[] params = StringUtils.split(fileName, "@@");
            String siteId = params[0];
            String studyId = params[1];
            String patientId = params[2];
            LOG.debug("SiteId: " + siteId);

            // the below code is not working, so parsing the file name for attributes.
            // DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            // DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            // Document document = documentBuilder.parse(loadFile);
            // XPathFactory factory = XPathFactory.newInstance();
            // XPath xPath = factory.newXPath();
            // String siteID = xPath.evaluate("/caCISRequest/clinicalMetaData/@siteIdRoot", document);

            loader.load(FileUtils.getStringFromFile(loadFile), loader.generateContext(), studyId, siteId,
                    patientId);
            LOG.info(String.format("Successfully processed file [%s] [%s] and moving into [%s]", fileNumber,
                    loadFile.getAbsolutePath(), cdwLoadProcessedDirectory));
            org.apache.commons.io.FileUtils.moveFileToDirectory(loadFile, new File(cdwLoadProcessedDirectory),
                    true);
            filesLoaded++;
        } catch (Exception e) {
            LOG.error(e.getMessage());
            e.printStackTrace();
            try {
                Properties props = new Properties();
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.smtp.host", cdwLoadSenderHost);
                props.put("mail.smtp.port", cdwLoadSenderPort);

                Session session = Session.getInstance(props, new javax.mail.Authenticator() {

                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(cdwLoadSenderUser, cdwLoadSenderPassword);
                    }
                });
                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress(cdwLoadSenderAddress));
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(cdwLoadRecipientAddress));
                message.setSubject(cdwLoadNotificationSubject);
                message.setText(cdwLoadNotificationMessage + " [" + e.getMessage() + "]");

                Transport.send(message);
                org.apache.commons.io.FileUtils.moveFileToDirectory(loadFile, new File(cdwLoadErrorDirectory),
                        true);
                // TODO add logic to send email
            } catch (Exception e1) {
                LOG.error(e1.getMessage());
                e1.printStackTrace();
            }
        }
    }
    LOG.info("Files Successfully Loaded: " + filesLoaded);
    LOG.info("EEEEEEE ENDED CDW LOAD EEEEEEE");
}

From source file:com.jaeksoft.searchlib.analysis.filter.NamedEntityExtractionFilter.java

@Override
public TokenStream create(TokenStream tokenStream) throws SearchLibException {
    Client indexClient = ClientCatalog.getClient(indexName);
    NamedEntityExtractionRequest request = (NamedEntityExtractionRequest) indexClient
            .getNewRequest(requestName);
    if (!StringUtils.isEmpty(returnField))
        request.setReturnedFields(StringUtils.split(returnField, '|'));
    for (FilterFactory filter : request.getFilterList(null))
        tokenStream = filter.create(tokenStream);
    return tokenStream;
}

From source file:cn.hxh.springside.orm.PageRequest.java

/**
 * ??.// w w  w  .j  av  a 2  s .c  o m
 */
public List<Sort> getSort() {
    String[] orderBys = StringUtils.split(orderBy, ',');
    String[] orderDirs = StringUtils.split(orderDir, ',');
    AssertUtils.isTrue(orderBys.length == orderDirs.length,
            "???,????");

    List<Sort> orders = Lists.newArrayList();
    for (int i = 0; i < orderBys.length; i++) {
        orders.add(new Sort(orderBys[i], orderDirs[i]));
    }

    return orders;
}

From source file:jp.ac.tokushima_u.is.ll.common.orm.PropertyFilter.java

/**
 * @param filterName ,???. // ww  w  .j a  v  a 2 s . co m
 *                   eg. LIKES_NAME_OR_LOGIN_NAME
 * @param value .
 */
public PropertyFilter(final String filterName, final Object value) {

    String matchTypeStr = StringUtils.substringBefore(filterName, "_");
    String matchTypeCode = StringUtils.substring(matchTypeStr, 0, matchTypeStr.length() - 1);
    String propertyTypeCode = StringUtils.substring(matchTypeStr, matchTypeStr.length() - 1,
            matchTypeStr.length());
    try {
        matchType = Enum.valueOf(MatchType.class, matchTypeCode);
    } catch (RuntimeException e) {
        throw new IllegalArgumentException(
                "filter??" + filterName + ",.", e);
    }

    try {
        propertyType = Enum.valueOf(PropertyType.class, propertyTypeCode).getValue();
    } catch (RuntimeException e) {
        throw new IllegalArgumentException(
                "filter??" + filterName + ",.", e);
    }

    String propertyNameStr = StringUtils.substringAfter(filterName, "_");
    propertyNames = StringUtils.split(propertyNameStr, PropertyFilter.OR_SEPARATOR);

    Assert.isTrue(propertyNames.length > 0,
            "filter??" + filterName + ",??.");
    //entity property.
    this.propertyValue = ReflectionUtils.convertValue(value, propertyType);
}

From source file:info.magnolia.module.delta.AbstractConditionalRepositoryTask.java

/**
 * {@inheritDoc}/*from  w  w  w  .j a va  2 s .c  o m*/
 */
@Override
public void execute(InstallContext ctx) throws TaskExecutionException {

    boolean executeTask = false;

    String[] tokens = StringUtils.split(getCheckedPath(), ":");
    if (tokens.length != 2) {
        log.error("Invalid checked path " + getCheckedPath() + " in " + this + ". Task will not be performed");
    }
    HierarchyManager hm = ctx.getHierarchyManager(tokens[0]);

    if (hm == null) {
        log.error("Repository " + tokens[0] + " requested in " + this
                + " not available. Task will not be performed");
    } else {
        try {
            hm.getContent(tokens[1]);
        } catch (PathNotFoundException e) {
            // ok, this is expected
            executeTask = true;
        } catch (RepositoryException e) {
            throw new TaskExecutionException("Could not execute task: " + e.getMessage(), e);
        }
    }
    if (executeTask) {
        try {
            doExecute(ctx);
        } catch (RepositoryException re) {
            throw new TaskExecutionException("Could not execute task: " + re.getMessage(), re);
        }
    }
}

From source file:com.rsmart.kuali.kfs.fp.batch.DisbursementVoucherInputFileType.java

/**
 * @see org.kuali.kfs.sys.batch.BatchInputType#getAuthorPrincipalName(java.io.File)
 *//*from   ww w  .  ja  v  a 2s  . c om*/
public String getAuthorPrincipalName(File file) {
    String[] fileNameParts = StringUtils.split(file.getName(), "_");
    if (fileNameParts.length > 3) {
        return fileNameParts[2];
    }
    return null;
}

From source file:com.mmj.app.web.controller.upload.FileUploadController.java

@RequestMapping(value = "/link/pic/upload")
public ModelAndView picUpload(String identifie, @RequestParam("imgUrl") MultipartFile... files) {
    ModelAndView mav = new ModelAndView("return");
    mav.getModel().put(CustomVelocityLayoutView.USE_LAYOUT, "false");

    if (files == null || files.length <= 0) {
        return returnErrorJson(mav);
    }//from   w ww  .ja  v a 2 s  .c  o m
    List<String> urlList = new ArrayList<String>();
    for (int i = 0; i < files.length; i++) {
        Result result = fileService.createFilePath(files[i]);
        if (result == null || result.getData() == null) {
            return returnErrorJson(mav);
        }
        urlList.add((String) result.getData());
    }
    String imgUrl = urlList.get(0);
    String[] urlArray = StringUtils.split(imgUrl, ".");
    imgUrl = urlArray[0] + "=420x185" + "." + urlArray[1];
    logger.error("FileUploadController : picUpload url:" + imgUrl);
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("result", new DefaultJsonResult(9999, "?", new ImgVO(imgUrl, identifie)));
    mav.addObject("json", new Gson().toJson(map));
    return mav;
}

From source file:eu.eexcess.opensearch.opensearchDescriptionDocument.parse.OpenSearchDocumentParserTest.java

License:asdf

/**
 * Verify that a detailed OpensearchDocument can be constructed from XML
 * described at <a/*www.j a  va2  s  . c  om*/
 * href="http://www.opensearch.org/Specifications/OpenSearch/1.1#Examples">
 * www.opensearch.org</a>
 */
@Test
public void OpenSearchDocumentParser_readFromFile() {
    OpensearchDescription document = readFromXMLFile("OpenSearchTestDescription.xml");
    assertEquals(new String("foo"), new String("foo"));

    assertEquals(document.adultContent, false);
    assertEquals(document.attribution, "Search data Copyright 2005, Example.com, Inc., All Rights Reserved");
    assertEquals(document.contact, "admin@example.com");
    assertEquals(document.description, "Use Example.com to search the Web.");
    assertEquals(document.developer, "Example.com Development Team");
    assertThat(document.inputEncodings, is(Arrays.asList(StringUtils.split("UTF-8 UTF-7", " "))));
    assertThat(document.outputEncodings, is(Arrays.asList(StringUtils.split("UTF-8 UTF-7", " "))));
    assertThat(document.languages, is(Arrays.asList(StringUtils.split("en-us de-at", " "))));
    assertEquals(document.longName, "Example.com Web Search");
    assertEquals(document.shortName, "Web Search");
    assertEquals(document.syndicationRight, OpensearchDescription.SyndicationRight.OPEN);
    assertThat(document.tags, is(Arrays.asList(StringUtils.split("example web", " "))));
    assertEquals(document.xmlns, "http://a9.com/-/spec/opensearch/1.1/");

    List<Image> images = new ArrayList<Image>();

    images.add(new Image(64, 64, "image/png", "http://example.com/websearch.png"));
    images.add(new Image(16, 16, "image/vnd.microsoft.icon", "http://example.com/websearch.ico"));
    assertThat(document.images, is(images));

    List<Query> queries = new ArrayList<Query>();
    queries.add(new Query("example", "", "cat", "", "", "", -1, -1, -1, -1));
    assertThat(document.queries, is(queries));

    List<Url> searchLinks = new ArrayList<Url>();
    searchLinks.add(new Url("application/atom+xml",
            "http://example.com/?q={searchTerms}&pw={startPage?}&format=atom", UrlRel.UNDEFINED, -1, -1));
    searchLinks.add(new Url("application/rss+xml",
            "http://example.com/?q={searchTerms}&pw={startPage?}&format=rss", UrlRel.UNDEFINED, -1, -1));
    searchLinks.add(new Url("text/html", "http://example.com/?q={searchTerms}&pw={startPage?}",
            UrlRel.UNDEFINED, -1, -1));
    assertThat(document.searchLinks, is(searchLinks));

}

From source file:de.hybris.platform.acceleratorfacades.device.impl.DefaultDeviceDetectionFacade.java

@Override
public void initializeRequest(final HttpServletRequest request) {
    // Only initialise the detected device once per session
    if (getCurrentDetectedDevice() == null || "true".equals(request.getParameter("clear"))) {
        // Detect the device in the current request
        final DeviceData deviceData = getRequestDeviceDataConverter().convert(request);
        setCurrentDetectedDevice(deviceData);

        // Map the detected device to a UiExperienceLevel
        final UiExperienceData uiExperienceData = getDeviceDataUiExperienceDataConverter().convert(deviceData);
        final List<String> supportedUiExperienceLevels = Arrays.asList(StringUtils.split(getSiteConfigService()
                .getString(DEVICE_DETECTION_UIEXPERIENCE_LEVEL_SUPPORTED, StringUtils.EMPTY), ","));

        if (uiExperienceData != null && uiExperienceData.getLevel() != null
                && (supportedUiExperienceLevels.isEmpty()
                        || supportedUiExperienceLevels.contains(uiExperienceData.getLevel().getCode()))) {
            getUiExperienceService().setDetectedUiExperienceLevel(uiExperienceData.getLevel());
        } else {// www. java2  s . c  o  m
            // Default to DESKTOP experience or the first supportUi
            UiExperienceLevel defaultExperience = UiExperienceLevel.DESKTOP;
            try {
                if (!supportedUiExperienceLevels.isEmpty()) {
                    defaultExperience = UiExperienceLevel.valueOf(supportedUiExperienceLevels.get(0));
                }
            } catch (IllegalArgumentException e) {
                LOG.warn(String.format("Invalid UiExperienceLevel enum %s will default to 'Desktop'",
                        supportedUiExperienceLevels.isEmpty() ? "" : supportedUiExperienceLevels.get(0)));
            }
            getUiExperienceService().setDetectedUiExperienceLevel(defaultExperience);
        }

        if (LOG.isDebugEnabled()) {
            final UserModel userModel = (UserModel) getSessionService()
                    .getAttribute(UserConstants.USER_SESSION_ATTR_KEY);
            final String userUid = (userModel != null) ? userModel.getUid() : "<null>";

            LOG.debug("Detected device [" + deviceData.getId() + "] User Agent [" + deviceData.getUserAgent()
                    + "] Mobile [" + deviceData.getMobileBrowser() + "] Session user [" + userUid + "]");
        }
    }
}