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

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

Introduction

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

Prototype

public static String defaultString(String str) 

Source Link

Document

Returns either the passed in String, or if the String is null, an empty String ("").

Usage

From source file:mitm.common.security.ca.CSVRequestConverter.java

/**
 * Converts the CSV to a list of RequestParameters. The first row should contain the column order. The CSV is 
 * considered to be US-ASCII encoded unless a Byte Ordering Mark (BOM) is used. 
 *  //from   w w w.ja v a 2s .  co  m
 * 
 * The following columns are supported:
 * 
 * EMAIL, ORGANISATION, COMMONNAME, FIRSTNAME, LASTNAME
 * 
 * Multiple aliases for the columns are available and names are case insensitive.
 * 
 * EMAIL        : [email, e]
 * ORGANISATION : [organisation, org, o]
 * COMMONNAME   : [commonname, cn]
 * FIRSTNAME    : [firstname, fn, givenname, gn]
 * LASTNAME     : [lastname, ln, surname, sn]
 * 
 * NOTE: all other fields, or fields that are not specified in the CSV, of the returned RequestParameters are 
 * NOT set.
 */
public List<RequestParameters> convertCSV(InputStream csv) throws IOException, RequestConverterException {
    Check.notNull(csv, "csv");

    foundEmails = new HashSet<String>();

    CSVReader reader = new CSVReader(new UnicodeReader(csv, CharacterEncoding.US_ASCII));

    readHeader(reader);

    checkRequiredColumns();

    List<RequestParameters> result = new LinkedList<RequestParameters>();

    String[] line;

    int currentLine = 0;

    while ((line = reader.readNext()) != null) {
        currentLine++;

        if (currentLine > maxLines) {
            throw new RequestConverterException("Maximum number of lines exceeded (" + maxLines + ").");
        }

        if (line == null || (line.length == 1 && StringUtils.isBlank(line[0]))) {
            /*
             * Skip empty lines 
             */
            continue;
        }

        if (line.length != columnOrder.length) {
            throw new RequestConverterException("Line " + currentLine + " does not contain the correct "
                    + "number of columns: " + StringUtils.join(line, ", "));
        }

        RequestParameters request = new RequestParametersImpl();

        X500PrincipalBuilder subjectBuilder = new X500PrincipalBuilder();

        for (int column = 0; column < line.length; column++) {
            String value = StringUtils.trim(line[column]);

            /*
             * Length sanity check
             */
            if (StringUtils.length(value) > maxValueLength) {
                throw new RequestConverterException("The column value " + StringUtils.defaultString(value)
                        + " at line " + currentLine + " and column " + column + " exceeds the maximum number of"
                        + " characters (" + maxValueLength + ").");
            }

            switch (columnOrder[column]) {
            case EMAIL:
                setEmail(value, request, subjectBuilder, column, currentLine);
                break;
            case ORGANISATION:
                subjectBuilder.setOrganisation(value);
                break;
            case COMMONNAME:
                setCommonName(value, subjectBuilder, column, currentLine);
                break;
            case FIRSTNAME:
                subjectBuilder.setGivenName(value);
                break;
            case LASTNAME:
                subjectBuilder.setSurname(value);
                break;

            default:
                throw new RequestConverterException("Unsupported column " + columnOrder[column]);
            }

            request.setSubject(subjectBuilder.buildPrincipal());
        }

        result.add(request);
    }

    return result;
}

From source file:gtu._work.ui.EstoreDAOCodeGenerateUI.java

private void makeFileBtnActionPerformed(ActionEvent evt) throws IOException {
    String entityName = entityNameText.getText();
    String daoImplName = StringUtils.defaultString(daoImplText.getText());
    String daoInterfaceName = StringUtils.defaultString(daoInterfaceText.getText());
    Validate.notBlank(entityName, "??");
    Validate.notBlank(daoImplName, "daoImpl");
    Validate.notBlank(daoInterfaceName, "daoInterface");

    String daoImplPackage = daoImplName.replaceFirst("src/main/java/", "").replaceFirst(".java", "")
            .replace('/', '.');
    String daoInterfacePackage = daoInterfaceName.replaceFirst("src/main/java/", "").replaceFirst(".java", "")
            .replace('/', '.');
    daoImplPackage = daoImplPackage.substring(0, daoImplPackage.lastIndexOf("."));
    daoInterfacePackage = daoInterfacePackage.substring(0, daoInterfacePackage.lastIndexOf("."));
    System.out.println("daoImplName = " + daoImplName);
    System.out.println("daoInterfaceName = " + daoInterfaceName);
    System.out.println("daoImplPackage = " + daoImplPackage);
    System.out.println("daoInterfacePackage = " + daoInterfacePackage);

    String littleEntityName = entityName.substring(0, 1).toLowerCase() + entityName.substring(1);

    String daoImplTxt = String.format(DAO_IMPL, entityName, daoImplPackage);
    String daoInterfaceTxt = String.format(DAO_INTERFACE, entityName, daoInterfacePackage);
    String daoSpringXmlTxt = String.format(DAO_SPRING_XML, entityName, littleEntityName, daoImplPackage);

    xmlConfigArea.setText(daoSpringXmlTxt);

    File daoImplFile = new File(FileUtil.DESKTOP_DIR, daoImplName);
    File daoInterfaceFile = new File(FileUtil.DESKTOP_DIR, daoInterfaceName);
    daoImplFile.getParentFile().mkdirs();
    daoInterfaceFile.getParentFile().mkdirs();

    FileUtils.write(daoImplFile, daoImplTxt, "utf8");
    FileUtils.write(daoInterfaceFile, daoInterfaceTxt, "utf8");
    JCommonUtil._jOptionPane_showMessageDialog_info("?!");
}

From source file:com.opengamma.masterdb.portfolio.DbPortfolioMaster.java

/**
 * Inserts a new document./*  w ww. j av  a 2 s  .  c  o  m*/
 * 
 * @param document the document, not null
 * @return the new document, not null
 */
@Override
protected PortfolioDocument insert(final PortfolioDocument document) {
    ArgumentChecker.notNull(document.getPortfolio(), "document.portfolio");
    ArgumentChecker.notNull(document.getPortfolio().getRootNode(), "document.portfolio.rootNode");

    final Long portfolioId = nextId("prt_master_seq");
    final Long portfolioOid = (document.getUniqueId() != null ? extractOid(document.getUniqueId())
            : portfolioId);
    final UniqueId portfolioUid = createUniqueId(portfolioOid, portfolioId);

    // the arguments for inserting into the portfolio table
    final DbMapSqlParameterSource docArgs = new DbMapSqlParameterSource().addValue("portfolio_id", portfolioId)
            .addValue("portfolio_oid", portfolioOid)
            .addTimestamp("ver_from_instant", document.getVersionFromInstant())
            .addTimestampNullFuture("ver_to_instant", document.getVersionToInstant())
            .addTimestamp("corr_from_instant", document.getCorrectionFromInstant())
            .addTimestampNullFuture("corr_to_instant", document.getCorrectionToInstant())
            .addValue("name", StringUtils.defaultString(document.getPortfolio().getName()))
            .addValue("visibility", document.getVisibility().getVisibilityLevel());

    // the arguments for inserting into the node table
    final List<DbMapSqlParameterSource> nodeList = new ArrayList<DbMapSqlParameterSource>(256);
    final List<DbMapSqlParameterSource> posList = new ArrayList<DbMapSqlParameterSource>(256);
    insertBuildArgs(portfolioUid, null, document.getPortfolio().getRootNode(), document.getUniqueId() != null,
            portfolioId, portfolioOid, null, null, new AtomicInteger(1), 0, nodeList, posList);

    // the arguments for inserting into the portifolio_attribute table
    final List<DbMapSqlParameterSource> prtAttrList = Lists.newArrayList();
    for (Entry<String, String> entry : document.getPortfolio().getAttributes().entrySet()) {
        final long prtAttrId = nextId("prt_portfolio_attr_seq");
        final DbMapSqlParameterSource posAttrArgs = new DbMapSqlParameterSource().addValue("attr_id", prtAttrId)
                .addValue("portfolio_id", portfolioId).addValue("portfolio_oid", portfolioOid)
                .addValue("key", entry.getKey()).addValue("value", entry.getValue());
        prtAttrList.add(posAttrArgs);
    }

    // insert
    final String sqlDoc = getElSqlBundle().getSql("Insert", docArgs);
    final String sqlNode = getElSqlBundle().getSql("InsertNode");
    final String sqlPosition = getElSqlBundle().getSql("InsertPosition");
    final String sqlAttributes = getElSqlBundle().getSql("InsertAttribute");
    getJdbcTemplate().update(sqlDoc, docArgs);
    getJdbcTemplate().batchUpdate(sqlNode, nodeList.toArray(new DbMapSqlParameterSource[nodeList.size()]));
    getJdbcTemplate().batchUpdate(sqlPosition, posList.toArray(new DbMapSqlParameterSource[posList.size()]));
    getJdbcTemplate().batchUpdate(sqlAttributes,
            prtAttrList.toArray(new DbMapSqlParameterSource[prtAttrList.size()]));

    // set the uniqueId
    document.getPortfolio().setUniqueId(portfolioUid);
    document.setUniqueId(portfolioUid);
    return document;
}

From source file:com.flexive.ejb.beans.workflow.WorkflowEngineBean.java

/**
 * {@inheritDoc}/*  ww  w. j ava2 s  .  c om*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void update(Workflow workflow) throws FxApplicationException {

    UserTicket ticket = FxContext.getUserTicket();

    // Permission checks
    FxPermissionUtils.checkRole(ticket, Role.WorkflowManagement);

    Workflow org = CacheAdmin.getEnvironment().getWorkflow(workflow.getId()).asEditable();

    List<Step> dups = new ArrayList<Step>(2); //duplicates (removed and re-added)
    for (Step check : workflow.getSteps()) {
        for (Step stp : org.getSteps())
            if (check.getId() < 0 && stp.getStepDefinitionId() == check.getStepDefinitionId())
                dups.add(check);
    }
    if (dups.size() > 0) {
        //sync steps
        workflow.getSteps().removeAll(dups);
        for (Step stp : org.getSteps())
            for (Step dp : dups)
                if (dp.getStepDefinitionId() == stp.getStepDefinitionId()) {
                    workflow.getSteps().add(stp);
                    break;
                }
        //sync routes
        boolean changes = true;
        while (changes) {
            changes = false;
            for (Route r : workflow.getRoutes()) {
                for (Step s : dups) {
                    if (r.getFromStepId() == s.getId()) {
                        long _from = r.getFromStepId();
                        for (Step stp : org.getSteps())
                            if (stp.getStepDefinitionId() == s.getStepDefinitionId()) {
                                _from = stp.getId();
                                break;
                            }
                        Route nr = new Route(r.getId(), r.getGroupId(), _from, r.getToStepId());
                        if (!workflow.getRoutes().contains(nr)) {
                            workflow.getRoutes().remove(r);
                            workflow.getRoutes().add(nr);
                            changes = true;
                        }
                        break;
                    } else if (r.getToStepId() == s.getId()) {
                        long _to = r.getToStepId();
                        for (Step stp : org.getSteps())
                            if (stp.getStepDefinitionId() == s.getStepDefinitionId()) {
                                _to = stp.getId();
                                break;
                            }
                        Route nr = new Route(r.getId(), r.getGroupId(), r.getFromStepId(), _to);
                        if (!workflow.getRoutes().contains(nr)) {
                            workflow.getRoutes().remove(r);
                            workflow.getRoutes().add(nr);
                            changes = true;
                        }
                        break;
                    }
                    if (changes)
                        break;
                }
                if (changes)
                    break;
            }
        }
    }
    Connection con = null;
    PreparedStatement stmt = null;
    String sql = "UPDATE " + TBL_WORKFLOW + " SET NAME=?, DESCRIPTION=? WHERE ID=?";

    boolean success = false;
    try {
        // Sanity checks
        checkIfValid(workflow);

        // Obtain a database connection
        con = Database.getDbConnection();

        // Update the workflow instance
        stmt = con.prepareStatement(sql);
        stmt.setString(1, workflow.getName());
        stmt.setString(2, StringUtils.defaultString(workflow.getDescription()));
        stmt.setLong(3, workflow.getId());

        stmt.executeUpdate();

        FxEnvironment fxEnvironment = CacheAdmin.getEnvironment();
        // Remove steps?
        List<Step> remove = new ArrayList<Step>(2);
        for (Step step : fxEnvironment.getStepsByWorkflow(workflow.getId())) {
            if (!workflow.getSteps().contains(step)) {
                // remove step
                remove.add(step);
            }
        }

        if (remove.size() > 0) {
            int tries = remove.size() * 2;
            List<Step> tmpRemove = new ArrayList<Step>(remove.size());
            while (remove.size() > 0 && --tries > 0) {
                for (Step step : remove) {
                    try {
                        //remove affected routes as well
                        for (Route route : org.getRoutes())
                            if (route.getFromStepId() == step.getId() || route.getToStepId() == step.getId())
                                routeEngine.remove(route.getId());

                        stepEngine.removeStep(step.getId());
                        tmpRemove.add(step);
                    } catch (FxApplicationException e) {
                        //ignore since rmeove order matters
                    }
                }
                remove.removeAll(tmpRemove);
            }
        }

        // Add/update steps, if necessary
        Map<Long, Step> createdSteps = new HashMap<Long, Step>();
        int index = 1;
        for (Step step : workflow.getSteps()) {
            if (step.getId() < 0) {
                long newStepId = stepEngine.createStep(step);
                // set position
                stepEngine.updateStep(newStepId, step.getAclId(), index);
                // map created steps using the old ID - if routes reference them
                createdSteps.put(step.getId(), new Step(newStepId, step));
            } else {
                // update ACL and position
                stepEngine.updateStep(step.getId(), step.getAclId(), index);
            }
            index++;
        }

        // Remove routes?
        boolean found;
        for (Route route : org.getRoutes()) {
            found = false;
            for (Route check : workflow.getRoutes()) {
                if (check.getGroupId() == route.getGroupId() && check.getFromStepId() == route.getFromStepId()
                        && check.getToStepId() == route.getToStepId()) {
                    workflow.getRoutes().remove(check); //dont add this one again
                    found = true;
                    break;
                }
            }
            // remove route if not found
            if (!found)
                routeEngine.remove(route.getId());
        }

        // add routes
        for (Route route : workflow.getRoutes()) {
            if (route.getId() < 0) {
                long fromStepId = resolveTemporaryStep(createdSteps, route.getFromStepId());
                long toStepId = resolveTemporaryStep(createdSteps, route.getToStepId());
                routeEngine.create(fromStepId, toStepId, route.getGroupId());
            }
        }

        success = true;
    } catch (SQLException exc) {
        if (StorageManager.isUniqueConstraintViolation(exc)) {
            throw new FxEntryExistsException("ex.workflow.exists");
        } else {
            throw new FxUpdateException(LOG, exc, "ex.workflow.update", workflow.getName(), exc.getMessage());
        }
    } catch (Exception exc) {
        throw new FxUpdateException(LOG, exc, "ex.workflow.update", workflow.getName(), exc.getMessage());
    } finally {
        Database.closeObjects(WorkflowEngineBean.class, con, stmt);
        if (!success) {
            EJBUtils.rollback(ctx);
        } else {
            StructureLoader.reloadWorkflows(FxContext.get().getDivisionId());
        }
    }
}

From source file:de.thischwa.pmcms.tool.connection.ftp.FtpTransfer.java

/**
 * Changes to 'targetDir' absolute to the 'serverRootDir'.
 * /* w  w w. j  av  a 2  s .  c om*/
 * @param targetDir Shouldn't start with '/'! Can have subdirs like a/b/c.
 * @return True, if targetDir exists and successful changed.
 * @throws ConnectionRunningException If any IOException was thrown by the FTPClient.
 */
private boolean chDirAbsolute(final String targetDir) throws ConnectionException {
    super.check();
    String absoluteDir = serverRootDir + StringUtils.defaultString(targetDir);
    try {
        boolean retval = ftpClient.changeWorkingDirectory(absoluteDir);
        if (retval)
            logger.debug("[FTP] successfull chdir to: " + absoluteDir);
        return retval;
    } catch (IOException e) {
        logger.error("Error while trying to chdir [" + absoluteDir + "]: " + e.getMessage(), e);
        throw new ConnectionException("Error while chDir to [" + absoluteDir + "]: " + e.getMessage(), e);
    }
}

From source file:com.mirth.connect.client.ui.SettingsPanelResources.java

public void doAddResource() {
    int selectedRow = resourceTable.getSelectedRow();
    if (selectedRow >= 0) {
        resetInvalidProperties();//from   w ww . j av a  2  s . co m
        final String errors = StringUtils.defaultString(checkProperties()).trim();
        if (StringUtils.isNotEmpty(errors)) {
            getFrame().alertError(getFrame(), "Error validating resource settings:\n\n" + errors);
            return;
        }

        updateResource(selectedRow);
    }

    if (propertiesPanelMap.size() > 0) {
        changePropertiesPanel(propertiesPanelMap.keySet().iterator().next());
        resetInvalidProperties();
        ResourceProperties properties = currentPropertiesPanel.getDefaults();

        int num = 1;
        do {
            properties.setName("Resource " + num++);
        } while (!checkUniqueName(properties.getName()));

        this.selectedRow = -1;
        ((RefreshTableModel) resourceTable.getModel())
                .addRow(new Object[] { properties, properties.getName(), properties.getType(), false });
        resourceTable.getSelectionModel().setSelectionInterval(resourceTable.getRowCount() - 1,
                resourceTable.getRowCount() - 1);
        getFrame().setSaveEnabled(true);
    }
}

From source file:com.doculibre.constellio.wicket.panels.results.DefaultSearchResultPanel.java

public DefaultSearchResultPanel(String id, SolrDocument doc, final SearchResultsDataProvider dataProvider) {
    super(id);/*w w w .  j  a  v  a2s . c  o  m*/

    RecordCollectionServices collectionServices = ConstellioSpringUtils.getRecordCollectionServices();
    RecordServices recordServices = ConstellioSpringUtils.getRecordServices();
    SearchInterfaceConfigServices searchInterfaceConfigServices = ConstellioSpringUtils
            .getSearchInterfaceConfigServices();

    String collectionName = dataProvider.getSimpleSearch().getCollectionName();

    RecordCollection collection = collectionServices.get(collectionName);
    Record record = recordServices.get(doc);
    if (record != null) {
        SearchInterfaceConfig searchInterfaceConfig = searchInterfaceConfigServices.get();

        IndexField uniqueKeyField = collection.getUniqueKeyIndexField();
        IndexField defaultSearchField = collection.getDefaultSearchIndexField();
        IndexField urlField = collection.getUrlIndexField();
        IndexField titleField = collection.getTitleIndexField();

        if (urlField == null) {
            urlField = uniqueKeyField;
        }
        if (titleField == null) {
            titleField = urlField;
        }

        final String recordURL = record.getUrl();
        final String displayURL;

        if (record.getDisplayUrl().startsWith("/get?file=")) {
            HttpServletRequest req = ((WebRequest) getRequest()).getHttpServletRequest();
            displayURL = ContextUrlUtils.getContextUrl(req) + record.getDisplayUrl();

        } else {
            displayURL = record.getDisplayUrl();
        }

        String title = record.getDisplayTitle();

        final String protocol = StringUtils.substringBefore(displayURL, ":");
        boolean linkEnabled = isLinkEnabled(protocol);

        // rcupration des champs highlight  partir de la cl unique
        // du document, dans le cas de Nutch c'est l'URL
        QueryResponse response = dataProvider.getQueryResponse();
        Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
        Map<String, List<String>> fieldsHighlighting = highlighting.get(recordURL);

        String titleHighlight = getTitleFromHighlight(titleField.getName(), fieldsHighlighting);
        if (titleHighlight != null) {
            title = titleHighlight;
        }

        String excerpt = null;
        String description = getDescription(record);
        String summary = getSummary(record);

        if (StringUtils.isNotBlank(description) && searchInterfaceConfig.isDescriptionAsExcerpt()) {
            excerpt = description;
        } else {
            excerpt = getExcerptFromHighlight(defaultSearchField.getName(), fieldsHighlighting);
            if (excerpt == null) {
                excerpt = description;
            }
        }

        toggleSummaryLink = new WebMarkupContainer("toggleSummaryLink");
        add(toggleSummaryLink);
        toggleSummaryLink.setVisible(StringUtils.isNotBlank(summary));
        toggleSummaryLink.add(new AttributeModifier("onclick", new LoadableDetachableModel() {
            @Override
            protected Object load() {
                return "toggleSearchResultSummary('" + summaryLabel.getMarkupId() + "')";
            }
        }));

        summaryLabel = new Label("summary", summary);
        add(summaryLabel);
        summaryLabel.setOutputMarkupId(true);
        summaryLabel.setVisible(StringUtils.isNotBlank(summary));

        ExternalLink titleLink;
        if (displayURL.startsWith("file://")) {
            HttpServletRequest req = ((WebRequest) getRequest()).getHttpServletRequest();
            String newDisplayURL = ContextUrlUtils.getContextUrl(req) + "app/getSmbFile?"
                    + SmbServletPage.RECORD_ID + "=" + record.getId() + "&" + SmbServletPage.COLLECTION + "="
                    + collectionName;
            titleLink = new ExternalLink("titleLink", newDisplayURL);
        } else {
            titleLink = new ExternalLink("titleLink", displayURL);
        }

        final RecordModel recordModel = new RecordModel(record);
        AttributeModifier computeClickAttributeModifier = new AttributeModifier("onmousedown", true,
                new LoadableDetachableModel() {
                    @Override
                    protected Object load() {
                        Record record = recordModel.getObject();
                        SimpleSearch simpleSearch = dataProvider.getSimpleSearch();
                        WebRequest webRequest = (WebRequest) RequestCycle.get().getRequest();
                        HttpServletRequest httpRequest = webRequest.getHttpServletRequest();
                        return ComputeSearchResultClickServlet.getCallbackJavascript(httpRequest, simpleSearch,
                                record);
                    }
                });
        titleLink.add(computeClickAttributeModifier);
        titleLink.setEnabled(linkEnabled);

        boolean resultsInNewWindow;
        PageParameters params = RequestCycle.get().getPageParameters();
        if (params != null && params.getString(POPUP_LINK) != null) {
            resultsInNewWindow = params.getBoolean(POPUP_LINK);
        } else {
            resultsInNewWindow = searchInterfaceConfig.isResultsInNewWindow();
        }
        titleLink.add(new SimpleAttributeModifier("target", resultsInNewWindow ? "_blank" : "_self"));

        // Add title
        title = StringUtils.remove(title, "\n");
        title = StringUtils.remove(title, "\r");
        if (StringUtils.isEmpty(title)) {
            title = StringUtils.defaultString(displayURL);
            title = StringUtils.substringAfterLast(title, "/");
            title = StringUtils.substringBefore(title, "?");
            try {
                title = URLDecoder.decode(title, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (title.length() > 120) {
                title = title.substring(0, 120) + " ...";
            }
        }

        Label titleLabel = new Label("title", title);
        titleLink.add(titleLabel.setEscapeModelStrings(false));
        add(titleLink);

        Label excerptLabel = new Label("excerpt", excerpt);
        add(excerptLabel.setEscapeModelStrings(false));
        // add(new ExternalLink("url", url,
        // url).add(computeClickAttributeModifier).setEnabled(linkEnabled));
        if (displayURL.startsWith("file://")) {
            // Creates a Windows path for file URLs
            String urlLabel = StringUtils.substringAfter(displayURL, "file:");
            urlLabel = StringUtils.stripStart(urlLabel, "/");
            urlLabel = "\\\\" + StringUtils.replace(urlLabel, "/", "\\");
            try {
                urlLabel = URLDecoder.decode(urlLabel, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            add(new Label("url", urlLabel));
        } else {
            add(new Label("url", displayURL));
        }

        final ReloadableEntityModel<RecordCollection> collectionModel = new ReloadableEntityModel<RecordCollection>(
                collection);
        add(new ListView("searchResultFields", new LoadableDetachableModel() {
            @Override
            protected Object load() {
                RecordCollection collection = collectionModel.getObject();
                return collection.getSearchResultFields();
            }

            /**
             * Detaches from the current request. Implement this method with
             * custom behavior, such as setting the model object to null.
             */
            protected void onDetach() {
                recordModel.detach();
                collectionModel.detach();
            }
        }) {
            @Override
            protected void populateItem(ListItem item) {
                SearchResultField searchResultField = (SearchResultField) item.getModelObject();
                IndexFieldServices indexFieldServices = ConstellioSpringUtils.getIndexFieldServices();
                Record record = recordModel.getObject();
                IndexField indexField = searchResultField.getIndexField();
                Locale locale = getLocale();
                String indexFieldTitle = indexField.getTitle(locale);
                if (StringUtils.isBlank(indexFieldTitle)) {
                    indexFieldTitle = indexField.getName();
                }
                StringBuffer fieldValueSb = new StringBuffer();
                List<Object> fieldValues = indexFieldServices.extractFieldValues(record, indexField);
                Map<String, String> defaultLabelledValues = indexFieldServices
                        .getDefaultLabelledValues(indexField, locale);
                for (Object fieldValue : fieldValues) {
                    if (fieldValueSb.length() > 0) {
                        fieldValueSb.append("\n");
                    }
                    String fieldValueLabel = indexField.getLabelledValue("" + fieldValue, locale);
                    if (fieldValueLabel == null) {
                        fieldValueLabel = defaultLabelledValues.get("" + fieldValue);
                    }
                    if (fieldValueLabel == null) {
                        fieldValueLabel = "" + fieldValue;
                    }
                    fieldValueSb.append(fieldValueLabel);
                }

                item.add(new Label("indexField", indexFieldTitle));
                item.add(new MultiLineLabel("indexFieldValue", fieldValueSb.toString()));
                item.setVisible(fieldValueSb.length() > 0);
            }

            @SuppressWarnings("unchecked")
            @Override
            public boolean isVisible() {
                boolean visible = super.isVisible();
                if (visible) {
                    List<SearchResultField> searchResultFields = (List<SearchResultField>) getModelObject();
                    visible = !searchResultFields.isEmpty();
                }
                return visible;
            }
        });

        // md5
        ConstellioSession session = ConstellioSession.get();
        ConstellioUser user = session.getUser();
        // TODO Provide access to unauthenticated users ?
        String md5 = "";
        if (user != null) {
            IntelliGIDServiceInfo intelligidServiceInfo = ConstellioSpringUtils.getIntelliGIDServiceInfo();
            if (intelligidServiceInfo != null) {
                Collection<Object> md5Coll = doc.getFieldValues(IndexField.MD5);
                if (md5Coll != null) {
                    for (Object md5Obj : md5Coll) {
                        try {
                            String md5Str = new String(Hex.encodeHex(Base64.decodeBase64(md5Obj.toString())));
                            InputStream is = HttpClientHelper
                                    .get(intelligidServiceInfo.getIntelligidUrl() + "/connector/checksum",
                                            "md5=" + URLEncoder.encode(md5Str, "ISO-8859-1"),
                                            "username=" + URLEncoder.encode(user.getUsername(), "ISO-8859-1"),
                                            "password=" + URLEncoder.encode(Base64.encodeBase64String(
                                                    ConstellioSession.get().getPassword().getBytes())),
                                            "ISO-8859-1");
                            try {
                                Document xmlDocument = new SAXReader().read(is);
                                Element root = xmlDocument.getRootElement();
                                for (Iterator<Element> it = root.elementIterator("fichier"); it.hasNext();) {
                                    Element fichier = it.next();
                                    String url = fichier.attributeValue("url");
                                    md5 += "<a href=\"" + url + "\">" + url + "</a> ";
                                }
                            } finally {
                                IOUtils.closeQuietly(is);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        Label md5Label = new Label("md5", md5) {
            public boolean isVisible() {
                boolean visible = super.isVisible();
                if (visible) {
                    visible = StringUtils.isNotBlank(this.getModelObjectAsString());
                }
                return visible;
            }
        };
        md5Label.setEscapeModelStrings(false);
        add(md5Label);

        add(new ElevatePanel("elevatePanel", record, dataProvider.getSimpleSearch()));
    } else {
        setVisible(false);
    }
}

From source file:mitm.djigzo.web.services.security.HMACFilterImpl.java

private String calculateHMAC(String input, boolean createASOIfNotExist)
        throws InvalidKeyException, NoSuchAlgorithmException {
    /*/*from w w  w  .java  2s.  c  om*/
     * Canonicalize the input before calculating the HMAC
     */
    input = StringUtils.deleteWhitespace(StringUtils.defaultString(input));

    String calculated = null;

    if (createASOIfNotExist || asm.exists(HMAC.class)) {
        calculated = asm.get(HMAC.class).calculateHMAC(input);
    }

    return calculated;
}

From source file:mitm.common.security.ca.CAImpl.java

private void handlePendingRequest(CertificateRequest request) throws CAException {
    String handlerName = request.getCertificateHandlerName();

    CertificateRequestHandler handler = handlerRegistry.getHandler(handlerName);

    if (handler == null) {
        /*//  w w  w  .  ja  v  a  2 s . c o  m
         * A handler was not found. We won't throw an exception because otherwise it will keep on throwing
         * exception is great succession. We will set the last message of the request.
         */
        String message = "A Certificate Request Handler with name " + handlerName + " is not available.";

        logger.warn(message);

        request.setLastMessage(message);

        return;
    }

    KeyAndCertificate keyAndCertificate = handler.handleRequest(request);

    if (keyAndCertificate != null) {
        logger.info(
                "A certificate for email " + StringUtils.defaultString(request.getEmail()) + " was issued.");

        /*
         * The certificate was issued. We can add it and remove it from the certificateRequestStore
         */
        addKeyAndCertificate(keyAndCertificate);
        deleteRequest(request);
    } else {
        logger.debug("A certificate for email " + StringUtils.defaultString(request.getEmail())
                + " was not yet ready.");
    }
}

From source file:mitm.application.djigzo.ws.impl.MailRepositoryWSImpl.java

@Override
@StartTransaction/*from   w w  w  .j a va  2 s. co m*/
public List<MailRepositoryItemDTO> searchItems(MailRepositorySearchField searchField, String key,
        Integer firstResult, Integer maxResults) throws WebServiceCheckedException {
    if (searchField == null) {
        throw new WebServiceCheckedException("searchField is missing.");
    }

    key = StringUtils.defaultString(key);

    List<MailRepositoryItemDTO> result = new LinkedList<MailRepositoryItemDTO>();

    List<? extends MailRepositoryItem> items = mailRepository.searchItems(searchField, key, firstResult,
            maxResults);

    for (MailRepositoryItem item : items) {
        result.add(toDTO(item));
    }

    return result;
}