Example usage for org.apache.commons.fileupload FileItem get

List of usage examples for org.apache.commons.fileupload FileItem get

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem get.

Prototype

byte[] get();

Source Link

Document

Returns the contents of the file item as an array of bytes.

Usage

From source file:org.eclipse.che.ide.ext.datasource.server.ssl.KeyStoreObject.java

public void addNewKey(String alias, Iterator<FileItem> uploadedFilesIterator) throws Exception {
    PrivateKey privateKey = null;
    Certificate[] certs = null;/*w  w  w.  ja  v a 2  s  .c om*/
    while (uploadedFilesIterator.hasNext()) {
        FileItem fileItem = uploadedFilesIterator.next();
        if (!fileItem.isFormField()) {
            if ("keyFile".equals(fileItem.getFieldName())) {
                KeyFactory kf = KeyFactory.getInstance("RSA");
                privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(fileItem.get()));
            }
            if ("certFile".equals(fileItem.getFieldName())) {
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                certs = cf.generateCertificates(fileItem.getInputStream()).toArray(new Certificate[] {});
            }
        }
    }

    if (privateKey == null || certs == null) {
        throw new WebApplicationException(
                Response.ok("<pre>Can't find input file.</pre>", MediaType.TEXT_HTML).build());
    }

    keystore.setKeyEntry(alias, privateKey, keyStorePassword.toCharArray(), certs);
    save();
}

From source file:org.eclipse.che.ide.ext.ssh.server.KeyService.java

/** Add prepared private key. */
@POST//from w  ww.  j  a va 2  s.  co  m
@Path("add")
@Consumes({ MediaType.MULTIPART_FORM_DATA })
public Response addPrivateKey(@QueryParam("host") String host, Iterator<FileItem> iterator) {
    /*
     * XXX : Temporary turn-off don't work on demo site if (!security.isSecure()) { throw new
     * WebApplicationException(Response.status(400)
     * .entity("Secure connection required to be able generate key. ").type(MediaType.TEXT_PLAIN).build()); }
     */
    byte[] key = null;
    while (iterator.hasNext() && key == null) {
        FileItem fileItem = iterator.next();
        if (!fileItem.isFormField()) {
            key = fileItem.get();
        }
    }
    // Return error response in <pre> HTML tag.
    if (key == null) {
        throw new WebApplicationException(
                Response.ok("<pre>Can't find input file.</pre>", MediaType.TEXT_HTML).build());
    }

    try {
        keyStore.addPrivateKey(host, key);
    } catch (SshKeyStoreException e) {
        throw new WebApplicationException(
                Response.ok("<pre>" + e.getMessage() + "</pre>", MediaType.TEXT_HTML).build());
    }
    return Response.ok("", MediaType.TEXT_HTML).build();
}

From source file:org.eclipse.kapua.app.console.servlet.FileServlet.java

private void doPostConfigurationSnapshot(KapuaFormFields kapuaFormFields, HttpServletResponse resp)
        throws ServletException, IOException {
    try {//from   w  w w .j av a  2s  .co  m
        List<FileItem> fileItems = kapuaFormFields.getFileItems();
        String scopeIdString = kapuaFormFields.get("scopeIdString");
        String deviceIdString = kapuaFormFields.get("deviceIdString");

        if (scopeIdString == null || scopeIdString.isEmpty()) {
            throw new IllegalArgumentException("scopeIdString");
        }

        if (deviceIdString == null || deviceIdString.isEmpty()) {
            throw new IllegalArgumentException("deviceIdString");
        }

        if (fileItems == null || fileItems.size() != 1) {
            throw new IllegalArgumentException("configuration");
        }

        KapuaLocator locator = KapuaLocator.getInstance();
        DeviceConfigurationManagementService deviceConfigurationManagementService = locator
                .getService(DeviceConfigurationManagementService.class);

        FileItem fileItem = fileItems.get(0);
        byte[] data = fileItem.get();
        String xmlConfigurationString = new String(data, "UTF-8");

        deviceConfigurationManagementService.put(KapuaEid.parseShortId(scopeIdString),
                KapuaEid.parseShortId(deviceIdString), xmlConfigurationString, null);

    } catch (IllegalArgumentException iae) {
        resp.sendError(400, "Illegal value for query parameter: " + iae.getMessage());
        return;
    } catch (KapuaEntityNotFoundException eenfe) {
        resp.sendError(400, eenfe.getMessage());
        return;
    } catch (KapuaUnauthenticatedException eiae) {
        resp.sendError(401, eiae.getMessage());
        return;
    } catch (KapuaIllegalAccessException eiae) {
        resp.sendError(403, eiae.getMessage());
        return;
    } catch (Exception e) {
        s_logger.error("Error posting configuration", e);
        throw new ServletException(e);
    }
}

From source file:org.eclipse.kura.web.server.servlet.FileServlet.java

private void doPostConfigurationSnapshot(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    UploadRequest upload = new UploadRequest(this.m_diskFileItemFactory);

    try {//from  ww  w .j av  a 2s.co  m
        upload.parse(req);
    } catch (FileUploadException e) {
        s_logger.error("Error parsing the file upload request");
        throw new ServletException("Error parsing the file upload request", e);
    }

    // BEGIN XSRF - Servlet dependent code
    Map<String, String> formFields = upload.getFormFields();

    try {
        GwtXSRFToken token = new GwtXSRFToken(formFields.get("xsrfToken"));
        KuraRemoteServiceServlet.checkXSRFToken(req, token);
    } catch (Exception e) {
        throw new ServletException("Security error: please retry this operation correctly.", e);
    }
    // END XSRF security check

    List<FileItem> fileItems = upload.getFileItems();
    if (fileItems.size() != 1) {
        s_logger.error("expected 1 file item but found {}", fileItems.size());
        throw new ServletException("Wrong number of file items");
    }

    FileItem fileItem = fileItems.get(0);
    byte[] data = fileItem.get();
    String xmlString = new String(data, "UTF-8");
    XmlComponentConfigurations xmlConfigs;
    try {
        xmlConfigs = XmlUtil.unmarshal(xmlString, XmlComponentConfigurations.class);
    } catch (Exception e) {
        s_logger.error("Error unmarshaling device configuration", e);
        throw new ServletException("Error unmarshaling device configuration", e);
    }

    ServiceLocator locator = ServiceLocator.getInstance();
    try {

        ConfigurationService cs = locator.getService(ConfigurationService.class);
        List<ComponentConfigurationImpl> configImpls = xmlConfigs.getConfigurations();

        List<ComponentConfiguration> configs = new ArrayList<ComponentConfiguration>();
        configs.addAll(configImpls);

        cs.updateConfigurations(configs);

        //
        // Add an additional delay after the configuration update
        // to give the time to the device to apply the received
        // configuration
        SystemService ss = locator.getService(SystemService.class);
        long delay = Long.parseLong(ss.getProperties().getProperty("console.updateConfigDelay", "5000"));
        if (delay > 0) {
            Thread.sleep(delay);
        }
    } catch (Exception e) {
        s_logger.error("Error updating device configuration: {}", e);
        throw new ServletException("Error updating device configuration", e);
    }
}

From source file:org.eclipse.vorto.remoterepository.rest.ModelResource.java

private byte[] extractFileFromUploadContent(HttpServletRequest request) throws Exception {
    final FileItemFactory factory = new DiskFileItemFactory();
    final ServletFileUpload fileUpload = new ServletFileUpload(factory);
    @SuppressWarnings("unchecked")
    final List<FileItem> items = fileUpload.parseRequest(request);
    final FileItem item = (FileItem) items.iterator().next();
    return item.get();

}

From source file:org.ednovo.gooru.application.server.service.uploadServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    FileItem uploadedFileItem = null;
    String fileName = "";
    JSONArray jsonArray = null;//  ww w. jav a2s . co  m
    boolean isMultiPart = ServletFileUpload.isMultipartContent(new ServletRequestContext(request));
    if (isMultiPart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(31457280);
        String responsedata = "";
        try {
            try {
                @SuppressWarnings("rawtypes")
                java.util.List items = upload.parseRequest(request);
                ApplicationContext appContext = new ClassPathXmlApplicationContext("gooruContext-service.xml");
                Properties restConstants = (Properties) appContext.getBean("restConstants");
                for (int i = 0; i < items.size(); i++) {
                    uploadedFileItem = (FileItem) items.get(i);
                }
                String stoken = (String) request.getSession(false).getAttribute("gooru-session-token");
                try {
                    //This will replace all the non-word characters with '_' excluding the dot.
                    fileName = uploadedFileItem.getName().replaceAll("[^\\w.]", "_");
                } catch (Exception e) {
                    logger.error("Exception:::" + e);
                }
                String requestData = "uploadFileName=" + fileName + "&imageURL=&sessionToken=" + stoken;
                String url = UrlGenerator.generateUrl(restConstants.getProperty(REST_ENDPOINT),
                        UrlToken.FILE_UPLOAD_GET_URL, fileName, stoken);
                try {
                    responsedata = webInvokeForImage("POST", requestData, "multipart/form-data", request,
                            uploadedFileItem.get(), fileName, uploadedFileItem.getSize(), url);
                    jsonArray = new JSONArray(responsedata);
                } catch (UnsupportedEncodingException e) {
                    logger.error("UnsupportedEncodingException:::" + e);
                }
                response.setContentType("text/html");
                response.getOutputStream().print(jsonArray.get(0).toString());
                response.getOutputStream().flush();
            } catch (FileUploadBase.FileSizeLimitExceededException e) {
                logger.error("FileSizeLimitExceededException:::" + e);
                responsedata = "file size error";
                response.setContentType("text/html");
                response.getOutputStream().print(responsedata);
                response.getOutputStream().flush();
            }
        } catch (Exception e) {
            logger.error("Global exception:::" + e);
        }
    }
}

From source file:org.etudes.mneme.impl.AttachmentServiceImpl.java

/**
 * {@inheritDoc}/*w ww.j av a2  s  .  co m*/
 */
public Reference addAttachment(String application, String context, String prefix,
        NameConflictResolution onConflict, FileItem file, boolean makeThumb, String altRef) {
    pushAdvisor();

    try {
        String name = file.getName();
        if (name != null) {
            name = massageName(name);
        }

        String type = file.getContentType();

        // TODO: change to file.getInputStream() for after Sakai 2.3 more efficient support
        // InputStream body = file.getInputStream();
        byte[] body = file.get();

        long size = file.getSize();

        // detect no file selected
        if ((name == null) || (type == null) || (body == null) || (size == 0)) {
            // TODO: if using input stream, close it
            // if (body != null) body.close();
            return null;
        }

        Reference rv = addAttachment(name, name, application, context, prefix, onConflict, type, body, size,
                makeThumb, altRef);
        return rv;
    } finally {
        popAdvisor();
    }
}

From source file:org.etudes.mneme.tool.UploadXml.java

/**
 * Unzip the QTI file/*from  w  ww .  j  a v a2 s. co m*/
 * 
 * @param fileName_M
 * @param backupFile_M
 * @return
 * @throws Exception
 */
private String unpackageZipFile(String fileName_M, FileItem backupFile_M) throws Exception {
    String packagingdirpath = ServerConfigurationService.getString("mnemeQTI.import", "");
    FileOutputStream out = null;
    try {
        String actFileName;
        // write the uploaded zip file to disk
        if (fileName_M.indexOf('\\') != -1)
            actFileName = fileName_M.substring(fileName_M.lastIndexOf('\\') + 1);
        else
            actFileName = fileName_M.substring(fileName_M.lastIndexOf('/') + 1);

        // write zip file first
        File baseDir = new File(packagingdirpath + File.separator + "importQTI");
        if (!baseDir.exists())
            baseDir.mkdirs();

        File outputFile = new File(packagingdirpath + File.separator + "importQTI" + File.separator
                + actFileName.replace(' ', '_'));
        if (outputFile.exists())
            outputFile.delete();
        out = new FileOutputStream(outputFile);
        byte buf[] = backupFile_M.get();
        out.write(buf);
        out.close();

        // unzipping dir
        File unzippeddir = new File(packagingdirpath + File.separator + "importQTI" + File.separator
                + actFileName.substring(0, actFileName.lastIndexOf('.')));
        if (unzippeddir.exists())
            deleteFiles(unzippeddir);
        if (!unzippeddir.exists())
            unzippeddir.mkdirs();
        String unzippedDirpath = unzippeddir.getAbsolutePath();
        // unzip files
        unZipFile(outputFile, unzippedDirpath);
        if (outputFile.exists())
            outputFile.delete();
        return unzippedDirpath;
    } finally {
        if (out != null)
            out.close();
    }
}

From source file:org.eurekastreams.server.service.actions.strategies.ImageWriter.java

/**
 * Writes an uploaded file to the disk.//from   w w w  . ja  v a 2  s  .  co m
 *
 * @param fileItem
 *            The file to write.
 * @param identifier
 *            The path to write it too.
 * @throws Exception
 *             again, the evil.
 */
public void write(final FileItem fileItem, final String identifier) throws Exception {
    Image imageInDb = getMapper.execute(identifier);

    if (imageInDb == null) {
        insertMapper.execute(new PersistenceRequest<Image>(new Image(identifier, fileItem.get())));
    } else {
        imageInDb.setImageBlob(fileItem.get());
        updateMapper.execute(new PersistenceRequest<Image>(imageInDb));
    }

}

From source file:org.eurekastreams.server.service.actions.strategies.ImageWriter.java

/**
 * Get an Image from a File.// w  w w . j  a  v a  2 s.  c o  m
 * @param file the file.
 * @return the image.
 * @throws IOException an IO exception.
 */
public BufferedImage getImageFromFile(final FileItem file) throws IOException {
    ByteArrayInputStream baos = new ByteArrayInputStream(file.get());
    return ImageIO.read(baos);
}