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

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

Introduction

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

Prototype

public static String trimToNull(String str) 

Source Link

Document

Removes control characters (char <= 32) from both ends of this String returning null if the String is empty ("") after the trim or if it is null.

Usage

From source file:au.org.ala.names.search.ALANameSearcher.java

/**
 * Dumps a list of the species LSID's that are contained in the index.
 *//*ww w  .j  a  va2s  . c  o m*/
public void dumpSpecies() {
    try {
        OutputStreamWriter fileOut = new OutputStreamWriter(new FileOutputStream("/data/species.txt"), "UTF-8");
        Term term = new Term("rank", "species");
        TopDocs hits = cbSearcher.search(new TermQuery(term), 2000000);

        for (ScoreDoc sdoc : hits.scoreDocs) {
            Document doc = cbReader.document(sdoc.doc);

            if (doc.getField("synonym") == null) {
                String lsid = StringUtils.trimToNull(doc.getField("lsid").stringValue());
                if (lsid == null)
                    lsid = doc.getField("id").stringValue();
                fileOut.write(lsid + "\n");
            }

        }
        fileOut.flush();

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:net.sf.eclipsecs.ui.config.ResolvablePropertiesDialog.java

/**
 * {@inheritDoc}/*from www .  j  a v a  2s .  c o  m*/
 */
protected void okPressed() {

    // check for properties without value - these must be fixed before
    // OK'ing
    for (ResolvableProperty prop : mResolvableProperties) {

        if (StringUtils.trimToNull(prop.getValue()) == null) {
            this.setErrorMessage(NLS.bind(Messages.ResolvablePropertiesDialog_msgMissingPropertyValue,
                    prop.getPropertyName()));
            return;
        }
    }

    mCheckConfig.getResolvableProperties().clear();
    mCheckConfig.getResolvableProperties().addAll(mResolvableProperties);
    super.okPressed();
}

From source file:net.sf.eclipsecs.ui.config.RuleConfigurationEditDialog.java

private Composite createAdvancedSection() {

    Composite advancedSettings = new Composite(mMainTab, SWT.NULL);
    advancedSettings.setLayoutData(new GridData(GridData.FILL_BOTH));
    GridLayout layout = new GridLayout(2, false);
    advancedSettings.setLayout(layout);/*from  w w w .jav a 2s  .c om*/

    // Build comment
    Label commentLabel = new Label(advancedSettings, SWT.NULL);
    commentLabel.setText(Messages.RuleConfigurationEditDialog_lblComment);
    commentLabel.setLayoutData(new GridData());

    mCommentText = new Text(advancedSettings, SWT.SINGLE | SWT.BORDER);
    mCommentText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

    Label idLabel = new Label(advancedSettings, SWT.NULL);
    idLabel.setText(Messages.RuleConfigurationEditDialog_lblId);
    idLabel.setLayoutData(new GridData());

    mIdText = new Text(advancedSettings, SWT.SINGLE | SWT.BORDER);
    mIdText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

    Group messagesGroup = new Group(advancedSettings, SWT.NULL);
    messagesGroup.setText(Messages.RuleConfigurationEditDialog_titleCustMsg);
    messagesGroup.setLayout(new GridLayout(2, false));
    GridData d = new GridData(GridData.FILL_HORIZONTAL);
    d.horizontalSpan = 2;
    messagesGroup.setLayoutData(d);

    mCustomMessages = new HashMap<String, Text>();

    // take keys from metadata as well as predefined from the
    // configuration. This way we don't lose keys not defined in metadata.
    Set<String> msgKeys = new TreeSet<String>();
    msgKeys.addAll(mRule.getMetaData().getMessageKeys());
    msgKeys.addAll(mRule.getCustomMessages().keySet());

    for (String msgKey : msgKeys) {

        Label msgLabel = new Label(messagesGroup, SWT.NULL);
        msgLabel.setText(msgKey);
        msgLabel.setLayoutData(new GridData());

        final Text msgText = new Text(messagesGroup, SWT.SINGLE | SWT.BORDER); //| SWT.SEARCH see below
        msgText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

        final String standardMessage = MetadataFactory.getStandardMessage(msgKey,
                mRule.getMetaData().getInternalName());

        //msgText.setMessage(standardMessage); //a nice solution, sadly only for Eclipse 3.3+

        //alternative for above 
        if (standardMessage != null) {
            msgText.setText(standardMessage);
        }
        msgText.addFocusListener(new FocusListener() {

            public void focusGained(FocusEvent e) {
                Display.getCurrent().asyncExec(new Runnable() {

                    public void run() {
                        if (msgText.getText().equals(standardMessage)) {
                            msgText.selectAll();
                        }
                    }
                });
            }

            public void focusLost(FocusEvent e) {
                // NOOP
            }
        });

        String message = mRule.getCustomMessages().get(msgKey);
        if (StringUtils.trimToNull(message) != null) {
            msgText.setText(message);
        }
        msgText.setEnabled(!mReadonly);

        mCustomMessages.put(msgKey, msgText);
    }

    return advancedSettings;
}

From source file:ch.entwine.weblounge.dispatcher.impl.handler.ImageRequestHandlerImpl.java

/**
 * Handles the request for an image resource that is believed to be in the
 * content repository. The handler scales the image as requested, sets the
 * response headers and the writes the image contents to the response.
 * <p>/*  w  ww.j  a v  a2  s . c o m*/
 * This method returns <code>true</code> if the handler is decided to handle
 * the request, <code>false</code> otherwise.
 * 
 * @param request
 *          the weblounge request
 * @param response
 *          the weblounge response
 */
public boolean service(WebloungeRequest request, WebloungeResponse response) {

    WebUrl url = request.getUrl();
    Site site = request.getSite();
    String path = url.getPath();
    String fileName = null;

    // Get hold of the content repository
    ContentRepository contentRepository = site.getContentRepository();
    if (contentRepository == null) {
        logger.warn("No content repository found for site '{}'", site);
        return false;
    } else if (contentRepository.isIndexing()) {
        logger.debug("Content repository of site '{}' is currently being indexed", site);
        DispatchUtils.sendServiceUnavailable(request, response);
        return true;
    }

    // Check if the request uri matches the special uri for images. If so, try
    // to extract the id from the last part of the path. If not, check if there
    // is an image with the current path.
    ResourceURI imageURI = null;
    ImageResource imageResource = null;
    try {
        String id = null;
        String imagePath = null;

        if (path.startsWith(URI_PREFIX)) {
            String uriSuffix = StringUtils.chomp(path.substring(URI_PREFIX.length()), "/");
            uriSuffix = URLDecoder.decode(uriSuffix, "utf-8");

            // Check whether we are looking at a uuid or a url path
            if (uriSuffix.length() == UUID_LENGTH) {
                id = uriSuffix;
            } else if (uriSuffix.length() >= UUID_LENGTH) {
                int lastSeparator = uriSuffix.indexOf('/');
                if (lastSeparator == UUID_LENGTH && uriSuffix.indexOf('/', lastSeparator + 1) < 0) {
                    id = uriSuffix.substring(0, lastSeparator);
                    fileName = uriSuffix.substring(lastSeparator + 1);
                } else {
                    imagePath = uriSuffix;
                    fileName = FilenameUtils.getName(imagePath);
                }
            } else {
                imagePath = "/" + uriSuffix;
                fileName = FilenameUtils.getName(imagePath);
            }
        } else {
            imagePath = path;
            fileName = FilenameUtils.getName(imagePath);
        }

        // Try to load the resource
        imageURI = new ImageResourceURIImpl(site, imagePath, id);
        imageResource = contentRepository.get(imageURI);
        if (imageResource == null) {
            logger.debug("No image found at {}", imageURI);
            return false;
        }
    } catch (ContentRepositoryException e) {
        logger.error("Error loading image from {}: {}", contentRepository, e.getMessage());
        DispatchUtils.sendInternalError(request, response);
        return true;
    } catch (UnsupportedEncodingException e) {
        logger.error("Error decoding image url {} using utf-8: {}", path, e.getMessage());
        DispatchUtils.sendInternalError(request, response);
        return true;
    }

    // Agree to serve the image
    logger.debug("Image handler agrees to handle {}", path);

    // Check the request method. Only GET is supported right now.
    String requestMethod = request.getMethod().toUpperCase();
    if ("OPTIONS".equals(requestMethod)) {
        String verbs = "OPTIONS,GET";
        logger.trace("Answering options request to {} with {}", url, verbs);
        response.setHeader("Allow", verbs);
        response.setContentLength(0);
        return true;
    } else if (!"GET".equals(requestMethod)) {
        logger.debug("Image request handler does not support {} requests", requestMethod);
        DispatchUtils.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, request, response);
        return true;
    }

    // Is it published?
    // TODO: Fix this. imageResource.isPublished() currently returns false,
    // as both from and to dates are null (see PublishingCtx)
    // if (!imageResource.isPublished()) {
    // logger.debug("Access to unpublished image {}", imageURI);
    // DispatchUtils.sendNotFound(request, response);
    // return true;
    // }

    // Can the image be accessed by the current user?
    User user = request.getUser();
    try {
        // TODO: Check permission
        // PagePermission p = new PagePermission(page, user);
        // AccessController.checkPermission(p);
    } catch (SecurityException e) {
        logger.warn("Access to image {} denied for user {}", imageURI, user);
        DispatchUtils.sendAccessDenied(request, response);
        return true;
    }

    // Determine the response language by filename
    Language language = null;
    if (StringUtils.isNotBlank(fileName)) {
        for (ImageContent c : imageResource.contents()) {
            if (c.getFilename().equalsIgnoreCase(fileName)) {
                if (language != null) {
                    logger.debug("Unable to determine language from ambiguous filename");
                    language = LanguageUtils.getPreferredContentLanguage(imageResource, request, site);
                    break;
                }
                language = c.getLanguage();
            }
        }
        if (language == null)
            language = LanguageUtils.getPreferredContentLanguage(imageResource, request, site);
    } else {
        language = LanguageUtils.getPreferredContentLanguage(imageResource, request, site);
    }

    // If the filename did not lead to a language, apply language resolution
    if (language == null) {
        logger.warn("Image {} does not exist in any supported language", imageURI);
        DispatchUtils.sendNotFound(request, response);
        return true;
    }

    // Extract the image style and scale the image
    String styleId = StringUtils.trimToNull(request.getParameter(OPT_IMAGE_STYLE));
    if (styleId != null) {
        try {
            StringBuffer redirect = new StringBuffer(PathUtils.concat(PreviewRequestHandlerImpl.URI_PREFIX,
                    imageResource.getURI().getIdentifier()));
            redirect.append("?style=").append(styleId);
            response.sendRedirect(redirect.toString());
        } catch (Throwable t) {
            logger.debug("Error sending redirect to the client: {}", t.getMessage());
        }
        return true;
    }

    // Check the modified headers
    long revalidationTime = MS_PER_DAY;
    long expirationDate = System.currentTimeMillis() + revalidationTime;
    if (!ResourceUtils.hasChanged(request, imageResource, language)) {
        logger.debug("Image {} was not modified", imageURI);
        response.setDateHeader("Expires", expirationDate);
        DispatchUtils.sendNotModified(request, response);
        return true;
    }

    // Load the image contents from the repository
    ImageContent imageContents = imageResource.getContent(language);

    // Add mime type header
    String contentType = imageContents.getMimetype();
    if (contentType == null)
        contentType = MediaType.APPLICATION_OCTET_STREAM;

    // Set the content type
    String characterEncoding = response.getCharacterEncoding();
    if (StringUtils.isNotBlank(characterEncoding))
        response.setContentType(contentType + "; charset=" + characterEncoding.toLowerCase());
    else
        response.setContentType(contentType);

    // Browser caches and proxies are allowed to keep a copy
    response.setHeader("Cache-Control", "public, max-age=" + revalidationTime);

    // Set Expires header
    response.setDateHeader("Expires", expirationDate);

    // Determine the resource's modification date
    long resourceLastModified = ResourceUtils.getModificationDate(imageResource, language).getTime();

    // Add last modified header
    response.setDateHeader("Last-Modified", resourceLastModified);

    // Add ETag header
    response.setHeader("ETag", ResourceUtils.getETagValue(imageResource));

    // Load the input stream from the repository
    InputStream imageInputStream = null;
    try {
        imageInputStream = contentRepository.getContent(imageURI, language);
    } catch (Throwable t) {
        logger.error("Error loading {} image '{}' from {}: {}",
                new Object[] { language, imageResource, contentRepository, t.getMessage() });
        logger.error(t.getMessage(), t);
        IOUtils.closeQuietly(imageInputStream);
        return false;
    }

    // Write the image back to the client
    try {
        response.setHeader("Content-Length", Long.toString(imageContents.getSize()));
        response.setHeader("Content-Disposition", "inline; filename=" + imageContents.getFilename());
        IOUtils.copy(imageInputStream, response.getOutputStream());
        response.getOutputStream().flush();
    } catch (EOFException e) {
        logger.debug("Error writing image '{}' back to client: connection closed by client", imageResource);
        return true;
    } catch (IOException e) {
        if (RequestUtils.isCausedByClient(e))
            return true;
        logger.error("Error writing {} image '{}' back to client: {}",
                new Object[] { language, imageResource, e.getMessage() });
    } finally {
        IOUtils.closeQuietly(imageInputStream);
    }
    return true;

}

From source file:net.sf.eclipsecs.ui.config.configtypes.ProjectConfigurationEditor.java

/**
 * {@inheritDoc}/*  w w w. j a  v  a2  s. co m*/
 */
public CheckConfigurationWorkingCopy getEditedWorkingCopy() throws CheckstylePluginException {
    mWorkingCopy.setName(mConfigName.getText());
    mWorkingCopy.setDescription(mDescription.getText());

    mWorkingCopy.getAdditionalData().put(ExternalFileConfigurationType.KEY_PROTECT_CONFIG,
            "" + mChkProtectConfig.getSelection()); //$NON-NLS-1$

    try {
        mWorkingCopy.setLocation(mLocation.getText());
    } catch (CheckstylePluginException e) {
        String location = mLocation.getText();

        if (StringUtils.trimToNull(location) == null) {
            throw e;
        }

        ICheckConfigurationWorkingSet ws = mCheckConfigDialog.getCheckConfigurationWorkingSet();
        IPath tmp = new Path(location);
        boolean isFirstPartProject = ResourcesPlugin.getWorkspace().getRoot().getProject(tmp.segment(0))
                .exists();

        if (ws instanceof LocalCheckConfigurationWorkingSet && !isFirstPartProject) {
            location = ((LocalCheckConfigurationWorkingSet) ws).getProject().getFullPath().append(location)
                    .toString();
            mLocation.setText(location);
        } else if (ws instanceof GlobalCheckConfigurationWorkingSet && !isFirstPartProject) {
            throw new CheckstylePluginException(
                    NLS.bind(Messages.ProjectConfigurationEditor_msgNoProjectInWorkspace, tmp.segment(0)));
        }

        if (ensureFileExists(location)) {
            mWorkingCopy.setLocation(mLocation.getText());
        } else {
            throw e;
        }
    }

    return mWorkingCopy;
}

From source file:com.bluexml.xforms.actions.WorkflowTransitionAction.java

/**
 * Worker function.//from  www  .  j  av a 2s  .  com
 * 
 * @return false if exception or can't do the transition. Otherwise true.
 * @throws ServletException
 */
protected TransitionResultBean submitWork() throws ServletException {
    TransitionResultBean resultBean = new TransitionResultBean();
    HashMap<QName, Serializable> properties = new HashMap<QName, Serializable>();
    currentPage = navigationPath.peekCurrentPage();

    // check the transition although should never throw up... normally.
    String transitionToTake = requestParameters.get(TRANSITION_NAME);
    if (StringUtils.trimToEmpty(transitionToTake).equals(StringUtils.EMPTY)) {
        throw new RuntimeException("XForms WorkflowTransitionAction: no transition name given.");
    }

    // collect info for use later
    String wkFormName = currentPage.getFormName();
    WorkflowTaskInfoBean taskBean = controller.getWorkflowTaskInfoBean(wkFormName);
    userName = getCurrentUserName();
    transaction.setLogin(userName);

    // get process id; try url params first.
    String candidateId = currentPage.getInitParams().get(MsgId.PARAM_WORKFLOW_PROCESS_ID.getText());
    String processId = findProcessId(candidateId, wkFormName);
    if (processId == null) {
        navigationPath.setStatusMsg("Could not find the process Id. Giving up.");
        return resultBean;
    }

    collectTaskProperties(properties, node, taskBean, processId);

    // check that the user is authorized. Already done for the initial task so don't redo.
    if (/*
        * (controller.isStartTaskForm(wkFormName) == false)
        * &&
        */(validateCurrentUser(taskBean, properties) == false)) {
        navigationPath.setStatusMsg(MsgPool.getMsg(MsgId.MSG_STATUS_WKFLW_FAIL_INITIATOR));
        if (logger.isErrorEnabled()) {
            logger.error(MsgPool.getMsg(MsgId.MSG_STATUS_WKFLW_FAIL_INITIATOR));
        }
        return resultBean;
    }

    // add properties from the form fields
    String formTaskName = controller.getWorkflowBlueXMLTaskName(wkFormName);

    // no need to continue if in standalone mode
    if (controller.isInStandaloneMode()) {
        navigationPath.setStatusMsg(
                "The Alfresco Controller is in standalone mode. Workflow actions are not available.");
        return resultBean;
    }

    // check that there's some repository content to associate with the workflow package
    // # 1299: try to save the data form. In case of initial task, this will provide a data id.
    // In all cases, currentPage.getDataId() returns a valid id. Certified :-)
    String dataForm = controller.getUnderlyingDataFormForWorkflow(wkFormName);
    if (dataForm != null) { // #1284
        SubmitAction action = new SubmitAction();
        action.setProperties(controller, uri);
        action.setSubmitProperties(this.result, submission, node,
                NavigationSessionListener.getServletURL(action.getSessionId()));
        try {
            action.submit();
        } catch (Exception e) {
            navigationPath.setStatusMsg("Could not save the data form.");
            if (logger.isErrorEnabled()) {
                logger.error("Auto-save at workflow: error when saving the data form.", e);
            }
            return resultBean;
        }
    }

    // launch a workflow if on a start task form - also set the instance id
    if (initializeTask(wkFormName, taskBean, properties, processId) == false) {
        return resultBean;
    }

    // there's no point in continuing without a workflow instance Id
    String wkflwInstanceId = currentPage.getWkflwInstanceId();
    if (StringUtils.trimToNull(wkflwInstanceId) == null) {
        navigationPath.setStatusMsg("Transition not followed. No workflow instance id is available.");
        return resultBean;
    }

    // check that an active task for the workflow instance is consistent with the current form
    logger.debug("Getting the current tasks for workflow instance with id: " + wkflwInstanceId);
    List<String> tasks = controller.workflowGetCurrentTasksInfo(transaction, wkflwInstanceId);
    if (tasks.size() == 0) {
        navigationPath.setStatusMsg(
                "Transition not followed. No tasks were found for instance id '" + wkflwInstanceId + "'.");
        return resultBean;
    }

    logger.debug("Finding the relevant tasks for form " + formTaskName + " amongst tasks '" + tasks + "'");
    String taskInfoString = findRelevantTaskForForm(formTaskName, tasks);
    if (taskInfoString == null) {
        navigationPath.setStatusMsg("Transition not followed. The form '" + wkFormName
                + "' is not consistent with the current task(s) on the workflow instance.");
        return resultBean;
    }

    // save the task's current state
    logger.debug("Updating task " + taskInfoString);
    String taskId = getIdFromTaskIdNameTitle(taskInfoString);
    if (controller.workflowUpdateTask(transaction, taskId, properties) == false) {
        navigationPath.setStatusMsg("Transition not followed. Failed while updating the task.");
        return resultBean;
    }

    // trigger the transition whose button was clicked
    logger.debug("Ending task " + taskId + " with transition " + transitionToTake);
    if (controller.workflowEndTask(transaction, taskId, transitionToTake) == false) {
        navigationPath.setStatusMsg("Transition not followed. Failed while ending the task.");
        return resultBean;
    }

    // set assignment for next task(s) if any
    logger.debug("Reassigning workflow " + wkflwInstanceId);
    return reassignWorkflow(transaction, properties);
}

From source file:mitm.application.djigzo.james.mailets.MailAttributes.java

private LinkedList<String> parseAttribute(String attribute, Mail mail) throws MessagingException {
    attribute = StringUtils.trimToNull(attribute);

    LinkedList<String> result = new LinkedList<String>();

    if (attribute != null) {
        /*/*from  ww w .  ja v a2 s  . c o  m*/
         * Check if the input is a special address
         */
        SpecialAddress specialAddress = SpecialAddress.fromName(attribute);

        if (specialAddress != null) {
            switch (specialAddress) {
            case ORIGINATOR:
                copyMailAddresses(messageOriginatorIdentifier.getOriginator(mail), result);
                break;
            case REPLY_TO:
                copyMailAddresses(mail.getMessage().getReplyTo(), result);
                break;
            case SENDER:
                copyMailAddresses(MailAddressUtils.toInternetAddress(mail.getSender()), result);
                break;
            case FROM:
                copyMailAddresses(mail.getMessage().getFrom(), result);
                break;

            default:
                throw new MessagingException("Unsupported SpecialAddress.");
            }
        } else {
            /*
             * Check if the input is a user property
             */
            Matcher matcher = USER_VAR_PATTERN.matcher(attribute);

            if (matcher.matches()) {
                InternetAddress originator = messageOriginatorIdentifier.getOriginator(mail);

                if (originator != null) {
                    String userProperty = matcher.group(1);

                    try {
                        User user = userWorkflow.getUser(originator.getAddress(),
                                UserWorkflow.GetUserMode.CREATE_IF_NOT_EXIST);

                        String value = user.getUserPreferences().getProperties().getProperty(userProperty,
                                false);

                        value = StringUtils.trimToNull(value);

                        if (value != null) {
                            result.add(value);
                        }
                    } catch (HierarchicalPropertiesException e) {
                        getLogger().error("Error getting user property " + userProperty, e);
                    }
                }
            } else {
                result.add(attribute);
            }
        }
    }

    return result;
}

From source file:com.adobe.acs.tools.tag_maker.impl.TagMakerServlet.java

private List<String> makeTags(final TagManager tagManager, final List<TagDataConverter> tagDataConverters,
        final Iterator<String[]> rows) throws InvalidTagFormatException, RepositoryException {

    final Set<String> result = new LinkedHashSet<String>();

    while (rows.hasNext()) {
        final String[] row = rows.next();

        log.debug("Processing data from row {}", Arrays.asList(row));

        String tagId = null;/*from w ww  .j  a  v a 2 s  .co m*/

        for (int i = 0; i < row.length; i++) {
            TagData tagData = null;

            final String element = StringUtils.trimToNull(row[i]);

            if (element == null) {
                log.warn("Element is null skipping this row [ {} ]", tagId);
                break;
            }

            for (final TagDataConverter tagDataConverter : tagDataConverters) {
                if (tagDataConverter.accepts(element)) {
                    tagData = tagDataConverter.convert(element);
                    break;
                }
            }

            if (tagData == null) {
                log.warn("Could not find a Tag Data Converter that accepts CSV element [ {} ]; skipping...");
                break;
            } else if (!tagData.isValid()) {
                log.warn("Could not convert CSV element [ {} ] into valid Tag Data; skipping...");
                break;
            }
            if (i == 0) {
                // Tag Namespace
                tagId = tagData.getName() + TagConstants.NAMESPACE_DELIMITER;
            } else if (i == 1) {
                // First Tag under Namespace
                tagId += tagData.getName();
            } else {
                // Subsequent Tags
                tagId += "/" + tagData.getName();
            }

            final Tag tag = tagManager.createTag(tagId, tagData.getTitle(), tagData.getDescription());

            if (tagData.getLocalizedTitles() != null) {
                Map<String, String> translationsMap = tagData.getLocalizedTitles();
                Node node = tag.adaptTo(Node.class);
                for (Map.Entry<String, String> entry : translationsMap.entrySet()) {
                    node.setProperty("jcr:title." + entry.getKey(), entry.getValue());
                }
                node.getSession().save();
            }
            log.trace("Created Tag [ {} ] with Title [ {} ]", tag.getTagID(), tagData.getTitle());

            result.add(tagId);
        }
    }

    if (tagManager.getSession().hasPendingChanges()) {
        final long start = System.currentTimeMillis();
        tagManager.getSession().save();
        if (log.isInfoEnabled()) {
            log.info("Persisting tags to JCR in {} ms", System.currentTimeMillis() - start);
        }
    }

    return new ArrayList<String>(result);
}

From source file:com.egt.core.util.STP.java

public static Object getObjeto(String string, EnumTipoDatoPar tipo) {
    String cadena = StringUtils.trimToNull(string);
    if (cadena == null) {
        return null;
    }//from w w w  .j a v a2  s.  co m
    Object objeto = null;
    switch (tipo) {
    case ALFANUMERICO:
        objeto = new String(string);
        break;
    case NUMERICO:
        try {
            objeto = new BigDecimal(cadena);
        } catch (NumberFormatException e) {
            objeto = null;
        }
        break;
    case FECHA_HORA:
        int year = 0;
        int monthOfYear = 0;
        int dayOfMonth = 0;
        int hourOfDay = 0;
        int minuteOfHour = 0;
        int secondOfMinute = 0;
        try {
            String xm = "";
            String xs = "";
            int len = cadena.length();
            switch (len) {
            case 22:
                xm = cadena.substring(20);
            case 19:
                if (xm.equals("")) {
                    xs = cadena.substring(17, 19);
                }
                if (xs.equalsIgnoreCase("AM") || xs.equalsIgnoreCase("PM")) {
                    xm = xs;
                } else {
                    secondOfMinute = Integer.parseInt(cadena.substring(17, 19));
                }
            case 16:
                minuteOfHour = Integer.parseInt(cadena.substring(14, 16));
                hourOfDay = Integer.parseInt(cadena.substring(11, 13));
                if (xm.equalsIgnoreCase("AM") && hourOfDay == 12) {
                    hourOfDay = 0;
                }
                if (xm.equalsIgnoreCase("PM") && hourOfDay <= 11) {
                    hourOfDay += 12;
                }
            case 10:
                year = Integer.parseInt(cadena.substring(6, 10));
                monthOfYear = Integer.parseInt(cadena.substring(3, 5));
                dayOfMonth = Integer.parseInt(cadena.substring(0, 2));
                break;
            }
            DateTime dateTime = new DateTime(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour,
                    secondOfMinute, 0);
            objeto = new Timestamp(dateTime.getMillis());
        } catch (RuntimeException e) {
            objeto = null;
        }
        break;
    case ENTERO:
        try {
            objeto = new Integer(new BigDecimal(cadena).intValue());
        } catch (NumberFormatException e) {
            objeto = null;
        }
        break;
    case ENTERO_GRANDE:
        try {
            objeto = new Long(new BigDecimal(cadena).longValue());
        } catch (NumberFormatException e) {
            objeto = null;
        }
        break;
    default:
        objeto = null;
        break;
    }
    return objeto;
}

From source file:mp.platform.cyclone.webservices.CyclosWebServicesClientFactory.java

/**
 * Sets the service client password// ww  w .j  a v a2 s.c  o  m
 */
public void setPassword(final String password) {
    this.password = StringUtils.trimToNull(password);
    invalidateCache();
}