Example usage for org.w3c.dom Element getAttributes

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

Introduction

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

Prototype

public NamedNodeMap getAttributes();

Source Link

Document

A NamedNodeMap containing the attributes of this node (if it is an Element) or null otherwise.

Usage

From source file:com.weibo.api.motan.config.springsupport.MotanBeanDefinitionParser.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private static BeanDefinition parse(Element element, ParserContext parserContext, Class<?> beanClass,
        boolean required) throws ClassNotFoundException {
    RootBeanDefinition bd = new RootBeanDefinition();
    bd.setBeanClass(beanClass);/*from  w w w.  jav  a2  s  . co  m*/
    // ??lazy init
    bd.setLazyInit(false);

    // id?id,idcontext
    String id = element.getAttribute("id");
    if ((id == null || id.length() == 0) && required) {
        String generatedBeanName = element.getAttribute("name");
        if (generatedBeanName == null || generatedBeanName.length() == 0) {
            generatedBeanName = element.getAttribute("class");
        }
        if (generatedBeanName == null || generatedBeanName.length() == 0) {
            generatedBeanName = beanClass.getName();
        }
        id = generatedBeanName;
        int counter = 2;
        while (parserContext.getRegistry().containsBeanDefinition(id)) {
            id = generatedBeanName + (counter++);
        }
    }
    if (id != null && id.length() > 0) {
        if (parserContext.getRegistry().containsBeanDefinition(id)) {
            throw new IllegalStateException("Duplicate spring bean id " + id);
        }
        parserContext.getRegistry().registerBeanDefinition(id, bd);
    }
    bd.getPropertyValues().addPropertyValue("id", id);
    if (ProtocolConfig.class.equals(beanClass)) {
        MotanNamespaceHandler.protocolDefineNames.add(id);

    } else if (RegistryConfig.class.equals(beanClass)) {
        MotanNamespaceHandler.registryDefineNames.add(id);

    } else if (BasicServiceInterfaceConfig.class.equals(beanClass)) {
        MotanNamespaceHandler.basicServiceConfigDefineNames.add(id);

    } else if (BasicRefererInterfaceConfig.class.equals(beanClass)) {
        MotanNamespaceHandler.basicRefererConfigDefineNames.add(id);

    } else if (ServiceConfigBean.class.equals(beanClass)) {
        String className = element.getAttribute("class");
        if (className != null && className.length() > 0) {
            RootBeanDefinition classDefinition = new RootBeanDefinition();
            classDefinition.setBeanClass(
                    Class.forName(className, true, Thread.currentThread().getContextClassLoader()));
            classDefinition.setLazyInit(false);
            parseProperties(element.getChildNodes(), classDefinition);
            bd.getPropertyValues().addPropertyValue("ref",
                    new BeanDefinitionHolder(classDefinition, id + "Impl"));
        }
    }

    Set<String> props = new HashSet<String>();
    ManagedMap parameters = null;
    // ??setbd
    for (Method setter : beanClass.getMethods()) {
        String name = setter.getName();
        // setXXX
        if (name.length() <= 3 || !name.startsWith("set") || !Modifier.isPublic(setter.getModifiers())
                || setter.getParameterTypes().length != 1) {
            continue;
        }
        String property = (name.substring(3, 4).toLowerCase() + name.substring(4)).replaceAll("_", "-");
        props.add(property);
        if ("id".equals(property)) {
            bd.getPropertyValues().addPropertyValue("id", id);
            continue;
        }
        String value = element.getAttribute(property);
        if ("methods".equals(property)) {
            parseMethods(id, element.getChildNodes(), bd, parserContext);
        }
        if (StringUtils.isBlank(value)) {
            continue;
        }
        value = value.trim();
        if (value.length() == 0) {
            continue;
        }
        Object reference;
        if ("ref".equals(property)) {
            if (parserContext.getRegistry().containsBeanDefinition(value)) {
                BeanDefinition refBean = parserContext.getRegistry().getBeanDefinition(value);
                if (!refBean.isSingleton()) {
                    throw new IllegalStateException(
                            "The exported service ref " + value + " must be singleton! Please set the " + value
                                    + " bean scope to singleton, eg: <bean id=\"" + value
                                    + "\" scope=\"singleton\" ...>");
                }
            }
            reference = new RuntimeBeanReference(value);
        } else if ("protocol".equals(property) && !StringUtils.isBlank(value)) {
            if (!value.contains(",")) {
                reference = new RuntimeBeanReference(value);
            } else {
                parseMultiRef("protocols", value, bd, parserContext);
                reference = null;
            }
        } else if ("registry".equals(property)) {
            parseMultiRef("registries", value, bd, parserContext);
            reference = null;
        } else if ("basicService".equals(property)) {
            reference = new RuntimeBeanReference(value);

        } else if ("basicReferer".equals(property)) {
            reference = new RuntimeBeanReference(value);

        } else if ("extConfig".equals(property)) {
            reference = new RuntimeBeanReference(value);
        } else {
            reference = new TypedStringValue(value);
        }

        if (reference != null) {
            bd.getPropertyValues().addPropertyValue(property, reference);
        }
    }
    if (ProtocolConfig.class.equals(beanClass)) {
        // protocolparameters?
        NamedNodeMap attributes = element.getAttributes();
        int len = attributes.getLength();
        for (int i = 0; i < len; i++) {
            Node node = attributes.item(i);
            String name = node.getLocalName();
            if (!props.contains(name)) {
                if (parameters == null) {
                    parameters = new ManagedMap();
                }
                String value = node.getNodeValue();
                parameters.put(name, new TypedStringValue(value, String.class));
            }
        }
        bd.getPropertyValues().addPropertyValue("parameters", parameters);
    }
    return bd;
}

From source file:com.twinsoft.convertigo.engine.translators.WebServiceTranslator.java

private void addElement(SOAPMessage responseMessage, SOAPEnvelope soapEnvelope, Context context,
        Element elementToAdd, SOAPElement soapElement) throws SOAPException {
    SOAPElement soapMethodResponseElement = (SOAPElement) soapEnvelope.getBody().getFirstChild();
    String targetNamespace = soapMethodResponseElement.getNamespaceURI();
    String prefix = soapMethodResponseElement.getPrefix();

    String nodeType = elementToAdd.getAttribute("type");
    SOAPElement childSoapElement = soapElement;

    boolean elementAdded = true;
    boolean bTable = false;

    if (nodeType.equals("table")) {
        bTable = true;/*from w  w  w  .  j a v  a 2 s .  com*/
        /*childSoapElement = soapElement.addChildElement("ArrayOf" + context.transactionName + "_" + tableName + "_Row", "");
                
           if (!context.httpServletRequest.getServletPath().endsWith(".wsl")) {
              childSoapElement.addAttribute(soapEnvelope.createName("xsi:type"), "soapenc:Array");
           }*/
        childSoapElement = soapElement.addChildElement(elementToAdd.getNodeName());
    } else if (nodeType.equals("row")) {
        /*String elementType = context.transactionName + "_" + tableName + "_Row";
        childSoapElement = soapElement.addChildElement(elementType, "");*/
        childSoapElement = soapElement.addChildElement(elementToAdd.getNodeName());
    } else if (nodeType.equals("attachment")) {
        childSoapElement = soapElement.addChildElement(elementToAdd.getNodeName());

        if (context.requestedObject instanceof AbstractHttpTransaction) {
            AttachmentDetails attachment = AttachmentManager.getAttachment(elementToAdd);
            if (attachment != null) {
                byte[] raw = attachment.getData();
                if (raw != null)
                    childSoapElement.addTextNode(Base64.encodeBase64String(raw));
            }

            /* DON'T WORK YET *\
            AttachmentPart ap = responseMessage.createAttachmentPart(new ByteArrayInputStream(raw), elementToAdd.getAttribute("content-type"));
            ap.setContentId(key);
            ap.setContentLocation(elementToAdd.getAttribute("url"));
            responseMessage.addAttachmentPart(ap);
            \* DON'T WORK YET */
        }
    } else {
        String elementNodeName = elementToAdd.getNodeName();
        String elementNodeNsUri = elementToAdd.getNamespaceURI();
        String elementNodePrefix = getPrefix(context.projectName, elementNodeNsUri);

        XmlSchemaElement xmlSchemaElement = getXmlSchemaElementByName(context.projectName, elementNodeName);
        boolean isGlobal = xmlSchemaElement != null;
        if (isGlobal) {
            elementNodeNsUri = xmlSchemaElement.getQName().getNamespaceURI();
            elementNodePrefix = getPrefix(context.projectName, elementNodeNsUri);
        }

        // ignore original SOAP message response elements
        //         if ((elementNodeName.toUpperCase().indexOf("SOAP-ENV:") != -1) || ((elementToAdd.getParentNode().getNodeName().toUpperCase().indexOf("SOAP-ENV:") != -1)) ||
        //            (elementNodeName.toUpperCase().indexOf("SOAPENV:") != -1) || ((elementToAdd.getParentNode().getNodeName().toUpperCase().indexOf("SOAPENV:") != -1)) ||
        //            (elementNodeName.toUpperCase().indexOf("NS0:") != -1) || ((elementToAdd.getParentNode().getNodeName().toUpperCase().indexOf("NS0:") != -1))) {
        //            elementAdded = false;
        //         }
        if ("http://schemas.xmlsoap.org/soap/envelope/".equals(elementToAdd.getNamespaceURI())
                || "http://schemas.xmlsoap.org/soap/envelope/"
                        .equals(elementToAdd.getParentNode().getNamespaceURI())
                || elementToAdd.getParentNode().getNodeName().toUpperCase().indexOf("NS0:") != -1
                || elementNodeName.toUpperCase().indexOf("NS0:") != -1) {
            elementAdded = false;
        } else {
            if (XsdForm.qualified == context.project.getSchemaElementForm() || isGlobal) {
                if (elementNodePrefix == null) {
                    childSoapElement = soapElement
                            .addChildElement(soapEnvelope.createName(elementNodeName, prefix, targetNamespace));
                } else {
                    childSoapElement = soapElement.addChildElement(
                            soapEnvelope.createName(elementNodeName, elementNodePrefix, elementNodeNsUri));
                }
            } else {
                childSoapElement = soapElement.addChildElement(elementNodeName);
            }
        }
    }

    if (elementAdded && elementToAdd.hasAttributes()) {
        addAttributes(responseMessage, soapEnvelope, context, elementToAdd.getAttributes(), childSoapElement);
    }

    if (elementToAdd.hasChildNodes()) {
        NodeList childNodes = elementToAdd.getChildNodes();
        int len = childNodes.getLength();

        if (bTable) {
            /*if (!context.httpServletRequest.getServletPath().endsWith(".wsl")) {
               childSoapElement.addAttribute(soapEnvelope.createName("soapenc:arrayType"), context.projectName+"_ns:" + context.transactionName + "_" + tableName + "_Row[" + (len - 1) + "]");
            }*/
        }

        org.w3c.dom.Node node;
        Element childElement;
        for (int i = 0; i < len; i++) {
            node = childNodes.item(i);
            switch (node.getNodeType()) {
            case org.w3c.dom.Node.ELEMENT_NODE:
                childElement = (Element) node;
                addElement(responseMessage, soapEnvelope, context, childElement, childSoapElement);
                break;
            case org.w3c.dom.Node.CDATA_SECTION_NODE:
            case org.w3c.dom.Node.TEXT_NODE:
                String text = node.getNodeValue();
                text = (text == null) ? "" : text;
                childSoapElement.addTextNode(text);
                break;
            default:
                break;
            }
        }

        /*org.w3c.dom.Node node;
        Element childElement;
        for (int i = 0 ; i < len ; i++) {
           node = childNodes.item(i);
           if (node instanceof Element) {
              childElement = (Element) node;
              addElement(responseMessage, soapEnvelope, context, childElement, childSoapElement);
           }
           else if (node instanceof CDATASection) {
              Node textNode = XMLUtils.findChildNode(elementToAdd, org.w3c.dom.Node.CDATA_SECTION_NODE);
              String text = textNode.getNodeValue();
              if (text == null) {
          text = "";
              }
              childSoapElement.addTextNode(text);
           }
           else {
              Node textNode = XMLUtils.findChildNode(elementToAdd, org.w3c.dom.Node.TEXT_NODE);
              if (textNode != null) {
          String text = textNode.getNodeValue();
          if (text == null) {
             text = "";
          }
          childSoapElement.addTextNode(text);
              }
           }
        }*/
    }
}

From source file:com.portfolio.data.provider.MysqlAdminProvider.java

private void convertAttr(Element attributes, String att) {
    String nodeString = "<?xml version='1.0' encoding='UTF-8' standalone='no'?><transfer " + att + "/>";

    try {/*from  w  w w .  j  a  va 2  s.  co m*/
        /// Ensure we can parse it correctly
        DocumentBuilder documentBuilder;
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(nodeString));
        Document doc = documentBuilder.parse(is);

        /// Transfer attributes
        Element attribNode = doc.getDocumentElement();
        NamedNodeMap attribMap = attribNode.getAttributes();

        for (int i = 0; i < attribMap.getLength(); ++i) {
            Node singleatt = attribMap.item(i);
            String name = singleatt.getNodeName();
            String value = singleatt.getNodeValue();
            attributes.setAttribute(name, value);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.portfolio.data.provider.MysqlAdminProvider.java

@Override
public boolean postNodeRight(int userId, String nodeUuid, int grid, String xml) {
    boolean status = false;
    try {//from w  w w.  j  ava  2s.co  m
        /// On devrait probablement parser le xml avant.
        Document doc = DomUtils.xmlString2Document(xml, new StringBuffer());
        Element node = doc.getDocumentElement();
        NamedNodeMap att = node.getAttributes();
        ArrayList<Integer> valuesInt = new ArrayList<Integer>();
        ArrayList<String> valuesStr = new ArrayList<String>();

        String sql = "UPDATE group_rights SET ";

        for (int i = 0; i < att.getLength(); ++i) {
            Node at = att.item(i);
            String name = at.getNodeName();
            String value = at.getNodeValue();
            if ("rd".equals(name)) {
                sql += "RD=?";
                valuesInt.add(Integer.parseInt(value));
            } else if ("wr".equals(name)) {
                sql += "WR=?";
                valuesInt.add(Integer.parseInt(value));
            } else if ("dl".equals(name)) {
                sql += "DL=?";
                valuesInt.add(Integer.parseInt(value));
            } else if ("sb".equals(name)) {
                sql += "SB=?";
                valuesInt.add(Integer.parseInt(value));
            } else if ("ad".equals(name)) {
                sql += "AD";
                valuesInt.add(Integer.parseInt(value));
            }
            if (i < att.getLength() - 1)
                sql += ",";
        }
        for (int i = 0; i < att.getLength(); ++i) {
            Node at = att.item(i);
            String name = at.getNodeName();
            String value = at.getNodeValue();
            if ("types".equals(name)) {
                sql += "types_id=?";
                valuesStr.add(value);
            } else if ("rules".equals(name)) {
                sql += "rules_id=?";
                valuesStr.add(value);
            } else if ("notify".equals(name)) {
                sql += "notify_roles=?";
                valuesStr.add(value);
            }
            if (i < att.getLength() - 1)
                sql += ",";
        }

        sql += " WHERE grid=? AND id=uuid2bin(?)";

        int size = valuesInt.size() + valuesStr.size() + 1;
        /*
        for( int i=0; i<valuesInt.size(); ++i )
        {
           sql += "?,";
        }
        for( int i=0; i<valuesStr.size(); ++i )
        {
           sql += "?,";
        }
        sql += "?,uuid2bin(?))";
        //*/

        PreparedStatement stInsert = connection.prepareStatement(sql);
        int index = 1;
        Iterator<Integer> iterAtt = valuesInt.iterator();
        while (iterAtt.hasNext()) {
            int v = iterAtt.next();
            stInsert.setInt(index, v);
            ++index;
        }
        Iterator<String> iterStr = valuesStr.iterator();
        while (iterStr.hasNext()) {
            String v = iterStr.next();
            stInsert.setString(index, v);
            ++index;
        }
        stInsert.setInt(size, grid);
        stInsert.setString(size + 1, nodeUuid);
        stInsert.executeUpdate();

        status = true;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        status = true;
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    return status;
}

From source file:edu.lternet.pasta.datapackagemanager.DataPackageManagerResource.java

/**
 * Boolean to determine whether the user contained in the AuthToken is
 * authorized to execute the specified service method.
 * /*from   w  w  w.j  a v  a  2 s  . c om*/
 * @param serviceMethodName
 *            the name of the service method
 * @param authToken
 *            the AuthToken containing the user name
 * @return true if authorized to run the service method, else false
 */
private boolean isServiceMethodAuthorized(String serviceMethodName, Rule.Permission permission,
        AuthToken authToken) {
    boolean isAuthorized = false;
    NodeList nodeList = null;
    String serviceDocumentStr = ConfigurationListener.getServiceDocument();
    Document document = XmlUtility.xmlStringToDoc(serviceDocumentStr);

    try {
        if (document != null) {
            NodeList documentNodeList = document.getChildNodes();
            Node rootNode = documentNodeList.item(0);
            nodeList = rootNode.getChildNodes();

            if (nodeList != null) {
                int nodeListLength = nodeList.getLength();
                for (int i = 0; i < nodeListLength; i++) {
                    Node childNode = nodeList.item(i);
                    String nodeName = childNode.getNodeName();
                    String nodeValue = childNode.getNodeValue();
                    if (nodeName.contains("service-method")) {
                        Element serviceElement = (Element) nodeList.item(i);
                        NamedNodeMap serviceAttributesList = serviceElement.getAttributes();

                        for (int j = 0; j < serviceAttributesList.getLength(); j++) {
                            Node attributeNode = serviceAttributesList.item(j);
                            nodeName = attributeNode.getNodeName();
                            nodeValue = attributeNode.getNodeValue();
                            if (nodeName.equals("name")) {
                                String name = nodeValue;
                                if (name.equals(serviceMethodName)) {
                                    NodeList accessNodeList = serviceElement.getElementsByTagName("access");
                                    Node accessNode = accessNodeList.item(0);
                                    String accessXML = XmlUtility.nodeToXmlString(accessNode);
                                    AccessMatrix accessMatrix = new AccessMatrix(accessXML);
                                    String principalOwner = "pasta";
                                    isAuthorized = accessMatrix.isAuthorized(authToken, principalOwner,
                                            permission);
                                }
                            }
                        }
                    }
                }
            }
        } else {
            String message = "No service methods were found in the service.xml file";
            throw new IllegalStateException(message);
        }
    } catch (InvalidPermissionException e) {
        throw new IllegalStateException(e);
    }

    return isAuthorized;
}

From source file:edu.lternet.pasta.datapackagemanager.DataPackageManagerResource.java

/**
 * <strong>List Service Methods</strong> operation, returning a simple list
 * of web service methods supported by the Data Package Manager web service.
 * //  w  w  w .j  a v  a2  s .c  o m
 * <h4>Requests:</h4>
 * <table border="1" cellspacing="0" cellpadding="3">
 * <tr>
 * <th><b>Message Body</b></th>
 * <th><b>MIME type</b></th>
 * <th><b>Sample Request</b></th>
 * </tr>
 * <tr>
 * <td align=center>none</td>
 * <td align=center>none</td>
 * <td>
 * <code>curl -i -X GET https://pasta.lternet.edu/package/service-methods</code>
 * </td>
 * </tr>
 * <tr>
 * <td align=center>none</td>
 * <td align=center>none</td>
 * <td>
 * <code>curl -i -X GET https://pasta.lternet.edu/package/eml/knb-lter-lno/1?filter=newest</code>
 * </td>
 * </tr>
 * </table>
 *
 * <h4>Responses:</h4>
 * <table border="1" cellspacing="0" cellpadding="3">
 * <tr>
 * <th><b>Status</b></th>
 * <th><b>Reason</b></th>
 * <th><b>Message Body</b></th>
 * <th><b>MIME type</b></th>
 * <th><b>Sample Message Body</b></th>
 * </tr>
 * <tr>
 * <td align=center>200 OK</td>
 * <td align=center>The list request was successful</td>
 * <td align=center>A newline-separated list of revision values matching the
 * specified scope and identifier values</td>
 * <td align=center><code>text/plain</code></td>
 * <td>
 * 
 * <pre>
 * appendProvenance
 * createDataPackage
 * createDataPackageArchive
 * .
 * .
 * . (truncated for brevity)
  * </pre>
 * 
 * </td>
 * </tr>
 * <tr>
 * <td align=center>400 Bad Request</td>
 * <td align=center>The request contains an error, such as an illegal scope
 * or identifier value</td>
 * <td align=center>An error message</td>
 * <td align=center><code>text/plain</code></td>
 * <td align=center><code>Error message</code></td>
 * </tr>
 * <tr>
 * <td align=center>401 Unauthorized</td>
 * <td align=center>The requesting user is not authorized to access a list
 * of the data package revisions</td>
 * <td align=center>An error message</td>
 * <td align=center><code>text/plain</code></td>
 * <td align=center><code>Error message</code></td>
 * </tr>
 * <tr>
 * <td align=center>404 Not Found</td>
 * <td align=center>No data package revisions associated with the specified
 * scope and identifier are found</td>
 * <td align=center>An error message</td>
 * <td align=center><code>text/plain</code></td>
 * <td align=center><code>Error message</code></td>
 * </tr>
 * <tr>
 * <td align=center>405 Method Not Allowed</td>
 * <td align=center>The specified HTTP method is not allowed for the
 * requested resource</td>
 * <td align=center>An error message</td>
 * <td align=center><code>text/plain</code></td>
 * <td align=center><code>Error message</code></td>
 * </tr>
 * <tr>
 * <td align=center>500 Internal Server Error</td>
 * <td align=center>The server encountered an unexpected condition which
 * prevented it from fulfilling the request</td>
 * <td align=center>An error message</td>
 * <td align=center><code>text/plain</code></td>
 * <td align=center><code>Error message</code></td>
 * </tr>
 * </table>
 * 
 * @return a Response, containing a newline-separated list of service
 *         method names supported by the Data Package Manager
 */
@GET
@Path("/service-methods")
@Produces("text/plain")
public Response listServiceMethods(@Context HttpHeaders headers) {
    ResponseBuilder responseBuilder = null;
    Response response = null;
    final String serviceMethodName = "listServiceMethods";
    Rule.Permission permission = Rule.Permission.read;
    AuthToken authToken = null;

    try {
        authToken = getAuthToken(headers);
        String userId = authToken.getUserId();

        // Is user authorized to run the service method?
        boolean serviceMethodAuthorized = isServiceMethodAuthorized(serviceMethodName, permission, authToken);
        if (!serviceMethodAuthorized) {
            throw new UnauthorizedException(
                    "User " + userId + " is not authorized to execute service method " + serviceMethodName);
        }

        String serviceMethods = "";
        StringBuffer stringBuffer = new StringBuffer();
        NodeList nodeList = null;
        String serviceDocumentStr = ConfigurationListener.getServiceDocument();
        Document document = XmlUtility.xmlStringToDoc(serviceDocumentStr);

        if (document != null) {
            NodeList documentNodeList = document.getChildNodes();
            Node rootNode = documentNodeList.item(0);
            nodeList = rootNode.getChildNodes();

            if (nodeList != null) {
                int nodeListLength = nodeList.getLength();
                for (int i = 0; i < nodeListLength; i++) {
                    Node childNode = nodeList.item(i);
                    String nodeName = childNode.getNodeName();
                    String nodeValue = childNode.getNodeValue();
                    if (nodeName.contains("service-method")) {
                        Element serviceElement = (Element) nodeList.item(i);
                        NamedNodeMap serviceAttributesList = serviceElement.getAttributes();

                        for (int j = 0; j < serviceAttributesList.getLength(); j++) {
                            Node attributeNode = serviceAttributesList.item(j);
                            nodeName = attributeNode.getNodeName();
                            nodeValue = attributeNode.getNodeValue();
                            if (nodeName.equals("name")) {
                                String name = nodeValue;
                                stringBuffer.append(String.format("%s\n", name));
                            }
                        }
                    }
                }
            }
        } else {
            String message = "No service methods were found in the service.xml file";
            throw new IllegalStateException(message);
        }

        serviceMethods = stringBuffer.toString();
        responseBuilder = Response.ok(serviceMethods.trim());
        response = responseBuilder.build();
    } catch (IllegalArgumentException e) {
        response = WebExceptionFactory.makeBadRequest(e).getResponse();
    } catch (ResourceNotFoundException e) {
        response = WebExceptionFactory.makeNotFound(e).getResponse();
    } catch (UnauthorizedException e) {
        response = WebExceptionFactory.makeUnauthorized(e).getResponse();
    } catch (UserErrorException e) {
        response = WebResponseFactory.makeBadRequest(e);
    } catch (Exception e) {
        WebApplicationException webApplicationException = WebExceptionFactory
                .make(Response.Status.INTERNAL_SERVER_ERROR, e, e.getMessage());
        response = webApplicationException.getResponse();
    }

    response = stampHeader(response);
    return response;
}

From source file:com.portfolio.data.provider.MysqlAdminProvider.java

@Override
public Object postGroup(String in, int userId) throws Exception {
    if (!credential.isAdmin(userId))
        throw new RestWebApplicationException(Status.FORBIDDEN, "No admin right");

    String result = null;/*from w  ww  .j  a  v a  2s.c  o  m*/
    Integer grid = 0;
    int owner = 0;
    String label = null;

    //On prepare les requetes SQL
    PreparedStatement stInsert;
    String sqlInsert;

    //On recupere le body
    Document doc = DomUtils.xmlString2Document(in, new StringBuffer());
    Element etu = doc.getDocumentElement();

    //On verifie le bon format
    if (etu.getNodeName().equals("group")) {
        //On recupere les attributs
        try {
            if (etu.getAttributes().getNamedItem("grid") != null) {
                grid = Integer.parseInt(etu.getAttributes().getNamedItem("grid").getNodeValue());
            } else {
                grid = null;
            }
        } catch (Exception ex) {
        }

        try {
            if (etu.getAttributes().getNamedItem("owner") != null) {
                owner = Integer.parseInt(etu.getAttributes().getNamedItem("owner").getNodeValue());
            }
        } catch (Exception ex) {
        }

        try {
            if (etu.getAttributes().getNamedItem("label") != null) {
                label = etu.getAttributes().getNamedItem("label").getNodeValue();
            }
        } catch (Exception ex) {
        }

    } else {
        result = "Erreur lors de la recuperation des attributs du groupe dans le XML";
    }

    //On ajoute le groupe dans la base de donnees
    sqlInsert = "REPLACE INTO group_info(grid, owner, label) VALUES (?, ?, ?)";
    if (dbserveur.equals("oracle")) {
        sqlInsert = "MERGE INTO group_info d using (SELECT ? grid,? owner,? label from dual) s ON (1=2) WHEN NOT MATCHED THEN INSERT (d.grid, d.owner, d.label) values (s.grid, s.owner, s.label)";
    }
    stInsert = connection.prepareStatement(sqlInsert);
    stInsert.setInt(1, grid);
    stInsert.setInt(2, owner);
    stInsert.setString(3, label);
    stInsert.executeUpdate();

    //On renvoie le body pour qu'il soit stock dans le log
    result = "<group ";
    result += DomUtils.getXmlAttributeOutputInt("grid", grid) + " ";
    result += DomUtils.getXmlAttributeOutputInt("owner", owner) + " ";
    result += DomUtils.getXmlAttributeOutput("label", label) + " ";
    result += ">";
    result += "</group>";

    return result;
}

From source file:com.portfolio.data.provider.MysqlAdminProvider.java

@Override
public Object postUser(String in, int userId) throws Exception {
    if (!credential.isAdmin(userId))
        throw new RestWebApplicationException(Status.FORBIDDEN, "No admin right");

    String result = null;//from   w  w w  . ja va  2  s. com
    String login = null;
    String firstname = null;
    String lastname = null;
    String label = null;
    String password = null;
    String active = "1";
    Integer uuid = 0;
    Integer newId = 0;

    //On prepare les requetes SQL
    PreparedStatement stInsert;
    String sqlInsert;

    //On recupere le body
    Document doc = DomUtils.xmlString2Document(in, new StringBuffer());
    Element etu = doc.getDocumentElement();

    //On verifie le bon format
    if (etu.getNodeName().equals("user")) {
        //On recupere les attributs
        try {
            if (etu.getAttributes().getNamedItem("uid") != null) {
                login = etu.getAttributes().getNamedItem("uid").getNodeValue();

                if (getMysqlUserUid(login) != null) {
                    uuid = Integer.parseInt(getMysqlUserUid(login));
                }
            }
        } catch (Exception ex) {
        }

        try {
            if (etu.getAttributes().getNamedItem("firstname") != null) {
                firstname = etu.getAttributes().getNamedItem("firstname").getNodeValue();
            }
        } catch (Exception ex) {
        }

        try {
            if (etu.getAttributes().getNamedItem("lastname") != null) {
                lastname = etu.getAttributes().getNamedItem("lastname").getNodeValue();
            }
        } catch (Exception ex) {
        }

        try {
            if (etu.getAttributes().getNamedItem("label") != null) {
                label = etu.getAttributes().getNamedItem("label").getNodeValue();
            }
        } catch (Exception ex) {
        }

        try {
            if (etu.getAttributes().getNamedItem("password") != null) {
                password = etu.getAttributes().getNamedItem("password").getNodeValue();
            }
        } catch (Exception ex) {
        }
        try {
            if (etu.getAttributes().getNamedItem("active") != null) {
                active = etu.getAttributes().getNamedItem("active").getNodeValue();
            }
        } catch (Exception ex) {
        }

    } else {
        result = "Erreur lors de la recuperation des attributs de l'utilisateur dans le XML";
    }

    //On ajoute l'utilisateur dans la base de donnees
    if (etu.getAttributes().getNamedItem("firstname") != null
            && etu.getAttributes().getNamedItem("lastname") != null
            && etu.getAttributes().getNamedItem("label") == null) {

        sqlInsert = "REPLACE INTO credential(userid, login, display_firstname, display_lastname, password, active) VALUES (?, ?, ?, ?, UNHEX(SHA1(?)),?)";
        stInsert = connection.prepareStatement(sqlInsert, Statement.RETURN_GENERATED_KEYS);
        if (dbserveur.equals("oracle")) {
            sqlInsert = "MERGE INTO credential d USING (SELECT ? userid,? login,? display_firstname,? display_lastname,crypt(?) password,? active FROM DUAL) s ON (d.userid=s.userid) WHEN MATCHED THEN UPDATE SET d.login=s.login, d.display_firstname = s.display_firstname, d.display_lastname = s.display_lastname, d.password = s.password, d.active = s.active WHEN NOT MATCHED THEN INSERT (d.userid, d.login, d.display_firstname, d.display_lastname, d.password, d.active) VALUES (s.userid, s.login, s.display_firstname, s.display_lastname, s.password, s.active)";
            stInsert = connection.prepareStatement(sqlInsert, new String[] { "userid" });
        }
        stInsert.setInt(1, uuid);
        stInsert.setString(2, login);
        stInsert.setString(3, firstname);
        stInsert.setString(4, lastname);
        stInsert.setString(5, password);
        stInsert.setString(6, active);
        stInsert.executeUpdate();
    } else {
        sqlInsert = "REPLACE INTO credential(userid, login, display_firstname, display_lastname, password, active) VALUES (?, ?, ?, ?, UNHEX(SHA1(?)),?)";
        stInsert = connection.prepareStatement(sqlInsert, Statement.RETURN_GENERATED_KEYS);
        if (dbserveur.equals("oracle")) {
            sqlInsert = "MERGE INTO credential d USING (SELECT ? userid,? login,? display_firstname,? display_lastname,crypt(?) password,? active FROM DUAL) s ON (d.userid=s.userid) WHEN MATCHED THEN UPDATE SET d.login=s.login, d.display_firstname = s.display_firstname, d.display_lastname = s.display_lastname, d.password = s.password, d.active = s.active WHEN NOT MATCHED THEN INSERT (d.userid, d.login, d.display_firstname, d.display_lastname, d.password, d.active) VALUES (s.userid, s.login, s.display_firstname, s.display_lastname, s.password, s.active)";
            stInsert = connection.prepareStatement(sqlInsert, new String[] { "userid" });
        }
        stInsert.setInt(1, uuid);
        stInsert.setString(2, login);
        stInsert.setString(3, " ");
        stInsert.setString(4, label);
        stInsert.setString(5, password);
        stInsert.setString(6, active);
        stInsert.executeUpdate();
    }

    ResultSet rs = stInsert.getGeneratedKeys();
    if (rs.next()) {
        newId = rs.getInt(1);
    }

    //On renvoie le body pour qu'il soit stock dans le log
    result = "<user ";
    result += DomUtils.getXmlAttributeOutput("uid", login) + " ";
    result += DomUtils.getXmlAttributeOutput("firstname", firstname) + " ";
    result += DomUtils.getXmlAttributeOutput("lastname", lastname) + " ";
    result += DomUtils.getXmlAttributeOutput("label", label) + " ";
    result += DomUtils.getXmlAttributeOutput("password", password) + " ";
    result += DomUtils.getXmlAttributeOutputInt("uuid", newId) + " ";
    result += ">";
    result += "</user>";

    return result;
}

From source file:com.portfolio.data.provider.MysqlAdminProvider.java

@Override
public String putInfUser(int userId, int userid2, String in) throws SQLException {
    String result1 = null;/*from  w  ww  .java2  s  .c o  m*/
    Integer id = 0;
    String password = null;
    String email = null;
    String result = null;
    String username = null;
    String firstname = null;
    String lastname = null;
    String active = null;
    String is_admin = null;

    //On prepare les requetes SQL
    PreparedStatement st;
    String sql;

    //On recupere le body
    Document doc;
    Element infUser = null;
    try {
        doc = DomUtils.xmlString2Document(in, new StringBuffer());
        infUser = doc.getDocumentElement();
    } catch (Exception e) {
        e.printStackTrace();
    }

    NodeList children = null;

    children = infUser.getChildNodes();

    //      if(infUser.getNodeName().equals("users"))
    //      {
    //         for(int i=0;i<children.getLength();i++)
    //         {
    if (infUser.getNodeName().equals("user")) {
        //On recupere les attributs

        if (infUser.getAttributes().getNamedItem("id") != null) {
            id = Integer.parseInt(infUser.getAttributes().getNamedItem("id").getNodeValue());
        } else {
            id = null;
        }
        NodeList children2 = null;
        children2 = infUser.getChildNodes();
        for (int y = 0; y < children2.getLength(); y++) {
            if (children2.item(y).getNodeName().equals("username")) {
                username = DomUtils.getInnerXml(children2.item(y));

                sql = "UPDATE credential SET login = ? WHERE  userid = ?";

                st = connection.prepareStatement(sql);
                st.setString(1, username);
                st.setInt(2, userid2);
                st.executeUpdate();
            }
            if (children2.item(y).getNodeName().equals("password")) {
                password = DomUtils.getInnerXml(children2.item(y));

                sql = "UPDATE credential SET password = UNHEX(SHA1(?)) WHERE  userid = ?";
                if (dbserveur.equals("oracle")) {
                    sql = "UPDATE credential SET password = crypt(?) WHERE  userid = ?";
                }

                st = connection.prepareStatement(sql);
                st.setString(1, password);
                st.setInt(2, userid2);
                st.executeUpdate();
            }
            if (children2.item(y).getNodeName().equals("firstname")) {
                firstname = DomUtils.getInnerXml(children2.item(y));

                sql = "UPDATE credential SET display_firstname = ? WHERE  userid = ?";

                st = connection.prepareStatement(sql);
                st.setString(1, firstname);
                st.setInt(2, userid2);
                st.executeUpdate();
            }
            if (children2.item(y).getNodeName().equals("lastname")) {
                lastname = DomUtils.getInnerXml(children2.item(y));

                sql = "UPDATE credential SET display_lastname = ? WHERE  userid = ?";

                st = connection.prepareStatement(sql);
                st.setString(1, lastname);
                st.setInt(2, userid2);
                st.executeUpdate();
            }
            if (children2.item(y).getNodeName().equals("email")) {
                email = DomUtils.getInnerXml(children2.item(y));

                sql = "UPDATE credential SET email = ? WHERE  userid = ?";

                st = connection.prepareStatement(sql);
                st.setString(1, email);
                st.setInt(2, userid2);
                st.executeUpdate();
            }
            if (children2.item(y).getNodeName().equals("is_admin")) {
                is_admin = DomUtils.getInnerXml(children2.item(y));

                int is_adminInt = Integer.parseInt(is_admin);

                sql = "UPDATE credential SET is_admin = ? WHERE  userid = ?";

                st = connection.prepareStatement(sql);
                st.setInt(1, is_adminInt);
                st.setInt(2, userid2);
                st.executeUpdate();
            }
            if (children2.item(y).getNodeName().equals("active")) {
                active = DomUtils.getInnerXml(children2.item(y));

                int activeInt = Integer.parseInt(active);

                sql = "UPDATE credential SET active = ? WHERE  userid = ?";

                st = connection.prepareStatement(sql);
                st.setInt(1, activeInt);
                st.setInt(2, userid2);
                st.executeUpdate();
            }
        }
    }

    result1 = "" + userid2;

    return result1;
}

From source file:com.portfolio.data.provider.MysqlDataProvider.java

@Override
public Object postGroup(String in, int userId) throws Exception {
    if (!credential.isAdmin(userId))
        throw new RestWebApplicationException(Status.FORBIDDEN, "No admin right");

    String result = null;/*from  www. ja v  a  2  s  . com*/
    Integer grid = 0;
    int owner = 0;
    String label = null;

    //On prepare les requetes SQL
    PreparedStatement stInsert;
    String sqlInsert;

    //On recupere le body
    Document doc = DomUtils.xmlString2Document(in, new StringBuffer());
    Element etu = doc.getDocumentElement();

    //On verifie le bon format
    if (etu.getNodeName().equals("group")) {
        //On recupere les attributs
        try {
            if (etu.getAttributes().getNamedItem("grid") != null) {
                grid = Integer.parseInt(etu.getAttributes().getNamedItem("grid").getNodeValue());
            } else {
                grid = null;
            }
        } catch (Exception ex) {
        }

        try {
            if (etu.getAttributes().getNamedItem("owner") != null) {
                owner = Integer.parseInt(etu.getAttributes().getNamedItem("owner").getNodeValue());
                if (owner == 0)
                    owner = userId;
            } else {
                owner = userId;
            }
        } catch (Exception ex) {
        }

        try {
            if (etu.getAttributes().getNamedItem("label") != null) {
                label = etu.getAttributes().getNamedItem("label").getNodeValue();
            }
        } catch (Exception ex) {
        }

    } else {
        result = "Erreur lors de la recuperation des attributs du groupe dans le XML";
    }

    if (grid == null)
        return "";

    //On ajoute le groupe dans la base de donnees
    sqlInsert = "REPLACE INTO group_info(grid, owner, label) VALUES (?, ?, ?)";
    if (dbserveur.equals("oracle")) {
        sqlInsert = "MERGE INTO group_info d using (SELECT ? grid,? owner,? label from dual) s ON (1=2) WHEN NOT MATCHED THEN INSERT (d.grid, d.owner, d.label) values (s.grid, s.owner, s.label)";
    }
    stInsert = connection.prepareStatement(sqlInsert);
    stInsert.setInt(1, grid);
    stInsert.setInt(2, owner);
    stInsert.setString(3, label);
    stInsert.executeUpdate();

    //On renvoie le body pour qu'il soit stock dans le log
    result = "<group ";
    result += DomUtils.getXmlAttributeOutputInt("grid", grid) + " ";
    result += DomUtils.getXmlAttributeOutputInt("owner", owner) + " ";
    result += DomUtils.getXmlAttributeOutput("label", label) + " ";
    result += ">";
    result += "</group>";

    return result;
}