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

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

Introduction

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

Prototype

public static boolean startsWith(String str, String prefix) 

Source Link

Document

Check if a String starts with a specified prefix.

Usage

From source file:de.fhg.iais.asc.workflow.AbstractScan.java

public File getTargetFile(File sourceFile) {
    String sourceRoot = getSource();
    if (!sourceRoot.endsWith(File.separator)) {
        sourceRoot += File.separator;
    }// w ww.  java  2s .  c om

    String sourcePath = sourceFile.getPath();
    if (!StringUtils.startsWith(sourcePath, sourceRoot)) {
        return null; // sourceDir is not equal or child of sourceRoot
    }

    int index = sourceRoot.length(), length = sourcePath.length();
    while ((index < length) && (isSeparator(sourcePath, index))) {
        ++index;
    }

    String subPath = sourcePath.substring(index);
    return StringUtils.isEmpty(subPath) ? null : new File(getTarget(), subPath);
}

From source file:jp.primecloud.auto.tool.management.service.UserService.java

public static void showUserPlatform() {
    try {//from  w w  w .j  ava 2 s  . co  m
        String userSql = "SELECT * FROM USER";
        List<User> users = SQLMain.selectExecuteWithResult(userSql, User.class);

        StringBuilder titles = new StringBuilder();
        titles.append(StringUtils.rightPad("Username", padSize, " "));
        titles.append(StringUtils.rightPad("Status", padSize, " "));
        titles.append(StringUtils.rightPad("Platform", padSize, " "));
        System.out.println(titles.toString());
        String disablecode = Config.getProperty("DISABLE_CODE");

        Map<Long, Platform> platformMap = new LinkedHashMap<Long, Platform>();
        String platformSql = "SELECT * FROM PLATFORM";
        List<Platform> platforms = SQLMain.selectExecuteWithResult(platformSql, Platform.class);
        for (Platform platform : platforms) {
            platformMap.put(platform.getPlatformNo(), platform);
        }

        Map<Long, List<AwsCertificate>> awsCertificateMap = new LinkedHashMap<Long, List<AwsCertificate>>();
        String awsAql = "SELECT * FROM AWS_CERTIFICATE";
        List<AwsCertificate> tmpAwsCertificates = SQLMain.selectExecuteWithResult(awsAql, AwsCertificate.class);
        for (AwsCertificate awsCertificate : tmpAwsCertificates) {
            List<AwsCertificate> list = awsCertificateMap.get(awsCertificate.getUserNo());
            if (list == null) {
                list = new ArrayList<AwsCertificate>();
            }
            list.add(awsCertificate);
            awsCertificateMap.put(awsCertificate.getUserNo(), list);
        }

        Map<Long, List<VmwareKeyPair>> vmwareKeyPairMap = new LinkedHashMap<Long, List<VmwareKeyPair>>();
        String vmwareSql = "SELECT * FROM VMWARE_KEY_PAIR";
        List<VmwareKeyPair> tmpVmwareKeyPairs = SQLMain.selectExecuteWithResult(vmwareSql, VmwareKeyPair.class);
        for (VmwareKeyPair vmwareKeyPair : tmpVmwareKeyPairs) {
            List<VmwareKeyPair> list = vmwareKeyPairMap.get(vmwareKeyPair.getUserNo());
            if (list == null) {
                list = new ArrayList<VmwareKeyPair>();
            }
            list.add(vmwareKeyPair);
            vmwareKeyPairMap.put(vmwareKeyPair.getUserNo(), list);
        }

        Map<Long, List<NiftyCertificate>> niftyCertificateMap = new LinkedHashMap<Long, List<NiftyCertificate>>();
        String niftySql = "SELECT * FROM NIFTY_CERTIFICATE";
        List<NiftyCertificate> tmpNiftyCertificates = SQLMain.selectExecuteWithResult(niftySql,
                NiftyCertificate.class);
        for (NiftyCertificate niftyCertificate : tmpNiftyCertificates) {
            List<NiftyCertificate> list = niftyCertificateMap.get(niftyCertificate.getUserNo());
            if (list == null) {
                list = new ArrayList<NiftyCertificate>();
            }
            list.add(niftyCertificate);
            niftyCertificateMap.put(niftyCertificate.getUserNo(), list);
        }

        Map<Long, List<CloudstackCertificate>> cloudstackCertificateMap = new LinkedHashMap<Long, List<CloudstackCertificate>>();
        String csSql = "SELECT * FROM CLOUDSTACK_CERTIFICATE";
        List<CloudstackCertificate> tmpCloudstackCertificates = SQLMain.selectExecuteWithResult(csSql,
                CloudstackCertificate.class);
        for (CloudstackCertificate cloudstackCertificate : tmpCloudstackCertificates) {
            List<CloudstackCertificate> list = cloudstackCertificateMap.get(cloudstackCertificate.getAccount());
            if (list == null) {
                list = new ArrayList<CloudstackCertificate>();
            }
            list.add(cloudstackCertificate);
            cloudstackCertificateMap.put(cloudstackCertificate.getAccount(), list);
        }

        Map<Long, List<VcloudCertificate>> vcloudCertificateMap = new LinkedHashMap<Long, List<VcloudCertificate>>();
        String vcSql = "SELECT * FROM VCLOUD_CERTIFICATE";
        List<VcloudCertificate> tmpVcloudCertificates = SQLMain.selectExecuteWithResult(vcSql,
                VcloudCertificate.class);
        for (VcloudCertificate vcloudCertificate : tmpVcloudCertificates) {
            List<VcloudCertificate> list = vcloudCertificateMap.get(vcloudCertificate.getUserNo());
            if (list == null) {
                list = new ArrayList<VcloudCertificate>();
            }
            list.add(vcloudCertificate);
            vcloudCertificateMap.put(vcloudCertificate.getUserNo(), list);
        }

        for (User user : users) {
            List<String> columns = new ArrayList<String>();
            columns.add(user.getUsername());
            // ??
            if (!StringUtils.startsWith(user.getPassword(), disablecode)) {
                columns.add("enable");
            } else {
                columns.add("disable");
            }

            // TODO CLOUD BRANCHING
            StringBuilder sb = new StringBuilder();
            List<AwsCertificate> awsCertificates = awsCertificateMap.get(user.getUserNo());
            if (awsCertificates != null && !awsCertificates.isEmpty()) {
                for (AwsCertificate awsCertificate : awsCertificates) {
                    Platform platform = platformMap.get(awsCertificate.getPlatformNo());
                    if ("aws".equals(platform.getPlatformType())
                            && BooleanUtils.isTrue(platform.getSelectable())) {
                        sb.append(platform.getPlatformName());
                        sb.append(" ");
                    }
                }
            }

            List<VmwareKeyPair> vmwareKeyPairs = vmwareKeyPairMap.get(user.getUserNo());
            if (vmwareKeyPairs != null && !vmwareKeyPairs.isEmpty()) {
                for (VmwareKeyPair vmwareKeyPair : vmwareKeyPairs) {
                    Platform platform = platformMap.get(vmwareKeyPair.getPlatformNo());
                    if ("vmware".equals(platform.getPlatformType())
                            && BooleanUtils.isTrue(platform.getSelectable())) {
                        sb.append(platform.getPlatformName());
                        sb.append(" ");
                    }
                }
            }

            List<NiftyCertificate> niftyCertificates = niftyCertificateMap.get(user.getUserNo());
            if (niftyCertificates != null && !niftyCertificates.isEmpty()) {
                for (NiftyCertificate niftyCertificate : niftyCertificates) {
                    Platform platform = platformMap.get(niftyCertificate.getPlatformNo());
                    if ("nifty".equals(platform.getPlatformType())
                            && BooleanUtils.isTrue(platform.getSelectable())) {
                        sb.append(platform.getPlatformName());
                        sb.append(" ");
                    }
                }
            }

            List<CloudstackCertificate> cloudstackCertificates = cloudstackCertificateMap.get(user.getUserNo());
            if (cloudstackCertificates != null && !cloudstackCertificates.isEmpty()) {
                for (CloudstackCertificate cloudstackCertificate : cloudstackCertificates) {
                    Platform platform = platformMap.get(cloudstackCertificate.getPlatformNo());
                    if ("cloudstack".equals(platform.getPlatformType())
                            && BooleanUtils.isTrue(platform.getSelectable())) {
                        sb.append(platform.getPlatformName());
                        sb.append(" ");
                    }
                }
            }

            List<VcloudCertificate> vcloudCertificates = vcloudCertificateMap.get(user.getUserNo());
            if (vcloudCertificates != null && !vcloudCertificates.isEmpty()) {
                for (VcloudCertificate vcloudCertificate : vcloudCertificates) {
                    Platform platform = platformMap.get(vcloudCertificate.getPlatformNo());
                    if ("vcloud".equals(platform.getPlatformType())
                            && BooleanUtils.isTrue(platform.getSelectable())) {
                        sb.append(platform.getPlatformName());
                        sb.append(" ");
                    }
                }
            }

            columns.add(sb.toString());
            for (String column : columns) {
                System.out.print(StringUtils.rightPad(column, padSize, " "));
            }
            System.out.println();
        }
        log.info("????");
    } catch (Exception e) {
        e.printStackTrace();
        log.error(e.getMessage(), e);
    }
}

From source file:com.activecq.tools.flipbook.components.impl.FlipbookServiceImpl.java

public List<ValueMap> getDialogFields(final Resource resource, final DialogType dialogType,
        List<Resource> cachedWidgetResources) throws RepositoryException {
    final ResourceResolver resourceResolver = resource.getResourceResolver();
    final List<ValueMap> list = new ArrayList<ValueMap>();
    final Component component = resource.adaptTo(Component.class);

    String path;//from  w  ww.  j  a  v a2  s .c om

    if (DialogType.DIALOG.equals(dialogType)) {
        path = component.getDialogPath();
    } else {
        path = component.getDesignDialogPath();
        log.error("DESIGN PATH {} ", path);
    }

    if (StringUtils.isBlank(path)) {
        return list;
    } else if (cachedWidgetResources == null) {
        cachedWidgetResources = getWidgetResources(resource);
    }

    for (final Resource cachedResource : cachedWidgetResources) {
        if (StringUtils.startsWith(cachedResource.getPath(), path)) {
            if (DialogType.DESIGN_DIALOG.equals(dialogType)) {
                log.error("DD: {}", cachedResource.getPath());
            }

            list.add(cachedResource.adaptTo(ValueMap.class));
        }
    }

    return list;
}

From source file:br.com.nordestefomento.jrimum.utilix.StringUtil.java

/**
 * <p>/*from w w  w.ja v a 2 s .co m*/
 * Remove os zeros iniciais de uma <code>String</code>, seja ela numrica ou
 * no.
 * </p>
 * <p>
 * <code>removeStartWithZeros("00000") => 0</code><br />
 * <code>removeStartWithZeros("00023") => 23</code><br />
 * <code>removeStartWithZeros("02003") => 2003</code>
 * <p>
 * 
 * @param str
 * @return a string sem zeros inicias ou um nico zero.
 * 
 * @since 0.2
 */

public static String removeStartWithZeros(final String str) {

    String withoutZeros = StringUtils.EMPTY;
    final String zero = "0";

    if (isNotNull(str)) {

        if (StringUtils.startsWith(str, zero)) {

            withoutZeros = StringUtils.removeStart(str, zero);

            while (StringUtils.startsWith(withoutZeros, zero)) {
                withoutZeros = StringUtils.removeStart(withoutZeros, zero);
            }

            if (withoutZeros.trim().length() == 0) {
                withoutZeros = zero;
            }

        } else {
            withoutZeros = str;
        }
    }

    return withoutZeros;
}

From source file:com.microsoft.alm.plugin.external.tools.TfTool.java

/**
 * Search thru given directories to find one of the given acceptable tf commands
 *
 * @param paths//from  w  w w. j  av a  2  s  . co m
 * @param exeNames
 * @return
 */
private static String searchDirectories(final File[] paths, final String[] exeNames) {
    for (final File path : paths) {
        if (path.exists()) {
            for (final File subDirectory : path.listFiles()) {
                if (StringUtils.startsWith(subDirectory.getName(), TF_DIRECTORY_PREFIX)
                        && subDirectory.isDirectory()) {
                    final String verifiedPath = checkTfPath(subDirectory.getPath(), exeNames);
                    if (verifiedPath != null) {
                        return verifiedPath;
                    }
                }
            }
        }
    }
    return null;
}

From source file:com.edgenius.core.UserSetting.java

public boolean hasWidgetAtHomelayout(String widgetType, String widgetKey) {
    if (homeLayout == null || homeLayout.size() == 0)
        return false;

    String widgetPrefix = widgetType + Constants.PORTLET_SEP + widgetKey + Constants.PORTLET_SEP;
    for (String widget : homeLayout) {
        if (StringUtils.startsWith(widget, widgetPrefix)) {
            return true;
        }/*from   ww w .  j  a  v  a 2  s. c o  m*/
    }
    return false;
}

From source file:edu.monash.merc.system.parser.GPMDbParser.java

public GPMDbBean parse(InputStream ins, String encoding, GPMDbType gpmDbType) {
    try {//from   www  .j av  a2 s  .c  om
        String defaultEncoding = "UTF-8";
        if (StringUtils.isNotBlank(encoding)) {
            defaultEncoding = encoding;
        }
        InputStreamReader insReader = new InputStreamReader(ins, Charset.forName(defaultEncoding));
        BufferedReader reader = new BufferedReader(insReader);

        //create a GPMDbBean
        GPMDbBean gpmDbBean = new GPMDbBean();
        //set the GPMDbType
        gpmDbBean.setGpmDbType(gpmDbType);

        List<GPMDbEntryBean> gpmDbEntryBeanList = new ArrayList<GPMDbEntryBean>();
        GPMDbEntryBean gpmDbEntryBean = null;

        String releaseDate = null;
        String nominalMass = null;
        String sequenceAssembly = null;
        String sequenceSource = null;
        String maximumLoge = null;
        String enspAccession = null;
        String ensgAccession = null;
        String enstAccession = null;
        String chromName = null;
        int chromStart = 0;
        int chromEnd = 0;
        String chromStrand = null;
        int modifiedPeptideObs = 0;
        int pos = 0;
        String res = null;
        int obs = 0;
        String line = null;
        int counterIndex = 0;
        while ((line = reader.readLine()) != null) {

            if (StringUtils.isNotBlank(line) && !StringUtils.startsWith(line, "#")) {
                //start to parse the head of psyt file from gpm
                if (StringUtils.startsWith(line, RELEASE_DATE)) {
                    String[] dateLineFields = DMUtil.splitByDelims(line, COLON_DELIM);
                    if (dateLineFields.length != 2) {
                        throw new DMFileException("Invalid gpm psyt file,  the release date is not specified");
                    }
                    //There are a total of 26 release dates, just add the first release date as a primary release date
                    if (StringUtils.isBlank(releaseDate)) {
                        releaseDate = dateLineFields[1];
                        gpmDbBean.setReleaseToken(releaseDate);
                    }
                }

                if (StringUtils.startsWith(line, NOMINAL_MASS)) {
                    String[] nominalMassLineFields = DMUtil.splitByDelims(line, COLON_DELIM);
                    if (nominalMassLineFields.length != 2) {
                        throw new DMFileException(
                                "Invalid gpm psyt file,  the nominal mass number is not specified");
                    }
                    if (StringUtils.isBlank(nominalMass)) {
                        nominalMass = nominalMassLineFields[1];
                        gpmDbBean.setNominalMass(nominalMass);
                    }
                }

                if (StringUtils.startsWith(line, SEQUENCE_ASEMBLY)
                        || StringUtils.startsWith(line, SEQUENCE_ASEMBLY)) {
                    String[] sequenceAssemblyLineFields = DMUtil.splitByDelims(line, COLON_DELIM);
                    if (sequenceAssemblyLineFields.length != 2) {
                        throw new DMFileException(
                                "Invalid gpm psyt file,  the sequence assembly version is not specified");
                    }
                    if (StringUtils.isBlank(sequenceAssembly)) {
                        sequenceAssembly = sequenceAssemblyLineFields[1];
                        gpmDbBean.setSequenceAssembly(sequenceAssembly);
                    }
                }

                if (StringUtils.startsWith(line, SEQUENCE_SOURCE)) {
                    String[] sequenceSourceLineFields = DMUtil.splitByDelims(line, COLON_DELIM);
                    if (sequenceSourceLineFields.length != 2) {
                        throw new DMFileException(
                                "Invalid gpm psyt file,  the sequence source number is not specified");
                    }
                    if (StringUtils.isBlank(sequenceSource)) {
                        sequenceSource = sequenceSourceLineFields[1];
                        gpmDbBean.setSequenceSource(sequenceSource);
                    }
                }

                if (StringUtils.startsWith(line, MAXIMUM_LOG_E)) {
                    String[] maxLogELineFields = DMUtil.splitByDelims(line, COLON_DELIM);
                    if (maxLogELineFields.length != 2) {
                        throw new DMFileException(
                                "Invalid gpm psyt file,  the maximum log(e) number is not specified");
                    }
                    if (StringUtils.isBlank(maximumLoge)) {
                        maximumLoge = maxLogELineFields[1];
                        gpmDbBean.setMaximumLoge(maximumLoge);
                    }
                }

                if (StringUtils.startsWith(line, PROTEIN)) {
                    gpmDbEntryBean = new GPMDbEntryBean();
                    //create the primary dbsource bean;
                    DBSourceBean gpmDbSourceBean = new DBSourceBean();
                    //all genes come from the gpm psty file as a datasource
                    if (gpmDbType.equals(GPMDbType.GPMDB_PSYT)) {
                        gpmDbSourceBean.setDbName(DbAcType.GPMPSYT.type());
                    }
                    if (gpmDbType.equals(GPMDbType.GPMDB_LYS)) {
                        gpmDbSourceBean.setDbName(DbAcType.GPMLYS.type());
                    }
                    if (gpmDbType.equals(GPMDbType.GPMDB_NTA)) {
                        gpmDbSourceBean.setDbName(DbAcType.GPMNTA.type());
                    }
                    gpmDbSourceBean.setPrimaryEvidences(true);
                    gpmDbEntryBean.setPrimaryDbSourceBean(gpmDbSourceBean);

                    //parse the protein accession
                    enspAccession = DMUtil.splitStrByDelim(line, COLON_DELIM)[1];
                    if (StringUtils.isBlank(enspAccession)) {
                        throw new DMFileException("The protein accession number not found");
                    } else {
                        //create an identified accession bean
                        AccessionBean identAccessionBean = createAcBean(enspAccession, DbAcType.Protein.type());
                        gpmDbEntryBean.setIdentifiedAccessionBean(identAccessionBean);
                    }
                }

                //parse gene accession
                if (StringUtils.startsWith(line, GENE)) {
                    ensgAccession = DMUtil.splitStrByDelim(line, COLON_DELIM)[1];
                }

                //parse transcript accession
                if (StringUtils.startsWith(line, TRANSCRIPT)) {
                    enstAccession = DMUtil.splitStrByDelim(line, COLON_DELIM)[1];
                }

                //chromosome fields
                if (StringUtils.startsWith(line, CHROMOSOME)) {
                    String[] chromLineFields = DMUtil.splitByDelims(line, "\t", "\r", "\n");
                    for (String chromField : chromLineFields) {
                        if (StringUtils.startsWith(chromField, CHROMOSOME)) {
                            String[] chromNameFileds = DMUtil.splitStrByDelim(chromField, COLON_DELIM);
                            if (chromNameFileds.length == 2) {
                                chromName = chromNameFileds[1].trim();
                            } else {
                                chromName = NameType.UNKNOWN.cn();
                            }
                        }
                        if (StringUtils.startsWith(chromField, CHROM_START)) {
                            String[] chromStartFields = DMUtil.splitStrByDelim(chromField, COLON_DELIM);
                            if (chromStartFields.length == 2) {
                                chromStart = Integer.valueOf(chromStartFields[1].trim());
                            }
                        }
                        if (StringUtils.startsWith(chromField, CHROM_END)) {
                            String[] chromEndFields = DMUtil.splitStrByDelim(chromField, COLON_DELIM);
                            if (chromEndFields.length == 2) {
                                chromEnd = Integer.valueOf(chromEndFields[1].trim());
                            }
                        }
                        if (StringUtils.startsWith(chromField, CHROM_STRAND)) {
                            String[] chromStrandFields = DMUtil.splitStrByDelim(chromField, COLON_DELIM);
                            if (chromStrandFields.length == 2) {
                                chromStrand = chromStrandFields[1].trim();
                            }
                        }
                    }
                    //create GeneBean
                    GeneBean geneBean = new GeneBean();
                    geneBean.setEnsgAccession(ensgAccession);
                    geneBean.setChromosome(chromName);
                    geneBean.setStartPosition(chromStart);
                    geneBean.setEndPosition(chromEnd);
                    geneBean.setStrand(chromStrand);
                    gpmDbEntryBean.setGeneBean(geneBean);
                }

                //Gene or Protein Desc
                if (StringUtils.startsWith(line, DES_ENSG_ENSP)) {
                    String[] desLineFields = DMUtil.splitByDelims(line, COLON_DELIM);
                    if (desLineFields.length == 2) {
                        String descValue = desLineFields[1];
                        String[] descValueFields = DMUtil.splitByDelims(descValue, ",", "\t");
                        String desc = "";
                        if (descValueFields.length >= 2) {
                            gpmDbEntryBean.getGeneBean().setDisplayName(descValueFields[0]);
                            for (int i = 1; i < descValueFields.length; i++) {
                                desc += descValueFields[i];
                            }
                        } else {
                            desc = descValueFields[0];
                        }
                        gpmDbEntryBean.getGeneBean().setDescription(StringUtils.trim(desc));
                    } else {
                        gpmDbEntryBean.getGeneBean().setDisplayName(NameType.UNKNOWN.cn());
                    }

                }

                //we add non evidence bean first once we meet the tag : modified_peptide_obs
                if (StringUtils.startsWith(line, MODIFIED_PEPTIDE_OBS)) {
                    //create dbsource and accession entry bean
                    List<DbSourceAcEntryBean> dbSourceAcEntryBeanList = parseDBSourceAcEntryBeans(enspAccession,
                            ensgAccession, enstAccession);
                    gpmDbEntryBean.setDbSourceAcEntryBeans(dbSourceAcEntryBeanList);

                    if (gpmDbType.equals(GPMDbType.GPMDB_PSYT)) {
                        //create a non phs s evidence bean
                        PTMEvidenceBean nonPhsSEvidenceBean = createNonEvidenceBean(enspAccession, nominalMass,
                                maximumLoge, GPMPTMSubType.PHS_S, gpmDbType);
                        gpmDbEntryBean.setPtmEvidenceBean(nonPhsSEvidenceBean, GPMPTMSubType.NON_PHS_S);
                        //create a non phs t evidence bean
                        PTMEvidenceBean nonPhsTEvidenceBean = createNonEvidenceBean(enspAccession, nominalMass,
                                maximumLoge, GPMPTMSubType.PHS_T, gpmDbType);
                        gpmDbEntryBean.setPtmEvidenceBean(nonPhsTEvidenceBean, GPMPTMSubType.NON_PHS_T);
                        //create a non phs y evidence bean
                        PTMEvidenceBean nonPhsYEvidenceBean = createNonEvidenceBean(enspAccession, nominalMass,
                                maximumLoge, GPMPTMSubType.PHS_Y, gpmDbType);
                        gpmDbEntryBean.setPtmEvidenceBean(nonPhsYEvidenceBean, GPMPTMSubType.NON_PHS_Y);

                    } else if (gpmDbType.equals(GPMDbType.GPMDB_LYS)) {
                        // Create Non LYS evidence bean first
                        PTMEvidenceBean nonLysEvidenceBean = createNonEvidenceBean(enspAccession, nominalMass,
                                maximumLoge, GPMPTMSubType.LYS, gpmDbType);
                        gpmDbEntryBean.setPtmEvidenceBean(nonLysEvidenceBean, GPMPTMSubType.NON_LYS);

                    } else if (gpmDbType.equals(GPMDbType.GPMDB_NTA)) {
                        //create non nta evidence bean first
                        PTMEvidenceBean nonNtaEvidenceBean = createNonEvidenceBean(enspAccession, nominalMass,
                                maximumLoge, GPMPTMSubType.NTA, gpmDbType);
                        gpmDbEntryBean.setPtmEvidenceBean(nonNtaEvidenceBean, GPMPTMSubType.NON_NTA);
                    }

                    gpmDbEntryBeanList.add(gpmDbEntryBean);
                    counterIndex = gpmDbEntryBeanList.size() - 1;
                }

                //parse the RES: S, T, Y or Others and POS and OBS
                if (StringUtils.startsWith(line, POS)) {
                    String[] posLineFields = DMUtil.splitByDelims(line, "\t", "\r", "\n");
                    for (String posLineField : posLineFields) {
                        if (StringUtils.startsWith(posLineField, POS)) {
                            String[] posFileds = DMUtil.splitByDelims(posLineField, COLON_DELIM);
                            if (posFileds.length == 2) {
                                pos = Integer.valueOf(posFileds[1]);
                            } else {
                                throw new DMFileException("The position value not found.");
                            }
                        }
                        if (StringUtils.startsWith(posLineField, RES)) {
                            String[] resFileds = DMUtil.splitByDelims(posLineField, COLON_DELIM);
                            if (resFileds.length == 2) {
                                res = resFileds[1];
                            } else {
                                throw new DMFileException("The res value not found.");
                            }
                        }
                        if (StringUtils.startsWith(posLineField, OBS)) {
                            String[] obsFileds = DMUtil.splitByDelims(posLineField, COLON_DELIM);
                            if (obsFileds.length == 2) {
                                obs = Integer.valueOf(obsFileds[1].trim());
                            } else {
                                throw new DMFileException("The obs value not found.");
                            }
                        }
                    }

                    PTMEvidenceBean ptmEvidenceBean = createPTMEvidenceBean(nominalMass, pos, res, obs,
                            enspAccession, maximumLoge, gpmDbType);

                    //Identify the type
                    GPMPTMSubType ptmSubType = GPMPTMSubType.PHS_S;

                    if (gpmDbType.equals(GPMDbType.GPMDB_PSYT)) {
                        ptmSubType = GPMPTMSubType.fromType(res);
                    } else if (gpmDbType.equals(GPMDbType.GPMDB_LYS)) {
                        ptmSubType = GPMPTMSubType.LYS;
                    } else if (gpmDbType.equals(GPMDbType.GPMDB_NTA)) {
                        ptmSubType = GPMPTMSubType.NTA;
                    }
                    //add the ptm evidence bean
                    gpmDbEntryBeanList.get(counterIndex).setPtmEvidenceBean(ptmEvidenceBean, ptmSubType);
                }
            }
        }
        logger.info("The total entry size of the " + gpmDbType.type() + " is :" + gpmDbEntryBeanList.size());
        gpmDbBean.setPgmDbEntryBeans(gpmDbEntryBeanList);
        return gpmDbBean;
    } catch (Exception ex) {
        logger.error(ex);
        throw new DMParserException(ex);
    } finally {
        if (ins != null) {
            try {
                ins.close();
            } catch (Exception e) {
                //ignore whatever caught.
            }
        }
    }
}

From source file:com.microsoft.alm.plugin.idea.common.utils.VcsHelper.java

/**
 * Use this method to get the team project name from a TFVC server path.
 * The team project name is always the first folder in the path.
 * If no team project name is found an empty string is returned.
 *
 * @param serverPath/*from w ww. j ava2 s  .co m*/
 * @return
 */
public static String getTeamProjectFromTfvcServerPath(final String serverPath) {
    if (StringUtils.isNotEmpty(serverPath) && StringUtils.startsWith(serverPath, TFVC_ROOT)
            && serverPath.length() > 2) {
        // Find the next separator after the $/
        final int index = serverPath.indexOf(TFVC_SEPARATOR, 2);
        if (index >= 0) {
            return serverPath.substring(2, index);
        } else {
            return serverPath.substring(2);
        }
    }

    logger.info("getTeamProjectFromTfvcServerPath: No project was found.");
    return StringUtils.EMPTY;
}

From source file:it.openutils.mgnlaws.magnolia.init.ClasspathProviderImpl.java

/**
 * @see info.magnolia.repository.Provider#init(info.magnolia.repository.RepositoryMapping)
 *//* w  w w.j  av a  2  s .  com*/
public void init(RepositoryMapping repositoryMapping) throws RepositoryNotInitializedException {
    checkXmlSettings();

    this.repositoryMapping = repositoryMapping;
    /* connect to repository */
    Map params = this.repositoryMapping.getParameters();
    String configFile = (String) params.get(CONFIG_FILENAME_KEY);
    if (!StringUtils.startsWith(configFile, ClasspathPropertiesInitializer.CLASSPATH_PREFIX)) {
        configFile = Path.getAbsoluteFileSystemPath(configFile);
    }
    String repositoryHome = (String) params.get(REPOSITORY_HOME_KEY);
    repositoryHome = getRepositoryHome(repositoryHome);

    // cleanup the path, to remove eventual ../.. and make it absolute
    try {
        File repoHomeFile = new File(repositoryHome);
        repositoryHome = repoHomeFile.getCanonicalPath();
    } catch (IOException e1) {
        // should never happen and it's not a problem at this point, just pass it to jackrabbit and see
    }

    String clusterid = SystemProperty.getProperty(MAGNOLIA_CLUSTERID_PROPERTY);
    if (StringUtils.isNotBlank(clusterid)) {
        System.setProperty(JACKRABBIT_CLUSTER_ID_PROPERTY, clusterid);
    }

    // get it back from system properties, if it has been set elsewhere
    clusterid = System.getProperty(JACKRABBIT_CLUSTER_ID_PROPERTY);

    log.info("Loading repository at {} (config file: {}) - cluster id: \"{}\"",
            new Object[] { repositoryHome, configFile, StringUtils.defaultString(clusterid, "<unset>") });

    bindName = (String) params.get(BIND_NAME_KEY);
    jndiEnv = new Hashtable<String, Object>();
    jndiEnv.put(Context.INITIAL_CONTEXT_FACTORY, params.get(CONTEXT_FACTORY_CLASS_KEY));
    jndiEnv.put(Context.PROVIDER_URL, params.get(PROVIDER_URL_KEY));

    try {
        InitialContext ctx = new InitialContext(jndiEnv);
        // first try to find the existing object if any
        try {
            this.repository = (Repository) ctx.lookup(bindName);
        } catch (NameNotFoundException ne) {
            log.debug("No JNDI bound Repository found with name {}, trying to initialize a new Repository",
                    bindName);
            ClasspathRegistryHelper.registerRepository(ctx, bindName, configFile, repositoryHome, true);
            this.repository = (Repository) ctx.lookup(bindName);
        }
        this.validateWorkspaces();
    } catch (NamingException e) {
        log.error("Unable to initialize repository: " + e.getMessage(), e);
        throw new RepositoryNotInitializedException(e);
    } catch (RepositoryException e) {
        log.error("Unable to initialize repository: " + e.getMessage(), e);
        throw new RepositoryNotInitializedException(e);
    } catch (TransformerFactoryConfigurationError e) {
        log.error("Unable to initialize repository: " + e.getMessage(), e);
        throw new RepositoryNotInitializedException(e);
    }
}

From source file:com.cloudera.cli.validator.components.ParcelFileRunner.java

@Override
public boolean run(String target, Writer writer) throws IOException {
    File parcelFile = new File(target);
    writer.write(String.format("Validating: %s\n", parcelFile.getPath()));

    if (!checkExistence(parcelFile, false, writer)) {
        return false;
    }/*from w ww  . ja v a  2  s.  co m*/

    String expectedDir;
    String distro;
    Matcher parcelMatcher = PARCEL_PATTERN.matcher(parcelFile.getName());
    if (parcelMatcher.find()) {
        expectedDir = parcelMatcher.group(1) + '-' + parcelMatcher.group(2);
        distro = parcelMatcher.group(3);
    } else {
        writer.write(String.format("==> %s is not a valid parcel filename\n", parcelFile.getName()));
        return false;
    }

    if (!KNOWN_DISTROS.contains(distro)) {
        writer.write(String.format("==> %s does not appear to be a distro supported by CM\n", distro));
    }

    FileInputStream fin = null;
    BufferedInputStream bin = null;
    GzipCompressorInputStream gin = null;
    TarArchiveInputStream tin = null;
    try {
        InputStream in = null;

        fin = new FileInputStream(parcelFile);
        bin = new BufferedInputStream(fin);
        try {
            gin = new GzipCompressorInputStream(bin);
            in = gin;
        } catch (IOException e) {
            // It's not compressed. Proceed as if uncompressed tar.
            writer.write(String.format("==> Warning: Parcel is not compressed with gzip\n"));
            in = bin;
        }
        tin = new TarArchiveInputStream(in);

        byte[] parcelJson = null;
        byte[] alternativesJson = null;
        byte[] permissionsJson = null;

        Map<String, Boolean> tarEntries = Maps.newHashMap();
        Set<String> unexpectedDirs = Sets.newHashSet();
        for (TarArchiveEntry e = tin.getNextTarEntry(); e != null; e = tin.getNextTarEntry()) {
            String name = e.getName();

            // Remove trailing '/'
            tarEntries.put(name.replaceAll("/$", ""), e.isDirectory());

            if (!StringUtils.startsWith(name, expectedDir)) {
                unexpectedDirs.add(name.split("/")[0]);
            }

            if (e.getName().equals(expectedDir + PARCEL_JSON_PATH)) {
                parcelJson = new byte[(int) e.getSize()];
                tin.read(parcelJson);
            } else if (e.getName().equals(expectedDir + ALTERNATIVES_JSON_PATH)) {
                alternativesJson = new byte[(int) e.getSize()];
                tin.read(alternativesJson);
            } else if (e.getName().equals(expectedDir + PERMISSIONS_JSON_PATH)) {
                permissionsJson = new byte[(int) e.getSize()];
                tin.read(permissionsJson);
            }
        }

        boolean ret = true;

        if (!unexpectedDirs.isEmpty()) {
            writer.write(String.format("==> The following unexpected top level directories were observed: %s\n",
                    unexpectedDirs.toString()));
            writer.write(
                    String.format("===> The only valid top level directory, based on parcel filename, is: %s\n",
                            expectedDir));
            ret = false;
        }

        ret &= checkParcelJson(expectedDir, parcelJson, tarEntries, writer);
        ret &= checkAlternatives(expectedDir, alternativesJson, tarEntries, writer);
        ret &= checkPermissions(expectedDir, permissionsJson, tarEntries, writer);

        return ret;
    } catch (IOException e) {
        writer.write(String.format("==> %s: %s\n", e.getClass().getName(), e.getMessage()));
        return false;
    } finally {
        IOUtils.closeQuietly(tin);
        IOUtils.closeQuietly(gin);
        IOUtils.closeQuietly(bin);
        IOUtils.closeQuietly(fin);
    }
}