Example usage for java.util LinkedList addFirst

List of usage examples for java.util LinkedList addFirst

Introduction

In this page you can find the example usage for java.util LinkedList addFirst.

Prototype

public void addFirst(E e) 

Source Link

Document

Inserts the specified element at the beginning of this list.

Usage

From source file:org.nuxeo.ecm.core.storage.sql.PersistenceContext.java

/**
 * Gets the full path, or the closest parent id which we don't have in
 * cache.// w ww.ja  v  a2  s.c o  m
 * <p>
 * If {@code fetch} is {@code true}, returns the full path.
 * <p>
 * If {@code fetch} is {@code false}, does not touch the mapper, only the
 * context, therefore may return a missing parent id instead of the path.
 *
 * @param fetch {@code true} if we can use the database, {@code false} if
 *            only caches should be used
 */
public PathAndId getPathOrMissingParentId(SimpleFragment hierFragment, boolean fetch) throws StorageException {
    LinkedList<String> list = new LinkedList<String>();
    Serializable parentId = null;
    while (true) {
        String name = hierFragment.getString(Model.HIER_CHILD_NAME_KEY);
        if (name == null) {
            // (empty string for normal databases, null for Oracle)
            name = "";
        }
        list.addFirst(name);
        parentId = hierFragment.get(Model.HIER_PARENT_KEY);
        if (parentId == null) {
            // root
            break;
        }
        // recurse in the parent
        RowId rowId = new RowId(Model.HIER_TABLE_NAME, parentId);
        hierFragment = (SimpleFragment) getIfPresent(rowId);
        if (hierFragment == null) {
            // try in mapper cache
            hierFragment = (SimpleFragment) getFromMapper(rowId, false, true);
            if (hierFragment == null) {
                if (!fetch) {
                    return new PathAndId(null, parentId);
                }
                hierFragment = (SimpleFragment) getFromMapper(rowId, true, false);
            }
        }
    }
    String path;
    if (list.size() == 1) {
        String name = list.peek();
        if (name.isEmpty()) {
            // root, special case
            path = "/";
        } else {
            // placeless document, no initial slash
            path = name;
        }
    } else {
        path = StringUtils.join(list, "/");
    }
    return new PathAndId(path, null);
}

From source file:org.openconcerto.sql.element.SQLElement.java

public final void addToMDPath(final String mdVariant) {
    if (mdVariant == null)
        throw new NullPointerException();
    synchronized (this) {
        final LinkedList<String> newL = new LinkedList<String>(this.mdPath);
        newL.addFirst(mdVariant);
        this.mdPath = Collections.unmodifiableList(newL);
    }/*ww  w .  j  a  v  a 2  s  .co m*/
}

From source file:com.commander4j.thread.InboundMessageThread.java

public void run() {
    logger.debug("InboundMessageThread running");
    Boolean dbconnected = false;/*from  w  w w .j a v a2 s  . co m*/

    if (Common.hostList.getHost(hostID).isConnected(sessionID) == false) {
        dbconnected = Common.hostList.getHost(hostID).connect(sessionID, hostID);
    } else {
        dbconnected = true;
    }

    if (dbconnected) {
        JDBInterfaceLog il = new JDBInterfaceLog(getHostID(), getSessionID());
        JeMail mail = new JeMail(getHostID(), getSessionID());
        JDBInterface inter = new JDBInterface(getHostID(), getSessionID());
        IncommingMaterialDefinition imd = new IncommingMaterialDefinition(getHostID(), getSessionID());
        IncommingProcessOrderStatusChange iposc = new IncommingProcessOrderStatusChange(getHostID(),
                getSessionID());
        IncommingProductionDeclarationConfirmation ipd = new IncommingProductionDeclarationConfirmation(
                getHostID(), getSessionID());
        IncommingProcessOrder ipo = new IncommingProcessOrder(getHostID(), getSessionID());
        IncommingLocation ilocn = new IncommingLocation(getHostID(), getSessionID());
        IncommingPalletStatusChange ipsc = new IncommingPalletStatusChange(getHostID(), getSessionID());
        IncommingPalletMove ipmv = new IncommingPalletMove(getHostID(), getSessionID());
        IncommingBatchStatusChange bsc = new IncommingBatchStatusChange(getHostID(), getSessionID());
        IncommingJourney ij = new IncommingJourney(getHostID(), getSessionID());
        IncommingInspectionResult iirslt = new IncommingInspectionResult(getHostID(), getSessionID());
        IncommingDespatchConfirmation idc = new IncommingDespatchConfirmation(getHostID(), getSessionID());
        IncommingQMInspectionRequest iireq = new IncommingQMInspectionRequest(getHostID(), getSessionID());
        IncommingMaterialAutoMove imam = new IncommingMaterialAutoMove(getHostID(), getSessionID());
        GenericMessageHeader gmh = new GenericMessageHeader();
        LinkedList<String> filenames = new LinkedList<String>();
        BasicFileAttributes attrs;

        while (true) {

            com.commander4j.util.JWait.milliSec(100);

            if (allDone) {
                if (dbconnected) {
                    Common.hostList.getHost(hostID).disconnect(getSessionID());
                }
                return;
            }

            if (InboundMessageCollectionThread.recoveringFiles == false) {

                dir = new File(inputPath);

                chld = dir.listFiles((FileFilter) FileFileFilter.FILE);

                if (chld == null) {
                    allDone = true;
                } else {
                    Arrays.sort(chld, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
                    filenames.clear();

                    for (int i = 0; (i < chld.length) & (i < maxfiles); i++) {
                        fileName = chld[i].getName();
                        try {
                            attrs = Files.readAttributes(chld[i].getAbsoluteFile().toPath(),
                                    BasicFileAttributes.class);

                            if (attrs.size() > 0) {
                                if (fileName.endsWith(".xml")) {
                                    filenames.addFirst(fileName);
                                    com.commander4j.util.JWait.milliSec(50);
                                }
                            } else {
                                try {
                                    chld[i].delete();
                                } catch (Exception ex) {

                                }
                            }
                        } catch (IOException e) {

                        }

                    }

                    if (filenames.size() > 0) {
                        logger.debug("Begin processing " + String.valueOf(filenames.size()) + " files.");
                        for (int i = filenames.size() - 1; i >= 0; i--) {
                            if (allDone) {
                                if (dbconnected) {
                                    Common.hostList.getHost(hostID).disconnect(getSessionID());
                                }
                                return;
                            }

                            fromFile = filenames.get(i);

                            try {
                                logger.debug("<---  START OF PROCESSING " + fromFile + "  ---->");
                                logger.debug("Reading message header : " + inputPath + fromFile);

                                if (gmh.readAddressInfo(inputPath + fromFile, getSessionID()) == true) {

                                    messageProcessedOK = true;
                                    errorMessage = "";

                                    if (gmh.getInterfaceType().length() == 0) {
                                        messageProcessedOK = false;
                                        errorMessage = "Unrecognised Commander4j XML message format in file "
                                                + fromFile;
                                        logger.debug(errorMessage);
                                        String datetime = "";
                                        datetime = JUtility
                                                .getISOTimeStampStringFormat(JUtility.getSQLDateTime());
                                        gmh.setMessageDate(datetime);
                                        gmh.setInterfaceDirection("Unknown");
                                        gmh.setMessageInformation(fromFile);
                                        gmh.setInterfaceType("Unknown");
                                        gmh.setMessageRef("Unknown");
                                    } else {
                                        if (gmh.getInterfaceDirection().equals("Input") == false) {
                                            messageProcessedOK = false;
                                            errorMessage = "Inbound message ignored - Interface Direction = "
                                                    + gmh.getInterfaceDirection();
                                        } else {
                                            String interfaceType = gmh.getInterfaceType();
                                            logger.debug("Processing " + interfaceType + " started.");
                                            if (interfaceType.equals("Despatch Confirmation") == true) {
                                                messageProcessedOK = idc.processMessage(gmh);
                                                errorMessage = idc.getErrorMessage();
                                            }

                                            if (interfaceType.equals("Material Definition") == true) {
                                                messageProcessedOK = imd.processMessage(gmh);
                                                errorMessage = imd.getErrorMessage();
                                            }

                                            if (interfaceType.equals("Process Order") == true) {
                                                messageProcessedOK = ipo.processMessage(gmh);
                                                errorMessage = ipo.getErrorMessage();
                                            }

                                            if (interfaceType.equals("Location") == true) {
                                                messageProcessedOK = ilocn.processMessage(gmh);
                                                errorMessage = ilocn.getErrorMessage();
                                            }

                                            if (interfaceType.equals("Pallet Status Change") == true) {
                                                messageProcessedOK = ipsc.processMessage(gmh);
                                                errorMessage = ipsc.getErrorMessage();
                                            }

                                            if (interfaceType.equals("Pallet Move") == true) {
                                                messageProcessedOK = ipmv.processMessage(gmh);
                                                errorMessage = ipmv.getErrorMessage();
                                            }

                                            if (interfaceType.equals("Batch Status Change") == true) {
                                                messageProcessedOK = bsc.processMessage(gmh);
                                                errorMessage = bsc.getErrorMessage();
                                            }

                                            if (interfaceType.equals("Journey Definition") == true) {
                                                messageProcessedOK = ij.processMessage(gmh);
                                                errorMessage = ij.getErrorMessage();
                                            }

                                            if (interfaceType.equals("Process Order Status Change") == true) {
                                                messageProcessedOK = iposc.processMessage(gmh);
                                                errorMessage = iposc.getErrorMessage();
                                            }

                                            if (interfaceType.equals("Production Declaration") == true) {
                                                messageProcessedOK = ipd.processMessage(gmh);
                                                errorMessage = ipd.getErrorMessage();
                                            }

                                            if (interfaceType.equals("QM Inspection Request") == true) {
                                                messageProcessedOK = iireq.processMessage(gmh);
                                                errorMessage = iireq.getErrorMessage();
                                            }

                                            if (interfaceType.equals("QM Inspection Result") == true) {
                                                messageProcessedOK = iirslt.processMessage(gmh);
                                                errorMessage = iirslt.getErrorMessage();
                                            }

                                            if (interfaceType.equals("Material Auto Move") == true) {
                                                messageProcessedOK = imam.processMessage(gmh);
                                                errorMessage = imam.getErrorMessage();
                                            }

                                            GenericMessageHeader.updateStats("Input", interfaceType,
                                                    messageProcessedOK.toString());

                                            logger.debug("Processing " + interfaceType + " finished.");
                                        }
                                    }

                                    logger.debug(
                                            "      ===  RESULT " + messageProcessedOK.toString() + "  ===");

                                    if (messageProcessedOK) {

                                        il.write(gmh, GenericMessageHeader.msgStatusSuccess, "Processed OK",
                                                "DB Update", fromFile);
                                        reader.deleteFile(backupPath + gmh.getInterfaceType() + File.separator
                                                + fromFile);
                                        reader.move_FileToDirectory(inputPath + fromFile,
                                                backupPath + gmh.getInterfaceType(), true);
                                    } else {
                                        il.write(gmh, GenericMessageHeader.msgStatusError, errorMessage,
                                                "DB Update", fromFile);
                                        if (inter.getInterfaceProperties(gmh.getInterfaceType(),
                                                "Input") == true) {
                                            if (inter.getEmailError() == true) {
                                                String emailaddresses = inter.getEmailAddresses();

                                                StringConverter stringConverter = new StringConverter();
                                                ArrayConverter arrayConverter = new ArrayConverter(
                                                        String[].class, stringConverter);
                                                arrayConverter.setDelimiter(';');
                                                arrayConverter.setAllowedChars(new char[] { '@', '_' });

                                                String[] emailList = (String[]) arrayConverter
                                                        .convert(String[].class, emailaddresses);

                                                if (emailList.length > 0) {
                                                    String siteName = Common.hostList.getHost(getHostID())
                                                            .getSiteDescription();
                                                    String attachedFilename = Common.base_dir
                                                            + java.io.File.separator + inputPath + fromFile;
                                                    logger.debug("Attaching file  " + Common.base_dir
                                                            + java.io.File.separator + inputPath + fromFile);
                                                    mail.postMail(emailList, "Error Processing Incoming "
                                                            + gmh.getInterfaceType() + " for [" + siteName
                                                            + "] on " + JUtility.getClientName(), errorMessage,
                                                            fromFile, attachedFilename);
                                                    com.commander4j.util.JWait.milliSec(2000);
                                                }
                                            }

                                        }
                                        reader.deleteFile(
                                                errorPath + gmh.getInterfaceType() + File.separator + fromFile);
                                        reader.move_FileToDirectory(inputPath + fromFile,
                                                errorPath + gmh.getInterfaceType(), true);
                                    }
                                }
                                logger.debug("<---  END OF PROCESSING " + fromFile + "  ---->");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:org.ejbca.ra.EnrollMakeNewRequestBean.java

/**
 * Adds end entity and creates its token that will be downloaded. This method is responsible for deleting the end entity if something goes wrong with token creation.
 * @param tokenType the type of the token that will be created (one of: TOKEN_USERGEN, TOKEN_SOFT_P12, TOKEN_SOFT_JKS from EndEntityConstants)
 * @param tokenName the name of the token. It will be used only in messages and logs
 * @param tokenDownloadType the download type/format of the token. This is used only with TOKEN_USERGEN since this is the only one that have different formats: PEM, DER,...)
 * @return generated token as byte array or null if token could not be generated
 *///from ww w.j  a v  a  2 s.  c  om
private byte[] addEndEntityAndGenerateToken(int tokenType, String tokenName,
        TokenDownloadType tokenDownloadType) {
    //Update the EndEntityInformation data
    getSubjectDn().update();
    getSubjectAlternativeName().update();
    getSubjectDirectoryAttributes().update();

    //Fill End Entity information
    final EndEntityInformation endEntityInformation = getEndEntityInformation();
    endEntityInformation.setCAId(getCAInfo().getCAId());
    endEntityInformation.setCardNumber(""); //TODO Card Number
    endEntityInformation.setCertificateProfileId(
            authorizedCertificateProfiles.get(Integer.parseInt(getSelectedCertificateProfile())).getId());
    endEntityInformation.setDN(getSubjectDn().toString());
    endEntityInformation.setEndEntityProfileId(
            authorizedEndEntityProfiles.get(Integer.parseInt(getSelectedEndEntityProfile())).getId());
    endEntityInformation.setExtendedinformation(new ExtendedInformation());//TODO don't know anything about it...
    endEntityInformation.setHardTokenIssuerId(0); //TODO not sure....
    endEntityInformation.setKeyRecoverable(false); //TODO not sure...
    endEntityInformation.setPrintUserData(false); // TODO not sure...
    endEntityInformation.setStatus(EndEntityConstants.STATUS_NEW);
    endEntityInformation.setSubjectAltName(getSubjectAlternativeName().toString());
    endEntityInformation.setTimeCreated(new Date());
    endEntityInformation.setTimeModified(new Date());
    endEntityInformation.setType(new EndEntityType(EndEntityTypes.ENDUSER));
    // sendnotification must be set after setType, because it adds to the type
    endEntityInformation.setSendNotification(
            getEndEntityProfile().getValue(EndEntityProfile.SENDNOTIFICATION, 0).equals(EndEntityProfile.TRUE)
                    && !endEntityInformation.getSendNotification());
    endEntityInformation.setTokenType(tokenType);

    // Fill end-entity information (Username and Password)
    final byte[] randomData = new byte[16];
    final Random random = new SecureRandom();
    random.nextBytes(randomData);
    if (StringUtils.isBlank(endEntityInformation.getUsername())) {
        String autousername = new String(Hex.encode(randomData));
        while (raMasterApiProxyBean.searchUser(raAuthenticationBean.getAuthenticationToken(),
                autousername) != null) {
            if (log.isDebugEnabled()) {
                log.debug("Autogenerated username '" + autousername
                        + "' is already reserved. Generating the new one...");
            }
            random.nextBytes(randomData);
            autousername = new String(Hex.encode(randomData));
        }
        if (log.isDebugEnabled()) {
            log.debug("Unique username '" + autousername + "' has been generated");
        }
        endEntityInformation.setUsername(autousername);
    }
    if (getEndEntityProfile().useAutoGeneratedPasswd()) {
        // If auto-generated passwords are used, this is set on the CA side when adding or changing the EE as long as the password is null 
        endEntityInformation.setPassword(null);
    } else if (StringUtils.isEmpty(endEntityInformation.getPassword())) {
        // If not needed just use some random data
        random.nextBytes(randomData);
        endEntityInformation
                .setPassword(new String(Hex.encode(CertTools.generateSHA256Fingerprint(randomData))));
    }

    //Fill end-entity information (KeyStoreAlgorithm* or CertificateRequest)
    if (KeyPairGeneration.ON_SERVER.equals(getSelectedKeyPairGenerationEnum())) {
        final String[] tokenKeySpecSplit = getSelectedAlgorithm().split("_");
        endEntityInformation.getExtendedinformation().setKeyStoreAlgorithmType(tokenKeySpecSplit[0]);
        endEntityInformation.getExtendedinformation().setKeyStoreAlgorithmSubType(tokenKeySpecSplit[1]);
    } else if (KeyPairGeneration.PROVIDED_BY_USER.equals(getSelectedKeyPairGenerationEnum())) {
        try {
            endEntityInformation.getExtendedinformation().setCertificateRequest(
                    CertTools.getCertificateRequestFromPem(getCertificateRequest()).getEncoded());
        } catch (IOException e) {
            raLocaleBean.addMessageError("enroll_invalid_certificate_request");
            return null;
        }
    }

    //Add end-entity
    try {
        if (raMasterApiProxyBean.addUser(raAuthenticationBean.getAuthenticationToken(), endEntityInformation,
                /*clearpwd=*/false)) {
            log.info("End entity with username " + endEntityInformation.getUsername()
                    + " has been successfully added");
        } else {
            raLocaleBean.addMessageInfo("enroll_end_entity_could_not_be_added",
                    endEntityInformation.getUsername());
            log.info("Certificate could not be generated for end entity with username "
                    + endEntityInformation.getUsername());
            return null;
        }
    } catch (AuthorizationDeniedException e) {
        raLocaleBean.addMessageInfo("enroll_unauthorized_operation", e.getMessage());
        log.info("You are not authorized to execute this operation", e);
        return null;
    } catch (WaitingForApprovalException e) {
        requestId = e.getRequestId();
        log.info("Request with ID " + requestId + " is still waiting for approval");
        return null;
    } catch (EjbcaException e) {
        ErrorCode errorCode = EjbcaException.getErrorCode(e);
        if (errorCode != null) {
            if (errorCode.equals(ErrorCode.USER_ALREADY_EXISTS)) {
                raLocaleBean.addMessageError("enroll_username_already_exists",
                        endEntityInformation.getUsername());
                log.info("The username " + endEntityInformation.getUsername() + " already exists");
            } else {
                raLocaleBean.addMessageError(errorCode);
                log.info("EjbcaException has been caught. Error Code: " + errorCode, e);
            }
        } else {
            raLocaleBean.addMessageError("enroll_end_entity_could_not_be_added",
                    endEntityInformation.getUsername(), e.getMessage());
            log.info("End entity with username " + endEntityInformation.getUsername()
                    + " could not be added. Contact your administrator or check the logs.", e);
        }
        return null;
    }

    //The end-entity has been added now! Make sure clean-up is done in this "try-finally" block if something goes wrong
    try {
        //Generates a keystore token if user has specified "ON SERVER" key pair generation.
        //Generates a certificate token if user has specified "PROVIDED_BY_USER" key pair generation
        byte[] ret = null;
        if (KeyPairGeneration.ON_SERVER.equals(getSelectedKeyPairGenerationEnum())) {
            try {
                ret = raMasterApiProxyBean.generateKeyStore(raAuthenticationBean.getAuthenticationToken(),
                        endEntityInformation);
            } catch (AuthorizationDeniedException e) {
                raLocaleBean.addMessageInfo("enroll_unauthorized_operation", e.getMessage());
                log.info("You are not authorized to execute this operation", e);
            } catch (EjbcaException e) {
                ErrorCode errorCode = EjbcaException.getErrorCode(e);
                if (errorCode != null) {
                    if (errorCode.equals(
                            ErrorCode.CERTIFICATE_WITH_THIS_SUBJECTDN_ALREADY_EXISTS_FOR_ANOTHER_USER)) {
                        raLocaleBean.addMessageError("enroll_subject_dn_already_exists_for_another_user",
                                subjectDn.getValue());
                        log.info("Subject DN " + subjectDn.getValue() + " already exists for another user", e);
                    } else if (errorCode.equals(ErrorCode.LOGIN_ERROR)) {
                        raLocaleBean.addMessageError("enroll_keystore_could_not_be_generated",
                                endEntityInformation.getUsername(), errorCode);
                        log.info(
                                "Keystore could not be generated for user " + endEntityInformation.getUsername()
                                        + ": " + e.getMessage() + ", " + errorCode);
                    } else {
                        raLocaleBean.addMessageError(errorCode);
                        log.info("Exception creating keystore. Error Code: " + errorCode, e);
                    }
                } else {
                    raLocaleBean.addMessageError("enroll_keystore_could_not_be_generated",
                            endEntityInformation.getUsername(), e.getMessage());
                    log.info("Keystore could not be generated for user " + endEntityInformation.getUsername()
                            + ": " + e.getMessage());
                }
            } catch (Exception e) {
                raLocaleBean.addMessageError("enroll_keystore_could_not_be_generated",
                        endEntityInformation.getUsername(), e.getMessage());
                log.info("Keystore could not be generated for user " + endEntityInformation.getUsername() + ": "
                        + e.getMessage());
            }
        } else if (KeyPairGeneration.PROVIDED_BY_USER.equals(getSelectedKeyPairGenerationEnum())) {
            try {
                endEntityInformation.getExtendedinformation().setCertificateRequest(
                        CertTools.getCertificateRequestFromPem(getCertificateRequest()).getEncoded());
                final byte[] certificateDataToDownload = raMasterApiProxyBean
                        .createCertificate(raAuthenticationBean.getAuthenticationToken(), endEntityInformation);
                if (certificateDataToDownload == null) {
                    raLocaleBean.addMessageError("enroll_certificate_could_not_be_generated",
                            endEntityInformation.getUsername(), "null");
                    log.info("Certificate could not be generated for end entity with username "
                            + endEntityInformation.getUsername() + ": null");
                } else if (tokenDownloadType == TokenDownloadType.PEM_FULL_CHAIN) {
                    X509Certificate certificate = CertTools.getCertfromByteArray(certificateDataToDownload,
                            X509Certificate.class);
                    LinkedList<Certificate> chain = new LinkedList<Certificate>(
                            getCAInfo().getCertificateChain());
                    chain.addFirst(certificate);
                    ret = CertTools.getPemFromCertificateChain(chain);
                } else if (tokenDownloadType == TokenDownloadType.PKCS7) {
                    X509Certificate certificate = CertTools.getCertfromByteArray(certificateDataToDownload,
                            X509Certificate.class);
                    LinkedList<Certificate> chain = new LinkedList<Certificate>(
                            getCAInfo().getCertificateChain());
                    chain.addFirst(certificate);
                    ret = CertTools.getPemFromPkcs7(
                            CertTools.createCertsOnlyCMS(CertTools.convertCertificateChainToX509Chain(chain)));
                } else if (tokenDownloadType == TokenDownloadType.PEM) {
                    X509Certificate certificate = CertTools.getCertfromByteArray(certificateDataToDownload,
                            X509Certificate.class);
                    ret = CertTools.getPemFromCertificateChain(Arrays.asList((Certificate) certificate));
                } else {
                    ret = certificateDataToDownload;
                }
            } catch (AuthorizationDeniedException e) {
                raLocaleBean.addMessageInfo("enroll_unauthorized_operation", e.getMessage());
                log.info("You are not authorized to execute this operation", e);
            } catch (EjbcaException | CertificateEncodingException | CertificateParsingException
                    | ClassCastException | CMSException | IOException e) {
                ErrorCode errorCode = EjbcaException.getErrorCode(e);
                if (errorCode != null) {
                    if (errorCode.equals(
                            ErrorCode.CERTIFICATE_WITH_THIS_SUBJECTDN_ALREADY_EXISTS_FOR_ANOTHER_USER)) {
                        raLocaleBean.addMessageError("enroll_subject_dn_already_exists_for_another_user",
                                subjectDn.getValue());
                        log.info("Subject DN " + subjectDn.getValue() + " already exists for another user", e);
                    } else if (errorCode.equals(ErrorCode.LOGIN_ERROR)) {
                        raLocaleBean.addMessageError("enroll_certificate_could_not_be_generated",
                                endEntityInformation.getUsername(), errorCode);
                        log.info("Certificate could not be generated for user "
                                + endEntityInformation.getUsername() + ": " + e.getMessage() + ", "
                                + errorCode);
                    } else {
                        raLocaleBean.addMessageError(errorCode);
                        log.info("Exception creating certificate. Error Code: " + errorCode, e);
                    }
                } else {
                    raLocaleBean.addMessageError("enroll_certificate_could_not_be_generated",
                            endEntityInformation.getUsername(), e.getMessage());
                    log.info("Certificate could not be generated for end entity with username "
                            + endEntityInformation.getUsername(), e);
                }
            }
        }
        return ret;
    } finally {
        //End entity clean-up must be done if enrollment could not be completed (but end-entity has been added)
        try {
            EndEntityInformation fromCA = raMasterApiProxyBean.searchUser(
                    raAuthenticationBean.getAuthenticationToken(), endEntityInformation.getUsername());
            if (fromCA != null && fromCA.getStatus() != EndEntityConstants.STATUS_GENERATED) {
                raMasterApiProxyBean.deleteUser(raAuthenticationBean.getAuthenticationToken(),
                        endEntityInformation.getUsername());
            }
        } catch (AuthorizationDeniedException e) {
            throw new IllegalStateException(e);
        }
        endEntityInformation.setUsername("");
    }
}

From source file:com.google.ie.business.service.impl.IdeaServiceImpl.java

@SuppressWarnings("unchecked")
public void addIdeaToListInCache(Idea originalIdea, String keyOfTheList, int noOfIdeas, int expiryDelay) {
    LinkedList<Idea> listOfIdeas = (LinkedList<Idea>) CacheHelper.getObject(CacheConstants.IDEA_NAMESPACE,
            keyOfTheList);// w  ww.j  a v  a  2s.c  o  m
    if (listOfIdeas != null) {
        if (listOfIdeas.size() >= noOfIdeas) {
            /* Remove the last element which is also the oldest */
            listOfIdeas.pollLast();
        }
    } else {
        listOfIdeas = new LinkedList<Idea>();
    }
    /* Create a new idea object to contain the required data only */
    Idea ideaWithTheRequiredDataOnly = new Idea();
    ideaWithTheRequiredDataOnly
            .setTitle(StringUtils.abbreviate(originalIdea.getTitle(), ServiceConstants.FIFTY));
    /* Limit the description to hundred characters */
    ideaWithTheRequiredDataOnly
            .setDescription(StringUtils.abbreviate(originalIdea.getDescription(), ServiceConstants.HUNDRED));
    ideaWithTheRequiredDataOnly.setKey(originalIdea.getKey());
    /* Add the idea to the head of the list */
    listOfIdeas.addFirst(ideaWithTheRequiredDataOnly);
    /* Put the updated list back to the cache */
    CacheHelper.putObject(CacheConstants.IDEA_NAMESPACE, keyOfTheList, listOfIdeas, expiryDelay);
}

From source file:com.mirth.connect.plugins.dashboardstatus.DashboardConnectorEventListener.java

@Override
protected void processEvent(Event event) {
    if (event instanceof ConnectionStatusEvent) {
        ConnectionStatusEvent connectionStatusEvent = (ConnectionStatusEvent) event;
        String channelId = connectionStatusEvent.getChannelId();
        Integer metaDataId = connectionStatusEvent.getMetaDataId();
        String information = connectionStatusEvent.getMessage();
        Timestamp timestamp = new Timestamp(event.getDateTime());

        String connectorId = channelId + "_" + metaDataId;

        ConnectionStatusEventType eventType = connectionStatusEvent.getState();

        ConnectionStatusEventType connectionStatusEventType = eventType;
        Integer connectorCount = null;
        Integer maximum = null;//from  ww w  . ja  v  a2  s  .c  om

        if (event instanceof ConnectorCountEvent) {
            ConnectorCountEvent connectorCountEvent = (ConnectorCountEvent) connectionStatusEvent;

            maximum = connectorCountEvent.getMaximum();
            Boolean increment = connectorCountEvent.isIncrement();

            if (maximum != null) {
                maxConnectionMap.put(connectorId, maximum);
            } else {
                maximum = maxConnectionMap.get(connectorId);
            }

            AtomicInteger count = connectorCountMap.get(connectorId);

            if (count == null) {
                count = new AtomicInteger();
                connectorCountMap.put(connectorId, count);
            }

            if (increment != null) {
                if (increment) {
                    count.incrementAndGet();
                } else {
                    count.decrementAndGet();
                }
            }

            connectorCount = count.get();

            if (connectorCount == 0) {
                connectionStatusEventType = ConnectionStatusEventType.IDLE;
            } else {
                connectionStatusEventType = ConnectionStatusEventType.CONNECTED;
            }
        }

        String stateString = null;
        if (connectionStatusEventType.isState()) {
            Color color = getColor(connectionStatusEventType);
            stateString = connectionStatusEventType.toString();
            if (connectorCount != null) {
                if (maximum != null && connectorCount.equals(maximum)) {
                    stateString += " <font color='red'>(" + connectorCount + ")</font>";
                } else if (connectorCount > 0) {
                    stateString += " (" + connectorCount + ")";
                }
            }

            connectorStateMap.put(connectorId, new Object[] { color, stateString });
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
        String channelName = "";
        String connectorType = "";

        LinkedList<String[]> channelLog = null;

        Channel channel = ControllerFactory.getFactory().createChannelController()
                .getDeployedChannelById(channelId);

        if (channel != null) {
            channelName = channel.getName();
            // grab the channel's log from the HashMap, if not exist, create
            // one.
            if (connectorInfoLogs.containsKey(channelId)) {
                channelLog = connectorInfoLogs.get(channelId);
            } else {
                channelLog = new LinkedList<String[]>();
            }

            if (metaDataId == 0) {
                connectorType = "Source: " + channel.getSourceConnector().getTransportName() + "  ("
                        + channel.getSourceConnector().getTransformer().getInboundDataType().toString() + " -> "
                        + channel.getSourceConnector().getTransformer().getOutboundDataType().toString() + ")";
            } else {
                Connector connector = getConnectorFromMetaDataId(channel.getDestinationConnectors(),
                        metaDataId);
                connectorType = "Destination: " + connector.getTransportName() + " - " + connector.getName();
            }
        }

        if (channelLog != null) {
            synchronized (this) {
                if (channelLog.size() == MAX_LOG_SIZE) {
                    channelLog.removeLast();
                }
                channelLog.addFirst(
                        new String[] { String.valueOf(logId), channelName, dateFormat.format(timestamp),
                                connectorType, ((ConnectionStatusEvent) event).getState().toString(),
                                information, channelId, Integer.toString(metaDataId) });

                if (entireConnectorInfoLogs.size() == MAX_LOG_SIZE) {
                    entireConnectorInfoLogs.removeLast();
                }
                entireConnectorInfoLogs.addFirst(
                        new String[] { String.valueOf(logId), channelName, dateFormat.format(timestamp),
                                connectorType, ((ConnectionStatusEvent) event).getState().toString(),
                                information, channelId, Integer.toString(metaDataId) });

                logId++;

                // put the channel log into the HashMap.
                connectorInfoLogs.put(channelId, channelLog);
            }
        }

    }
}

From source file:org.marketcetera.strategy.StrategyTestBase.java

/**
 * Creates a strategy with the given parameters.
 * /*from ww w  .ja  v  a2 s . c  o  m*/
 * <p>The strategy is guaranteed to be running at the successful exit of this method.  Strategies created by this method
 * are tracked and shut down, if necessary, at the end of the test.
 *
 * @param inParameters an <code>Object...</code> value containing the parameters to pass to the module creation command
 * @return a <code>ModuleURN</code> value containing the URN of the strategy
 * @throws Exception if an error occurs
 */
protected ModuleURN createStrategy(Object... inParameters) throws Exception {
    verifyNullProperties();
    LinkedList<Object> actualParameters = new LinkedList<Object>(Arrays.asList(inParameters));
    if (inParameters.length <= 6) {
        actualParameters.addFirst(null);
    }
    ModuleURN strategyURN = createModule(StrategyModuleFactory.PROVIDER_URN, actualParameters.toArray());
    theStrategy = strategyURN;
    verifyStrategyReady(strategyURN);
    return strategyURN;
}

From source file:org.nuxeo.ecm.core.storage.dbs.DBSSession.java

protected String getPath(State state) {
    LinkedList<String> list = new LinkedList<String>();
    for (boolean first = true;; first = false) {
        String name = (String) state.get(KEY_NAME);
        String parentId = (String) state.get(KEY_PARENT_ID);
        list.addFirst(name);
        if (parentId == null || (state = transaction.getStateForRead(parentId)) == null) {
            if (first) {
                if ("".equals(name)) {
                    return "/"; // root
                } else {
                    return name; // placeless, no slash
                }/*w  ww .  jav a 2s . c  o  m*/
            } else {
                return StringUtils.join(list, '/');
            }
        }
    }
}

From source file:net.spfbl.data.Block.java

public static boolean containsREGEX(String host) throws ProcessException {
    host = Domain.extractHost(host, true);
    if (host == null) {
        return false;
    } else {/*from w  w  w.ja v a2s.  c o m*/
        LinkedList<String> tokenList = new LinkedList<String>();
        do {
            int index = host.indexOf('.') + 1;
            host = host.substring(index);
            String token = '.' + host;
            tokenList.addFirst(token);
        } while (host.contains("."));
        return REGEX.get(null, tokenList, true) != null;
    }
}

From source file:jproxy.ProxyControl.java

/**
 * Finds all configuration objects of the given class applicable to the
 * recorded samplers, that is://  ww  w.j a  va  2  s  .  com
 * <ul>
 * <li>All such elements directly within the HTTP(S) Test Script Recorder (these have
 * the highest priority).
 * <li>All such elements directly within the target controller (higher
 * priority) or directly within any containing controller (lower priority),
 * including the Test Plan itself (lowest priority).
 * </ul>
 *
 * @param myTarget
 *            tree node for the recording target controller.
 * @param myClass
 *            Class of the elements to be found.
 * @param ascending
 *            true if returned elements should be ordered in ascending
 *            priority, false if they should be in descending priority.
 *
 * @return a collection of applicable objects of the given class.
 */
// TODO - could be converted to generic class?
private Collection<?> findApplicableElements(JMeterTreeNode myTarget, Class<? extends TestElement> myClass,
        boolean ascending) {
    JMeterTreeModel treeModel = GuiPackage.getInstance().getTreeModel();
    LinkedList<TestElement> elements = new LinkedList<>();

    // Look for elements directly within the HTTP proxy:
    Enumeration<?> kids = treeModel.getNodeOf(this).children();
    while (kids.hasMoreElements()) {
        JMeterTreeNode subNode = (JMeterTreeNode) kids.nextElement();
        if (subNode.isEnabled()) {
            TestElement element = (TestElement) subNode.getUserObject();
            if (myClass.isInstance(element)) {
                if (ascending) {
                    elements.addFirst(element);
                } else {
                    elements.add(element);
                }
            }
        }
    }

    // Look for arguments elements in the target controller or higher up:
    for (JMeterTreeNode controller = myTarget; controller != null; controller = (JMeterTreeNode) controller
            .getParent()) {
        kids = controller.children();
        while (kids.hasMoreElements()) {
            JMeterTreeNode subNode = (JMeterTreeNode) kids.nextElement();
            if (subNode.isEnabled()) {
                TestElement element = (TestElement) subNode.getUserObject();
                if (myClass.isInstance(element)) {
                    log.debug("Applicable: " + element.getName());
                    if (ascending) {
                        elements.addFirst(element);
                    } else {
                        elements.add(element);
                    }
                }

                // Special case for the TestPlan's Arguments sub-element:
                if (element instanceof TestPlan) {
                    TestPlan tp = (TestPlan) element;
                    Arguments args = tp.getArguments();
                    if (myClass.isInstance(args)) {
                        if (ascending) {
                            elements.addFirst(args);
                        } else {
                            elements.add(args);
                        }
                    }
                }
            }
        }
    }

    return elements;
}