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

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

Introduction

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

Prototype

public static boolean endsWithIgnoreCase(String str, String suffix) 

Source Link

Document

Case insensitive check if a String ends with a specified suffix.

Usage

From source file:org.beangle.model.persist.hibernate.support.RailsNamingStrategy.java

/**
 * ?????//  w  ww.  ja  va  2 s. c  om
 * 
 * <pre>
 * ??.??????
 * ???????(component.name)
 * </pre>
 * 
 * @param propertyName
 */
public String propertyToColumnName(String propertyName) {
    StringBuilder sb = new StringBuilder(addUnderscores(unqualify(propertyName)));
    if (!StringUtils.endsWithIgnoreCase(propertyName, "id") && isManyToOne()) {
        sb.append("_id");
    }
    if (sb.length() > MaxLength) {
        logger.error("{}'s length has greate more then 30, database will not be supported!", sb.toString());
    }
    return sb.toString();
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

private boolean validKeystoreAlias(String alias, String keystorePassword, String keystoreData,
        String keystoreFileName) throws KeystoreEditorException {
    boolean valid = false;
    try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(keystoreData))) {
        if (StringUtils.isBlank(alias)) {
            throw new IllegalArgumentException("Alias cannot be null.");
        }//from   w w  w.j av  a 2s . c  o m
        KeyStore ks = null;
        if (StringUtils.endsWithIgnoreCase(keystoreFileName, ".p12")) {
            ks = KeyStore.getInstance("PKCS12");
        } else if (StringUtils.endsWithIgnoreCase(keystoreFileName, ".jks")) {
            ks = KeyStore.getInstance("jks");
        }

        if (ks != null) {
            ks.load(inputStream, keystorePassword.toCharArray());
            valid = ks.containsAlias(alias);
        }
    } catch (Exception e) {
        LOGGER.error("Unable read keystore data.", e);
        throw new KeystoreEditorException("Unable read keystore data.", e);
    }
    return valid;
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

private synchronized void addToStore(String alias, String keyPassword, String storePassword, String data,
        String type, String fileName, String path, String storepass, KeyStore store)
        throws KeystoreEditorException {
    OutputStream fos = null;/*ww w.  j a va2s.c o  m*/
    try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data))) {
        if (StringUtils.isBlank(alias)) {
            throw new IllegalArgumentException("Alias cannot be null.");
        }
        Path storeFile = Paths.get(path);
        //check the two most common key/cert stores first (pkcs12 and jks)
        if (PKCS12_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".p12")) {
            //priv key + cert chain
            KeyStore pkcs12Store = KeyStore.getInstance("PKCS12");
            pkcs12Store.load(inputStream, storePassword.toCharArray());
            Certificate[] chain = pkcs12Store.getCertificateChain(alias);
            Key key = pkcs12Store.getKey(alias, keyPassword.toCharArray());
            if (key != null) {
                store.setKeyEntry(alias, key, keyPassword.toCharArray(), chain);
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        } else if (JKS_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".jks")) {
            //java keystore file
            KeyStore jks = KeyStore.getInstance("jks");
            jks.load(inputStream, storePassword.toCharArray());
            Enumeration<String> aliases = jks.aliases();

            //we are going to store all entries from the jks regardless of the passed in alias
            while (aliases.hasMoreElements()) {
                String jksAlias = aliases.nextElement();

                if (jks.isKeyEntry(jksAlias)) {
                    Key key = jks.getKey(jksAlias, keyPassword.toCharArray());
                    Certificate[] certificateChain = jks.getCertificateChain(jksAlias);
                    store.setKeyEntry(jksAlias, key, keyPassword.toCharArray(), certificateChain);
                } else {
                    Certificate certificate = jks.getCertificate(jksAlias);
                    store.setCertificateEntry(jksAlias, certificate);
                }
            }

            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //need to parse der separately from pem, der has the same mime type but is binary hence checking both
        } else if (DER_TYPE.equals(type) && StringUtils.endsWithIgnoreCase(fileName, ".der")) {
            ASN1InputStream asn1InputStream = new ASN1InputStream(inputStream);
            ASN1Primitive asn1Primitive = asn1InputStream.readObject();
            X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(asn1Primitive.getEncoded());
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
            Certificate certificate = certificateFactory
                    .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
            X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject();
            RDN cn = x500name.getRDNs(BCStyle.CN)[0];
            String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
            if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                store.setCertificateEntry(cnStr, certificate);
            }
            store.setCertificateEntry(alias, certificate);
            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //if it isn't one of the stores we support, it might be a key or cert by itself
        } else if (isPemParsable(type, fileName)) {
            //This is the catch all case for PEM, P7B, etc. with common file extensions if the mime type isn't read correctly in the browser
            Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            PEMParser pemParser = new PEMParser(reader);
            Object object;
            boolean setEntry = false;
            while ((object = pemParser.readObject()) != null) {
                if (object instanceof PEMEncryptedKeyPair || object instanceof PEMKeyPair) {
                    PEMKeyPair pemKeyPair;
                    if (object instanceof PEMEncryptedKeyPair) {
                        PEMEncryptedKeyPair pemEncryptedKeyPairKeyPair = (PEMEncryptedKeyPair) object;
                        JcePEMDecryptorProviderBuilder jcePEMDecryptorProviderBuilder = new JcePEMDecryptorProviderBuilder();
                        pemKeyPair = pemEncryptedKeyPairKeyPair.decryptKeyPair(
                                jcePEMDecryptorProviderBuilder.build(keyPassword.toCharArray()));
                    } else {
                        pemKeyPair = (PEMKeyPair) object;
                    }

                    KeyPair keyPair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemKeyPair);
                    PrivateKey privateKey = keyPair.getPrivate();
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    store.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), chain);
                    setEntry = true;
                } else if (object instanceof X509CertificateHolder) {
                    X509CertificateHolder x509CertificateHolder = (X509CertificateHolder) object;
                    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
                    Certificate certificate = certificateFactory
                            .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
                    X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate)
                            .getSubject();
                    RDN cn = x500name.getRDNs(BCStyle.CN)[0];
                    String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
                    if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                        store.setCertificateEntry(cnStr, certificate);
                    }
                    store.setCertificateEntry(alias, certificate);
                    setEntry = true;
                } else if (object instanceof ContentInfo) {
                    ContentInfo contentInfo = (ContentInfo) object;
                    if (contentInfo.getContentType().equals(CMSObjectIdentifiers.envelopedData)) {
                        CMSEnvelopedData cmsEnvelopedData = new CMSEnvelopedData(contentInfo);
                        OriginatorInfo originatorInfo = cmsEnvelopedData.getOriginatorInfo().toASN1Structure();
                        ASN1Set certificates = originatorInfo.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    } else if (contentInfo.getContentType().equals(CMSObjectIdentifiers.signedData)) {
                        SignedData signedData = SignedData.getInstance(contentInfo.getContent());
                        ASN1Set certificates = signedData.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    }
                } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
                    PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object;
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    try {
                        store.setKeyEntry(alias, pkcs8EncryptedPrivateKeyInfo.getEncoded(), chain);
                        setEntry = true;
                    } catch (KeyStoreException keyEx) {
                        try {
                            PKCS8Key pkcs8Key = new PKCS8Key(pkcs8EncryptedPrivateKeyInfo.getEncoded(),
                                    keyPassword.toCharArray());
                            store.setKeyEntry(alias, pkcs8Key.getPrivateKey(), keyPassword.toCharArray(),
                                    chain);
                            setEntry = true;
                        } catch (GeneralSecurityException e) {
                            LOGGER.error(
                                    "Unable to add PKCS8 key to keystore with secondary method. Throwing original exception.",
                                    e);
                            throw keyEx;
                        }
                    }
                }
            }
            if (setEntry) {
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Unable to add entry {} to store", alias, e);
        throw new KeystoreEditorException("Unable to add entry " + alias + " to store", e);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ignore) {
            }
        }
    }
    init();
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

private boolean isPemParsable(String type, String fileName) {
    //check mime types
    if (PKCS7_TYPE.equals(type) || CERT_TYPE.equals(type) || PEM_TYPE.equals(type)) {
        return true;
        //check file extensions
    } else if (StringUtils.endsWithIgnoreCase(fileName, ".crt")
            || StringUtils.endsWithIgnoreCase(fileName, ".key")
            || StringUtils.endsWithIgnoreCase(fileName, ".pem")
            || StringUtils.endsWithIgnoreCase(fileName, ".p7b")) {
        return true;
    }/*w w  w. j  a  v  a2 s  .  com*/
    return false;
}

From source file:org.dspace.rdf.providing.DataProviderServlet.java

protected String detectLanguage(HttpServletRequest request) {
    String pathInfo = request.getPathInfo();
    if (StringUtils.isEmpty(pathInfo))
        return DEFAULT_LANG;
    String[] path = request.getPathInfo().split("/");
    String lang = path[(path.length - 1)];

    if (StringUtils.endsWithIgnoreCase(lang, "ttl"))
        return "TURTLE";
    if (StringUtils.equalsIgnoreCase(lang, "n3"))
        return "N3";
    if (StringUtils.equalsIgnoreCase(lang, "rdf") || StringUtils.equalsIgnoreCase(lang, "xml")) {
        return "RDF/XML";
    }//from  w  w w .  ja v a  2 s. c o m
    if (StringUtils.endsWithIgnoreCase(lang, "nt"))
        return "N-TRIPLE";

    return DEFAULT_LANG;
}

From source file:org.eclipse.gyrex.preferences.internal.console.ExportCmd.java

@Override
protected void doExecute() throws Exception {
    final IPreferencesService preferencesService = EclipsePreferencesUtil.getPreferencesService();

    if (!StringUtils.endsWithIgnoreCase(file.getName(), FILE_EXT_EPF)) {
        file = new File(file.getParentFile(), file.getName().concat(FILE_EXT_EPF));
    }/* w  ww. j a va  2s. c  o m*/

    IEclipsePreferences node = preferencesService.getRootNode();

    if (StringUtils.isNotBlank(path)) {
        node = (IEclipsePreferences) node.node(path);
    }

    final FileOutputStream output = FileUtils.openOutputStream(file);
    try {
        preferencesService.exportPreferences(node, output, null);
        printf("Successfully exported %s to %s.", node.absolutePath(), file.getAbsolutePath());
    } finally {
        IOUtils.closeQuietly(output);
    }
}

From source file:org.eclipse.gyrex.preferences.internal.console.ImportCmd.java

@Override
protected void doExecute() throws Exception {
    final IPreferencesService preferencesService = EclipsePreferencesUtil.getPreferencesService();

    if (!StringUtils.endsWithIgnoreCase(file.getName(), FILE_EXT_EPF)) {
        file = new File(file.getParentFile(), file.getName().concat(FILE_EXT_EPF));
    }//from   ww w .  j  av a2 s . co  m

    if (!file.isFile() || !file.canRead()) {
        printf("ERROR: Unable to read file %s", file.getAbsolutePath());
        return;
    }

    IEclipsePreferences node = preferencesService.getRootNode();

    final String path = ci.nextArgument();
    if (StringUtils.isNotBlank(path)) {
        node = (IEclipsePreferences) node.node(path);
    }

    final FileInputStream in = FileUtils.openInputStream(file);
    try {
        preferencesService.importPreferences(in);
        printf("Successfully imported preferences from %s.", node.absolutePath(), file.getAbsolutePath());
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:org.eclipse.skalli.core.storage.Historian.java

Collection<File> getHistoryFiles(final File file) {
    String prefix = FilenameUtils.getBaseName(file.getAbsolutePath());
    IOFileFilter fileFilter = FileFilterUtils.andFileFilter(FileFilterUtils.prefixFileFilter(prefix),
            FileFilterUtils.suffixFileFilter("history")); //$NON-NLS-1$
    fileFilter = new IOFileFilter() {
        @Override//from  www  . j a va  2s .c  o  m
        public boolean accept(File arg0, String arg1) {
            return false;
        }

        @Override
        public boolean accept(File historyFile) {
            boolean ret = StringUtils.startsWithIgnoreCase(historyFile.getAbsolutePath(),
                    file.getAbsolutePath());
            ret &= StringUtils.endsWithIgnoreCase(historyFile.getAbsolutePath(), ".history"); //$NON-NLS-1$
            return ret;
        }
    };
    @SuppressWarnings("unchecked")
    Collection<File> files = FileUtils.listFiles(file.getParentFile(), fileFilter, null);
    return files;
}

From source file:org.fenixedu.academic.ui.struts.action.manager.payments.SIBSPaymentsDA.java

public ActionForward uploadSIBSPaymentFiles(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException {

    UploadBean bean = getRenderedObject("uploadBean");
    RenderUtils.invalidateViewState("uploadBean");

    if (bean == null) {
        return prepareUploadSIBSPaymentFiles(mapping, form, request, response);
    }//from  w w w .ja v  a  2  s  . c  om

    if (StringUtils.endsWithIgnoreCase(bean.getFilename(), ZIP_FILE_EXTENSION)) {
        File zipFile = org.fenixedu.academic.util.FileUtils.copyToTemporaryFile(bean.getInputStream());
        File unzipDir = null;
        try {
            unzipDir = org.fenixedu.academic.util.FileUtils.unzipFile(zipFile);
            if (!unzipDir.isDirectory()) {
                addActionMessage("error", request, "error.manager.SIBS.zipException", bean.getFilename());
                return prepareUploadSIBSPaymentFiles(mapping, form, request, response);
            }
        } catch (Exception e) {
            addActionMessage("error", request, "error.manager.SIBS.zipException", getMessage(e));
            return prepareUploadSIBSPaymentFiles(mapping, form, request, response);
        } finally {
            zipFile.delete();
        }

        recursiveZipProcess(unzipDir, request);

    } else if (StringUtils.endsWithIgnoreCase(bean.getFilename(), PAYMENT_FILE_EXTENSION)) {
        InputStream inputStream = bean.getInputStream();
        File dir = Files.createTempDir();
        File tmp = new File(dir, bean.getFilename());
        tmp.deleteOnExit();

        try (OutputStream out = new FileOutputStream(tmp)) {
            ByteStreams.copy(inputStream, out);
        } finally {
            inputStream.close();
        }
        File file = tmp;
        ProcessResult result = new ProcessResult(request);
        result.addMessage("label.manager.SIBS.processingFile", file.getName());
        try {
            processFile(file, request);
        } catch (FileNotFoundException e) {
            addActionMessage("error", request, "error.manager.SIBS.zipException", getMessage(e));
        } catch (IOException e) {
            addActionMessage("error", request, "error.manager.SIBS.IOException", getMessage(e));
        } catch (Exception e) {
            addActionMessage("error", request, "error.manager.SIBS.fileException", getMessage(e));
        } finally {
            file.delete();
        }
    } else {
        addActionMessage("error", request, "error.manager.SIBS.notSupportedExtension", bean.getFilename());
    }
    return prepareUploadSIBSPaymentFiles(mapping, form, request, response);
}

From source file:org.fenixedu.treasury.services.payments.sibs.SIBSPaymentsImporter.java

public ProcessResult processSIBSPaymentFiles(SibsInputFile inputFile) throws IOException {
    ProcessResult result = new ProcessResult();

    if (StringUtils.endsWithIgnoreCase(inputFile.getFilename(), PAYMENT_FILE_EXTENSION)) {
        result.addMessage("label.manager.SIBS.processingFile", inputFile.getFilename());
        try {//from w w w .j  ava2s  . c o m
            processFile(inputFile, result);
        } catch (FileNotFoundException e) {
            throw new TreasuryDomainException("error.manager.SIBS.zipException", getMessage(e));
        } catch (IOException e) {
            throw new TreasuryDomainException("error.manager.SIBS.IOException", getMessage(e));
        } catch (Exception e) {
            throw new TreasuryDomainException("error.manager.SIBS.fileException", getMessage(e));
        } finally {
        }
    } else {
        throw new TreasuryDomainException("error.manager.SIBS.notSupportedExtension", inputFile.getFilename());
    }
    return result;
}