Example usage for org.w3c.dom Element setTextContent

List of usage examples for org.w3c.dom Element setTextContent

Introduction

In this page you can find the example usage for org.w3c.dom Element setTextContent.

Prototype

public void setTextContent(String textContent) throws DOMException;

Source Link

Document

This attribute returns the text content of this node and its descendants.

Usage

From source file:com.mirth.connect.model.util.ImportConverter.java

private static void updateTransformerFor1_7(Document document) {
    Element inboundPropertiesElement, outboundPropertiesElement;

    NodeList transformers = document.getElementsByTagName("transformer");

    for (int i = 0; i < transformers.getLength(); i++) {
        Element transformerRoot = (Element) transformers.item(i);

        // Update the inbound protocol properties.
        if (transformerRoot.getElementsByTagName("inboundProtocol").item(0).getTextContent().equals("HL7V2")) {
            if (transformerRoot.getElementsByTagName("inboundProperties").getLength() != 0) {

                inboundPropertiesElement = (Element) transformerRoot.getElementsByTagName("inboundProperties")
                        .item(0);/*from w w w .  j  a v a 2 s.  com*/

                // Find out if encodeEntities already exists. If it was 1.5
                // it won't.
                boolean hasEncodeEntities = false;
                NodeList propertyNames = inboundPropertiesElement.getElementsByTagName("property");
                for (int j = 0; j < propertyNames.getLength(); j++) {
                    Node nameAttribute = propertyNames.item(j).getAttributes().getNamedItem("name");
                    if (propertyNames.item(j).getAttributes().getLength() > 0 && nameAttribute != null) {
                        if (nameAttribute.getNodeValue().equals("encodeEntities")) {
                            hasEncodeEntities = true;
                        }
                    }
                }

                // Add encodeEntities if it doesn't exist.
                if (!hasEncodeEntities) {
                    Element encodeEntities = document.createElement("property");
                    encodeEntities.setAttribute("name", "encodeEntities");
                    encodeEntities.setTextContent("true");

                    inboundPropertiesElement.appendChild(encodeEntities);
                }

                Element convertLFtoCRProperty = document.createElement("property");
                convertLFtoCRProperty.setAttribute("name", "convertLFtoCR");
                convertLFtoCRProperty.setTextContent("true");

                inboundPropertiesElement.appendChild(convertLFtoCRProperty);
            } else {
                inboundPropertiesElement = document.createElement("inboundProperties");

                Element convertLFtoCRProperty = document.createElement("property");
                convertLFtoCRProperty.setAttribute("name", "convertLFtoCR");
                convertLFtoCRProperty.setTextContent("true");

                Element encodeEntitiesProperty = document.createElement("property");
                encodeEntitiesProperty.setAttribute("name", "encodeEntities");
                encodeEntitiesProperty.setTextContent("true");

                Element handleRepetitionsProperty = document.createElement("property");
                handleRepetitionsProperty.setAttribute("name", "handleRepetitions");
                handleRepetitionsProperty.setTextContent("false");

                Element useStrictValidationProperty = document.createElement("property");
                useStrictValidationProperty.setAttribute("name", "useStrictValidation");
                useStrictValidationProperty.setTextContent("false");

                Element useStrictParserProperty = document.createElement("property");
                useStrictParserProperty.setAttribute("name", "useStrictParser");
                useStrictParserProperty.setTextContent("false");

                inboundPropertiesElement.appendChild(convertLFtoCRProperty);
                inboundPropertiesElement.appendChild(encodeEntitiesProperty);
                inboundPropertiesElement.appendChild(handleRepetitionsProperty);
                inboundPropertiesElement.appendChild(useStrictValidationProperty);
                inboundPropertiesElement.appendChild(useStrictParserProperty);

                transformerRoot.appendChild(inboundPropertiesElement);
            }
        }

        // Update the outbound protocol properties.
        if (transformerRoot.getElementsByTagName("outboundProtocol").item(0).getTextContent().equals("HL7V2")) {
            if (transformerRoot.getElementsByTagName("outboundProperties").getLength() != 0) {
                outboundPropertiesElement = (Element) transformerRoot.getElementsByTagName("outboundProperties")
                        .item(0);

                // Find out if encodeEntities already exists. If it was 1.5
                // it won't.
                boolean hasEncodeEntities = false;
                NodeList propertyNames = outboundPropertiesElement.getElementsByTagName("property");
                for (int j = 0; j < propertyNames.getLength(); j++) {
                    Node nameAttribute = propertyNames.item(j).getAttributes().getNamedItem("name");
                    if (propertyNames.item(j).getAttributes().getLength() > 0 && nameAttribute != null) {
                        if (nameAttribute.getNodeValue().equals("encodeEntities")) {
                            hasEncodeEntities = true;
                        }
                    }
                }

                // Add encodeEntities if it doesn't exist.
                if (!hasEncodeEntities) {
                    Element encodeEntities = document.createElement("property");
                    encodeEntities.setAttribute("name", "encodeEntities");
                    encodeEntities.setTextContent("true");

                    outboundPropertiesElement.appendChild(encodeEntities);
                }

                Element convertLFtoCRProperty = document.createElement("property");
                convertLFtoCRProperty.setAttribute("name", "convertLFtoCR");
                convertLFtoCRProperty.setTextContent("true");

                outboundPropertiesElement.appendChild(convertLFtoCRProperty);
            } else {
                outboundPropertiesElement = document.createElement("outboundProperties");

                Element convertLFtoCRProperty = document.createElement("property");
                convertLFtoCRProperty.setAttribute("name", "convertLFtoCR");
                convertLFtoCRProperty.setTextContent("true");

                Element encodeEntitiesProperty = document.createElement("property");
                encodeEntitiesProperty.setAttribute("name", "encodeEntities");
                encodeEntitiesProperty.setTextContent("true");

                Element handleRepetitionsProperty = document.createElement("property");
                handleRepetitionsProperty.setAttribute("name", "handleRepetitions");
                handleRepetitionsProperty.setTextContent("false");

                Element useStrictValidationProperty = document.createElement("property");
                useStrictValidationProperty.setAttribute("name", "useStrictValidation");
                useStrictValidationProperty.setTextContent("false");

                Element useStrictParserProperty = document.createElement("property");
                useStrictParserProperty.setAttribute("name", "useStrictParser");
                useStrictParserProperty.setTextContent("false");

                outboundPropertiesElement.appendChild(convertLFtoCRProperty);
                outboundPropertiesElement.appendChild(encodeEntitiesProperty);
                outboundPropertiesElement.appendChild(handleRepetitionsProperty);
                outboundPropertiesElement.appendChild(useStrictValidationProperty);
                outboundPropertiesElement.appendChild(useStrictParserProperty);

                transformerRoot.appendChild(outboundPropertiesElement);
            }
        }
    }
}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileBES.java

private DOMXMLSignature createEnveloped(SignatureParameters params, DOMSignContext signContext,
        org.w3c.dom.Document doc, String signatureId, String signatureValueId) throws NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, JAXBException, MarshalException, XMLSignatureException {

    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());

    signContext.setURIDereferencer(new URIDereferencer() {

        @Override/*  w w w .j  a va 2s.  c om*/
        public Data dereference(URIReference uriReference, XMLCryptoContext context)
                throws URIReferenceException {
            final XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());
            Data data = fac.getURIDereferencer().dereference(uriReference, context);
            return data;
        }
    });

    Map<String, String> xpathNamespaceMap = new HashMap<String, String>();
    xpathNamespaceMap.put("ds", XMLSignature.XMLNS);

    List<Reference> references = new ArrayList<Reference>();

    /* The first reference concern the whole document */
    List<Transform> transforms = new ArrayList<Transform>();
    transforms.add(fac.newTransform(CanonicalizationMethod.ENVELOPED, (TransformParameterSpec) null));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    org.w3c.dom.Document empty;
    try {
        empty = dbf.newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException e1) {
        throw new RuntimeException(e1);
    }
    Element xpathEl = empty.createElementNS(XMLSignature.XMLNS, "XPath");
    xpathEl.setTextContent("");
    empty.adoptNode(xpathEl);
    XPathFilterParameterSpec specs = new XPathFilterParameterSpec("not(ancestor-or-self::ds:Signature)");
    DOMTransform t = (DOMTransform) fac.newTransform("http://www.w3.org/TR/1999/REC-xpath-19991116", specs);

    transforms.add(t);
    DigestMethod digestMethod = fac.newDigestMethod(params.getDigestAlgorithm().getXmlId(), null);
    Reference reference = fac.newReference("", digestMethod, transforms, null, "xml_ref_id");
    references.add(reference);

    List<XMLObject> objects = new ArrayList<XMLObject>();

    String xadesSignedPropertiesId = "xades-" + computeDeterministicId(params);
    QualifyingPropertiesType qualifyingProperties = createXAdESQualifyingProperties(params,
            xadesSignedPropertiesId, reference, MimeType.XML);
    qualifyingProperties.setTarget("#" + signatureId);

    Node marshallNode = doc.createElement("marshall-node");
    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.marshal(xades13ObjectFactory.createQualifyingProperties(qualifyingProperties), marshallNode);
    Element qualifier = (Element) marshallNode.getFirstChild();

    // add XAdES ds:Object
    List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>();
    xadesObjectContent.add(new DOMStructure(marshallNode.getFirstChild()));
    XMLObject xadesObject = fac.newXMLObject(xadesObjectContent, null, null, null);
    objects.add(xadesObject);

    Reference xadesreference = fac.newReference("#" + xadesSignedPropertiesId, digestMethod,
            Collections.singletonList(
                    fac.newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null)),
            XADES_TYPE, null);
    references.add(xadesreference);

    /* Signed Info */
    SignatureMethod sm = fac.newSignatureMethod(
            params.getSignatureAlgorithm().getXMLSignatureAlgorithm(params.getDigestAlgorithm()), null);

    CanonicalizationMethod canonicalizationMethod = fac
            .newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = fac.newSignedInfo(canonicalizationMethod, sm, references);

    /* Creation of signature */
    KeyInfoFactory keyFactory = KeyInfoFactory.getInstance("DOM", new XMLDSigRI());

    List<Object> infos = new ArrayList<Object>();
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(params.getSigningCertificate());
    if (params.getCertificateChain() != null) {
        for (X509Certificate c : params.getCertificateChain()) {
            if (!c.getSubjectX500Principal().equals(params.getSigningCertificate().getSubjectX500Principal())) {
                certs.add(c);
            }
        }
    }
    infos.add(keyFactory.newX509Data(certs));
    KeyInfo keyInfo = keyFactory.newKeyInfo(infos);

    DOMXMLSignature signature = (DOMXMLSignature) fac.newXMLSignature(signedInfo, keyInfo, objects, signatureId,
            signatureValueId);

    /* Marshall the signature to permit the digest. Need to be done before digesting the references. */
    signature.marshal(doc.getDocumentElement(), "ds", signContext);

    signContext.setIdAttributeNS((Element) qualifier.getFirstChild(), null, "Id");

    digestReferences(signContext, references);

    return signature;

}

From source file:de.qucosa.webapi.v1.DocumentResource.java

private void modifyDcDatastream(String pid, List<String> urns, String title)
        throws FedoraClientException, ParserConfigurationException, IOException, SAXException,
        TransformerException, XPathExpressionException {
    if ((urns == null || urns.isEmpty()) && (title == null || title.isEmpty()))
        return;/*from  w w w. j  a va 2 s. co  m*/

    InputStream dcStream = fedoraRepository.getDatastreamContent(pid, "DC");
    Document dcDocument = documentBuilder.parse(dcStream);

    if (urns != null) {
        for (String urnnbn : urns) {
            String urn = urnnbn.trim().toLowerCase();
            if (!(boolean) xPath.compile("//ns:identifier[text()='" + urn + "']").evaluate(dcDocument,
                    XPathConstants.BOOLEAN)) {
                Element newDcIdentifier = dcDocument.createElementNS("http://purl.org/dc/elements/1.1/",
                        "identifier");
                newDcIdentifier.setTextContent(urn);
                dcDocument.getDocumentElement().appendChild(newDcIdentifier);
            }
        }
    }

    if ((title != null) && (!title.isEmpty())) {
        Element dcTitle = (Element) dcDocument
                .getElementsByTagNameNS("http://purl.org/dc/elements/1.1/", "title").item(0);
        dcTitle.setTextContent(title);
    }

    InputStream modifiedDcStream = IOUtils.toInputStream(DOMSerializer.toString(dcDocument));
    fedoraRepository.modifyDatastreamContent(pid, "DC", "text/xml", modifiedDcStream);
}

From source file:com.mirth.connect.connectors.jdbc.DatabaseReader.java

private void updateIncomingData(String[] data) {
    try {/* w  ww  . j a  va  2  s .  co m*/
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        Element resultElement = document.createElement("result");
        for (int i = 0; i < data.length; i++) {
            Element columnElement = document.createElement(data[i]);
            columnElement.setTextContent("value");
            resultElement.appendChild(columnElement);
        }
        document.appendChild(resultElement);

        DocumentSerializer docSerializer = new DocumentSerializer();

        String xml = docSerializer.toXML(document);

        //            parent.channelEditPanel.currentChannel.getSourceConnector().getTransformer().setInboundTemplate(xml.replaceAll("\\r\\n", "\n"));  // Not required with current text area
        parent.channelEditPanel.currentChannel.getSourceConnector().getTransformer().setInboundTemplate(xml);

        if (parent.channelEditPanel.currentChannel.getSourceConnector().getTransformer().getOutboundDataType()
                .equals(UIConstants.DATATYPE_XML)
                && parent.channelEditPanel.currentChannel.getSourceConnector().getTransformer()
                        .getOutboundTemplate() != null
                && parent.channelEditPanel.currentChannel.getSourceConnector().getTransformer()
                        .getOutboundTemplate().length() == 0) {
            List<Connector> list = parent.channelEditPanel.currentChannel.getDestinationConnectors();
            for (Connector c : list) {
                //                    c.getTransformer().setInboundTemplate(xml.replaceAll("\\r\\n", "\n"));  // Not required with current text area
                c.getTransformer().setInboundTemplate(xml);
            }
        }
    } catch (Exception ex) {
    }
}

From source file:ai.ilikeplaces.logic.Listeners.ListenerMain.java

/**
 * @param request__//  ww w  .  ja  va  2  s  .  c om
 * @param response__
 */
@Override
public void processRequest(final ItsNatServletRequest request__, final ItsNatServletResponse response__) {
    new AbstractListener(request__, response__) {
        protected String location;

        protected String superLocation;

        protected Long WOEID;

        /**
         * Initialize your document here by appending fragments
         */
        @Override
        @SuppressWarnings("unchecked")
        @_todo(task = "If location is not available, it should be added through a w" + "id"
                + "get(or fragment maybe?)")
        protected final void init(final ItsNatHTMLDocument itsNatHTMLDocument__,
                final HTMLDocument hTMLDocument__, final ItsNatDocument itsNatDocument__,
                final Object... initArgs) {
            final SmartLogger sl = SmartLogger.start(Loggers.LEVEL.DEBUG, "Location Page.", 60000, null, true);

            //this.location = (String) request_.getServletRequest().getAttribute(RBGet.config.getString("HttpSessionAttr.location"));
            getLocationSuperLocation: {
                final String[] attr = ((String) request__.getServletRequest()
                        .getAttribute(RBGet.globalConfig.getString(HTTP_SESSION_ATTR_LOCATION))).split("_");
                location = attr[0];
                if (attr.length == 3) {
                    superLocation = attr[2];
                } else {
                    superLocation = EMPTY;
                }
                tryLocationId: {
                    try {
                        final String w = request__.getServletRequest().getParameter(Location.WOEID);
                        if (w != null) {
                            WOEID = Long.parseLong(request__.getServletRequest().getParameter(Location.WOEID));
                        }
                    } catch (final NumberFormatException e) {
                        Loggers.USER_EXCEPTION.error(WRONG_WOEID_FORMAT, e);
                    }
                }
            }

            sl.appendToLogMSG(RETURNING_LOCATION + location + TO_USER);

            final ResourceBundle gUI = ResourceBundle.getBundle(AI_ILIKEPLACES_RBS_GUI);

            layoutNeededForAllPages: {
                setLoginWidget: {
                    try {
                        new SignInOn(request__, $(Main_login_widget),
                                new SignInOnCriteria().setHumanId(new HumanId(getUsername()))
                                        .setSignInOnDisplayComponent(
                                                SignInOnCriteria.SignInOnDisplayComponent.MOMENTS)) {
                        };
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SET_LOGIN_WIDGET, t);
                    }
                }

                SEO: {
                    try {
                        setMainTitle: {
                            $(mainTitle).setTextContent(
                                    MessageFormat.format(gUI.getString("woeidpage.title"), location));
                        }
                        setMetaDescription: {
                            $(mainMetaDesc).setAttribute(MarkupTag.META.content(),
                                    MessageFormat.format(gUI.getString("woeidpage.desc"), location));
                        }
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SEO, t);
                    }
                }
                signOnDisplayLink: {
                    try {
                        if (getUsername() != null) {
                            $(Main_othersidebar_identity).setTextContent(
                                    gUI.getString(AI_ILIKEPLACES_LOGIC_LISTENERS_LISTENER_MAIN_0004)
                                            + getUsernameAsValid());
                        } else {
                            $(Main_othersidebar_identity).setTextContent(
                                    gUI.getString(AI_ILIKEPLACES_LOGIC_LISTENERS_LISTENER_MAIN_0005)
                                            + location);
                        }
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SIGN_ON_DISPLAY_LINK, t);
                    }
                }
                setProfileLink: {
                    try {
                        if (getUsername() != null) {
                            $(Main_othersidebar_profile_link).setAttribute(MarkupTag.A.href(),
                                    Controller.Page.Profile.getURL());
                        } else {
                            $(Main_othersidebar_profile_link).setAttribute(MarkupTag.A.href(),
                                    Controller.Page.signup.getURL());
                        }
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SET_PROFILE_LINK, t);
                    }
                }
                setProfilePhotoLink: {
                    try {
                        if (getUsername() != null) {
                            /**
                             * TODO check for db failure
                             */
                            String url = DB.getHumanCRUDHumanLocal(true)
                                    .doDirtyRHumansProfilePhoto(new HumanId(getUsernameAsValid()))
                                    .returnValueBadly();
                            url = url == null ? null : RBGet.globalConfig.getString(PROFILE_PHOTOS) + url;
                            if (url != null) {
                                $(Main_profile_photo).setAttribute(MarkupTag.IMG.src(), url);
                                //displayBlock($(Main_profile_photo));
                            } else {
                                //displayNone($(Main_profile_photo));
                            }
                        } else {
                            //displayNone($(Main_profile_photo));
                        }
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SET_PROFILE_PHOTO_LINK, t);
                    }
                }
            }

            final Return<Location> r;
            if (WOEID != null) {
                r = DB.getHumanCRUDLocationLocal(true).doRLocation(WOEID, REFRESH_SPEC);
            } else {
                r = new ReturnImpl<Location>(ExceptionCache.UNSUPPORTED_OPERATION_EXCEPTION,
                        "Search Unavailable", false);
                //r = DB.getHumanCRUDLocationLocal(true).dirtyRLocation(location, superLocation);
            }

            if (r.returnStatus() == 0 && r.returnValue() != null) {
                final Location existingLocation_ = r.returnValue();

                GEO: {
                    if (existingLocation_.getLocationGeo1() == null
                            || existingLocation_.getLocationGeo2() == null) {
                        final Client ygpClient = YAHOO_GEO_PLANET_FACTORY
                                .getInstance(RBGet.globalConfig.getString("where.yahooapis.com.v1.place"));
                        final Place place = ygpClient.getPlace(existingLocation_.getLocationId().toString());
                        existingLocation_.setLocationGeo1(Double.toString(place.getCoordinates().getY()));
                        existingLocation_.setLocationGeo2(Double.toString(place.getCoordinates().getX()));

                        new Thread(new Runnable() {

                            @Override
                            public void run() {
                                DB.getHumanCRUDLocationLocal(true).doULocationLatLng(
                                        new Obj<Long>(existingLocation_.getLocationId()),
                                        new Obj<Double>(place.getCoordinates().getY()),
                                        new Obj<Double>(place.getCoordinates().getX()));
                            }
                        }).run();
                    }
                }

                final Location locationSuperSet = existingLocation_.getLocationSuperSet();
                GEO_WIDGET: {
                    new ai.ilikeplaces.logic.Listeners.widgets.schema.thing.Comment(request__,
                            new CommentCriteria(), $(Controller.Page.Main_right_column)) {
                        @Override
                        protected void init(CommentCriteria commentCriteria) {
                            final ai.ilikeplaces.logic.Listeners.widgets.schema.thing.Place place = new ai.ilikeplaces.logic.Listeners.widgets.schema.thing.Place(
                                    request__, new PlaceCriteria()
                                            //This Place
                                            .setPlaceNamePre("Exciting events in ")
                                            .setPlaceName(existingLocation_.getLocationName())
                                            .setPlaceLat(existingLocation_.getLocationGeo1())
                                            .setPlaceLng(existingLocation_.getLocationGeo2())
                            //Parent Place
                            //.setPlaceSuperName(locationSuperSet.getLocationName())
                            //.setPlaceSuperLat(locationSuperSet.getLocationGeo1())
                            //.setPlaceSuperLng(locationSuperSet.getLocationGeo2())
                            //Parent WOEID
                            //.setPlaceSuperWOEID(locationSuperSet.getWOEID().toString())
                            , $$(CommentIds.commentPerson));
                            place.$$displayNone(place.$$(
                                    ai.ilikeplaces.logic.Listeners.widgets.schema.thing.Place.PlaceIds.placeWidget));
                        }
                    };
                }

                final List<String> titleManifest = new ArrayList<String>();

                EVENTS_WIDGETS: {
                    try {
                        /* final JSONObject jsonObject = Modules.getModules().getYahooUplcomingFactory()
                            .getInstance("http://upcoming.yahooapis.com/services/rest/")
                            .get("",
                                    new HashMap<String, String>() {
                                        {//Don't worry, this is a static initializer of this map :)
                                            put("method", "event.search");
                                            put("woeid", WOEID.toString());
                                            put("format", "json");
                                        }
                                    }
                                
                            );
                         final JSONArray events = jsonObject.getJSONObject("rsp").getJSONArray("event");*/

                        final JSONObject jsonObject = Modules.getModules().getEventulFactory()
                                .getInstance("http://api.eventful.com/json/events/search/")
                                .get("", new HashMap<String, String>() {
                                    {//Don't worry, this is a static initializer of this map :)
                                        put("location", "" + existingLocation_.getLocationGeo1() + ","
                                                + existingLocation_.getLocationGeo2());
                                        put("within", "" + 100);
                                    }
                                }

                        );

                        Loggers.debug("Eventful Reply:" + jsonObject.toString());

                        //                            final String eventName = eventJSONObject.getString("title");
                        //                            final String eventUrl = eventJSONObject.getString("url");
                        //                            final String eventDate = eventJSONObject.getString("start_time");
                        //                            final String eventVenue = eventJSONObject.getString("venue_name");

                        final JSONArray events = jsonObject.getJSONObject("events").getJSONArray("event");

                        for (int i = 0; i < events.length(); i++) {
                            final JSONObject eventJSONObject = new JSONObject(events.get(i).toString());

                            titleManifest.add(eventJSONObject.get("title").toString());

                            final String photoUrl;
                            String temp = null;
                            try {
                                temp = eventJSONObject.getJSONObject("image").get("url").toString();
                            } catch (final Throwable e) {
                                SmartLogger.g().l(e.getMessage());
                            } finally {
                                photoUrl = temp;
                            }
                            //The pain I go through to make variables final :D

                            new Event(request__, new EventCriteria()
                                    .setEventName(eventJSONObject.get("title").toString())
                                    .setEventStartDate(eventJSONObject.get("start_time").toString())
                                    .setEventPhoto(photoUrl)
                                    .setPlaceCriteria(new PlaceCriteria()
                                            .setPlaceNamePre("This event is taking place in ")
                                            .setPlaceName(existingLocation_.getLocationName())
                                            .setPlaceLat(eventJSONObject.get("latitude").toString())
                                            .setPlaceLng(eventJSONObject.get("longitude").toString())
                                            //Parent Place
                                            .setPlaceSuperNamePre(
                                                    existingLocation_.getLocationName() + " is located in ")
                                            .setPlaceSuperName(locationSuperSet.getLocationName())
                                            .setPlaceSuperLat(locationSuperSet.getLocationGeo1())
                                            .setPlaceSuperLng(locationSuperSet.getLocationGeo2())
                                            //Parent WOEID
                                            .setPlaceSuperWOEID(locationSuperSet.getWOEID().toString())

                            ), $(Controller.Page.Main_right_column));
                        }
                    } catch (final JSONException e) {
                        sl.l("Error fetching data from Yahoo Upcoming: " + e.getMessage());
                    }
                }

                TWITTER_WIDGETS: {
                    try {
                        final Query _query = new Query(
                                "fun OR happening OR enjoy OR nightclub OR restaurant OR party OR travel :)");
                        _query.geoCode(
                                new GeoLocation(Double.parseDouble(existingLocation_.getLocationGeo1()),
                                        Double.parseDouble(existingLocation_.getLocationGeo2())),
                                40, Query.MILES);
                        _query.setResultType(Query.MIXED);
                        final QueryResult result = TWITTER.search(_query);

                        //final QueryResult result = TWITTER.search(new Query("Happy").geoCode(new GeoLocation(Double.parseDouble(existingLocation_.getLocationGeo1()), Double.parseDouble(existingLocation_.getLocationGeo2())), 160, Query.MILES));
                        for (Status tweet : result.getTweets()) {
                            new ai.ilikeplaces.logic.Listeners.widgets.schema.thing.Person(request__,
                                    new PersonCriteria().setPersonName(tweet.getUser().getName())
                                            .setPersonPhoto(tweet.getUser().getProfileImageURL())
                                            .setPersonData(tweet.getText()),
                                    $(Main_right_column));
                            titleManifest.add(tweet.getText());
                        }
                        if (result.getTweets().size() == 0) {
                            sl.l("No twitter results found");
                        }
                    } catch (final Throwable t) {
                        sl.l("An error occurred during twitter fetch:" + t.getMessage());
                    }
                }

                SEO: {
                    setMetaGEOData: {
                        $(Main_ICBM).setAttribute(MarkupTag.META.content(), existingLocation_.getLocationGeo1()
                                + COMMA + existingLocation_.getLocationGeo2());
                        $(Main_geoposition).setAttribute(MarkupTag.META.content(),
                                existingLocation_.getLocationGeo1() + COMMA
                                        + existingLocation_.getLocationGeo2());
                        $(Main_geoplacename).setAttribute(MarkupTag.META.content(),
                                existingLocation_.getLocationName());
                        $(Main_georegion).setAttribute(MarkupTag.META.content(),
                                locationSuperSet.getLocationName());
                    }
                }

                setLocationIdForJSReference: {
                    try {
                        final Element hiddenLocationIdInputTag = $(INPUT);
                        hiddenLocationIdInputTag.setAttribute(INPUT.type(), INPUT.typeValueHidden());
                        hiddenLocationIdInputTag.setAttribute(INPUT.id(), JSCodeToSend.LocationId);
                        hiddenLocationIdInputTag.setAttribute(INPUT.value(),
                                existingLocation_.getLocationId().toString());
                        hTMLDocument__.getBody().appendChild(hiddenLocationIdInputTag);

                        $(Main_location_name).setAttribute(INPUT.value(),
                                existingLocation_.getLocationName() + "");
                        $(Main_super_location_name).setAttribute(INPUT.value(),
                                locationSuperSet.getLocationName() + "");
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SET_LOCATION_ID_FOR_JSREFERENCE, t);
                    }
                }

                setLocationNameForJSReference: {
                    try {
                        final Element hiddenLocationIdInputTag = $(INPUT);
                        hiddenLocationIdInputTag.setAttribute(INPUT.type(), INPUT.typeValueHidden());
                        hiddenLocationIdInputTag.setAttribute(INPUT.id(), JSCodeToSend.LocationName);
                        hiddenLocationIdInputTag.setAttribute(INPUT.value(),
                                existingLocation_.getLocationName() + OF + locationSuperSet.getLocationName());
                        hTMLDocument__.getBody().appendChild(hiddenLocationIdInputTag);
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SET_LOCATION_NAME_FOR_JSREFERENCE, t);
                    }
                }

                setLocationAsPageTopic: {
                    try {

                        final StringBuilder title = new StringBuilder();

                        for (final String titleGuest : titleManifest) {
                            title.append(titleGuest);
                        }

                        final String finalTitle = title.toString();

                        $(Main_center_main_location_title).setTextContent(finalTitle.isEmpty()
                                ? (THIS_IS + existingLocation_.getLocationName() + OF + locationSuperSet)
                                : finalTitle);

                        for (final Element element : generateLocationLinks(DB.getHumanCRUDLocationLocal(true)
                                .doDirtyRLocationsBySuperLocation(existingLocation_))) {
                            $(Main_location_list).appendChild(element);
                            displayBlock($(Main_notice_sh));
                        }
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SET_LOCATION_AS_PAGE_TOPIC, t);
                    }
                }
            } else {
                noSupportForNewLocations: {
                    try {
                        //                            $(Main_notice).appendChild(($(P).appendChild(
                        //                                    hTMLDocument__.createTextNode(RBGet.logMsgs.getString("CANT_FIND_LOCATION")
                        //                                            + " Were you looking for "
                        //                                    ))));
                        //                            for (final Element element : generateLocationLinks(DB.getHumanCRUDLocationLocal(true).dirtyRLikeLocations(location))) {
                        //                                $(Main_notice).appendChild(element);
                        //                                displayBlock($(Main_notice_sh));
                        //                            }
                        NotSupportingLikeSearchTooForNow: {
                            $(Main_notice).appendChild(($(P).appendChild(hTMLDocument__
                                    .createTextNode(RBGet.logMsgs.getString("CANT_FIND_LOCATION")))));
                        }
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_NO_SUPPORT_FOR_NEW_LOCATIONS, t);
                    }
                }
            }
            sl.complete(Loggers.LEVEL.SERVER_STATUS, Loggers.DONE);
        }

        /**
         * Use ItsNatHTMLDocument variable stored in the AbstractListener class
         */
        @Override
        protected void registerEventListeners(final ItsNatHTMLDocument itsNatHTMLDocument__,
                final HTMLDocument hTMLDocument__, final ItsNatDocument itsNatDocument__) {
        }

        private List<Element> generateLocationLinks(final List<Location> locationList) {
            final ElementComposer UList = ElementComposer.compose($(UL)).$ElementSetAttribute(MarkupTag.UL.id(),
                    PLACE_LIST);

            for (Location location : locationList) {
                final Element link = $(A);

                link.setTextContent(TRAVEL_TO + location.getLocationName() + OF
                        + location.getLocationSuperSet().getLocationName());

                link.setAttribute(A.href(),
                        PAGE + location.getLocationName() + _OF_
                                + location.getLocationSuperSet().getLocationName()
                                + Parameter.get(Location.WOEID, location.getWOEID().toString(), true));

                link.setAttribute(A.alt(), PAGE + location.getLocationName() + _OF_
                        + location.getLocationSuperSet().getLocationName());

                link.setAttribute(A.title(), CLICK_TO_EXPLORE + location.getLocationName() + OF
                        + location.getLocationSuperSet().getLocationName());

                link.setAttribute(A.classs(), VTIP);

                final Element linkDiv = $(DIV);

                linkDiv.appendChild(link);

                UList.wrapThis(ElementComposer.compose($(LI)).wrapThis(linkDiv).get());
            }

            final List<Element> elements = new ArrayList<Element>();
            elements.add(UList.get());
            return elements;
        }

        private Element generateLocationLink(final Location location) {
            final Element link = $(A);
            link.setTextContent(TRAVEL_TO + location.getLocationName() + OF
                    + location.getLocationSuperSet().getLocationName());
            link.setAttribute(A.href(),
                    PAGE + location.getLocationName() + _OF_ + location.getLocationSuperSet().getLocationName()
                            + Parameter.get(Location.WOEID, location.getWOEID().toString(), true));

            link.setAttribute(A.alt(), PAGE + location.getLocationName() + _OF_
                    + location.getLocationSuperSet().getLocationName());
            return link;
        }

        private Element generateSimpleLocationLink(final Location location) {
            final Element link = $(A);
            link.setTextContent(location.getLocationName());
            link.setAttribute(A.href(), PAGE + location.getLocationName()
                    + Parameter.get(Location.WOEID, location.getWOEID().toString(), true));

            link.setAttribute(A.alt(), PAGE + location.getLocationName());
            return link;
        }
    };//Listener
}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileBES.java

Document signDocument(Document document, SignatureParameters parameters, byte[] signatureValue) {

    try {/*from ww w  . j av  a2  s . c  o m*/

        /* Read the document */
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        org.w3c.dom.Document doc = null;
        if (parameters.getSignaturePackaging() == SignaturePackaging.ENVELOPED) {
            doc = db.parse(document.openStream());
        } else {
            doc = db.newDocument();
            doc.appendChild(doc.createElement("empty"));
        }

        /* Interceptor */
        SpecialPrivateKey dummyPrivateKey = new SpecialPrivateKey();

        /* Context */
        DOMSignContext signContext = new DOMSignContext(dummyPrivateKey, doc.getDocumentElement());
        signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");

        String signatureValueId = "value-" + computeDeterministicId(parameters);

        DOMXMLSignature domSig = createSignature(parameters, doc, document, signContext, signatureValueId);

        String xpathString = "//ds:SignatureValue[@Id='" + signatureValueId + "']";
        Element signatureValueEl = XMLUtils.getElement(doc, xpathString);

        if (parameters.getSignatureAlgorithm() == SignatureAlgorithm.ECDSA) {
            signatureValueEl.setTextContent(
                    new String(Base64.encode(SignatureECDSA.convertASN1toXMLDSIG(signatureValue))));
        } else if (parameters.getSignatureAlgorithm() == SignatureAlgorithm.DSA) {
            signatureValueEl.setTextContent(new String(Base64.encode(convertASN1toXMLDSIG(signatureValue))));
        } else {
            signatureValueEl.setTextContent(new String(Base64.encode(signatureValue)));
        }

        UnsignedPropertiesType unsigned = createUnsignedXAdESProperties(parameters, domSig, null,
                signatureValueEl);
        if (unsigned != null) {
            JAXBContext xadesJaxbContext = JAXBContext.newInstance(getXades13ObjectFactory().getClass());
            Marshaller m = xadesJaxbContext.createMarshaller();
            JAXBElement<UnsignedPropertiesType> el = getXades13ObjectFactory()
                    .createUnsignedProperties(unsigned);
            m.marshal(el, getXAdESQualifyingProperties(parameters, doc));
        }

        /* Output document */
        ByteArrayOutputStream outputDoc = new ByteArrayOutputStream();
        Result output = new StreamResult(outputDoc);
        Transformer xformer = TransformerFactory.newInstance().newTransformer();
        Source source = new DOMSource(doc);
        xformer.transform(source, output);
        outputDoc.close();

        return new InMemoryDocument(outputDoc.toByteArray());

    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (JAXBException e) {
        throw new RuntimeException(e);
    } catch (XPathExpressionException e) {
        throw new RuntimeException(e);
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    } catch (SAXException e) {
        throw new RuntimeException(e);
    } catch (XMLSignatureException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new RuntimeException(e);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileBES.java

private DOMXMLSignature createEnveloping(SignatureParameters params, DOMSignContext signContext,
        org.w3c.dom.Document doc, String signatureId, String signatureValueId, Document inside)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, JAXBException, MarshalException,
        XMLSignatureException, ParserConfigurationException, IOException {

    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());

    DigestMethod digestMethod = fac.newDigestMethod(params.getDigestAlgorithm().getXmlId(), null);

    List<XMLObject> objects = new ArrayList<XMLObject>();
    List<Reference> references = new ArrayList<Reference>();

    byte[] b64data = Base64.encode(IOUtils.toByteArray(inside.openStream()));

    List<Transform> transforms = new ArrayList<Transform>();
    Map<String, String> xpathNamespaceMap = new HashMap<String, String>();
    xpathNamespaceMap.put("ds", "http://www.w3.org/2000/09/xmldsig#");
    Transform exclusiveTransform = fac.newTransform(CanonicalizationMethod.BASE64,
            (TransformParameterSpec) null);
    transforms.add(exclusiveTransform);/*  www  .  j  av a  2  s. co m*/

    /* The first reference concern the whole document */
    Reference reference = fac.newReference("#signed-data-" + computeDeterministicId(params), digestMethod,
            transforms, null, "signed-data-ref");
    references.add(reference);

    String xadesSignedPropertiesId = "xades-" + computeDeterministicId(params);
    QualifyingPropertiesType qualifyingProperties = createXAdESQualifyingProperties(params,
            xadesSignedPropertiesId, reference, MimeType.PLAIN);
    qualifyingProperties.setTarget("#" + signatureId);

    Node marshallNode = doc.createElement("marshall-node");

    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.marshal(xades13ObjectFactory.createQualifyingProperties(qualifyingProperties), marshallNode);

    Element qualifier = (Element) marshallNode.getFirstChild();

    // add XAdES ds:Object
    List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>();
    xadesObjectContent.add(new DOMStructure(marshallNode.getFirstChild()));
    XMLObject xadesObject = fac.newXMLObject(xadesObjectContent, null, null, null);
    objects.add(xadesObject);

    List<Transform> xadesTranforms = new ArrayList<Transform>();
    Transform exclusiveTransform2 = fac.newTransform(CanonicalizationMethod.INCLUSIVE,
            (TransformParameterSpec) null);
    xadesTranforms.add(exclusiveTransform2);
    Reference xadesreference = fac.newReference("#" + xadesSignedPropertiesId, digestMethod, xadesTranforms,
            XADES_TYPE, null);
    references.add(xadesreference);

    /* Signed Info */
    SignatureMethod sm = fac.newSignatureMethod(
            params.getSignatureAlgorithm().getXMLSignatureAlgorithm(params.getDigestAlgorithm()), null);

    CanonicalizationMethod canonicalizationMethod = fac
            .newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = fac.newSignedInfo(canonicalizationMethod, sm, references);

    /* Creation of signature */
    KeyInfoFactory keyFactory = KeyInfoFactory.getInstance("DOM", new XMLDSigRI());

    List<Object> infos = new ArrayList<Object>();
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(params.getSigningCertificate());
    if (params.getCertificateChain() != null) {
        for (X509Certificate c : params.getCertificateChain()) {
            if (!c.getSubjectX500Principal().equals(params.getSigningCertificate().getSubjectX500Principal())) {
                certs.add(c);
            }
        }
    }
    infos.add(keyFactory.newX509Data(certs));
    KeyInfo keyInfo = keyFactory.newKeyInfo(infos);

    DOMXMLSignature signature = (DOMXMLSignature) fac.newXMLSignature(signedInfo, keyInfo, objects, signatureId,
            signatureValueId);

    /* Marshall the signature to permit the digest. Need to be done before digesting the references. */
    doc.removeChild(doc.getDocumentElement());
    signature.marshal(doc, "ds", signContext);

    Element dsObject = doc.createElementNS(XMLSignature.XMLNS, "Object");
    dsObject.setAttribute("Id", "signed-data-" + computeDeterministicId(params));
    dsObject.setTextContent(new String(b64data));
    doc.getDocumentElement().appendChild(dsObject);

    signContext.setIdAttributeNS((Element) qualifier.getFirstChild(), null, "Id");
    signContext.setIdAttributeNS(dsObject, null, "Id");

    digestReferences(signContext, references);

    return signature;

}

From source file:com.ggvaidya.scinames.model.Dataset.java

public Element serializeToElement(Document doc) {
    Element datasetElement = doc.createElement("dataset");

    datasetElement.setAttribute("name", getName());
    datasetElement.setAttribute("type", getType());
    dateProperty.getValue().setDateAttributesOnElement(datasetElement);
    datasetElement.setAttribute("nameExtractors", getNameExtractorsAsString());

    // Properties
    Element propertiesElement = doc.createElement("properties");
    for (String key : getProperties().keySet()) {
        Element propertyElement = doc.createElement("property");
        propertyElement.setAttribute("name", key);
        propertyElement.setTextContent(getProperties().get(key));
        propertiesElement.appendChild(propertyElement);
    }/*from   w  ww. j  a va2 s  .com*/
    datasetElement.appendChild(propertiesElement);

    Element changesElement = doc.createElement("changes");
    for (Change ch : explicitChanges) {
        Element changeElement = ch.serializeToElement(doc);
        changesElement.appendChild(changeElement);
    }
    datasetElement.appendChild(changesElement);

    Element columnsElement = doc.createElement("columns");
    for (DatasetColumn col : columns) {
        Element columnElement = doc.createElement("column");
        columnElement.setAttribute("name", col.getName());
        columnsElement.appendChild(columnElement);
    }
    datasetElement.appendChild(columnsElement);

    Element rowsElement = doc.createElement("rows");
    for (DatasetRow row : rows) {
        Element rowElement = doc.createElement("row");

        for (DatasetColumn col : row.getColumns()) {
            // Ignore elements without a value.
            String val = row.get(col);
            if (val == null || val.equals(""))
                continue;

            Element itemElement = doc.createElement("key");
            itemElement.setAttribute("name", col.getName());
            itemElement.setTextContent(val);
            rowElement.appendChild(itemElement);
        }

        rowsElement.appendChild(rowElement);
    }
    datasetElement.appendChild(rowsElement);

    return datasetElement;
}

From source file:org.apache.cxf.cwiki.SiteExporter.java

public int getBlogVersion(String pageId) throws Exception {
    Document doc = DOMUtils.newDocument();
    Element el = doc.createElementNS(SOAPNS, "ns1:getBlogEntry");
    Element el2 = doc.createElement("in0");
    el.appendChild(el2);//  ww w.j a v  a2  s .  c o  m
    el2.setTextContent(loginToken);
    el2 = doc.createElement("in1");
    el.appendChild(el2);
    el2.setTextContent(pageId);
    doc.appendChild(el);
    doc = getDispatch().invoke(doc);

    Node nd = doc.getDocumentElement().getFirstChild();

    String version = DOMUtils.getChildContent(nd, "version");
    return Integer.parseInt(version);
}

From source file:org.apache.cxf.cwiki.SiteExporter.java

private void checkVersion() throws ParserConfigurationException, IOException {
    Document doc = DOMUtils.createDocument();
    Element el = doc.createElementNS(SOAPNS, "ns1:getServerInfo");
    Element el2 = doc.createElement("in0");
    el.appendChild(el2);//from  w ww .jav  a 2  s  .  c o  m
    el2.setTextContent(loginToken);
    doc.appendChild(el);

    doc = getDispatch().invoke(doc);
    el = DOMUtils.getFirstElement(DOMUtils.getFirstElement(doc.getDocumentElement()));
    while (el != null) {
        if ("majorVersion".equals(el.getLocalName())) {
            String major = DOMUtils.getContent(el);
            if (Integer.parseInt(major) >= 5) {
                apiVersion = 2;
                ((java.io.Closeable) dispatch).close();
                dispatch = null;
            }
        }

        el = DOMUtils.getNextElement(el);
    }
}