Example usage for javax.activation MimeType MimeType

List of usage examples for javax.activation MimeType MimeType

Introduction

In this page you can find the example usage for javax.activation MimeType MimeType.

Prototype

public MimeType(String rawdata) throws MimeTypeParseException 

Source Link

Document

Constructor that builds a MimeType from a String.

Usage

From source file:com.portfolio.rest.RestServicePortfolio.java

@Path("/nodes/{node-id}/xsl/{xsl-file}")
@GET/*from   w w  w.j av a 2  s . c  o m*/
@Produces(MediaType.TEXT_HTML)
@Consumes(MediaType.APPLICATION_XML)
public String getNodeWithXSL(@CookieParam("user") String user, @CookieParam("credential") String token,
        @QueryParam("group") int groupId, @PathParam("node-id") String nodeUuid,
        @PathParam("xsl-file") String xslFile, @Context ServletConfig sc,
        @Context HttpServletRequest httpServletRequest, @HeaderParam("Accept") String accept,
        @QueryParam("user") Integer userId, @QueryParam("p1") String p1, @QueryParam("p2") String p2,
        @QueryParam("p3") String p3) {
    UserInfo ui = checkCredential(httpServletRequest, user, token, null);

    try {
        javax.servlet.http.HttpSession session = httpServletRequest.getSession(true);
        String ppath = session.getServletContext().getRealPath(File.separator);
        // TODO xslFile avec _ => repertoire_fichier
        xslFile = xslFile.replace(".", "");
        xslFile = xslFile.replace("/", "");
        String[] tmp = xslFile.split("-");

        xslFile = ppath.substring(0, ppath.lastIndexOf(File.separator)) + File.separator + "xsl"
                + File.separator + tmp[0] + File.separator + tmp[1] + ".xsl";
        String returnValue = dataProvider
                .getNodeWithXSL(new MimeType("text/xml"), nodeUuid, xslFile, ui.userId, groupId).toString();
        if (returnValue.length() != 0) {
            if (accept.equals(MediaType.APPLICATION_JSON))
                returnValue = XML.toJSONObject(returnValue).toString();
            logRestRequest(httpServletRequest, null, returnValue, Status.OK.getStatusCode());
        } else {
            throw new RestWebApplicationException(Status.FORBIDDEN, "Vous n'avez pas les droits necessaires");
        }

        return returnValue;
    } catch (RestWebApplicationException ex) {
        throw new RestWebApplicationException(Status.FORBIDDEN, "Vous n'avez pas les droits necessaires");
    }

    catch (NullPointerException ex) {
        logRestRequest(httpServletRequest, null, null, Status.NOT_FOUND.getStatusCode());

        throw new RestWebApplicationException(Status.NOT_FOUND,
                "Node " + nodeUuid + " not found or xsl not found :" + ex.getMessage());
    } catch (Exception ex) {
        ex.printStackTrace();
        logRestRequest(httpServletRequest, null, ex.getMessage() + "\n\n" + javaUtils.getCompleteStackTrace(ex),
                Status.INTERNAL_SERVER_ERROR.getStatusCode());

        throw new RestWebApplicationException(Status.INTERNAL_SERVER_ERROR, ex.getMessage());
    } finally {
        dataProvider.disconnect();
    }
}

From source file:com.portfolio.rest.RestServicePortfolio.java

@Path("/nodes/{node-id}/frommodelbysemantictag/{semantic-tag}")
@POST// w  ww.j  av a  2s .  c  om
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public String postNodeFromModelBySemanticTag(String xmlNode, @CookieParam("user") String user,
        @CookieParam("credential") String token, @QueryParam("group") int groupId,
        @PathParam("node-id") String nodeUuid, @PathParam("semantic-tag") String semantictag,
        @Context ServletConfig sc, @Context HttpServletRequest httpServletRequest,
        @QueryParam("user") Integer userId) {
    UserInfo ui = checkCredential(httpServletRequest, user, token, null);

    try {
        String returnValue = dataProvider.postNodeFromModelBySemanticTag(new MimeType("text/xml"), nodeUuid,
                semantictag, ui.userId, groupId).toString();
        logRestRequest(httpServletRequest, xmlNode, returnValue, Status.OK.getStatusCode());

        if (returnValue == "faux") {
            throw new RestWebApplicationException(Status.FORBIDDEN, "Vous n'avez pas les droits d'acces");
        }

        return returnValue;
    } catch (RestWebApplicationException ex) {
        throw new RestWebApplicationException(Status.FORBIDDEN, ex.getResponse().getEntity().toString());
    } catch (Exception ex) {
        ex.printStackTrace();
        logRestRequest(httpServletRequest, xmlNode,
                ex.getMessage() + "\n\n" + javaUtils.getCompleteStackTrace(ex),
                Status.INTERNAL_SERVER_ERROR.getStatusCode());

        throw new RestWebApplicationException(Status.INTERNAL_SERVER_ERROR, ex.getMessage());
    } finally {
        dataProvider.disconnect();
    }
}

From source file:com.portfolio.rest.RestServicePortfolio.java

@Path("/portfolios/zip")
@POST/*from   www  .  j  a v  a 2 s  .co m*/
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
public String postPortfolioByForm(@CookieParam("user") String user, @CookieParam("credential") String token,
        @QueryParam("group") int groupId, @Context ServletConfig sc,
        @Context HttpServletRequest httpServletRequest, @QueryParam("user") Integer userId,
        @QueryParam("model") String modelId) {
    UserInfo ui = checkCredential(httpServletRequest, user, token, null);
    String returnValue = "";

    try {
        returnValue = dataProvider.postPortfolioZip(new MimeType("text/xml"), new MimeType("text/xml"),
                httpServletRequest, ui.userId, groupId, modelId, ui.subId).toString();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        dataProvider.disconnect();
    }

    return returnValue;
    /*
    String xmlPortfolio = "";
    try
    {
       MultipartRequest multi;
       String os = System.getProperty("os.name").toLowerCase();
       // windows
       if(os.indexOf("win") >= 0)
       {
    multi = new MultipartRequest(httpServletRequest,"c:\\windows\\temp",5*1024*1024);
       }
       else
       {
    multi = new MultipartRequest(httpServletRequest,"/tmp",5*1024*1024);
       }
       Enumeration files = multi.getFileNames();
       java.io.File f = null;
       String type = "";
       String name= "";
            
       while(files.hasMoreElements()) {
    name=(String)files.nextElement();
    String filename = multi.getFilesystemName(name);
    type = multi.getContentType(name);
    f = multi.getFile(name);
       }
       if (f!=null)
       {
            
    xmlPortfolio = DomUtils.file2String(f.getPath(), new StringBuffer());
       }
    }
    catch (Exception ex)
    {
       ex.printStackTrace();
       logRestRequest(httpServletRequest, xmlPortfolio, ex.getMessage()+"\n\n"+javaUtils.getCompleteStackTrace(ex), Status.INTERNAL_SERVER_ERROR.getStatusCode());
            
       throw new RestWebApplicationException(Status.INTERNAL_SERVER_ERROR, ex.getMessage());
    }
    //*/

    //      UserInfo ui = checkCredential(httpServletRequest, user, token, null);

    /*
    try
    {
       //try { this.userId = userId; } catch(Exception ex) { this.userId = -1; };
       String returnValue = dataProvider.postPortfolio(new MimeType("text/xml"),new MimeType("text/xml"),xmlPortfolio, ui.userId, groupId, modelId, ui.subId).toString();
       logRestRequest(httpServletRequest, xmlPortfolio, returnValue, Status.OK.getStatusCode());
       //                                            dataProvider.disconnect();
       return returnValue;
    }
    catch(Exception ex)
    {
       ex.printStackTrace();
       logRestRequest(httpServletRequest, xmlPortfolio, ex.getMessage()+"\n\n"+javaUtils.getCompleteStackTrace(ex), Status.INTERNAL_SERVER_ERROR.getStatusCode());
            
       throw new RestWebApplicationException(Status.INTERNAL_SERVER_ERROR, ex.getMessage());
    }
    finally
    {
       dataProvider.disconnect();
    }
    //*/
}

From source file:com.portfolio.rest.RestServicePortfolio.java

/********************************************************/

@Path("/rights")
@POST/* w  w w .j  av a  2 s.c o m*/
@Produces(MediaType.APPLICATION_XML)
public String postChangeRights(String xmlNode, @Context ServletConfig sc,
        @Context HttpServletRequest httpServletRequest) {
    UserInfo ui = checkCredential(httpServletRequest, null, null, null);

    String returnValue = "";
    try {
        /**
         * <node uuid="">
         *   <role name="">
         *     <right RD="" WR="" DL="" />
         *     <action>reset</action>
         *   </role>
         * </node>
         *======
         * <portfolio uuid="">
         *   <xpath>XPATH</xpath>
         *   <role name="">
         *     <right RD="" WR="" DL="" />
         *     <action>reset</action>
         *   </role>
         * </portfolio>
         *======
         * <portfoliogroup name="">
         *   <xpath>XPATH</xpath>
         *   <role name="">
         *     <right RD="" WR="" DL="" />
         *     <action>reset</action>
         *   </role>
         * </portfoliogroup>
         **/

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document doc = documentBuilder.parse(new ByteArrayInputStream(xmlNode.getBytes("UTF-8")));

        XPath xPath = XPathFactory.newInstance().newXPath();
        ArrayList<String> portfolio = new ArrayList<String>();
        String xpathRole = "/role";
        XPathExpression findRole = xPath.compile(xpathRole);
        String xpathNodeFilter = "/xpath";
        XPathExpression findXpath = xPath.compile(xpathNodeFilter);
        String nodefilter = "";
        NodeList roles = null;

        /// Fetch portfolio(s)
        String portfolioNode = "//portfoliogroup";
        Node portgroupnode = (Node) xPath.compile(portfolioNode).evaluate(doc, XPathConstants.NODE);
        if (portgroupnode == null) {
            String portgroupname = portgroupnode.getAttributes().getNamedItem("name").getNodeValue();
            // Query portfolio group for list of uuid

            // while( res.next() )
            // portfolio.add(portfolio);

            Node xpathNode = (Node) findXpath.evaluate(portgroupnode, XPathConstants.NODE);
            nodefilter = xpathNode.getNodeValue();
            roles = (NodeList) findRole.evaluate(portgroupnode, XPathConstants.NODESET);
        } else {
            // Or add the single one
            portfolioNode = "//portfolio[@uuid]";
            Node portnode = (Node) xPath.compile(portfolioNode).evaluate(doc, XPathConstants.NODE);
            portfolio.add(portnode.getNodeValue());

            Node xpathNode = (Node) findXpath.evaluate(portnode, XPathConstants.NODE);
            nodefilter = xpathNode.getNodeValue();
            roles = (NodeList) findRole.evaluate(portnode, XPathConstants.NODESET);
        }

        ArrayList<String> nodes = new ArrayList<String>();
        XPathExpression xpathFilter = xPath.compile(nodefilter);
        for (int i = 0; i < portfolio.size(); ++i) // For all portfolio
        {
            String portfolioUuid = portfolio.get(i);
            String portfolioStr = dataProvider.getPortfolio(new MimeType("text/xml"), portfolioUuid, ui.userId,
                    0, this.label, null, null, ui.subId).toString();
            Document docPort = documentBuilder.parse(new ByteArrayInputStream(portfolioStr.getBytes("UTF-8")));

            /// Fetch nodes inside those portfolios
            NodeList portNodes = (NodeList) xpathFilter.evaluate(docPort, XPathConstants.NODESET);
            for (int j = 0; j < portNodes.getLength(); ++j) {
                Node node = portNodes.item(j);
                String nodeuuid = node.getAttributes().getNamedItem("id").getNodeValue();

                nodes.add(nodeuuid); // Keep those we have to change rights
            }
        }

        /// Fetching single node
        if (nodes.isEmpty()) {
            String singleNode = "/node";
            Node sNode = (Node) xPath.compile(singleNode).evaluate(doc, XPathConstants.NODE);
            String uuid = sNode.getAttributes().getNamedItem("uuid").getNodeValue();
            nodes.add(uuid);
            roles = (NodeList) findRole.evaluate(sNode, XPathConstants.NODESET);
        }

        /// For all roles we have to change
        for (int i = 0; i < roles.getLength(); ++i) {
            Node rolenode = roles.item(i);
            String rolename = rolenode.getAttributes().getNamedItem("name").getNodeValue();
            Node right = rolenode.getFirstChild();

            //
            if ("user".equals(rolename)) {
                /// username as role
            }

            if ("#text".equals(right.getNodeName()))
                right = right.getNextSibling();

            if ("right".equals(right.getNodeName())) // Changing node rights
            {
                NamedNodeMap rights = right.getAttributes();

                NodeRight noderight = new NodeRight(null, null, null, null, null, null);

                String val = rights.getNamedItem("RD").getNodeValue();
                if (val != null)
                    noderight.read = Boolean.parseBoolean(val);
                val = rights.getNamedItem("WR").getNodeValue();
                if (val != null)
                    noderight.write = Boolean.parseBoolean(val);
                val = rights.getNamedItem("DL").getNodeValue();
                if (val != null)
                    noderight.delete = Boolean.parseBoolean(val);
                val = rights.getNamedItem("SB").getNodeValue();
                if (val != null)
                    noderight.submit = Boolean.parseBoolean(val);

                /// Apply modification for all nodes
                for (int j = 0; j < nodes.size(); ++j) {
                    String nodeid = nodes.get(j);

                    // change right
                    dataProvider.postRights(ui.userId, nodeid, rolename, noderight);
                }
            } else if ("action".equals(right.getNodeName())) // Using an action on node
            {
                /// Apply modification for all nodes
                for (int j = 0; j < nodes.size(); ++j) {
                    String nodeid = nodes.get(j);

                    // TODO: check for reset keyword
                    // reset right
                    dataProvider.postMacroOnNode(ui.userId, nodeid, "reset");
                }
            }
        }

        //         returnValue = dataProvider.postRRGCreate(ui.userId, xmlNode);
        logRestRequest(httpServletRequest, xmlNode, returnValue, Status.OK.getStatusCode());

        if (returnValue == "faux") {
            throw new RestWebApplicationException(Status.FORBIDDEN, "Vous n'avez pas les droits d'acces");
        }

        return returnValue;
    } catch (RestWebApplicationException ex) {
        throw new RestWebApplicationException(Status.FORBIDDEN, "Vous n'avez pas les droits necessaires");
    } catch (Exception ex) {
        ex.printStackTrace();
        logRestRequest(httpServletRequest, xmlNode,
                ex.getMessage() + "\n\n" + javaUtils.getCompleteStackTrace(ex),
                Status.INTERNAL_SERVER_ERROR.getStatusCode());
        dataProvider.disconnect();
        throw new RestWebApplicationException(Status.INTERNAL_SERVER_ERROR, ex.getMessage());
    } finally {
        dataProvider.disconnect();
    }
}

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

@Override
public Object postPortfolioZip(MimeType mimeType, MimeType mimeType2, HttpServletRequest httpServletRequest,
        int userId, int groupId, String modelId) throws FileNotFoundException, IOException {
    if (!credential.isAdmin(userId))
        throw new RestWebApplicationException(Status.FORBIDDEN, "No admin right");

    DataInputStream inZip = new DataInputStream(httpServletRequest.getInputStream());

    ByteArrayOutputStream byte2 = new ByteArrayOutputStream();
    StringBuffer outTrace = new StringBuffer();

    String portfolioId = null;//from   w ww  . j  ava  2s .  co  m
    portfolioId = httpServletRequest.getParameter("portfolio");

    String foldersfiles = null;
    String filename;
    String[] xmlFiles;
    String[] allFiles;
    String[] ImgFiles;
    int formDataLength = httpServletRequest.getContentLength();
    byte[] buff = new byte[formDataLength];

    // Recuperation de l'heure  laquelle le zip est cr
    //Calendar cal = Calendar.getInstance();
    //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss_S");
    //String now = sdf.format(cal.getTime());

    this.genererPortfolioUuidPreliminaire();

    javax.servlet.http.HttpSession session = httpServletRequest.getSession(true);
    String ppath = session.getServletContext().getRealPath(File.separator);
    String outsideDir = ppath.substring(0, ppath.lastIndexOf(File.separator)) + "_files" + File.separator;
    File outsideDirectoryFile = new File(outsideDir);
    System.out.println(outsideDir);
    // if the directory does not exist, create it
    if (!outsideDirectoryFile.exists()) {
        outsideDirectoryFile.mkdir();
    }

    //Creation du zip
    filename = outsideDir + "xml_" + this.portfolioUuidPreliminaire + ".zip";
    FileOutputStream outZip = new FileOutputStream(filename);

    int len;

    while ((len = inZip.read(buff)) != -1) {
        outZip.write(buff, 0, len);
    }

    inZip.close();
    outZip.close();

    //-- unzip --
    foldersfiles = unzip(filename, outsideDir + this.portfolioUuidPreliminaire + File.separator);
    //TODO Attention si plusieurs XML dans le fichier
    xmlFiles = findFiles(outsideDir + this.portfolioUuidPreliminaire + File.separator, "xml");
    allFiles = findFiles(outsideDir + this.portfolioUuidPreliminaire + File.separator, null);

    for (int i = 0; i < allFiles.length; i++) {
        portfolioRessourcesImportPath.add(allFiles[i]);
        String tmpFileName = allFiles[i].substring(allFiles[i].lastIndexOf(File.separator) + 1);
        String uuid = tmpFileName.substring(0, tmpFileName.indexOf("_"));
        portfolioRessourcesImportUuid.add(uuid);

        tmpFileName = allFiles[i].substring(allFiles[i].lastIndexOf(File.separator) + 1);
        String lang;
        try {
            int tmpPos = tmpFileName.indexOf("_");
            lang = tmpFileName.substring(tmpPos + 1, tmpPos + 3);
        } catch (Exception ex) {
            lang = "";
        }
        InputStream is = new FileInputStream(allFiles[i]);
        byte b[] = new byte[is.available()];
        is.read(b);
        String extension;
        try {
            extension = tmpFileName.substring(tmpFileName.lastIndexOf(".") + 1);
        } catch (Exception ex) {
            extension = null;

        }

        // trop long
        //String tmpMimeType = FileUtils.getMimeType("file://"+allFiles[i]);
        String tmpMimeType = FileUtils.getMimeTypeFromExtension(extension);

        // Attention on initialise la ligne file
        // avec l'UUID d'origine de l'asmContext parent
        // Il sera mis  jour avec l'UUID asmContext final dans writeNode
        try {
            UUID tmpUuid = UUID.fromString(uuid);

            if (tmpUuid.toString().equals(uuid))
                this.putFile(uuid, lang, tmpFileName, outsideDir, tmpMimeType, extension, b.length, b, userId);
        } catch (Exception ex) {
            // Le nom du fichier ne commence pas par un UUID,
            // ce n'est donc pas une ressource
        }
    }

    //TODO Supprimer le zip quand a fonctionnera bien

    //--- Read xml fileL ----
    for (int i = 0; i < xmlFiles.length; i++) {
        BufferedReader br = new BufferedReader(new FileReader(new File(xmlFiles[i])));
        String line;
        StringBuilder sb = new StringBuilder();

        while ((line = br.readLine()) != null) {
            sb.append(line.trim());
        }
        String xml = "?";
        xml = sb.toString();

        if (xml.contains("<portfolio id=")) {
            try {
                Object returnValue = postPortfolio(new MimeType("text/xml"), new MimeType("text/xml"), xml,
                        userId, groupId, null);
                return returnValue;
            } catch (MimeTypeParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    return false;
}