Example usage for java.io ByteArrayInputStream close

List of usage examples for java.io ByteArrayInputStream close

Introduction

In this page you can find the example usage for java.io ByteArrayInputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closing a ByteArrayInputStream has no effect.

Usage

From source file:org.jaqpot.algorithm.resource.Standarization.java

@POST
@Path("prediction")
public Response prediction(PredictionRequest request) {
    try {//w w w  .ja v  a  2 s .c o m
        if (request.getDataset().getDataEntry().isEmpty()
                || request.getDataset().getDataEntry().get(0).getValues().isEmpty()) {
            return Response
                    .status(Response.Status.BAD_REQUEST).entity(ErrorReportFactory
                            .badRequest("Dataset is empty", "Cannot make predictions on empty dataset"))
                    .build();
        }
        List<String> features = request.getDataset().getDataEntry().stream().findFirst().get().getValues()
                .keySet().stream().collect(Collectors.toList());
        String base64Model = (String) request.getRawModel();
        byte[] modelBytes = Base64.getDecoder().decode(base64Model);
        ByteArrayInputStream bais = new ByteArrayInputStream(modelBytes);
        ObjectInput in = new ObjectInputStream(bais);
        ScalingModel model = (ScalingModel) in.readObject();
        in.close();
        bais.close();

        List<LinkedHashMap<String, Object>> predictions = new ArrayList<>();

        for (DataEntry dataEntry : request.getDataset().getDataEntry()) {
            LinkedHashMap<String, Object> data = new LinkedHashMap<>();
            for (String feature : features) {
                Double stdev = model.getMaxValues().get(feature);
                Double mean = model.getMinValues().get(feature);
                Double value = Double.parseDouble(dataEntry.getValues().get(feature).toString());
                if (stdev != null && stdev != 0.0 && mean != null) {
                    value = (value - mean) / stdev;
                } else {
                    value = 1.0;
                }
                data.put("Standarized " + feature, value);
            }
            predictions.add(data);
        }

        PredictionResponse response = new PredictionResponse();
        response.setPredictions(predictions);

        return Response.ok(response).build();
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, null, ex);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
    }
}

From source file:org.busko.routemanager.web.admin.community.GpxToShapeParser.java

public void parse(RouteOutline routeOutline) {
    if ((routeOutline != null) && routeOutline.getFileContent() != null) {
        shapeCollection = new ShapeCollection();
        shapeCollection.setRoute(routeOutline.getRoute());

        Digester digester = new Digester();
        digester.setValidating(false);//www . j ava 2 s.c om
        digester.push(this);
        digester.addObjectCreate("gpx/trk/trkseg/trkpt", Shape.class.getName());
        digester.addSetProperties("gpx/trk/trkseg/trkpt");
        digester.addSetNext("gpx/trk/trkseg/trkpt", "addShape", Shape.class.getName());

        ByteArrayInputStream input = null;
        try {
            input = new ByteArrayInputStream(routeOutline.getFileContent());
            digester.parse(input);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (input != null)
                try {
                    input.close();
                } catch (Exception e) {
                }
        }
    }
}

From source file:com.codercowboy.photo.organizer.service.LibraryMarshaller.java

public Library loadLibrary(String fileName) throws Exception {
    byte[] fileData = FileUtils.readFileToByteArray(new File(fileName));
    ByteArrayInputStream bais = new ByteArrayInputStream(fileData);
    try {/*from  w w w . j a v  a 2 s.c  om*/
        Unmarshaller unmarshaller = this.createContext().createUnmarshaller();
        @SuppressWarnings("unchecked")
        JAXBElement<Library> jaxbElement = (JAXBElement<Library>) unmarshaller.unmarshal(bais);
        return jaxbElement.getValue();

    } finally {
        bais.close();
    }
}

From source file:com.baasbox.configuration.IosCertificateHandler.java

@Override
public void change(Object iCurrentValue, Object iNewValue) {

    if (iNewValue == null) {
        return;//  w  ww.  j av a 2 s .  co  m
    }
    String folder = BBConfiguration.getPushCertificateFolder();
    File f = new File(folder);
    if (!f.exists()) {
        f.mkdirs();
    }
    ConfigurationFileContainer newValue = null;
    ConfigurationFileContainer currentValue = null;
    if (iNewValue != null && iNewValue instanceof ConfigurationFileContainer) {

        newValue = (ConfigurationFileContainer) iNewValue;
    }
    if (iCurrentValue != null) {
        if (iCurrentValue instanceof String) {
            try {
                currentValue = new ObjectMapper().readValue(iCurrentValue.toString(),
                        ConfigurationFileContainer.class);
            } catch (Exception e) {
                if (BaasBoxLogger.isDebugEnabled())
                    BaasBoxLogger.debug("unable to convert value to ConfigurationFileContainer");
            }
        } else if (iCurrentValue instanceof ConfigurationFileContainer) {
            currentValue = (ConfigurationFileContainer) iCurrentValue;
        }
    }
    if (currentValue != null) {
        File oldFile = new File(folder + sep + currentValue.getName());
        if (oldFile.exists()) {
            try {
                FileUtils.forceDelete(oldFile);
            } catch (Exception e) {
                BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            }
        }
    }
    if (newValue != null) {
        File newFile = new File(folder + sep + newValue.getName());
        try {
            if (!newFile.exists()) {
                newFile.createNewFile();
            }
        } catch (IOException ioe) {
            throw new RuntimeException("unable to create file:" + ExceptionUtils.getMessage(ioe));
        }
        ByteArrayInputStream bais = new ByteArrayInputStream(newValue.getContent());
        try {
            FileUtils.copyInputStreamToFile(bais, newFile);
            bais.close();
        } catch (IOException ioe) {
            //TODO:more specific exception
            throw new RuntimeException(ExceptionUtils.getMessage(ioe));
        }

    } else {
        BaasBoxLogger.warn("Ios Certificate Handler invoked with wrong parameters");
        //TODO:throw an exception?
    }

}

From source file:com.openkm.ws.endpoint.OKMDocument.java

@WebMethod
public void setContent(@WebParam(name = "token") String token, @WebParam(name = "docPath") String docPath,
        @WebParam(name = "content") byte[] content) throws FileSizeExceededException,
        UserQuotaExceededException, VirusDetectedException, VersionException, LockException,
        PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException {
    log.debug("setContent({}, {}, {})", new Object[] { token, docPath, content });
    DocumentModule dm = ModuleManager.getDocumentModule();
    ByteArrayInputStream bais = new ByteArrayInputStream(content);
    dm.setContent(token, docPath, bais);
    bais.close();
    log.debug("setContent: void");
}

From source file:org.javaswift.cloudie.preview.PlainTextPanel.java

/**
 * {@inheritDoc}.// www . j av a  2  s. c om
 */
@Override
public void displayPreview(String contentType, ByteArrayInputStream in) {
    try {
        try {
            StringBuilder sb = new StringBuilder();
            for (String line : IOUtils.readLines(in)) {
                sb.append(line);
                sb.append(System.getProperty("line.separator"));
            }
            area.setText(sb.toString());
        } finally {
            in.close();
        }
    } catch (IOException e) {
        area.setText("");
        e.printStackTrace();
    }
}

From source file:org.ops4j.pax.exam.rbc.internal.RemoteBundleContextImpl.java

/**
 * {@inheritDoc}/*from   w ww.  j av a 2  s  .com*/
 */
public long installBundle(final String bundleLocation, final byte[] bundle) throws BundleException {
    LOG.info("Install bundle [" + bundleLocation + "] from byte array");
    final ByteArrayInputStream inp = new ByteArrayInputStream(bundle);
    try {
        return m_bundleContext.installBundle(bundleLocation, inp).getBundleId();
    } finally {
        try {
            inp.close();
        } catch (IOException e) {
            // ignore.
        }
    }
}

From source file:net.sf.groovyMonkey.actions.PasteScriptFromClipboardAction.java

private IFile createScriptFile(final IFolder destination, final ScriptMetadata metadata, final String script)
        throws CoreException, IOException {
    final String defaultName = substringAfterLast(metadata.scriptPath(), "/");
    String basename = defaultName;
    final int ix = basename.lastIndexOf(".");
    if (ix > 0)
        basename = basename.substring(0, ix);
    createFolder(destination);//  w w w.j  a  v  a 2s .  c o m
    final IResource[] members = destination.members(0);
    final Pattern suffix = compile(basename + "(-(\\d+))?\\" + FILE_EXTENSION);
    int maxsuffix = -1;
    for (final IResource resource : members) {
        if (resource instanceof IFile) {
            final IFile file = (IFile) resource;
            final String filename = file.getName();
            final Matcher match = suffix.matcher(filename);
            if (match.matches()) {
                if (file.exists() && file.getName().equals(defaultName)) {
                    final MessageDialog dialog = new MessageDialog(shell(), "Overwrite?", null,
                            "Overwrite existing script: " + file.getName() + " ?", MessageDialog.WARNING,
                            new String[] { "Yes", "No" }, 0);
                    if (dialog.open() == 0) {
                        file.delete(true, null);
                        closeEditor(file);
                        maxsuffix = -1;
                        basename = substringBeforeLast(file.getName(), ".");
                        break;
                    }
                }
                if (match.group(2) == null)
                    maxsuffix = max(maxsuffix, 0);
                else {
                    final int n = Integer.parseInt(match.group(2));
                    maxsuffix = max(maxsuffix, n);
                }
            }
        }
    }
    final String filename = maxsuffix == -1 ? basename + FILE_EXTENSION
            : basename + "-" + (maxsuffix + 1) + FILE_EXTENSION;
    final IFile file = destination.getFile(filename);
    final ByteArrayInputStream stream = new ByteArrayInputStream(script.getBytes());
    file.create(stream, true, null);
    stream.close();
    return file;
}

From source file:gov.redhawk.rap.internal.PluginProviderServlet.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    final Path path = new Path(req.getRequestURI());
    String pluginId = path.lastSegment();
    if (pluginId.endsWith(".jar")) {
        pluginId = pluginId.substring(0, pluginId.length() - 4);
    }/*from w w w.  ja  va2 s.co  m*/
    final Bundle b = Platform.getBundle(pluginId);
    if (b == null) {
        final String protocol = req.getProtocol();
        final String msg = "Plugin does not exist: " + pluginId;
        if (protocol.endsWith("1.1")) {
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
        } else {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        }
        return;
    }
    final File file = FileLocator.getBundleFile(b);
    resp.setContentType("application/octet-stream");

    if (file.isFile()) {
        final String contentDisposition = "attachment; filename=\"" + file.getName() + "\"";
        resp.setHeader("Content-Disposition", contentDisposition);
        resp.setContentLength((int) file.length());
        final FileInputStream istream = new FileInputStream(file);
        try {
            IOUtils.copy(istream, resp.getOutputStream());
        } finally {
            istream.close();
        }
        resp.flushBuffer();
    } else {
        final String contentDisposition = "attachment; filename=\"" + file.getName() + ".jar\"";
        resp.setHeader("Content-Disposition", contentDisposition);
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        final Manifest man = new Manifest(new FileInputStream(new File(file, "META-INF/MANIFEST.MF")));
        final JarOutputStream out = new JarOutputStream(outputStream, man);
        final File binDir = new File(file, "bin");

        if (binDir.exists()) {
            addFiles(out, Path.ROOT, binDir.listFiles());
            for (final File f : file.listFiles()) {
                if (!f.getName().equals("bin")) {
                    addFiles(out, Path.ROOT, f);
                }
            }
        } else {
            addFiles(out, Path.ROOT, file.listFiles());
        }
        out.close();
        outputStream.close();
        final ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        resp.setContentLength(outputStream.size());
        try {
            IOUtils.copy(inputStream, resp.getOutputStream());
        } finally {
            inputStream.close();
        }
        resp.flushBuffer();
    }

}

From source file:com.github.davidcarboni.encryptedfileupload.EncryptedFileItemSerializeTest.java

/**
 * Do deserialization//from   w  ww .j av  a2 s .  c  om
 */
private Object deserialize(ByteArrayOutputStream baos) throws Exception {
    Object result = null;
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    ObjectInputStream ois = new ObjectInputStream(bais);
    result = ois.readObject();
    bais.close();

    return result;
}