Example usage for org.dom4j Element elementText

List of usage examples for org.dom4j Element elementText

Introduction

In this page you can find the example usage for org.dom4j Element elementText.

Prototype

String elementText(QName qname);

Source Link

Usage

From source file:org.b5chat.crossfire.xmpp.handler.IQRegisterHandler.java

License:Open Source License

@Override
public IQ handleIQ(IQ packet) throws PacketException, UnauthorizedException {
    IClientSession session = sessionManager.getSession(packet.getFrom());
    IQ reply = null;/*  ww w.j  ava2s  . c o  m*/
    // If no session was found then answer an error (if possible)
    if (session == null) {
        Log.error("Error during registration. ISession not found in " + sessionManager.getPreAuthenticatedKeys()
                + " for key " + packet.getFrom());
        // This error packet will probably won't make it through
        reply = IQ.createResultIQ(packet);
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(PacketError.Condition.internal_server_error);
        return reply;
    }
    if (IQ.Type.get.equals(packet.getType())) {
        // If inband registration is not allowed, return an error.
        if (!registrationEnabled) {
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.forbidden);
        } else {
            reply = IQ.createResultIQ(packet);
            if (session.getStatus() == ISession.STATUS_AUTHENTICATED) {
                try {
                    User user = userManager.getUser(session.getUsername());
                    Element currentRegistration = probeResult.createCopy();
                    currentRegistration.addElement("registered");
                    currentRegistration.element("username").setText(user.getUsername());
                    currentRegistration.element("password").setText("");
                    currentRegistration.element("email")
                            .setText(user.getEmail() == null ? "" : user.getEmail());
                    currentRegistration.element("name").setText(user.getName());

                    Element form = currentRegistration.element(QName.get("x", "jabber:x:data"));
                    Iterator fields = form.elementIterator("field");
                    Element field;
                    while (fields.hasNext()) {
                        field = (Element) fields.next();
                        if ("username".equals(field.attributeValue("var"))) {
                            field.addElement("value").addText(user.getUsername());
                        } else if ("name".equals(field.attributeValue("var"))) {
                            field.addElement("value").addText(user.getName());
                        } else if ("email".equals(field.attributeValue("var"))) {
                            field.addElement("value").addText(user.getEmail() == null ? "" : user.getEmail());
                        }
                    }
                    reply.setChildElement(currentRegistration);
                } catch (UserNotFoundException e) {
                    reply.setChildElement(probeResult.createCopy());
                }
            } else {
                // This is a workaround. Since we don't want to have an incorrect TO attribute
                // value we need to clean up the TO attribute. The TO attribute will contain an
                // incorrect value since we are setting a fake JID until the user actually
                // authenticates with the server.
                reply.setTo((JID) null);
                reply.setChildElement(probeResult.createCopy());
            }
        }
    } else if (IQ.Type.set.equals(packet.getType())) {
        try {
            Element iqElement = packet.getChildElement();
            if (iqElement.element("remove") != null) {
                // If inband registration is not allowed, return an error.
                if (!registrationEnabled) {
                    reply = IQ.createResultIQ(packet);
                    reply.setChildElement(packet.getChildElement().createCopy());
                    reply.setError(PacketError.Condition.forbidden);
                } else {
                    if (session.getStatus() == ISession.STATUS_AUTHENTICATED) {
                        User user = userManager.getUser(session.getUsername());
                        // Delete the user
                        userManager.deleteUser(user);
                        // Delete the roster of the user
                        rosterManager.deleteRoster(session.getAddress());
                        // Delete the user from all the Groups
                        GroupManager.getInstance().deleteUser(user);

                        reply = IQ.createResultIQ(packet);
                        session.process(reply);
                        // Take a quick nap so that the client can process the result
                        Thread.sleep(10);
                        // Close the user's connection
                        final StreamError error = new StreamError(StreamError.Condition.not_authorized);
                        for (IClientSession sess : sessionManager.getSessions(user.getUsername())) {
                            sess.deliverRawText(error.toXML());
                            sess.close();
                        }
                        // The reply has been sent so clean up the variable
                        reply = null;
                    } else {
                        throw new UnauthorizedException();
                    }
                }
            } else {
                String username;
                String password = null;
                String email = null;
                String name = null;
                User newUser;
                DataForm registrationForm;
                FormField field;

                Element formElement = iqElement.element("x");
                // Check if a form was used to provide the registration info
                if (formElement != null) {
                    // Get the sent form
                    registrationForm = new DataForm(formElement);
                    // Get the username sent in the form
                    List<String> values = registrationForm.getField("username").getValues();
                    username = (!values.isEmpty() ? values.get(0) : " ");
                    // Get the password sent in the form
                    field = registrationForm.getField("password");
                    if (field != null) {
                        values = field.getValues();
                        password = (!values.isEmpty() ? values.get(0) : " ");
                    }
                    // Get the email sent in the form
                    field = registrationForm.getField("email");
                    if (field != null) {
                        values = field.getValues();
                        email = (!values.isEmpty() ? values.get(0) : " ");
                    }
                    // Get the name sent in the form
                    field = registrationForm.getField("name");
                    if (field != null) {
                        values = field.getValues();
                        name = (!values.isEmpty() ? values.get(0) : " ");
                    }
                } else {
                    // Get the registration info from the query elements
                    username = iqElement.elementText("username");
                    password = iqElement.elementText("password");
                    email = iqElement.elementText("email");
                    name = iqElement.elementText("name");
                }
                if (email != null && email.matches("\\s*")) {
                    email = null;
                }
                if (name != null && name.matches("\\s*")) {
                    name = null;
                }

                // So that we can set a more informative error message back, lets test this for
                // stringprep validity now.
                if (username != null) {
                    Stringprep.nodeprep(username);
                }

                if (session.getStatus() == ISession.STATUS_AUTHENTICATED) {
                    // Flag that indicates if the user is *only* changing his password
                    boolean onlyPassword = false;
                    if (iqElement.elements().size() == 2 && iqElement.element("username") != null
                            && iqElement.element("password") != null) {
                        onlyPassword = true;
                    }
                    // If users are not allowed to change their password, return an error.
                    if (password != null && !canChangePassword) {
                        reply = IQ.createResultIQ(packet);
                        reply.setChildElement(packet.getChildElement().createCopy());
                        reply.setError(PacketError.Condition.forbidden);
                        return reply;
                    }
                    // If inband registration is not allowed, return an error.
                    else if (!onlyPassword && !registrationEnabled) {
                        reply = IQ.createResultIQ(packet);
                        reply.setChildElement(packet.getChildElement().createCopy());
                        reply.setError(PacketError.Condition.forbidden);
                        return reply;
                    } else {
                        User user = userManager.getUser(session.getUsername());
                        if (user.getUsername().equalsIgnoreCase(username)) {
                            if (password != null && password.trim().length() > 0) {
                                user.setPassword(password);
                            }
                            if (!onlyPassword) {
                                user.setEmail(email);
                            }
                            newUser = user;
                        } else if (password != null && password.trim().length() > 0) {
                            // An admin can create new accounts when logged in.
                            newUser = userManager.createUser(username, password, null, email);
                        } else {
                            // Deny registration of users with no password
                            reply = IQ.createResultIQ(packet);
                            reply.setChildElement(packet.getChildElement().createCopy());
                            reply.setError(PacketError.Condition.not_acceptable);
                            return reply;
                        }
                    }
                } else {
                    // If inband registration is not allowed, return an error.
                    if (!registrationEnabled) {
                        reply = IQ.createResultIQ(packet);
                        reply.setChildElement(packet.getChildElement().createCopy());
                        reply.setError(PacketError.Condition.forbidden);
                        return reply;
                    }
                    // Inform the entity of failed registration if some required
                    // information was not provided
                    else if (password == null || password.trim().length() == 0) {
                        reply = IQ.createResultIQ(packet);
                        reply.setChildElement(packet.getChildElement().createCopy());
                        reply.setError(PacketError.Condition.not_acceptable);
                        return reply;
                    } else {
                        // Create the new account
                        newUser = userManager.createUser(username, password, name, email);
                    }
                }
                // Set and save the extra user info (e.g. full name, etc.)
                if (newUser != null && name != null && !name.equals(newUser.getName())) {
                    newUser.setName(name);
                }

                reply = IQ.createResultIQ(packet);
            }
        } catch (UserAlreadyExistsException e) {
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.conflict);
        } catch (UserNotFoundException e) {
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.bad_request);
        } catch (StringprepException e) {
            // The specified username is not correct according to the stringprep specs
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.jid_malformed);
        } catch (IllegalArgumentException e) {
            // At least one of the fields passed in is not valid
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.not_acceptable);
            Log.warn(e.getMessage(), e);
        } catch (UnsupportedOperationException e) {
            // The User provider is read-only so this operation is not allowed
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.not_allowed);
        } catch (Exception e) {
            // Some unexpected error happened so return an internal_server_error
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.internal_server_error);
            Log.error(e.getMessage(), e);
        }
    }
    if (reply != null) {
        // why is this done here instead of letting the iq handler do it?
        session.process(reply);
    }
    return null;
}

From source file:org.brunocvcunha.sockettester.core.SocketTesterController.java

License:Apache License

public static SocketTesterVO validateEnvironmentNode(Element env) throws IOException {
    log.info("Validating environment node...");

    SocketTesterVO vo = new SocketTesterVO();
    vo.setType(env.elementText("type"));
    vo.setName(env.elementText("description"));
    vo.setHost(env.elementText("host"));
    vo.setPort(Integer.valueOf(env.elementText("port")));
    vo.setValid(SocketTesterHelper.isValidSocket(vo.getHost(), vo.getPort()));
    vo.setService(env.elementText("service"));

    if (vo.isValid()) {
        vo.setStatus("OK");
        vo.setValid(true);//from  ww w  .ja  va2s .  c om

        validate(vo);

    } else {
        vo.setStatus("Error establishing connection.");
    }

    return vo;
}

From source file:org.cpsolver.ifs.example.tt.TimetableModel.java

License:Open Source License

public static TimetableModel loadFromXML(File inFile, Assignment<Activity, Location> assignment)
        throws IOException, DocumentException {
    Document document = (new SAXReader()).read(inFile);
    Element root = document.getRootElement();
    if (!"Timetable".equals(root.getName())) {
        sLogger.error("Given XML file is not interactive timetabling problem.");
        return null;
    }/*from  w ww  . ja  v a  2  s. co  m*/

    Element problem = root.element("Problem");
    Element problemGen = problem.element("General");
    TimetableModel m = new TimetableModel(Integer.parseInt(problemGen.elementText("DaysPerWeek")),
            Integer.parseInt(problemGen.elementText("SlotsPerDay")));

    Element resources = problem.element("Resources");

    HashMap<String, Resource> resTab = new HashMap<String, Resource>();

    Element resEl = resources.element("Classrooms");
    for (Iterator<?> i = resEl.elementIterator("Resource"); i.hasNext();) {
        Element el = (Element) i.next();
        Resource r = new Resource(el.attributeValue("id"), Resource.TYPE_ROOM, el.elementText("Name"));
        Element pref = el.element("TimePreferences");
        for (Iterator<?> j = pref.elementIterator("Soft"); j.hasNext();)
            r.addDiscouragedSlot(Integer.parseInt(((Element) j.next()).getText()));
        for (Iterator<?> j = pref.elementIterator("Hard"); j.hasNext();)
            r.addProhibitedSlot(Integer.parseInt(((Element) j.next()).getText()));
        m.addConstraint(r);
        resTab.put(r.getResourceId(), r);
    }

    resEl = resources.element("Teachers");
    for (Iterator<?> i = resEl.elementIterator("Resource"); i.hasNext();) {
        Element el = (Element) i.next();
        Resource r = new Resource(el.attributeValue("id"), Resource.TYPE_INSTRUCTOR, el.elementText("Name"));
        Element pref = el.element("TimePreferences");
        for (Iterator<?> j = pref.elementIterator("Soft"); j.hasNext();)
            r.addDiscouragedSlot(Integer.parseInt(((Element) j.next()).getText()));
        for (Iterator<?> j = pref.elementIterator("Hard"); j.hasNext();)
            r.addProhibitedSlot(Integer.parseInt(((Element) j.next()).getText()));
        m.addConstraint(r);
        resTab.put(r.getResourceId(), r);
    }

    resEl = resources.element("Classes");
    for (Iterator<?> i = resEl.elementIterator("Resource"); i.hasNext();) {
        Element el = (Element) i.next();
        Resource r = new Resource(el.attributeValue("id"), Resource.TYPE_CLASS, el.elementText("Name"));
        Element pref = el.element("TimePreferences");
        for (Iterator<?> j = pref.elementIterator("Soft"); j.hasNext();)
            r.addDiscouragedSlot(Integer.parseInt(((Element) j.next()).getText()));
        for (Iterator<?> j = pref.elementIterator("Hard"); j.hasNext();)
            r.addProhibitedSlot(Integer.parseInt(((Element) j.next()).getText()));
        m.addConstraint(r);
        resTab.put(r.getResourceId(), r);
    }

    resEl = resources.element("Special");
    for (Iterator<?> i = resEl.elementIterator("Resource"); i.hasNext();) {
        Element el = (Element) i.next();
        Resource r = new Resource(el.attributeValue("id"), Resource.TYPE_OTHER, el.elementText("Name"));
        Element pref = el.element("TimePreferences");
        for (Iterator<?> j = pref.elementIterator("Soft"); j.hasNext();)
            r.addDiscouragedSlot(Integer.parseInt(((Element) j.next()).getText()));
        for (Iterator<?> j = pref.elementIterator("Hard"); j.hasNext();)
            r.addProhibitedSlot(Integer.parseInt(((Element) j.next()).getText()));
        m.addConstraint(r);
        resTab.put(r.getResourceId(), r);
    }

    Element actEl = problem.element("Activities");
    HashMap<String, Activity> actTab = new HashMap<String, Activity>();
    for (Iterator<?> i = actEl.elementIterator("Activity"); i.hasNext();) {
        Element el = (Element) i.next();
        Activity a = new Activity(Integer.parseInt(el.elementText("Length")), el.attributeValue("id"),
                el.elementText("Name"));
        Element pref = el.element("TimePreferences");
        for (Iterator<?> j = pref.elementIterator("Soft"); j.hasNext();)
            a.addDiscouragedSlot(Integer.parseInt(((Element) j.next()).getText()));
        for (Iterator<?> j = pref.elementIterator("Hard"); j.hasNext();)
            a.addProhibitedSlot(Integer.parseInt(((Element) j.next()).getText()));
        Element req = el.element("RequiredResources");
        for (Iterator<?> j = req.elementIterator(); j.hasNext();) {
            Element rqEl = (Element) j.next();
            if ("Resource".equals(rqEl.getName())) {
                a.addResourceGroup(resTab.get(rqEl.getText()));
            } else if ("Group".equals(rqEl.getName())) {
                if ("no".equalsIgnoreCase(rqEl.attributeValue("conjunctive"))
                        || "false".equalsIgnoreCase(rqEl.attributeValue("conjunctive"))) {
                    List<Resource> gr = new ArrayList<Resource>();
                    for (Iterator<?> k = rqEl.elementIterator("Resource"); k.hasNext();)
                        gr.add(resTab.get(((Element) k.next()).getText()));
                    a.addResourceGroup(gr);
                } else {
                    for (Iterator<?> k = rqEl.elementIterator("Resource"); k.hasNext();)
                        a.addResourceGroup(resTab.get(((Element) k.next()).getText()));
                }
            }
        }
        m.addVariable(a);
        a.init();
        actTab.put(a.getActivityId(), a);
    }

    Element depEl = problem.element("Dependences");
    for (Iterator<?> i = depEl.elementIterator("Dependence"); i.hasNext();) {
        Element el = (Element) i.next();
        int type = Dependence.TYPE_NO_DEPENDENCE;
        String typeStr = el.elementText("Operator");
        if ("After".equals(typeStr))
            type = Dependence.TYPE_AFTER;
        else if ("Before".equals(typeStr))
            type = Dependence.TYPE_BEFORE;
        else if ("After".equals(typeStr))
            type = Dependence.TYPE_AFTER;
        else if ("Closely before".equals(typeStr))
            type = Dependence.TYPE_CLOSELY_BEFORE;
        else if ("Closely after".equals(typeStr))
            type = Dependence.TYPE_CLOSELY_AFTER;
        else if ("Concurrently".equals(typeStr))
            type = Dependence.TYPE_CONCURRENCY;
        Dependence d = new Dependence(el.attributeValue("id"), type);
        d.addVariable(actTab.get(el.elementText("FirstActivity")));
        d.addVariable(actTab.get(el.elementText("SecondActivity")));
        m.addConstraint(d);
    }

    Element solEl = root.element("Solution");
    if (solEl != null) {
        for (Iterator<?> i = solEl.elementIterator("Activity"); i.hasNext();) {
            Element el = (Element) i.next();
            Activity a = actTab.get(el.attributeValue("id"));
            if (a == null)
                continue;
            int slot = Integer.parseInt(el.elementText("StartTime"));
            Element usResEl = el.element("UsedResources");
            List<Resource> res = new ArrayList<Resource>();
            for (Iterator<?> j = usResEl.elementIterator("Resource"); j.hasNext();)
                res.add(resTab.get(((Element) j.next()).getText()));
            for (Location loc : a.values(assignment)) {
                if (loc.getSlot() != slot || loc.getResources().length != res.size())
                    continue;
                boolean same = true;
                for (int j = 0; j < loc.getResources().length && same; j++)
                    if (!res.get(j).equals(loc.getResources()[j]))
                        same = false;
                if (!same)
                    continue;
                a.setInitialAssignment(loc);
                if (assignment != null)
                    assignment.assign(0, loc);
                break;
            }
        }
    }
    return m;
}

From source file:org.dcm4chex.archive.hl7.HL7SendService.java

License:LGPL

/** Parse the PID entries into a list of maps */
public static final List<Map<String, String>> parsePDQ(Document msg) {
    List<Map<String, String>> ret = new ArrayList<Map<String, String>>();
    Element root = msg.getRootElement();
    List<?> content = root.content();
    for (Object c : content) {
        if (!(c instanceof Element))
            continue;
        Element e = (Element) c;
        if (e.getName().equals("PID")) {
            Map<String, String> pid = new HashMap<String, String>();
            pid.put("Type", "Patient");
            List<?> fields = e.elements(HL7XMLLiterate.TAG_FIELD);

            int pidNo = 0;
            for (Object f : fields) {
                pidNo++;/* w  ww  .jav a  2 s .  c o m*/
                if (pidNo >= FIELD_NAMES.length)
                    continue;
                String fieldName = FIELD_NAMES[pidNo];
                if (fieldName == null)
                    continue;
                Element field = (Element) f;
                if (field.isTextOnly()) {
                    String txt = field.getText();
                    if (txt == null || txt.length() == 0)
                        continue;
                    pid.put(fieldName, txt);
                    continue;
                }
                if (pidNo == 3) {
                    List<?> comps = field.elements(HL7XMLLiterate.TAG_COMPONENT);
                    if (comps.size() < 3) {
                        throw new IllegalArgumentException("Missing Authority in PID-3");
                    }
                    Element authority = (Element) comps.get(2);
                    List<?> authorityUID = authority.elements(HL7XMLLiterate.TAG_SUBCOMPONENT);
                    pid.put("PatientID", field.getText());
                    StringBuffer issuer = new StringBuffer(authority.getText());
                    for (int i = 0; i < authorityUID.size(); i++) {
                        issuer.append("&").append(((Element) authorityUID.get(i)).getText());
                    }
                    pid.put("IssuerOfPatientID", issuer.toString());
                    continue;
                }
                if (pidNo == 5) {
                    String name = field.getText() + "^" + field.elementText(HL7XMLLiterate.TAG_COMPONENT);
                    pid.put(fieldName, name);
                    continue;
                }
                pid.put(fieldName, field.asXML());
            }
            ret.add(pid);
        }
    }
    return ret;
}

From source file:org.eclipse.ecr.core.io.impl.AbstractDocumentModelWriter.java

License:Open Source License

@SuppressWarnings("unchecked")
private static Object getElementData(ExportedDocument xdoc, Element element, Type type) {
    if (type.isSimpleType()) {
        return type.decode(element.getText());
    } else if (type.isListType()) {
        ListType ltype = (ListType) type;
        List<Object> list = new ArrayList<Object>();
        Iterator<Element> it = element.elementIterator();
        while (it.hasNext()) {
            Element el = it.next();
            list.add(getElementData(xdoc, el, ltype.getFieldType()));
        }/*from  w  w  w  .ja v  a 2s .  c om*/
        Type ftype = ltype.getFieldType();
        if (ftype.isSimpleType()) { // these are stored as arrays
            Class klass = JavaTypes.getClass(ftype);
            if (klass.isPrimitive()) {
                return PrimitiveArrays.toPrimitiveArray(list, klass);
            } else {
                return list.toArray((Object[]) Array.newInstance(klass, list.size()));
            }
        }
        return list;
    } else {
        ComplexType ctype = (ComplexType) type;
        if (TypeConstants.isContentType(ctype)) {
            String mimeType = element.elementText(ExportConstants.BLOB_MIME_TYPE);
            String encoding = element.elementText(ExportConstants.BLOB_ENCODING);
            String content = element.elementTextTrim(ExportConstants.BLOB_DATA);
            String filename = element.elementTextTrim(ExportConstants.BLOB_FILENAME);
            if ((content == null || content.length() == 0) && (mimeType == null || mimeType.length() == 0)) {
                return null; // remove blob
            }
            Blob blob = null;
            if (xdoc.hasExternalBlobs()) {
                blob = xdoc.getBlob(content);
            }
            if (blob == null) { // maybe the blob is embedded in Base64
                // encoded data
                byte[] bytes = Base64.decode(content);
                blob = new StreamingBlob(new ByteArraySource(bytes));
            }
            blob.setMimeType(mimeType);
            blob.setEncoding(encoding);
            blob.setFilename(filename);
            return blob;
        } else { // a complex type
            Map<String, Object> map = new HashMap<String, Object>();
            Iterator<Element> it = element.elementIterator();
            while (it.hasNext()) {
                Element el = it.next();
                String name = el.getName();
                Object value = getElementData(xdoc, el, ctype.getField(el.getName()).getType());
                map.put(name, value);
            }
            return map;
        }
    }
}

From source file:org.faster.generator.Settings.java

License:Open Source License

public Settings(String cfgFile) {
    InputStream in = null;/*w  w  w  .  jav a  2 s . c o m*/
    try {
        in = new FileInputStream(cfgFile);
    } catch (FileNotFoundException e) {
        throw new IllegalArgumentException(cfgFile + " does not exist.");
    }
    try {
        Document doc = new SAXReader().read(in);
        Element root = doc.getRootElement();
        Element dirEle = root.element("dir");
        templateDir = dirEle.elementText("template").trim();
        coreOutputDir = dirEle.elementText("core").trim();
        rsOutputDir = dirEle.elementText("rs").trim();
        basePackage = root.attributeValue("basePackage").trim();
        overwrite = Boolean.valueOf(root.attributeValue("overwrite").trim());
        String outputValues = root.attributeValue("output").trim();
        coreOutputEnabled = outputValues.contains("core");
        rsOutputEnabled = outputValues.contains("rs");

        List<Element> propertyEles = root.elements("property");
        properties = new HashMap<String, Object>(propertyEles.size());
        for (Element ele : propertyEles) {
            properties.put(ele.attributeValue("name"), ele.attributeValue("value"));
        }

        List<Element> modelEles = root.elements("model");
        modelSettings = new ArrayList<ModelSetting>(modelEles.size());
        for (Element ele : modelEles) {
            ModelSetting ms = new ModelSetting();
            ms.setModelName(ele.attributeValue("name"));
            ms.setTable(ele.attributeValue("table"));
            ms.setParent(ele.attributeValue("parent"));
            ms.setRemark(ele.attributeValue("remark"));
            modelSettings.add(ms);
        }
    } catch (DocumentException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:org.gearman.example.JenkinsJobStatus.java

License:BSD License

public GearmanJobResult executeFunction() {

    boolean status = true;
    StringBuffer sb = new StringBuffer(ByteUtils.fromUTF8Bytes((byte[]) this.data));
    String sb_str = sb.toString();

    Gson gson = new Gson();

    try {// w  w  w  .j a v a 2s .  c o  m

        // convert json string to an object 
        JenkinsData jdata = gson.fromJson(sb_str, JenkinsData.class);

        // create the url of the jenkins job
        String jenkins_job_xml = jdata.getUrl() + "/job/" + jdata.getJobId() + "/api/xml";

        // every Hudson model object exposes the .../api/xml, but in this example
        // we'll just take the root object as an example
        URL url = new URL(jenkins_job_xml);

        // if you are calling security-enabled Hudson and
        // need to invoke operations and APIs that are protected,
        // consult the 'SecuredMain" class
        // in this package for an example using HttpClient.

        // read it into DOM.
        Document dom = new SAXReader().read(url);

        for (Element job : (List<Element>) dom.getRootElement().elements("healthReport")) {
            System.out.println(String.format("Health Report:%s\tStatus:%s", job.elementText("description"),
                    job.elementText("score")));
        }

    } catch (Exception e) {
        System.out.println("Error!!!!!");
        status = false;

    }

    GearmanJobResult gjr = new GearmanJobResultImpl(this.jobHandle, status, sb.toString().getBytes(),
            new byte[0], new byte[0], 0, 0);

    return gjr;

}

From source file:org.jboss.pnc.pvt.execution.ParamJenkinsJob.java

License:Apache License

private List<SerializableStringParam> readJobParams() {
    List<Node> nodes = doc.selectNodes("//hudson.model.StringParameterDefinition");
    List<SerializableStringParam> params = new ArrayList<>();
    if (null == nodes || 0 == nodes.size()) {
        return params;
    }// w  w w.j av a 2  s  .c om

    for (Node node : nodes) {
        Element paramEle = (Element) node;
        String name = paramEle.elementText("name");
        String description = paramEle.elementText("description");
        String defaultValue = paramEle.elementText("defaultValue");
        StringParameterDefinition spd = new StringParameterDefinition(name, description, defaultValue);
        params.add(new SerializableStringParam(spd));
    }
    return params;
}

From source file:org.jeedevframework.jpush.server.xmpp.handler.IQRegisterHandler.java

License:Open Source License

/**
 * Handles the received IQ packet.//from   w  w  w .  j a  va 2 s. co m
 * 
 * @param packet the packet
 * @return the response to send back
 * @throws UnauthorizedException if the user is not authorized
 */
public IQ handleIQ(IQ packet) throws UnauthorizedException {
    IQ reply = null;

    ClientSession session = sessionManager.getSession(packet.getFrom());
    if (session == null) {
        log.error("Session not found for key " + packet.getFrom());
        reply = IQ.createResultIQ(packet);
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(PacketError.Condition.internal_server_error);
        return reply;
    }

    if (IQ.Type.get.equals(packet.getType())) {
        reply = IQ.createResultIQ(packet);
        if (session.getStatus() == Session.STATUS_AUTHENTICATED) {
            // TODO
        } else {
            reply.setTo((JID) null);
            reply.setChildElement(probeResponse.createCopy());
        }
    } else if (IQ.Type.set.equals(packet.getType())) {
        try {
            Element query = packet.getChildElement();
            if (query.element("remove") != null) {
                if (session.getStatus() == Session.STATUS_AUTHENTICATED) {
                    // TODO
                } else {
                    throw new UnauthorizedException();
                }
            } else {
                String username = query.elementText("username");
                String password = query.elementText("password");
                String email = query.elementText("email");
                String name = query.elementText("name");

                // Verify the username
                if (username != null) {
                    Stringprep.nodeprep(username);
                }

                // Deny registration of users with no password
                if (password == null || password.trim().length() == 0) {
                    reply = IQ.createResultIQ(packet);
                    reply.setChildElement(packet.getChildElement().createCopy());
                    reply.setError(PacketError.Condition.not_acceptable);
                    return reply;
                }

                if (email != null && email.matches("\\s*")) {
                    email = null;
                }

                if (name != null && name.matches("\\s*")) {
                    name = null;
                }

                User user = null;
                if (session.getStatus() == Session.STATUS_AUTHENTICATED) {
                    try {
                        user = userService.getUserByUsername(session.getUsername());
                    } catch (UserNotFoundException e) {
                        log.info(session.getUsername() + ":" + e.getMessage());
                    }

                } else {
                    try {
                        user = userService.getUserByUsername(session.getUsername());
                    } catch (UserNotFoundException e) {
                        log.info(session.getUsername() + ":" + e.getMessage());
                    }
                }

                if ((user == null) || (user.getId() == null) || (user.getId() == 0)) {
                    user = new User();
                    user.setUsername(username);
                    user.setPassword(password);
                    user.setEmail(email);
                    user.setName(name);
                    userService.saveUser(user);
                }

                //reply = IQ.createResultIQ(packet);

                Element userprobeResponse = DocumentHelper.createElement(QName.get("query", NAMESPACE));
                userprobeResponse.addElement("username").setText(user.getUsername());
                userprobeResponse.addElement("password").setText(user.getPassword());
                reply = IQ.createResultIQ(packet);
                reply.setChildElement(userprobeResponse);
            }
        } catch (Exception ex) {
            log.error(ex);
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            if (ex instanceof UserExistsException) {
                reply.setError(PacketError.Condition.conflict);
            } else if (ex instanceof UserNotFoundException) {
                reply.setError(PacketError.Condition.bad_request);
            } else if (ex instanceof StringprepException) {
                reply.setError(PacketError.Condition.jid_malformed);
            } else if (ex instanceof IllegalArgumentException) {
                reply.setError(PacketError.Condition.not_acceptable);
            } else {
                reply.setError(PacketError.Condition.internal_server_error);
            }
        }
    }

    // Send the response directly to the session
    if (reply != null) {
        session.process(reply);
    }
    return null;
}

From source file:org.jivesoftware.multiplexer.net.StanzaHandler.java

License:Open Source License

/**
 * Start using compression but first check if the connection can and should use compression.
 * The connection will be closed if the requested method is not supported, if the connection
 * is already using compression or if client requested to use compression but this feature
 * is disabled./*from  w ww.j  av a 2  s. c  o  m*/
 *
 * @param stanza the XML stanza sent by the client requesting compression. Compression method is
 *            included.
 * @return true if it was possible to use compression.
 */
private boolean compressClient(String stanza) {
    String error = null;
    if (connection.getCompressionPolicy() == Connection.CompressionPolicy.disabled) {
        // Client requested compression but this feature is disabled
        error = "<failure xmlns='http://jabber.org/protocol/compress'><setup-failed/></failure>";
        // Log a warning so that admins can track this case from the server side
        Log.warn("Client requested compression while compression is disabled. Closing " + "connection : "
                + connection);
    } else if (connection.isCompressed()) {
        // Client requested compression but connection is already compressed
        error = "<failure xmlns='http://jabber.org/protocol/compress'><setup-failed/></failure>";
        // Log a warning so that admins can track this case from the server side
        Log.warn("Client requested compression and connection is already compressed. Closing " + "connection : "
                + connection);
    } else {
        XMPPPacketReader xmppReader = new XMPPPacketReader();
        xmppReader.setXPPFactory(factory);
        Element doc;
        try {
            doc = xmppReader.read(new StringReader(stanza)).getRootElement();
        } catch (Exception e) {
            Log.error("Error parsing compression stanza: " + stanza, e);
            connection.close();
            return false;
        }

        // Check that the requested method is supported
        String method = doc.elementText("method");
        if (!"zlib".equals(method)) {
            error = "<failure xmlns='http://jabber.org/protocol/compress'><unsupported-method/></failure>";
            // Log a warning so that admins can track this case from the server side
            Log.warn("Requested compression method is not supported: " + method + ". Closing connection : "
                    + connection);
        }
    }

    if (error != null) {
        // Deliver stanza
        connection.deliverRawText(error);
        return false;
    } else {
        // Indicate client that he can proceed and compress the socket
        connection.deliverRawText("<compressed xmlns='http://jabber.org/protocol/compress'/>");

        // Start using compression
        connection.startCompression();
        return true;
    }
}