Example usage for java.util HashMap containsKey

List of usage examples for java.util HashMap containsKey

Introduction

In this page you can find the example usage for java.util HashMap containsKey.

Prototype

public boolean containsKey(Object key) 

Source Link

Document

Returns true if this map contains a mapping for the specified key.

Usage

From source file:edu.cornell.mannlib.vitro.webapp.controller.freemarker.ViewLabelsServlet.java

private HashMap<String, List<LabelInformation>> getLabelsSortedByLanguageName(List<Literal> labels,
        Map<String, String> localeCodeToNameMap, VitroRequest vreq, String subjectUri) {

    //Iterate through the labels and create a hashmap
    HashMap<String, List<LabelInformation>> labelsHash = new HashMap<String, List<LabelInformation>>();

    for (Literal l : labels) {
        String languageTag = l.getLanguage();
        String languageName = "";
        if (languageTag == "") {
            languageName = "untyped";
        } else if (localeCodeToNameMap.containsKey(languageTag)) {
            languageName = localeCodeToNameMap.get(languageTag);
        } else {//  www. j  av a 2s . co m
            log.warn("This language tag " + languageTag
                    + " does not have corresponding name in the system and was not processed");
        }

        if (languageName != "") {
            if (!labelsHash.containsKey(languageName)) {
                labelsHash.put(languageName, new ArrayList<LabelInformation>());
            }
            ArrayList<LabelInformation> labelsList = (ArrayList<LabelInformation>) labelsHash.get(languageName);
            //This should put the label in the list
            //Create label information instance with the required information
            //To generate link

            labelsList.add(new LabelInformation(l, languageTag, languageName));
        }
    }

    //Sort each label list
    LabelInformationComparator lic = new LabelInformationComparator();
    for (String languageName : labelsHash.keySet()) {
        List<LabelInformation> labelInfo = labelsHash.get(languageName);
        Collections.sort(labelInfo, lic);
    }
    return labelsHash;

}

From source file:com.proctorcam.proctorserv.ProctorservApi.java

/**
 *  Checks options (HashMap) for required parameters provided in arguments (String[]).
 *
 *  Iterates through arguments to check if parameters in arguments represent keys in
 *  options. If not found, MissingRequiredParameterException is thrown and an error
 *  message is displayed. /*from  w w  w .  j  a  va2s .c o m*/
 */

protected void requiresOf(HashMap<String, Object> options, String[] arguments)
        throws MissingRequiredParameterException {
    for (int i = 0; i < (arguments.length) - 1; i++) {
        if (options.containsKey(arguments[i]) == false) {
            throw new MissingRequiredParameterException(arguments[i] + " is a required parameter");
        }
    }
}

From source file:com.concursive.connect.web.modules.api.beans.TransactionItem.java

public void setObject(Element element, HashMap mapping) throws Exception {
    name = element.getTagName();/*  w  w w. ja v  a 2s  . c o  m*/
    if (mapping.containsKey(name)) {
        SyncTable thisMapping = (SyncTable) mapping.get(name);
        // Instantiate the object
        object = Class.forName(thisMapping.getMappedClassName()).newInstance();
        LOG.debug("Instantiated object: " + object.getClass().getName());
    } else {
        LOG.warn("Mapping does not exist for creating object: " + name);
    }
}

From source file:com.trellmor.berrymotes.sync.SubredditEmoteDownloader.java

private List<EmoteImage> getEmoteList() throws IOException, RemoteException, OperationApplicationException,
        URISyntaxException, InterruptedException {
    Log.debug("Getting emote list");
    List<EmoteImage> emotes = downloadEmoteList();

    if (emotes != null) {
        checkInterrupted();//from  w  w w  .j av a 2  s . com

        HashMap<String, EmoteImage> emotesHash = new HashMap<String, EmoteImage>();
        int i = 0;
        while (i < emotes.size()) {
            EmoteImage emote = emotes.get(i);
            if (!mDownloadNSFW && emote.isNsfw()) {
                Log.debug("Skipped emote " + emote.getImage() + " (NSFW)");
                emotes.remove(i);
                continue;
            } else {
                if (!emotesHash.containsKey(emote.getHash())) {
                    emotesHash.put(emote.getHash(), emote);
                } else {
                    EmoteImage collision = emotesHash.get(emote.getHash());
                    Log.error("Hash collission! " + emote.getImage() + " (" + emote.getHash() + ") <-> "
                            + collision.getImage() + " (" + collision.getHash() + ")");
                }
            }
            i++;
        }
        Log.info("Removed ignored emotes, " + Integer.toString(emotesHash.size()) + " left.");

        checkInterrupted();
        Cursor c = mContentResolver.query(EmotesContract.Emote.CONTENT_URI_DISTINCT,
                new String[] { EmotesContract.Emote.COLUMN_HASH, EmotesContract.Emote.COLUMN_IMAGE },
                EmotesContract.Emote.COLUMN_SUBREDDIT + "=?", new String[] { mSubreddit }, null);
        if (c != null) {
            ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
            try {
                if (c.moveToFirst()) {
                    final int POS_HASH = c.getColumnIndex(EmotesContract.Emote.COLUMN_HASH);
                    final int POS_IMAGE = c.getColumnIndex(EmotesContract.Emote.COLUMN_IMAGE);
                    do {
                        String hash = c.getString(POS_HASH);
                        if (!emotesHash.containsKey(hash)) {
                            Log.debug("Removing " + c.getString(POS_IMAGE) + " (" + hash
                                    + ") (not in emote list)");
                            batch.add(ContentProviderOperation.newDelete(EmotesContract.Emote.CONTENT_URI)
                                    .withSelection(EmotesContract.Emote.COLUMN_HASH + "=?",
                                            new String[] { hash })
                                    .build());

                            mEmoteDownloader.checkStorageAvailable();
                            File file = new File(c.getString(POS_IMAGE));
                            if (file.exists()) {
                                file.delete();
                            }
                        }
                    } while (c.moveToNext());
                }

                c.close();

            } finally {
                Log.debug("Removing emotes from DB");
                applyBatch(batch);
                mSyncResult.stats.numDeletes += batch.size();
                Log.info("Removed " + Integer.toString(batch.size()) + " emotes from DB");
            }
        }
    }
    return emotes;
}

From source file:com.andrada.sitracker.reader.Samlib.java

@Override
public boolean updateAuthor(@NotNull Author author) throws SQLException {
    boolean authorUpdated = false;
    HttpRequest request;/*from www .ja v  a2  s  . c  o  m*/
    AuthorPageReader reader;
    try {
        URL authorURL = new URL(author.getUrl());
        request = HttpRequest.get(authorURL);
        if (request.code() == 404) {
            //skip this author
            //Not available atm
            return false;
        }
        if (!authorURL.getHost().equals(request.url().getHost())) {
            //We are being redirected hell knows where.
            //Skip
            return false;
        }
        //TODO OutOfMemory thrown here
        reader = new SamlibAuthorPageReader(request.body());
        //We go a blank response but no exception, skip author
        if (reader.isPageBlank()) {
            return false;
        }
    } catch (MalformedURLException e) {
        //Just swallow exception, as this is unlikely to happen
        //Skip author
        trackException(e.getMessage());
        return false;
    } catch (HttpRequest.HttpRequestException e) {
        //Author currently inaccessible or no internet
        //Skip author
        trackException(e.getMessage());
        return false;
    }
    AuthorDao authorDao = null;
    PublicationDao publicationsDao = null;

    try {
        publicationsDao = helper.getDao(Publication.class);
    } catch (SQLException e) {
        Log.e("Samlib", "Could not create DAO publicationsDao", e);
    }
    try {
        authorDao = helper.getDao(Author.class);
    } catch (SQLException e) {
        Log.e("Samlib", "Could not create DAO authorDao", e);
    }

    assert authorDao != null;
    assert publicationsDao != null;

    String authImgUrl = reader.getAuthorImageUrl(author.getUrl());
    String authDescription = reader.getAuthorDescription();
    if (authImgUrl != null) {
        author.setAuthorImageUrl(authImgUrl);
    }
    if (authDescription != null) {
        author.setAuthorDescription(authDescription);
    }

    authorDao.update(author);

    ForeignCollection<Publication> oldItems = author.getPublications();
    List<Publication> newItems = reader.getPublications(author);

    HashMap<String, Publication> oldItemsMap = new HashMap<String, Publication>();
    for (Publication oldPub : oldItems) {
        oldItemsMap.put(oldPub.getUrl(), oldPub);
    }

    if (newItems.size() == 0 && oldItemsMap.size() > 1) {
        LogUtils.LOGW(Constants.APP_TAG,
                "Something went wrong. No publications found for author that already exists");
        //Just skip for now to be on the safe side.
        return false;
    }

    for (Publication pub : newItems) {
        //Find pub in oldItems
        if (oldItemsMap.containsKey(pub.getUrl())) {
            Publication old = oldItemsMap.get(pub.getUrl());
            if (old.getUpdatesIgnored()) {
                //Do not check anything
                continue;
            }
            //Check size/name/description
            if (pub.getSize() != old.getSize() || !pub.getName().equals(old.getName())) {
                //if something differs
                //Store the old size
                if (old.getOldSize() != 0) {
                    pub.setOldSize(old.getOldSize());
                } else {
                    pub.setOldSize(old.getSize());
                }
                //Swap the ids, do an update in DB
                pub.setId(old.getId());
                //Copy over custom properties that do not relate to samlib
                pub.setMyVote(old.getMyVote());
                pub.setVoteCookie(old.getVoteCookie());
                pub.setVoteDate(old.getVoteDate());
                pub.setUpdatesIgnored(old.getUpdatesIgnored());
                pub.setNew(true);
                authorUpdated = true;
                publicationsDao.update(pub);
                //Mark author new, update in DB
                author.setUpdateDate(new Date());
                author.setNew(true);
                authorDao.update(author);
            } else if (!StringUtils.equalsIgnoreCase(old.getImagePageUrl(), pub.getImagePageUrl())) {
                pub.setId(old.getId());
                //Update silently
                publicationsDao.update(pub);
            }
        } else {
            //Mark author new, update in DB
            author.setUpdateDate(new Date());
            author.setNew(true);
            authorDao.update(author);
            //Mark publication new, create in DB
            pub.setNew(true);
            authorUpdated = true;
            publicationsDao.create(pub);
        }
    }

    return authorUpdated;
}

From source file:freenet.client.ArchiveManager.java

private void addToDirectory(HashMap<String, Object> dir, String name, String prefix)
        throws ArchiveFailureException {
    int x = name.indexOf('/');
    if (x < 0) {
        if (dir.containsKey(name)) {
            throw new ArchiveFailureException("Invalid archive: contains " + prefix + name + " twice");
        }/*from ww  w  .ja  v a 2  s. c om*/
        dir.put(name, name);
    } else {
        String before = name.substring(0, x);
        String after;
        if (x == name.length() - 1) {
            // Last char
            after = "";
        } else
            after = name.substring(x + 1, name.length());
        Object o = dir.get(before);
        if (o == null) {
            dir.put(before, o = new HashMap<String, Object>());
        } else if (o instanceof String) {
            throw new ArchiveFailureException("Invalid archive: contains " + name + " as both file and dir");
        }
        addToDirectory(Metadata.forceMap(o), after, prefix + before + '/');
    }
}

From source file:it.intecs.pisa.openCatalogue.solr.SolrHandler.java

private String prepareUrl2(HashMap<String, String> request) throws UnsupportedEncodingException, Exception {
    String[] params = request.keySet().toArray(new String[0]);
    String fq = "";
    String q = this.solrHost + "/select?q=*%3A*&wt=xml&indent=true";

    if (request.containsKey("q") && (request.get("q").equals("*.*") == false)) {
        String newQ = request.get("q");
        if (null == newQ || newQ.isEmpty())
            newQ = "*%3A*";
        q = this.solrHost + "/select?q=" + URLDecoder.decode(newQ, "ISO-8859-1") + "&wt=xml&indent=true";
    }/* w  ww  .  ja  va2s .c  o m*/

    String lat = null;
    String lon = null;
    String radius = null;

    for (String name : params) {
        String value = request.get(name);

        if (value != null && value.equals("") == false) {
            if (name.equals("count")) {
                q += "&rows=" + value;
            } else if (name.equals("startPage")) {
            } else if (name.equals("startIndex")) {
                q += "&start=" + (Integer.parseInt(value) - 1);
            } else if (name.equals("uid")) {
            } else if (name.equals("bbox")) {
                String[] values = value.split(",");
                if (values.length != 4) {
                    throw new Exception();
                }
                value = "[" + values[1] + "," + values[0] + " " + values[3] + "," + values[2] + "]";
                Log.debug("BBOX " + value);
                fq += " AND posList:" + URLDecoder.decode(value, "ISO-8859-1");
            } else if (name.equals("geom")) {
                fq += " AND posList :\"Intersects(" + (URLDecoder.decode(value, "ISO-8859-1")) + ")\"";
            } else if (name.equals("id")) {
                fq += " AND id:\"" + URLDecoder.decode(value, "ISO-8859-1") + "\"";
            } else if (name.equals("lat")) {
                lat = URLDecoder.decode(value, "ISO-8859-1");
            } else if (name.equals("lon")) {
                lon = URLDecoder.decode(value, "ISO-8859-1");
            } else if (name.equals("radius")) {
                radius = URLDecoder.decode(value, "ISO-8859-1");
            } else if (name.equals("startdate")) {
                value = value.endsWith("Z") ? value : value + "Z";
                fq += " AND beginPosition:[" + URLDecoder.decode(value, "ISO-8859-1") + " TO *]";
            } else if (name.equals("stopdate")) {
                value = value.endsWith("Z") ? value : value + "Z";
                fq += " AND endPosition:[* TO " + URLDecoder.decode(value, "ISO-8859-1") + "]";
            } else if (name.equals("tp")) {
            }
            //Table 3 - OpenSearch Parameters for Collection Search
            else if (name.equals("pt")) {
                fq += parse("productType", value);
            } else if (name.equals("psn")) {
                fq += parse("platformShortName", value);
            } else if (name.equals("psi")) {
                fq += parse("platformSerialIdentifier", value);
            } else if (name.equals("inst")) {
                fq += parse("instrument", value);
            } else if (name.equals("st")) {
                fq += parse("sensorType", value);
            } else if (name.equals("ct")) {
                fq += parse("compositeType", value);
            } else if (name.equals("pl")) {
                fq += parse("processingLevel", value);
            } else if (name.equals("ot")) {
                fq += parse("orbitType", value);
            } else if (name.equals("res")) {
                fq += parse("resolution", value);
            } else if (name.equals("sr")) {
                fq += parse("spectralRange", value);
            } else if (name.equals("wl")) {
                fq += parse("wavelengths", value);
            } else if (name.equals("ul")) {
                fq += parse("useLimitation", value);
            } else if (name.equals("hsc")) {
                fq += parse("hasSecurityConstraints", value);
            } else if (name.equals("orgname")) {
                fq += parse("organisationName", value);
            } else if (name.equals("diss")) {
                fq += parse("dissemination", value);
            }
            //Table 4 - OpenSearch Parameters for Product Search
            else if (name.equals("pid")) {
                fq += parse("parentIdentifier", value);
            } else if (name.equals("ps")) {//productionStatus
                fq += parse("productionStatus", value);
            } else if (name.equals("at")) {
                fq += parse("acquisitionType", value);
            } else if (name.equals("on")) {
                fq += parse("orbitNumber", value);
            } else if (name.equals("od")) {
                fq += parse("orbitDirection", value);
            } else if (name.equals("tr")) {
                fq += parse("track", value);
            } else if (name.equals("fr")) {
                fq += parse("frame", value);
            } else if (name.equals("si")) {
                fq += parse("swathIdentifier", value);
            } else if (name.equals("cc")) {
                fq += parse("cloudCover", value);
            } else if (name.equals("sc")) {
                fq += parse("snowCover", value);
            } else if (name.equals("pqd")) {
                fq += parse("productQualityDegradation", value);
            } else if (name.equals("pqdt")) {
                fq += parse("productQualityDegradationTag", value);
            } else if (name.equals("pn")) {
                fq += parse("processorName", value);
            } else if (name.equals("pcen")) {
                fq += parse("processingCenter", value);
            } else if (name.equals("pd")) {
                fq += parse("processingDate", value);
            } else if (name.equals("sm")) {
                fq += parse("sensorMode", value);
            } else if (name.equals("ac")) {
                fq += parse("archivingCenter", value);
            } else if (name.equals("procm")) {
                fq += parse("processingMode", value);
            }
            //Table 5 - OpenSearch Parameters for Acquistion Parameters Search                
            // todo availabilityTime
            else if (name.equals("as")) {
                fq += parse("acquisitionStation", value);
            } else if (name.equals("ast")) {
                fq += parse("acquisitionSubType", value);
            } else if (name.equals("stfan")) {
                fq += parse("startTimeFromAscendingNode", value);
            } else if (name.equals("ctfan")) {
                fq += parse("completionTimeFromAscendingNode", value);
            } else if (name.equals("iaa")) {
                fq += parse("illuminationAzimuthAngle", value);
            } else if (name.equals("iza")) {
                fq += parse("illuminationZenithAngle", value);
            } else if (name.equals("iea")) {
                fq += parse("illuminationElevationAngle", value);
            } else if (name.equals("pm")) {
                fq += parse("polarisationMode", value);
            } else if (name.equals("pc")) {
                fq += parse("polarisationChannels", value);
            } else if (name.equals("ald")) {
                fq += parse("antennaLookDirection", value);
            } else if (name.equals("minia")) {
                fq += parse("minimumIncidenceAngle", value);
            } else if (name.equals("maxia")) {
                fq += parse("maximumIncidenceAngle", value);
            } else if (name.equals("df")) {
                fq += parse("dopplerFrequency", value);
            } else if (name.equals("iav")) {
                fq += parse("incidenceAngleVariation", value);
            } else {
            }
        }
    }

    if ((lat != null) && (lon != null) && (radius != null)) {
        fq += " AND posList :\"Intersects(Circle(" + lon + "," + lat + " d=" + radius + "))\"";
    }

    String url = q;
    if (fq.length() > 1) {
        url += "&fq=" + URLEncoder.encode(fq.substring(5), "ISO-8859-1");
    }
    return url;
}

From source file:eu.sisob.uma.NPL.Researchers.GateResearcherAnnCollector.java

/**
 *
 * @param doc/*from  w  w  w. java 2  s .c o  m*/
 * @param aoData
 */
@Override
public void collect(Object doc, MiddleData aoData) {
    int n_expressions = 0;
    org.dom4j.Element eOut = org.dom4j.DocumentFactory.getInstance().createElement("blockinfo");
    eOut.addAttribute(DataExchangeLiterals.MIDDLE_ELEMENT_XML_ID_ANNOTATIONRECOLLECTING,
            aoData.getId_annotationrecollecting()); // aoData[MiddleData.I_INDEX_DATA_TYPE].toString());
    eOut.addAttribute(DataExchangeLiterals.MIDDLE_ELEMENT_XML_ID_ENTITY_ATT, aoData.getId_entity()); // aoData[MiddleData.I_INDEX_DATA_ID].toString());

    gate.Document docGate = (gate.Document) doc;

    HashMap<String, String> extra_data = null;
    try {
        extra_data = (HashMap<String, String>) aoData.getData_extra();
    } catch (Exception ex) {
        extra_data = null;
    }
    boolean collect_expressions = false;
    List<String> expression_to_collect = new ArrayList<String>();
    if (extra_data != null) {
        if (extra_data.containsKey(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_BLOCK_TYPE)) {

            String block_type = extra_data.get(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_BLOCK_TYPE);
            if (block_type.equals(CVBlocks.CVBLOCK_REST.toString())) {
                expression_to_collect.add("ProfessionalActivityCurrent");
                expression_to_collect.add("ProfessionalActivityNoCurrent");
                expression_to_collect.add("AccreditedUniversityStudiesOtherPostGrade");
                expression_to_collect.add("AccreditedUniversityStudiesDegree");
                expression_to_collect.add("AccreditedUniversityStudiesPhDStudies");
                collect_expressions = true;
            } else if (block_type.equals(CVBlocks.CVBLOCK_PROFESSIONAL_ACTIVITY.toString())) {
                expression_to_collect.add("ProfessionalActivityCurrent");
                expression_to_collect.add("ProfessionalActivityNoCurrent");
                collect_expressions = true;
            } else if (block_type.equals(CVBlocks.CVBLOCK_UNIVERSITY_STUDIES.toString())) {
                expression_to_collect.add("AccreditedUniversityStudiesOtherPostGrade");
                expression_to_collect.add("AccreditedUniversityStudiesDegree");
                expression_to_collect.add("AccreditedUniversityStudiesPhDStudies");
                collect_expressions = true;
            }

        } else {

            expression_to_collect.add("ProfessionalActivityCurrent");
            expression_to_collect.add("ProfessionalActivityNoCurrent");
            expression_to_collect.add("AccreditedUniversityStudiesOtherPostGrade");
            expression_to_collect.add("AccreditedUniversityStudiesDegree");
            expression_to_collect.add("AccreditedUniversityStudiesPhDStudies");
            collect_expressions = true;
        }
    } else {

        expression_to_collect.add("ProfessionalActivityCurrent");
        expression_to_collect.add("ProfessionalActivityNoCurrent");
        expression_to_collect.add("AccreditedUniversityStudiesOtherPostGrade");
        expression_to_collect.add("AccreditedUniversityStudiesDegree");
        expression_to_collect.add("AccreditedUniversityStudiesPhDStudies");
        collect_expressions = true;
    }

    eOut.addAttribute("URL", docGate.getSourceUrl() != null ? docGate.getSourceUrl().toString() : "");

    AnnotationSet annoset = docGate.getAnnotations();

    if (collect_expressions) {

        List<Annotation> anns = new ArrayList<Annotation>();

        for (String exp : expression_to_collect)
            anns.addAll(annoset.get(exp));

        //Collections.sort(anns, new OffsetBeginEndComparator());

        //need to bee order
        if (anns.size() > 0) {
            for (Annotation an : anns) {
                String cvnItemName = an.getType();
                org.dom4j.Element eAux = new org.dom4j.DocumentFactory().createElement(cvnItemName);
                //                        eAux.addElement("Domain").addText(gate.Utils.stringFor(docGate,
                //                                                          an.getStartNode().getOffset() > 100 ? an.getStartNode().getOffset() - 100 : an.getStartNode().getOffset(),
                //                                                          an.getEndNode().getOffset() + 100 < docGate.getContent().size() ? an.getEndNode().getOffset() + 100 :  an.getEndNode().getOffset()));
                eAux.addAttribute("action_mode", "add");
                eAux.addElement("Content").addText(gate.Utils.stringFor(docGate, an));
                FeatureMap fmap = an.getFeatures();
                for (Object key : fmap.keySet()) {
                    String fieldName = key.toString();
                    eAux.addElement(fieldName).addText(fmap.get(key).toString());
                }
                eOut.add(eAux);
            }
        }

        n_expressions += eOut.elements().size();
    }

    collect_expressions = false;
    if (extra_data != null) {
        if (extra_data.containsKey(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_BLOCK_TYPE)) {

            String block_type = extra_data.get(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_BLOCK_TYPE);
            if (block_type.equals(CVBlocks.CVBLOCK_REST.toString())) {
                collect_expressions = true;
            } else if (block_type.equals(CVBlocks.CVBLOCK_PERSONAL.toString())) {
                collect_expressions = true;
            }

        } else {
            collect_expressions = true;
        }
    } else {

        collect_expressions = true;
    }

    if (collect_expressions) {

        ArrayList<Annotation> anns = new ArrayList<Annotation>();
        anns.addAll(annoset.get("AgentIdentification"));

        if (anns.size() > 0) {
            String lastname = "";
            String initials = "";
            String name = "";
            String firstname = "";

            if (extra_data != null) {
                lastname = extra_data.get(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_LASTNAME);
                initials = extra_data.get(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_INITIALS);
                name = extra_data.get(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_NAME);
                firstname = extra_data.get(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_FIRSTNAME);
            }

            if (firstname.equals("")) {
                firstname = initials;
            }

            for (Annotation an : anns) {
                String cvnItemName = an.getType();
                org.dom4j.Element eAux = new org.dom4j.DocumentFactory().createElement(cvnItemName);
                //                        eAux.addElement("Domain").addText(gate.Utils.stringFor(docGate,
                //                                                          an.getStartNode().getOffset() > 100 ? an.getStartNode().getOffset() - 100 : an.getStartNode().getOffset(),
                //                                                          an.getEndNode().getOffset() + 100 < docGate.getContent().size() ? an.getEndNode().getOffset() + 100 :  an.getEndNode().getOffset()));
                eAux.addAttribute("action_mode", "overwrite");
                eAux.addAttribute("extra_gets", "getInformation");
                eAux.addElement("Content").addText(gate.Utils.stringFor(docGate, an));
                FeatureMap fmap = an.getFeatures();
                for (Object key : fmap.keySet()) {
                    String fieldName = key.toString();
                    eAux.addElement(fieldName).addText(fmap.get(key).toString());
                }
                eAux.addElement(CVItemExtracted.AgentIdentification.GivenName).addText(firstname);
                eAux.addElement(CVItemExtracted.AgentIdentification.FirstFamilyName).addText(lastname);

                eOut.add(eAux);
            }
        }

        n_expressions += eOut.elements().size();
    }

    ProjectLogger.LOGGER.info(String.format("%3d expressions in %s : ", n_expressions, docGate.getName())); // + docXML.asXML()
    if (eOut == null)
        ProjectLogger.LOGGER.info("Output is null"); // + docXML.asXML()

    aoData.setData_out(eOut);

    if (aoData.getVerbose()) {
        File dest_dir = aoData.getVerboseDir();
        File path = null;
        String fileName = "";

        if (extra_data != null
                && extra_data.containsKey(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_DOCUMENT_NAME)) {

            fileName = extra_data.get(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_DOCUMENT_NAME);

        } else {

            URL url = docGate.getSourceUrl();
            try {
                path = new File(url.toURI());
                fileName = path.getName();
            } catch (Exception e) {
                String filename;
                try {
                    filename = URLEncoder.encode(url.toString(), "UTF-8") + ".html";
                } catch (Exception ex) {
                    filename = docGate.getName() + ".html";
                }
                path = new File(filename);
                fileName = path.getName();
            }

            if (!fileName.equals("")) {
                fileName = fileName.substring(0, fileName.lastIndexOf("."));
            }

        }

        File file_result = new File(dest_dir, fileName + "_verbose.html");

        try {
            writeResultsInHTMLFile(docGate, file_result);
        } catch (Exception ex) {
            Logger.getRootLogger().error("Error writing verbose results. " + ex.toString());
        }

    }
}

From source file:marytts.server.http.MivoqSynthesisRequestHandler.java

public void process(Address serverAddressAtClient, Map<String, String> queryItems, HttpResponse response) {
    if (queryItems == null || !(queryItems.containsKey("input[type]") && queryItems.containsKey("output[type]")
            && queryItems.containsKey("input[content]"))) {
        MaryHttpServerUtils.errorMissingQueryParameter(response,
                "'input[content]' and 'input[type]' and 'output[type]'");
        return;/*w  ww  .  j a  v  a  2  s.  com*/
    }

    String inputContent = queryItems.get("input[content]");
    String inputTypeString = queryItems.get("input[type]");
    String outputTypeString = queryItems.get("output[type]");
    MaryDataType inputType = MaryDataType.get(inputTypeString);
    if (inputType == null) {
        MaryHttpServerUtils.errorWrongQueryParameterValue(response, "input[type]", inputTypeString, null);
        return;
    }

    MaryDataType outputType = MaryDataType.get(outputTypeString);
    if (outputType == null) {
        MaryHttpServerUtils.errorWrongQueryParameterValue(response, "output[type]", outputTypeString, null);
        return;
    }

    if (inputType.isTextType()) {
        if (!queryItems.containsKey("input[locale]")) {
            MaryHttpServerUtils.errorMissingQueryParameter(response,
                    "'input[locale]', needed for input[type] = " + inputTypeString);
        }
    }
    String inputLocaleString = queryItems.get("input[locale]");
    Locale inputLocale = MaryUtils.string2locale(inputLocaleString);
    if (inputLocale == null) {
        MaryHttpServerUtils.errorWrongQueryParameterValue(response, "input[locale]", inputLocaleString, null);
        return;
    }

    boolean isOutputText = true;
    boolean streamingAudio = false;
    AudioFileFormat.Type audioFileFormatType = null;
    if (outputType.name().contains("AUDIO")) {
        isOutputText = false;
        String outputFormatString = queryItems.get("output[format]");
        if (outputFormatString == null) {
            MaryHttpServerUtils.errorMissingQueryParameter(response,
                    "'output[format]' when output[type] = AUDIO");
            return;
        }
        if (outputFormatString.endsWith("_STREAM")) {
            streamingAudio = true;
        }
        int lastUnderscore = outputFormatString.lastIndexOf('_');
        if (lastUnderscore != -1) {
            outputFormatString = outputFormatString.substring(0, lastUnderscore);
        }
        try {
            audioFileFormatType = MaryAudioUtils.getAudioFileFormatType(outputFormatString);
        } catch (Exception ex) {
        }
        if (audioFileFormatType == null) {
            MaryHttpServerUtils.errorWrongQueryParameterValue(response, "output[format]", outputFormatString,
                    null);
            return;
        } else if (audioFileFormatType.toString().equals("MP3") && !MaryRuntimeUtils.canCreateMP3()) {
            MaryHttpServerUtils.errorWrongQueryParameterValue(response, "output[format]", outputFormatString,
                    "Conversion to MP3 not supported.");
            return;
        } else if (audioFileFormatType.toString().equals("Vorbis") && !MaryRuntimeUtils.canCreateOgg()) {
            MaryHttpServerUtils.errorWrongQueryParameterValue(response, "output[format]", outputFormatString,
                    "Conversion to OGG Vorbis format not supported.");
            return;
        }
    }

    Voice voice = null;
    String voiceGenderString = queryItems.get("voice[gender]");
    Voice.Gender voiceGender = null;
    if (voiceGenderString != null) {
        if (!(voiceGenderString.equals("male") || voiceGenderString.equals("female")
                || voiceGenderString.equals("neutral"))) {
            MaryHttpServerUtils.errorWrongQueryParameterValue(response, "voice[gender]", voiceGenderString,
                    null);
        }
        voiceGender = new Voice.Gender(voiceGenderString);
    }
    String voiceAgeString = queryItems.get("voice[age]");
    int voiceAge = -1;
    if (voiceAgeString != null) {
        voiceAge = Integer.parseInt(voiceAgeString);
        if (voiceAge < 0) {
            MaryHttpServerUtils.errorWrongQueryParameterValue(response, "voice[age]", voiceAgeString, null);
        }
    }
    String voiceVariantString = queryItems.get("voice[variant]");
    int voiceVariant = -1;
    if (voiceVariantString != null) {
        voiceVariant = Integer.parseInt(voiceVariantString);
        if (voiceVariant < 0) {
            MaryHttpServerUtils.errorWrongQueryParameterValue(response, "voice[variant]", voiceVariantString,
                    null);
        }
    }
    String utteranceStyle = queryItems.get("utterance[style]");
    if (utteranceStyle == null) {
        utteranceStyle = "";
    }

    String voiceName = queryItems.get("voice[name]");
    String[] voiceNameList = null;
    if (voiceName != null) {
        voiceNameList = voiceName.split(" ");
    }

    String utteranceEffects = queryItems.get("utterance[effects]");
    if (utteranceEffects == null) {
        utteranceEffects = "";
    }
    if (utteranceEffects.length() > 0)
        logger.debug("Audio effects requested: " + utteranceEffects);
    else
        logger.debug("No audio effects requested");

    // TODO(START,Parsing)

    // optionally, there may be output type parameters
    // (e.g., the list of features to produce for the output type TARGETFEATURES)
    String outputTypeParams = queryItems.get("OUTPUT_TYPE_PARAMS");

    String logMsg = queryItems.get("LOG");
    if (logMsg != null) {
        logger.info("Connection info: " + logMsg);
    }

    // TODO(END,Parsing)

    List<Voice> voiceResult = Voice.getVoiceWithSSMLAlgorythm(inputLocale, voiceGender, voiceNameList,
            voiceAge);
    if (voice == null) { // no voice tag -- use locale default if it exists.
        voice = Voice.getDefaultVoice(inputLocale);
        logger.debug("No voice requested -- using default " + voice);
    }
    if (voiceResult.isEmpty()) {
        MaryHttpServerUtils.errorWrongQueryParameterValue(response, "input[] and voice[]",
                "No suitable voice found for the requested configuration", null);
        return;
    }
    if (voiceVariant > 0) {
        voiceVariant--;
        if (voiceVariant >= voiceResult.size()) {
            voiceVariant = voiceResult.size() - 1;
        }
    } else {
        voiceVariant = 0;
    }
    voice = voiceResult.get(voiceVariant);
    inputLocale = voice.getLocale();

    String utteranceStyleEffects = "";
    if (fakeStylesByGender.containsKey(voice.gender().toString())) {
        HashMap<String, String> s = fakeStylesByGender.get(voice.gender().toString());
        if (s.containsKey(utteranceStyle)) {
            utteranceStyleEffects = s.get(utteranceStyle);
        }
    }
    HashMap<String, Object> effects_values = new HashMap<String, Object>();
    if (utteranceStyleEffects.length() > 0) {
        JSONArray effects = new JSONArray(utteranceStyleEffects);
        for (int i = 0; i < effects.length(); i++) {
            JSONObject obj = effects.getJSONObject(i);
            parseEffectsIntoHashMap(effectsRegistry, effects_values, obj);
            // System.out.println(toOldStyleEffectsString(registry, effects_values));
        }
        // System.out.println(toOldStyleEffectsString(registry, effects_values));
    }
    if (utteranceEffects.length() > 0) {
        JSONArray effects = new JSONArray(utteranceEffects);
        for (int i = 0; i < effects.length(); i++) {
            JSONObject obj = effects.getJSONObject(i);
            parseEffectsIntoHashMap(effectsRegistry, effects_values, obj);
            // System.out.println(toOldStyleEffectsString(registry, effects_values));
        }
        // System.out.println(toOldStyleEffectsString(registry, effects_values));
    }
    utteranceEffects = toOldStyleEffectsString(effectsRegistry, effects_values);
    if (utteranceEffects.length() > 0)
        logger.debug("Audio effects requested: " + utteranceEffects);
    else
        logger.debug("No audio effects requested");
    // Now, the parse is complete.

    // Construct audio file format -- even when output is not AUDIO,
    // in case we need to pass via audio to get our output type.
    if (audioFileFormatType == null) {
        audioFileFormatType = AudioFileFormat.Type.AU;
    }
    AudioFormat audioFormat;
    if (audioFileFormatType.toString().equals("MP3")) {
        audioFormat = MaryRuntimeUtils.getMP3AudioFormat();
    } else if (audioFileFormatType.toString().equals("Vorbis")) {
        audioFormat = MaryRuntimeUtils.getOggAudioFormat();
    } else if (voice != null) {
        audioFormat = voice.dbAudioFormat();
    } else {
        audioFormat = Voice.AF16000;
    }
    AudioFileFormat audioFileFormat = new AudioFileFormat(audioFileFormatType, audioFormat,
            AudioSystem.NOT_SPECIFIED);

    final Request maryRequest = new Request(inputType, outputType, inputLocale, voice, utteranceEffects,
            utteranceStyle, getId(), audioFileFormat, streamingAudio, outputTypeParams);

    // Process the request and send back the data
    boolean ok = true;
    try {
        maryRequest.setInputData(inputContent);
        logger.info("Read: " + inputContent);
    } catch (Exception e) {
        String message = "Problem reading input";
        logger.warn(message, e);
        MaryHttpServerUtils.errorInternalServerError(response, message, e);
        ok = false;
    }
    if (ok) {
        if (streamingAudio) {
            // Start two separate threads:
            // 1. one thread to process the request;
            new Thread("RH " + maryRequest.getId()) {
                public void run() {
                    Logger myLogger = MaryUtils.getLogger(this.getName());
                    try {
                        maryRequest.process();
                        myLogger.info("Streaming request processed successfully.");
                    } catch (Throwable t) {
                        myLogger.error("Processing failed.", t);
                    }
                }
            }.start();

            // 2. one thread to take the audio data as it becomes available
            //    and write it into the ProducingNHttpEntity.
            // The second one does not depend on the first one practically,
            // because the AppendableSequenceAudioInputStream returned by
            // maryRequest.getAudio() was already created in the constructor of Request.
            AudioInputStream audio = maryRequest.getAudio();
            assert audio != null : "Streaming audio but no audio stream -- very strange indeed! :-(";
            AudioFileFormat.Type audioType = maryRequest.getAudioFileFormat().getType();
            AudioStreamNHttpEntity entity = new AudioStreamNHttpEntity(maryRequest);
            new Thread(entity, "HTTPWriter " + maryRequest.getId()).start();
            // entity knows its contentType, no need to set explicitly here.
            response.setEntity(entity);
            response.setStatusCode(HttpStatus.SC_OK);
            return;
        } else { // not streaming audio
            // Process input data to output data
            try {
                maryRequest.process(); // this may take some time
            } catch (Throwable e) {
                String message = "Processing failed.";
                logger.error(message, e);
                MaryHttpServerUtils.errorInternalServerError(response, message, e);
                ok = false;
            }
            if (ok) {
                // Write output data to client
                try {
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    maryRequest.writeOutputData(outputStream);
                    String contentType;
                    if (maryRequest.getOutputType().isXMLType() || maryRequest.getOutputType().isTextType()) //text output
                        contentType = "text/plain; charset=UTF-8";
                    else //audio output
                        contentType = MaryHttpServerUtils
                                .getMimeType(maryRequest.getAudioFileFormat().getType());
                    MaryHttpServerUtils.toHttpResponse(outputStream.toByteArray(), response, contentType);
                } catch (Exception e) {
                    String message = "Cannot write output";
                    logger.warn(message, e);
                    MaryHttpServerUtils.errorInternalServerError(response, message, e);
                    ok = false;
                }
            }
        }
    }

    if (ok)
        logger.info("Request handled successfully.");
    else
        logger.info("Request couldn't be handled successfully.");
    if (MaryRuntimeUtils.lowMemoryCondition()) {
        logger.info("Low memory condition detected (only " + MaryUtils.availableMemory()
                + " bytes left). Triggering garbage collection.");
        Runtime.getRuntime().gc();
        logger.info("After garbage collection: " + MaryUtils.availableMemory() + " bytes available.");
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.dao.jena.DataPropertyDaoJena.java

private List<DataProperty> getDataPropertyStatements(List<DataPropertyStatement> dataPropertyStmts) {
    if (dataPropertyStmts == null || dataPropertyStmts.isEmpty()) {
        return new ArrayList<DataProperty>();
    }/*from   ww  w  . jav  a2s  . co  m*/

    HashMap<String, DataProperty> hash = new HashMap<String, DataProperty>();
    for (DataPropertyStatement dataPropertyStmt : dataPropertyStmts) {
        if (hash.containsKey(dataPropertyStmt.getDatapropURI())) {
            DataProperty p = hash.get(dataPropertyStmt.getDatapropURI());
            p.addDataPropertyStatement(dataPropertyStmt);
        } else {
            OntModel ontModel = getOntModelSelector().getTBoxModel();
            ontModel.enterCriticalSection(Lock.READ);
            try {
                OntProperty op = ontModel.getOntProperty(dataPropertyStmt.getDatapropURI());
                if (op != null) {
                    DataProperty p = datapropFromOntProperty(op);
                    hash.put(p.getURI(), p);
                    p.addDataPropertyStatement(dataPropertyStmt);
                }
            } finally {
                ontModel.leaveCriticalSection();
            }
        }
    }

    List<DataProperty> dataprops = new ArrayList<DataProperty>(hash.values());
    Collections.sort(dataprops, new DataPropertyRanker());
    return dataprops;
}