Example usage for java.util Vector iterator

List of usage examples for java.util Vector iterator

Introduction

In this page you can find the example usage for java.util Vector iterator.

Prototype

public synchronized Iterator<E> iterator() 

Source Link

Document

Returns an iterator over the elements in this list in proper sequence.

Usage

From source file:com.globalsight.webservices.Ambassador.java

/**
 * Get job translation percentage//from   www .  j av a  2s.c o  m
 * 
 * @param p_jobId
 *            Job id can not empty.
 * @param p_targetLocales
 *            Target locale can be empty, can be one or more.
 * @return Return xml, for example: <?xml version="1.0" encoding="UTF-8" ?>
 *         <job> <id>280</id> <name>job_4012_861430940</name> <workflows>
 *         <workflow> <targetLocal>French (France) [fr_FR]</targetLocal>
 *         <workflowTranslationPercentage>3%</workflowTranslationPercentage>
 *         <targetPages> <targetPage>
 *         <pageName>en_US\280\Welocalize_Company_IncludingRepeat_Codesensitive
 *         .html</pageName>
 *         <pageTranslationPercentage>100%</pageTranslationPercentage>
 *         </targetPage> <targetPage>
 *         <pageName>en_US\280\Welocalize_Company_IncludingRepeat_Leverage
 *         Match Threshold.html</pageName>
 *         <pageTranslationPercentage>1%</pageTranslationPercentage>
 *         </targetPage> </targetPages> </workflow> </workflows> </job>
 * */
public String getTranslationPercentage(String p_accessToken, String p_jobId, String p_targetLocales)
        throws WebServiceException {
    checkAccess(p_accessToken, GET_TRANSLATION_PERCENTAGE);
    String userName = getUsernameFromSession(p_accessToken);
    Map<Object, Object> activityArgs = new HashMap<Object, Object>();
    activityArgs.put("loggedUserName", userName);
    activityArgs.put("jobId", p_jobId);
    activityArgs.put("targetLocales", p_targetLocales);
    WebServicesLog.Start activityStart = WebServicesLog.start(Ambassador.class,
            "getTranslationPercentage(p_accessToken,p_jobId,p_targetLocales)", activityArgs);
    try {
        Assert.assertNotEmpty(p_jobId);
        Assert.assertIsInteger(p_jobId);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return makeErrorXml(GET_TRANSLATION_PERCENTAGE, e.getMessage());
    }

    Job job = null;
    try {
        job = ServerProxy.getJobHandler().getJobById(Long.parseLong(p_jobId));
        if (job == null) {
            return makeErrorXml(GET_TRANSLATION_PERCENTAGE, "Invalid job id:" + p_jobId);
        }

        if (!isInSameCompany(userName, String.valueOf(job.getCompanyId()))) {
            return makeErrorXml(GET_TRANSLATION_PERCENTAGE,
                    "Invalid job id:" + p_jobId + ", current user is not in the same company with the job.");
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return makeErrorXml(GET_TRANSLATION_PERCENTAGE, e.getMessage());
    }

    Set<Long> trgLocalIdSet = new HashSet<Long>();
    if (StringUtil.isNotEmpty(p_targetLocales)) {
        String[] trgLocalArr = p_targetLocales.split(",");
        GlobalSightLocale targetGSLocale = null;
        for (int i = 0; i < trgLocalArr.length; i++) {
            try {
                targetGSLocale = getLocaleByName(trgLocalArr[i].trim());
                if (targetGSLocale == null) {
                    return makeErrorXml(GET_TRANSLATION_PERCENTAGE,
                            "Invalid target locale: " + trgLocalArr[i].trim());
                }

                long sameId = -1;
                for (Workflow wf : job.getWorkflows()) {
                    if (targetGSLocale.getId() == wf.getTargetLocale().getId()) {
                        sameId = wf.getTargetLocale().getId();
                        trgLocalIdSet.add(targetGSLocale.getId());
                    }
                }
                if (sameId == -1) {
                    return makeErrorXml(GET_TRANSLATION_PERCENTAGE, "Invalid target locale: " + trgLocalArr[i]
                            + ", the current job is not included the target locale.");
                }
            } catch (Exception e) {
                return makeErrorXml(GET_TRANSLATION_PERCENTAGE,
                        "Invalid target locale: " + trgLocalArr[i].trim());
            }
        }
    }

    StringBuffer xml = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n");
    xml.append("<job>\r\n");
    xml.append("\t<id>").append(job.getId()).append("</id>\r\n");
    xml.append("\t<name>").append(job.getJobName()).append("</name>\r\n");
    xml.append("\t<workflows>\r\n");
    Iterator<Workflow> it = job.getWorkflows().iterator();
    while (it.hasNext()) {
        Workflow wf = (Workflow) it.next();
        if (trgLocalIdSet != null && trgLocalIdSet.size() > 0) {
            if (!trgLocalIdSet.contains(wf.getTargetLocale().getId())) {
                continue;
            }
        }

        xml.append("\t\t<workflow>\r\n");
        xml.append("\t\t\t<targetLocal>").append(wf.getTargetLocale().getDisplayName())
                .append("</targetLocal>\r\n");
        int taskPrecentage = SegmentTuvUtil.getTranslatedPercentageForTargetPages(wf.getTargetPages());
        xml.append("\t\t\t<workflowTranslationPercentage>").append(taskPrecentage)
                .append("%</workflowTranslationPercentage>\r\n");
        xml.append("\t\t\t<targetPages>\r\n");
        Vector<TargetPage> trgPages = wf.getTargetPages();
        Iterator<TargetPage> itPages = trgPages.iterator();
        while (itPages.hasNext()) {
            TargetPage page = (TargetPage) itPages.next();
            xml.append("\t\t\t\t<targetPage>\r\n");
            xml.append("\t\t\t\t\t<pageName>").append(page.getExternalPageId()).append("</pageName>\r\n");
            int pagePercentage = SegmentTuvUtil.getTranslatedPercentageForTargetPage(page.getId());
            xml.append("\t\t\t\t\t<pageTranslationPercentage>").append(pagePercentage)
                    .append("%</pageTranslationPercentage>\r\n");
            xml.append("\t\t\t\t</targetPage>\r\n");
        }
        xml.append("\t\t\t</targetPages>\r\n");
        xml.append("\t\t</workflow>\r\n");
    }
    xml.append("\t</workflows>\r\n");
    xml.append("</job>");

    activityStart.end();

    return xml.toString();
}

From source file:com.globalsight.webservices.Ambassador.java

/**
 * Get xliff file profiles id-name map./* w  w  w .j ava 2s.c om*/
 * 
 * @param p_accessToken
 * @return HashMap (Long:String)
 * @throws WebServiceException
 */
public HashMap getXliffFileProfile(String p_accessToken) throws WebServiceException {
    HashMap xliffFPMap = new HashMap();
    checkAccess(p_accessToken, "getXliffFileProfile");
    checkPermission(p_accessToken, Permission.FILE_PROFILES_VIEW);

    Iterator fileProfileIter = null;
    try {
        Collection results = ServerProxy.getFileProfilePersistenceManager().getAllFileProfiles();
        fileProfileIter = results.iterator();
    } catch (Exception e) {
        String message = "Unable to get file profiles from db.";
        logger.error(message, e);
        message = makeErrorXml("getXliffFileProfile", message);
        throw new WebServiceException(message);
    }

    while (fileProfileIter.hasNext()) {
        FileProfile fp = (FileProfile) fileProfileIter.next();
        long knownFormatTypeId = fp.getKnownFormatTypeId();
        // 39 : Xliff
        if (knownFormatTypeId == 39) {
            boolean hasXlfAsExtension = false;
            Vector fileExtensionIds = fp.getFileExtensionIds();
            Iterator iter = null;
            if (fileExtensionIds != null && fileExtensionIds.size() > 0) {
                iter = fileExtensionIds.iterator();
            }
            if (iter == null)
                continue;
            while (iter.hasNext()) {
                long fileExtensionId = ((Long) iter.next()).longValue();
                try {
                    FileExtensionImpl fileExtension = ServerProxy.getFileProfilePersistenceManager()
                            .getFileExtension(fileExtensionId);
                    String extName = fileExtension.getName();
                    if (extName != null && ("xlf".equals(extName) || "xliff".equals(extName))) {
                        hasXlfAsExtension = true;
                    }
                } catch (Exception e) {

                }
            }

            if (hasXlfAsExtension) {
                xliffFPMap.put(fp.getId(), fp.getName());
            }
        }
    }

    return xliffFPMap;
}

From source file:com.globalsight.webservices.Ambassador.java

/**
 * Returns an XML description containing all user information, including ID,
 * first name, last name and status/* www.j a v  a  2  s . co m*/
 * 
 * @return java.lang.String Returns an XML description which contains all
 *         current users information
 * 
 * @exception WebServiceException
 */
public String getAllUsers(String p_accessToken) throws WebServiceException {
    checkAccess(p_accessToken, "getAllUsers");
    checkPermission(p_accessToken, Permission.USERS_VIEW);

    Vector v = null;
    try {
        v = ServerProxy.getUserManager().getUsersForCurrentCompany();
    } catch (Exception e) {
        String message = "Unable to get all users";
        logger.error(message, e);
        message = makeErrorXml("getAllUsers", message);
        throw new WebServiceException(message);
    }
    StringBuffer xml = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n");
    xml.append("<userInformation>\r\n");
    Iterator it = v.iterator();
    while (it.hasNext()) {
        User user = (User) it.next();
        xml.append("<user>\r\n");
        xml.append("\t<id>").append(user.getUserId()).append("</id>\r\n");
        xml.append("\t<name>").append(user.getUserName()).append("</name>\r\n");
        xml.append("\t<firstName>").append(user.getFirstName()).append("</firstName>\r\n");
        xml.append("\t<lastName>").append(user.getLastName()).append("</lastName>\r\n");
        xml.append("\t<status>").append(LdapHelper.getStateAsString(user.getState())).append("</status>\r\n");
        xml.append("</user>\r\n");
    }
    xml.append("</userInformation>\r\n");
    return xml.toString();

}

From source file:com.globalsight.webservices.Ambassador.java

/**
 * Returns an XML description containing all locale pairs information
 * // ww  w.j av a  2 s .c om
 * @param p_accessToken
 * 
 * @return java.lang.String An XML description which contains all locale
 *         pairs information
 * 
 * @throws WebServiceException
 */
public String getAllLocalePairs(String p_accessToken) throws WebServiceException {
    checkAccess(p_accessToken, "getAllLocalePairs");
    checkPermission(p_accessToken, Permission.LOCALE_PAIRS_VIEW);

    Vector v = null;
    try {
        v = ServerProxy.getLocaleManager().getSourceTargetLocalePairs();
    } catch (Exception e) {
        String message = "Unable to get all locale pairs";
        logger.error(message, e);
        message = makeErrorXml("getAllLocalePairs", message);
        throw new WebServiceException(message);
    }
    StringBuffer xml = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n");
    xml.append("<LocalePairInformation>\r\n");
    Iterator it = v.iterator();
    while (it.hasNext()) {
        LocalePair lp = (LocalePair) it.next();
        xml.append("<localePair>\r\n");
        xml.append("\t<id>").append(lp.getId()).append("</id>\r\n");
        xml.append("\t<sourceLocale>\r\n");
        xml.append("\t<code>").append(lp.getSource().toString()).append("</code>\r\n");
        xml.append("\t<displayName>").append(lp.getSource().getDisplayName()).append("</displayName>\r\n");
        xml.append("\t</sourceLocale>\r\n");
        xml.append("\t<targetLocale>\r\n");
        xml.append("\t<code>").append(lp.getTarget().toString()).append("</code>\r\n");
        xml.append("\t<displayName>").append(lp.getTarget().getDisplayName()).append("</displayName>\r\n");
        xml.append("\t</targetLocale>\r\n");
        xml.append("</localePair>\r\n");
    }
    xml.append("</LocalePairInformation>\r\n");
    return xml.toString();

}

From source file:com.globalsight.webservices.Ambassador.java

/**
 * Searchs entries in tm./*from  w  w w .j av a  2  s.  c  o m*/
 * 
 * An example XML response is:
 * 
 * <pre>
 * &lt;entries&gt;
 *     &lt;entry&gt;
 *         &lt;percentage&gt;100%&lt;/percentage&gt;
 *         &lt;source&gt;
 *           &lt;locale&gt;en_US&lt;/sourceLocale&gt;
 *           &lt;segment&gt;source_100%&lt;/segment&gt;
 *         &lt;/source&gt;
 *         &lt;target&gt;
 *           &lt;locale&gt;fr_FR&lt;/sourceLocale&gt;
 *           &lt;segment&gt;target_fr_FR&lt;/segment&gt;
 *         &lt;/target&gt;
 *     &lt;/entry&gt;
 * 
 *     &lt;entry&gt;
 *         &lt;percentage&gt;90%&lt;/percentage&gt;
 *         &lt;source&gt;
 *           &lt;locale&gt;en_US&lt;/sourceLocale&gt;
 *           &lt;segment&gt;source_90%&lt;/segment&gt;
 *         &lt;/source&gt;
 *         &lt;target&gt;
 *           &lt;locale&gt;de_DE&lt;/sourceLocale&gt;
 *           &lt;segment&gt;target_de_DE&lt;/segment&gt;
 *         &lt;/target&gt;
 *     &lt;/entry&gt;
 * lt;/entries&gt;
 * </pre>
 * 
 * @param tmProfileName
 *            The name of tm profile, can not be null.
 * @param string
 *            Search entries will according to it, can not be null.
 * @param sourceLocale
 *            The locale of segment, can not be null.
 * @param escapeString
 *            Is convert all the escapable characters into their string
 *            (escaped) equivalents or not, the value must be 'true' or
 *            'false'.
 * @return The search result, may be null.
 * @throws WebServiceException
 * 
 * @see #login(username, password)
 */
public String searchEntries(String p_accessToken, String p_tmProfileName, String p_string,
        String p_sourceLocale, String escapeString) throws WebServiceException {
    try {
        Assert.assertNotEmpty(p_accessToken, "access token");
        Assert.assertNotEmpty(p_tmProfileName, "tm profile name");
        Assert.assertNotEmpty(p_sourceLocale, "source locale");
        Assert.assertNotEmpty(p_string, "source string");
        if (escapeString == null || escapeString.trim().length() == 0
                || (!"true".equals(escapeString.trim()) && !"false".equals(escapeString.trim()))) {
            escapeString = "false";
        }
        escapeString = escapeString.toLowerCase();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new WebServiceException(e.getMessage());
    }

    checkAccess(p_accessToken, "searchEntries");
    // checkPermission(p_accessToken, Permission.SERVICE_TM_SEARCH_ENTRY);

    StringBuilder returnString = new StringBuilder(XML_HEAD);
    returnString.append("<entries>");

    LeverageMatchResults levMatchResult = null;
    Vector localePairs = null;
    try {
        localePairs = ServerProxy.getLocaleManager().getSourceTargetLocalePairs();
    } catch (Exception e) {
        String message = "Unable to get all locale pairs";
        logger.error(message, e);
        throw new WebServiceException(message);
    }

    GlobalSightLocale sourceLocale = getLocaleByName(p_sourceLocale);
    Session session = null;
    WebServicesLog.Start activityStart = null;
    try {
        String loggedUserName = this.getUsernameFromSession(p_accessToken);
        Map<Object, Object> activityArgs = new HashMap<Object, Object>();
        activityArgs.put("loggedUserName", loggedUserName);
        activityArgs.put("tmProfileName", p_tmProfileName);
        activityArgs.put("string", p_string);
        activityArgs.put("sourceLocale", p_sourceLocale);
        activityArgs.put("escapeString", escapeString);
        activityStart = WebServicesLog.start(Ambassador.class,
                "searchEntries(p_accessToken,p_tmProfileName,p_string,p_sourceLocale,escapeString)",
                activityArgs);

        session = HibernateUtil.getSession();
        Leverager leverager = new Leverager(session);
        LeveragingLocales levLocales = new LeveragingLocales();

        Map<String, List<LeveragedTuv>> storedTuvs = new HashMap<String, List<LeveragedTuv>>();
        ArrayList trgLocales = new ArrayList();
        Iterator it = localePairs.iterator();
        while (it.hasNext()) {
            LocalePair localePair = (LocalePair) it.next();
            if (localePair.getSource().equals(sourceLocale)) {
                GlobalSightLocale targetLocale = localePair.getTarget();
                trgLocales.add(targetLocale);
                levLocales.setLeveragingLocale(targetLocale, null);
            }
        }

        TranslationMemoryProfile tmp = TMProfileHandlerHelper.getTMProfileByName(p_tmProfileName);
        if (tmp == null) {
            String message = "Unable to get translation memory profile:" + p_tmProfileName;
            logger.error(message);
            throw new WebServiceException(message);
        }
        ProjectTM ptm = ServerProxy.getProjectHandler().getProjectTMById(tmp.getProjectTmIdForSave(), false);
        String companyId = String.valueOf(ptm.getCompanyId());

        Set tmIdsOverride = new HashSet();
        Vector<LeverageProjectTM> tms = tmp.getProjectTMsToLeverageFrom();
        for (LeverageProjectTM tm : tms) {
            tmIdsOverride.add(tm.getProjectTmId());
        }

        OverridableLeverageOptions levOptions = new OverridableLeverageOptions(tmp, levLocales);

        int threshold = (int) tmp.getFuzzyMatchThreshold();
        levOptions.setMatchThreshold(threshold);
        levOptions.setTmsToLeverageFrom(tmIdsOverride);
        boolean isTmProcedence = tmp.isTmProcendence();
        String segment = wrapSegment(p_string, Boolean.valueOf(escapeString));
        PageTmTu tu = new PageTmTu(-1, -1, "plaintext", "text", true);
        PageTmTuv tuv = new PageTmTuv(-1, segment, sourceLocale);
        tuv.setTu(tu);
        tuv.setExactMatchKey();
        tu.addTuv(tuv);

        Iterator<LeverageMatches> itLeverageMatches = LingServerProxy.getTmCoreManager()
                .leverageSegments(Collections.singletonList(tuv), sourceLocale, trgLocales, levOptions)
                .leverageResultIterator();

        long jobId = -1;// -1 is fine here.
        // In fact only ONE levMatches in this iterator.
        while (itLeverageMatches.hasNext()) {
            LeverageMatches levMatches = (LeverageMatches) itLeverageMatches.next();

            // walk through all target locales in the LeverageMatches
            Iterator itLocales = levMatches.targetLocaleIterator(jobId);
            while (itLocales.hasNext()) {
                GlobalSightLocale tLocale = (GlobalSightLocale) itLocales.next();
                // walk through all matches in the locale
                Iterator itMatch = levMatches.matchIterator(tLocale, jobId);
                while (itMatch.hasNext()) {
                    LeveragedTuv matchedTuv = (LeveragedTuv) itMatch.next();

                    if (matchedTuv.getScore() < threshold) {
                        continue;
                    }

                    List<LeveragedTuv> tuvs = storedTuvs.get(tLocale.toString());
                    if (tuvs == null) {
                        tuvs = new ArrayList<LeveragedTuv>();
                        storedTuvs.put(tLocale.toString(), tuvs);
                    }

                    storedTuvs.get(tLocale.toString()).add(matchedTuv);
                }
            }
        }

        Set<String> localeNames = storedTuvs.keySet();
        if (localeNames.size() > 0) {
            Connection connection = null;
            try {
                connection = ConnectionPool.getConnection();
                String tmName = "";

                for (String name : localeNames) {
                    List<LeveragedTuv> matchedTuvs = storedTuvs.get(name);
                    Collections.sort(matchedTuvs, getMatchedTuvComparator(levOptions, isTmProcedence));
                    int size = Math.min(matchedTuvs.size(), (int) tmp.getNumberOfMatchesReturned());
                    for (int i = 0; i < size; i++) {
                        LeveragedTuv matchedTuv = matchedTuvs.get(i);
                        BaseTmTuv sourceTuv = matchedTuv.getSourceTuv();

                        long tmId = sourceTuv.getTu().getTmId();
                        logger.info("tmId : " + tmId);
                        try {
                            tmName = getProjectTmName(tmId, connection);
                        } catch (Exception e) {
                            logger.error("Cannot get tm name.", e);
                        }
                        logger.info("tmName : " + tmName);
                        String strTmId = "'" + tmId + "'";

                        String entryXml = MessageFormat.format(ENTRY_XML, strTmId, tmName,
                                matchedTuv.getScore(), sourceTuv.getSid(), sourceTuv.getLocale(),
                                sourceTuv.getSegmentNoTopTag(), matchedTuv.getLocale(),
                                matchedTuv.getSegmentNoTopTag());

                        if (sourceTuv.getSid() == null || sourceTuv.getSid().length() == 0) {
                            entryXml = entryXml.replaceAll("\r\n\t\t<sid>.*?</sid>", "");
                        }

                        returnString.append(entryXml);
                    }
                    // Remained trgLocales have no tm matches better than
                    // threshold
                    for (int i = 0; i < trgLocales.size(); i++) {
                        GlobalSightLocale trgLocale = (GlobalSightLocale) trgLocales.get(i);
                        if (trgLocale.toString().equals(name)) {
                            trgLocales.remove(trgLocale);
                        }
                    }
                }
            } catch (Exception e) {
                logger.error("Error found in searchEntries(...).", e);
            } finally {
                ConnectionPool.returnConnection(connection);
            }
        }

        // Return NULL_XML if no TM matches whose score is higher than TM
        // threshold.
        if (localeNames.size() == 0) {
            return NULL_XML;
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new WebServiceException(e.getMessage());
    } finally {
        if (activityStart != null) {
            activityStart.end();
        }
        try {
            if (session != null) {
                session.close();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new WebServiceException(e.getMessage());
        }
    }

    returnString.append("\r\n</entries>");
    return returnString.toString();
}