Example usage for java.io FileInputStream available

List of usage examples for java.io FileInputStream available

Introduction

In this page you can find the example usage for java.io FileInputStream available.

Prototype

public int available() throws IOException 

Source Link

Document

Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

Usage

From source file:com.cloopen.rest.sdk.CCPRestSDK.java

public HashMap<String, Object> MediaFileUpload(String filename, FileInputStream fis) {

    HashMap<String, Object> validate = accountValidate();
    if (validate != null)
        return validate;
    if ((isEmpty(filename))) {
        LoggerUtil.fatal("?: filename  ");
        throw new IllegalArgumentException("?: filename ");
    }//from ww  w .j av a  2s . c  om
    if (fis == null) {
        LoggerUtil.fatal("?: fis  ");
        throw new IllegalArgumentException("");
    }

    Filename = filename;
    CcopHttpClient chc = new CcopHttpClient();
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        httpclient = chc.registerSSL(SERVER_IP, "TLS", Integer.parseInt(SERVER_PORT), "https");
    } catch (Exception e1) {
        e1.printStackTrace();
        LoggerUtil.error(e1.getMessage());
        throw new RuntimeException("?httpclient" + e1.getMessage());
    }
    String result = "";
    try {
        HttpPost httppost = (HttpPost) getHttpRequestBase(1, mediaFileUpload);

        LoggerUtil.info("MediaFileUpload Request body = : " + fis);
        BasicHttpEntity requestBody = new BasicHttpEntity();
        requestBody.setContent(fis);
        requestBody.setContentLength(fis.available());
        System.out.println("" + requestBody);

        httppost.setEntity(requestBody);
        HttpResponse response = httpclient.execute(httppost);
        status = response.getStatusLine().getStatusCode();
        System.out.println("Https??" + status);

        HttpEntity entity = response.getEntity();
        if (entity != null)
            result = EntityUtils.toString(entity, "UTF-8");

        EntityUtils.consume(entity);
    } catch (IOException e) {
        e.printStackTrace();
        LoggerUtil.error(e.getMessage());
        return getMyError("172001", "");
    } catch (Exception e) {
        e.printStackTrace();
        LoggerUtil.error(e.getMessage());
        return getMyError("172002", "");
    } finally {
        if (httpclient != null)
            httpclient.getConnectionManager().shutdown();
    }
    LoggerUtil.info("billRecords response body = " + result);
    try {
        if (BODY_TYPE == BodyType.Type_JSON) {
            return jsonToMap(result);
        } else {
            return xmlToMap(result);
        }
    } catch (Exception e) {

        return getMyError("172003", "");
    }
}

From source file:com.liferay.lms.servlet.SCORMFileServerServlet.java

/**
 * Procesa los metodos HTTP GET y POST.<br>
 * Busca en la ruta que se le ha pedido el comienzo del directorio
 * "contenidos" y sirve el fichero.//w ww .ja  v a2 s  . co m
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content)
        throws ServletException, java.io.IOException {
    String mime_type;
    String charset;
    String patharchivo;
    String uri;

    try {
        User user = PortalUtil.getUser(request);

        if (user == null) {
            String userId = null;
            String companyId = null;
            Cookie[] cookies = ((HttpServletRequest) request).getCookies();
            if (Validator.isNotNull(cookies)) {
                for (Cookie c : cookies) {
                    if ("COMPANY_ID".equals(c.getName())) {
                        companyId = c.getValue();
                    } else if ("ID".equals(c.getName())) {
                        userId = hexStringToStringByAscii(c.getValue());
                    }
                }
            }

            if (userId != null && companyId != null) {
                try {
                    Company company = CompanyLocalServiceUtil.getCompany(Long.parseLong(companyId));
                    Key key = company.getKeyObj();

                    String userIdPlain = Encryptor.decrypt(key, userId);

                    user = UserLocalServiceUtil.getUser(Long.valueOf(userIdPlain));

                    // Now you can set the liferayUser into a thread local
                    // for later use or
                    // something like that.

                } catch (Exception pException) {
                    throw new RuntimeException(pException);
                }
            }
        }

        String rutaDatos = SCORMContentLocalServiceUtil.getBaseDir();

        // Se comprueba que el usuario tiene permisos para acceder.
        // Damos acceso a todo el mundo al directorio "personalizacion",
        // para permitir mostrar a todos la pantalla de identificacion.
        uri = URLDecoder.decode(request.getRequestURI(), "UTF-8");
        uri = uri.substring(uri.indexOf("scorm/") + "scorm/".length());
        patharchivo = rutaDatos + "/" + uri;

        String[] params = uri.split("/");
        long groupId = GetterUtil.getLong(params[1]);
        String uuid = params[2];
        SCORMContent scormContent = SCORMContentLocalServiceUtil.getSCORMContentByUuidAndGroupId(uuid, groupId);

        boolean allowed = false;
        if (user == null) {
            user = UserLocalServiceUtil.getDefaultUser(PortalUtil.getDefaultCompanyId());
        }
        PermissionChecker pc = PermissionCheckerFactoryUtil.create(user);
        allowed = pc.hasPermission(groupId, SCORMContent.class.getName(), scormContent.getScormId(),
                ActionKeys.VIEW);
        if (!allowed) {
            AssetEntry scormAsset = AssetEntryLocalServiceUtil.getEntry(SCORMContent.class.getName(),
                    scormContent.getPrimaryKey());
            long scormAssetId = scormAsset.getEntryId();
            int typeId = new Long((new SCORMLearningActivityType()).getTypeId()).intValue();
            long[] groupIds = user.getGroupIds();
            for (long gId : groupIds) {
                List<LearningActivity> acts = LearningActivityLocalServiceUtil
                        .getLearningActivitiesOfGroupAndType(gId, typeId);
                for (LearningActivity act : acts) {
                    String entryId = LearningActivityLocalServiceUtil.getExtraContentValue(act.getActId(),
                            "assetEntry");
                    if (Validator.isNotNull(entryId) && Long.valueOf(entryId) == scormAssetId) {
                        allowed = pc.hasPermission(gId, LearningActivity.class.getName(), act.getActId(),
                                ActionKeys.VIEW);
                        if (allowed) {
                            break;
                        }
                    }
                }
                if (allowed) {
                    break;
                }
            }

        }
        if (allowed) {

            File archivo = new File(patharchivo);

            // Si el archivo existe y no es un directorio se sirve. Si no,
            // no se hace nada.
            if (archivo.exists() && archivo.isFile()) {

                // El content type siempre antes del printwriter
                mime_type = MimeTypesUtil.getContentType(archivo);
                charset = "";
                if (archivo.getName().toLowerCase().endsWith(".html")
                        || archivo.getName().toLowerCase().endsWith(".htm")) {
                    mime_type = "text/html";
                    if (isISO(FileUtils.readFileToString(archivo))) {
                        charset = "ISO-8859-1";
                    }
                }
                if (archivo.getName().toLowerCase().endsWith(".swf")) {
                    mime_type = "application/x-shockwave-flash";
                }
                if (archivo.getName().toLowerCase().endsWith(".mp4")) {
                    mime_type = "video/mp4";
                }
                if (archivo.getName().toLowerCase().endsWith(".flv")) {
                    mime_type = "video/x-flv";
                }
                response.setContentType(mime_type);
                if (Validator.isNotNull(charset)) {
                    response.setCharacterEncoding(charset);

                }
                response.addHeader("Content-Type",
                        mime_type + (Validator.isNotNull(charset) ? "; " + charset : ""));
                /*if (archivo.getName().toLowerCase().endsWith(".swf")
                      || archivo.getName().toLowerCase().endsWith(".flv")) {
                   response.addHeader("Content-Length",
                String.valueOf(archivo.length()));
                }
                */
                if (archivo.getName().toLowerCase().endsWith("imsmanifest.xml")) {
                    FileInputStream fis = new FileInputStream(patharchivo);

                    String sco = ParamUtil.get(request, "scoshow", "");
                    Document manifest = SAXReaderUtil.read(fis);
                    if (sco.length() > 0) {

                        Element organizatEl = manifest.getRootElement().element("organizations")
                                .element("organization");
                        Element selectedItem = selectItem(organizatEl, sco);
                        if (selectedItem != null) {
                            selectedItem.detach();
                            java.util.List<Element> items = organizatEl.elements("item");
                            for (Element item : items) {

                                organizatEl.remove(item);
                            }
                            organizatEl.add(selectedItem);
                        }
                    }
                    //clean unused resources.
                    Element resources = manifest.getRootElement().element("resources");
                    java.util.List<Element> theResources = resources.elements("resource");
                    Element organizatEl = manifest.getRootElement().element("organizations")
                            .element("organization");
                    java.util.List<String> identifiers = getIdentifierRefs(organizatEl);
                    for (Element resource : theResources) {
                        String identifier = resource.attributeValue("identifier");
                        if (!identifiers.contains(identifier)) {
                            resources.remove(resource);
                        }
                    }
                    response.getWriter().print(manifest.asXML());
                    fis.close();
                    return;

                }

                if (mime_type.startsWith("text") || mime_type.endsWith("javascript")
                        || mime_type.equals("application/xml")) {

                    java.io.OutputStream out = response.getOutputStream();
                    FileInputStream fis = new FileInputStream(patharchivo);

                    byte[] buffer = new byte[512];
                    int i = 0;

                    while (fis.available() > 0) {
                        i = fis.read(buffer);
                        if (i == 512)
                            out.write(buffer);
                        else
                            out.write(buffer, 0, i);

                    }

                    fis.close();
                    out.flush();
                    out.close();
                    return;
                }
                //If not manifest
                String fileName = archivo.getName();
                long length = archivo.length();
                long lastModified = archivo.lastModified();
                String eTag = fileName + "_" + length + "_" + lastModified;
                long expires = System.currentTimeMillis() + DEFAULT_EXPIRE_TIME;
                String ifNoneMatch = request.getHeader("If-None-Match");
                if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    response.setHeader("ETag", eTag); // Required in 304.
                    response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
                    return;
                }
                long ifModifiedSince = request.getDateHeader("If-Modified-Since");
                if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    response.setHeader("ETag", eTag); // Required in 304.
                    response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
                    return;
                }

                // If-Match header should contain "*" or ETag. If not, then return 412.
                String ifMatch = request.getHeader("If-Match");
                if (ifMatch != null && !matches(ifMatch, eTag)) {
                    response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                    return;
                }

                // If-Unmodified-Since header should be greater than LastModified. If not, then return 412.
                long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
                if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
                    response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                    return;
                }

                // Validate and process range -------------------------------------------------------------

                // Prepare some variables. The full Range represents the complete file.
                Range full = new Range(0, length - 1, length);
                List<Range> ranges = new ArrayList<Range>();

                // Validate and process Range and If-Range headers.
                String range = request.getHeader("Range");
                if (range != null) {

                    // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416.
                    if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
                        response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
                        response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                        return;
                    }

                    // If-Range header should either match ETag or be greater then LastModified. If not,
                    // then return full file.
                    String ifRange = request.getHeader("If-Range");
                    if (ifRange != null && !ifRange.equals(eTag)) {
                        try {
                            long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid.
                            if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) {
                                ranges.add(full);
                            }
                        } catch (IllegalArgumentException ignore) {
                            ranges.add(full);
                        }
                    }

                    // If any valid If-Range header, then process each part of byte range.
                    if (ranges.isEmpty()) {
                        for (String part : range.substring(6).split(",")) {
                            // Assuming a file with length of 100, the following examples returns bytes at:
                            // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100).
                            long start = sublong(part, 0, part.indexOf("-"));
                            long end = sublong(part, part.indexOf("-") + 1, part.length());

                            if (start == -1) {
                                start = length - end;
                                end = length - 1;
                            } else if (end == -1 || end > length - 1) {
                                end = length - 1;
                            }

                            // Check if Range is syntactically valid. If not, then return 416.
                            if (start > end) {
                                response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
                                response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                                return;
                            }

                            // Add range.
                            ranges.add(new Range(start, end, length));
                        }
                    }
                }
                boolean acceptsGzip = false;
                String disposition = "inline";

                if (mime_type.startsWith("text")) {
                    //String acceptEncoding = request.getHeader("Accept-Encoding");
                    // acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip");
                    // mime_type += ";charset=UTF-8";
                }

                // Else, expect for images, determine content disposition. If content type is supported by
                // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
                else if (!mime_type.startsWith("image")) {
                    String accept = request.getHeader("Accept");
                    disposition = accept != null && accepts(accept, mime_type) ? "inline" : "attachment";
                }

                // Initialize response.
                response.reset();
                response.setBufferSize(DEFAULT_BUFFER_SIZE);
                response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
                response.setHeader("Accept-Ranges", "bytes");
                response.setHeader("ETag", eTag);
                response.setDateHeader("Last-Modified", lastModified);
                response.setDateHeader("Expires", expires);

                // Send requested file (part(s)) to client ------------------------------------------------

                // Prepare streams.
                RandomAccessFile input = null;
                OutputStream output = null;

                try {
                    // Open streams.
                    input = new RandomAccessFile(archivo, "r");
                    output = response.getOutputStream();

                    if (ranges.isEmpty() || ranges.get(0) == full) {

                        // Return full file.
                        Range r = full;
                        response.setContentType(mime_type);
                        response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);

                        if (content) {

                            // Content length is not directly predictable in case of GZIP.
                            // So only add it if there is no means of GZIP, else browser will hang.
                            response.setHeader("Content-Length", String.valueOf(r.length));

                            // Copy full range.
                            copy(input, output, r.start, r.length);
                        }

                    } else if (ranges.size() == 1) {

                        // Return single part of file.
                        Range r = ranges.get(0);
                        response.setContentType(mime_type);
                        response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
                        response.setHeader("Content-Length", String.valueOf(r.length));
                        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

                        if (content) {
                            // Copy single part range.
                            copy(input, output, r.start, r.length);
                        }

                    } else {

                        // Return multiple parts of file.
                        response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
                        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

                        if (content) {
                            // Cast back to ServletOutputStream to get the easy println methods.
                            ServletOutputStream sos = (ServletOutputStream) output;

                            // Copy multi part range.
                            for (Range r : ranges) {
                                // Add multipart boundary and header fields for every range.
                                sos.println();
                                sos.println("--" + MULTIPART_BOUNDARY);
                                sos.println("Content-Type: " + mime_type);
                                sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                                // Copy single part range of multi part range.
                                copy(input, output, r.start, r.length);
                            }

                            // End with multipart boundary.
                            sos.println();
                            sos.println("--" + MULTIPART_BOUNDARY + "--");
                        }
                    }
                } finally {
                    // Gently close streams.
                    close(output);
                    close(input);
                }
            } else {
                //java.io.OutputStream out = response.getOutputStream();
                response.sendError(404);
                //out.write(uri.getBytes());
            }
        } else {
            response.sendError(401);
        }
    } catch (Exception e) {
        System.out.println("Error en el processRequest() de ServidorArchivos: " + e.getMessage());
    }
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String UpdateCallBack(String sFileName) {
    String sRet = sErrorPrefix + "No file specified";
    String sIP = "";
    String sPort = "";
    int nEnd = 0;
    int nStart = 0;

    if ((sFileName == null) || (sFileName.length() == 0))
        return (sRet);

    Context ctx = contextWrapper.getApplicationContext();
    try {//w ww.j  av  a  2s.c  o m
        FileInputStream fis = ctx.openFileInput(sFileName);
        int nBytes = fis.available();
        if (nBytes > 0) {
            byte[] buffer = new byte[nBytes + 1];
            int nRead = fis.read(buffer, 0, nBytes);
            fis.close();
            ctx.deleteFile(sFileName);
            if (nRead > 0) {
                String sBuffer = new String(buffer);
                nEnd = sBuffer.indexOf(',');
                if (nEnd > 0) {
                    sIP = (sBuffer.substring(0, nEnd)).trim();
                    nStart = nEnd + 1;
                    nEnd = sBuffer.indexOf('\r', nStart);
                    if (nEnd > 0) {
                        sPort = (sBuffer.substring(nStart, nEnd)).trim();
                        Thread.sleep(5000);
                        sRet = RegisterTheDevice(sIP, sPort, sBuffer.substring(nEnd + 1));
                    }
                }
            }
        }
    } catch (FileNotFoundException e) {
        sRet = sErrorPrefix + "Nothing to do";
    } catch (IOException e) {
        sRet = sErrorPrefix + "Couldn't send info to " + sIP + ":" + sPort;
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return (sRet);
}

From source file:edu.cmu.cylab.starslinger.view.HomeActivity.java

private void doLoadAttachment(String path) throws FileNotFoundException {
    File phy = new File(path); // physical
    File vir = new File(path); // virtual, change if needed
    DraftData d = DraftData.INSTANCE;/*from  www . j a  v a 2s  .  co  m*/

    try {
        FileInputStream is = new FileInputStream(phy.getAbsolutePath());
        try {
            byte[] outFileData = new byte[is.available()];
            is.read(outFileData);
            d.setFileData(outFileData);
            d.setFileSize(outFileData.length);

            if (d.getFileSize() > SafeSlingerConfig.MAX_FILEBYTES) {
                is.close();
                showNote(String.format(getString(R.string.error_CannotSendFilesOver),
                        SafeSlingerConfig.MAX_FILEBYTES));
                refreshView();
                return;
            }

            String type = URLConnection.guessContentTypeFromStream(is);
            if (type != null)
                d.setFileType(type);
            else {
                String extension = SSUtil.getFileExtensionOnly(vir.getName());
                type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
                if (type != null) {
                    d.setFileType(type);
                } else {
                    d.setFileType(SafeSlingerConfig.MIMETYPE_OPEN_ATTACH_DEF);
                }
            }
        } finally {
            is.close();
        }
    } catch (OutOfMemoryError e) {
        showNote(R.string.error_OutOfMemoryError);
        refreshView();
        return;
    } catch (IOException e) {
        showNote(e);
        refreshView();
        return;
    }
    d.setFileName(vir.getName());
    d.setFileDir(phy.getPath());
    d.setMsgHash(null);
}

From source file:org.skt.runtime.html5apis.file.FileTransfer.java

/**
 * Uploads the specified file to the server URL provided using an HTTP multipart request.
 * @param source        Full path of the file on the file system
 * @param target        URL of the server to receive the file
 * @param args          JSON Array of args
 *
 * args[2] fileKey       Name of file request parameter
 * args[3] fileName      File name to be used on server
 * args[4] mimeType      Describes file content type
 * args[5] params        key:value pairs of user-defined parameters
 * @return FileUploadResult containing result of upload request
 *//*ww w .j  a  va  2s . c o m*/
private PluginResult upload(String source, String target, JSONArray args) {
    Log.d(LOG_TAG, "upload " + source + " to " + target);

    HttpURLConnection conn = null;
    try {
        // Setup the options
        String fileKey = getArgument(args, 2, "file");
        String fileName = getArgument(args, 3, "image.jpg");
        String mimeType = getArgument(args, 4, "image/jpeg");
        JSONObject params = args.optJSONObject(5);
        if (params == null) {
            params = new JSONObject();
        }
        boolean trustEveryone = args.optBoolean(6);
        boolean chunkedMode = args.optBoolean(7) || args.isNull(7); //Always use chunked mode unless set to false as per API

        Log.d(LOG_TAG, "fileKey: " + fileKey);
        Log.d(LOG_TAG, "fileName: " + fileName);
        Log.d(LOG_TAG, "mimeType: " + mimeType);
        Log.d(LOG_TAG, "params: " + params);
        Log.d(LOG_TAG, "trustEveryone: " + trustEveryone);
        Log.d(LOG_TAG, "chunkedMode: " + chunkedMode);

        // Create return object
        FileUploadResult result = new FileUploadResult();

        // Get a input stream of the file on the phone
        FileInputStream fileInputStream = (FileInputStream) getPathFromUri(source);

        DataOutputStream dos = null;

        int bytesRead, bytesAvailable, bufferSize;
        long totalBytes;
        byte[] buffer;
        int maxBufferSize = 8096;

        //------------------ CLIENT REQUEST
        // open a URL connection to the server
        URL url = new URL(target);

        // Open a HTTP connection to the URL based on protocol
        if (url.getProtocol().toLowerCase().equals("https")) {
            // Using standard HTTPS connection. Will not allow self signed certificate
            if (!trustEveryone) {
                conn = (HttpsURLConnection) url.openConnection();
            }
            // Use our HTTPS connection that blindly trusts everyone.
            // This should only be used in debug environments
            else {
                // Setup the HTTPS connection class to trust everyone
                trustAllHosts();
                HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
                // Save the current hostnameVerifier
                defaultHostnameVerifier = https.getHostnameVerifier();
                // Setup the connection not to verify hostnames
                https.setHostnameVerifier(DO_NOT_VERIFY);
                conn = https;
            }
        }
        // Return a standard HTTP connection
        else {
            conn = (HttpURLConnection) url.openConnection();
        }

        // Allow Inputs
        conn.setDoInput(true);

        // Allow Outputs
        conn.setDoOutput(true);

        // Don't use a cached copy.
        conn.setUseCaches(false);

        // Use a post method.
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);

        // Handle the other headers
        try {
            JSONObject headers = params.getJSONObject("headers");
            for (Iterator iter = headers.keys(); iter.hasNext();) {
                String headerKey = iter.next().toString();
                conn.setRequestProperty(headerKey, headers.getString(headerKey));
            }
        } catch (JSONException e1) {
            // No headers to be manipulated!
        }

        // Set the cookies on the response
        String cookie = CookieManager.getInstance().getCookie(target);
        if (cookie != null) {
            conn.setRequestProperty("Cookie", cookie);
        }

        /*
        * Store the non-file portions of the multipart data as a string, so that we can add it
        * to the contentSize, since it is part of the body of the HTTP request.
        */
        String extraParams = "";
        try {
            for (Iterator iter = params.keys(); iter.hasNext();) {
                Object key = iter.next();
                if (!String.valueOf(key).equals("headers")) {
                    extraParams += LINE_START + BOUNDARY + LINE_END;
                    extraParams += "Content-Disposition: form-data; name=\"" + key.toString() + "\";";
                    extraParams += LINE_END + LINE_END;
                    extraParams += params.getString(key.toString());
                    extraParams += LINE_END;
                }
            }
        } catch (JSONException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
        }

        extraParams += LINE_START + BOUNDARY + LINE_END;
        extraParams += "Content-Disposition: form-data; name=\"" + fileKey + "\";" + " filename=\"";

        String midParams = "\"" + LINE_END + "Content-Type: " + mimeType + LINE_END + LINE_END;
        String tailParams = LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END;

        // Should set this up as an option
        if (chunkedMode) {
            conn.setChunkedStreamingMode(maxBufferSize);
        } else {
            int stringLength = extraParams.getBytes("UTF-8").length + midParams.getBytes("UTF-8").length
                    + tailParams.getBytes("UTF-8").length + fileName.getBytes("UTF-8").length;
            Log.d(LOG_TAG, "String Length: " + stringLength);
            int fixedLength = (int) fileInputStream.getChannel().size() + stringLength;
            Log.d(LOG_TAG, "Content Length: " + fixedLength);
            conn.setFixedLengthStreamingMode(fixedLength);
        }

        dos = new DataOutputStream(conn.getOutputStream());
        dos.write(extraParams.getBytes("UTF-8"));
        //We don't want to chagne encoding, we just want this to write for all Unicode.
        dos.write(fileName.getBytes("UTF-8"));
        dos.write(midParams.getBytes("UTF-8"));

        // create a buffer of maximum size
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        totalBytes = 0;

        while (bytesRead > 0) {
            totalBytes += bytesRead;
            result.setBytesSent(totalBytes);
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        // send multipart form data necesssary after file data...
        dos.write(tailParams.getBytes("UTF-8"));

        // close streams
        fileInputStream.close();
        dos.flush();
        dos.close();

        //------------------ read the SERVER RESPONSE
        StringBuffer responseString = new StringBuffer("");
        DataInputStream inStream;
        try {
            inStream = new DataInputStream(conn.getInputStream());
        } catch (FileNotFoundException e) {
            Log.e(LOG_TAG, e.toString(), e);
            throw new IOException("Received error from server");
        }

        String line;
        while ((line = inStream.readLine()) != null) {
            responseString.append(line);
        }
        Log.d(LOG_TAG, "got response from server");
        Log.d(LOG_TAG, responseString.toString());

        // send request and retrieve response
        result.setResponseCode(conn.getResponseCode());
        result.setResponse(responseString.toString());

        inStream.close();

        // Revert back to the proper verifier and socket factories
        if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) {
            ((HttpsURLConnection) conn).setHostnameVerifier(defaultHostnameVerifier);
            HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
        }

        Log.d(LOG_TAG, "****** About to return a result from upload");
        return new PluginResult(PluginResult.Status.OK, result.toJSONObject());

    } catch (FileNotFoundException e) {
        JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn);
        Log.e(LOG_TAG, error.toString(), e);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } catch (MalformedURLException e) {
        JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, conn);
        Log.e(LOG_TAG, error.toString(), e);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } catch (IOException e) {
        JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
        Log.e(LOG_TAG, error.toString(), e);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
    } catch (Throwable t) {
        // Shouldn't happen, but will
        JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
        Log.wtf(LOG_TAG, error.toString(), t);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:ome.formats.OMEROMetadataStoreClient.java

/**
 * Writes binary original file data to the OMERO server.
 * @param files Files to populate against an original file list.
 * @param originalFileMap Map of absolute path against original file
 * objects that we are to populate./*from w ww  . ja  va 2  s  . co  m*/
 */
public void writeFilesToFileStore(List<File> files, Map<String, OriginalFile> originalFileMap) {
    // Lookup each source file in our hash map and write it to the
    // correct original file object server side.
    byte[] buf = new byte[1048576]; // 1 MB buffer
    for (File file : files) {
        String path = file.getAbsolutePath();
        OriginalFile originalFile = originalFileMap.get(path);
        if (originalFile == null) {
            originalFile = byUUID(path, originalFileMap);
        }
        if (originalFile == null) {
            log.warn("Cannot lookup original file with path: " + file.getAbsolutePath());
            continue;
        }

        FileInputStream stream = null;
        try {
            stream = new FileInputStream(file);
            rawFileStore.setFileId(originalFile.getId().getValue());
            int rlen = 0;
            int offset = 0;
            while (stream.available() != 0) {
                rlen = stream.read(buf);
                rawFileStore.write(buf, offset, rlen);
                offset += rlen;
            }
        } catch (Exception e) {
            log.error("I/O or server error populating file store.", e);
            break;
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (Exception e) {
                    log.error("I/O error closing stream.", e);
                }
            }
        }
    }
}

From source file:ee.sk.digidoc.DataFile.java

/** 
 * Calculates the DataFiles size and digest
 * Since it calculates the digest of the external file
 * then this is only useful for detatched files
 * @throws DigiDocException for all errors
 *///from   ww  w  .j  a  v  a 2 s.  c o  m
public void calculateFileSizeAndDigest(OutputStream os) throws DigiDocException {
    if (m_logger.isDebugEnabled())
        m_logger.debug("calculateFileSizeAndDigest(" + getId() + ") body: " + ((m_body != null) ? "OK" : "NULL")
                + " base64: " + m_bodyIsBase64 + " DF cache: "
                + ((m_fDfCache != null) ? m_fDfCache.getAbsolutePath() : "NULL"));
    FileInputStream fis = null;
    if (m_contentType.equals(CONTENT_BINARY)) {
        InputStream is = null;
        try {
            if (getDfCacheFile() != null)
                is = getBodyAsStream();
            else if (is == null && m_body != null)
                is = new java.io.ByteArrayInputStream(m_body);
            else if (is == null && m_fileName != null)
                is = new java.io.FileInputStream(m_fileName);
            if (is != null)
                calcHashes(is);
        } catch (java.io.FileNotFoundException ex) {
            throw new DigiDocException(DigiDocException.ERR_READ_FILE, "Cannot read file: " + m_fileName, null);
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (Exception ex) {
                m_logger.error("Error closing stream: " + ex);
            }
        }
        return;
    }

    MessageDigest sha = null;
    boolean bUse64ByteLines = true;
    String use64Flag = ConfigManager.instance().getProperty("DATAFILE_USE_64BYTE_LINES");
    if (use64Flag != null && use64Flag.equalsIgnoreCase("FALSE"))
        bUse64ByteLines = false;
    try {
        sha = MessageDigest.getInstance("SHA-1"); // TODO: fix digest type
        // if DataFile's digest has already been initialized
        // and body in memory, e.g. has been read from digidoc
        // then write directly to output stream and don't calculate again
        if (m_origDigestValue != null && m_body != null && os != null) {
            os.write(xmlHeader());
            if (m_logger.isDebugEnabled())
                m_logger.debug("write df header1: " + xmlHeader());
            os.write(m_body);
            os.write(xmlTrailer());
            return;
        }
        String longFileName = m_fileName;
        File fIn = new File(m_fileName);
        m_fileName = fIn.getName();
        if (fIn.canRead() && m_fDfCache == null) {
            fis = new FileInputStream(longFileName);
            if (m_logger.isDebugEnabled())
                m_logger.debug("Read file: " + longFileName);
        } else if (m_fDfCache != null) {
            fis = new FileInputStream(m_fDfCache);
            if (m_logger.isDebugEnabled())
                m_logger.debug("Read cache: " + m_fDfCache);
        }
        byte[] tmp1 = null, tmp2 = null, tmp3 = null;
        ByteArrayOutputStream sbDig = new ByteArrayOutputStream();
        sbDig.write(xmlHeader());
        // add trailer and canonicalize
        tmp3 = xmlTrailer();
        sbDig.write(tmp3);
        tmp1 = canonicalizeXml(sbDig.toByteArray());
        // now remove the end tag again and calculate digest of the start tag only
        if (tmp1 != null) {
            tmp2 = new byte[tmp1.length - tmp3.length];
            System.arraycopy(tmp1, 0, tmp2, 0, tmp2.length);
            sha.update(tmp2);
            if (os != null)
                os.write(xmlHeader());
        }
        // reset the collecting buffer and other temp buffers
        sbDig = new ByteArrayOutputStream();
        tmp1 = tmp2 = tmp3 = null;
        // content must be read from file
        if (m_body == null) {
            if (m_logger.isDebugEnabled())
                m_logger.debug("Reading input file: " + ((fIn.canRead() && m_fDfCache == null) ? longFileName
                        : ((m_fDfCache != null) ? m_fDfCache.getAbsolutePath() : "no-cache")));
            byte[] buf = new byte[block_size];
            byte[] b64leftover = null;
            int fRead = 0, b64left = 0;
            ByteArrayOutputStream content = null;
            if (m_contentType.equals(CONTENT_EMBEDDED_BASE64)) {
                // optimization for 64 char base64 lines
                // convert to base64 online at a time to conserve memory
                // VS: DF temp file base64 decoding fix
                if (m_fDfCache == null) {
                    if (bUse64ByteLines)
                        b64leftover = new byte[65];
                    else
                        content = new ByteArrayOutputStream();
                }
            }
            while ((fRead = fis.read(buf)) > 0 || b64left > 0) { // read input file
                if (m_logger.isDebugEnabled())
                    m_logger.debug("read: " + fRead + " bytes of input data");
                if (m_contentType.equals(CONTENT_EMBEDDED_BASE64)) {
                    // VS: DF temp file base64 decoding fix
                    if (m_fDfCache != null) {
                        if (os != null)
                            os.write(buf, 0, fRead);
                        sha.update(buf, 0, fRead);
                    } else {
                        if (bUse64ByteLines) { // 1 line base64 optimization
                            b64left = calculateAndWriteBase64Block(os, sha, b64leftover, b64left, buf, fRead,
                                    fRead < block_size);
                        } else { // no optimization
                            content.write(buf, 0, fRead);
                        }
                    }
                } else {
                    if (fRead < buf.length) {
                        tmp2 = new byte[fRead];
                        System.arraycopy(buf, 0, tmp2, 0, fRead);
                        tmp1 = ConvertUtils.data2utf8(tmp2, m_codepage);
                    } else
                        tmp1 = ConvertUtils.data2utf8(buf, m_codepage);
                    sbDig.write(tmp1);
                }
                if (m_logger.isDebugEnabled())
                    m_logger.debug(
                            "End using block: " + fRead + " in: " + ((fis != null) ? fis.available() : 0));
            } // end reading input file
            if (m_contentType.equals(CONTENT_EMBEDDED_BASE64)) {
                // VS: DF temp file base64 decoding fix
                if (!bUse64ByteLines && m_fDfCache == null)
                    sbDig.write(Base64Util.encode(content.toByteArray(), 0).getBytes());
                content = null;
            }
            if (m_logger.isDebugEnabled())
                m_logger.debug("End reading content");
        } else { // content allready in memeory
            if (m_logger.isDebugEnabled())
                m_logger.debug("Using mem content, len: " + ((m_body != null) ? m_body.length : 0) + " b64: "
                        + m_bodyIsBase64);
            if (m_body != null) {
                if (bUse64ByteLines && m_contentType.equals(CONTENT_EMBEDDED_BASE64) && !m_bodyIsBase64) {
                    calculateAndWriteBase64Block(os, sha, null, 0, m_body, m_body.length, true);
                    m_body = Base64Util.encode(m_body).getBytes();
                    //sbDig.write(m_body); // this code block not used any more ?
                } else {
                    if (m_contentType.equals(CONTENT_EMBEDDED_BASE64) && !m_bodyIsBase64) {
                        tmp1 = Base64Util.encode(m_body).getBytes();
                    } else if (m_contentType.equals(CONTENT_EMBEDDED_BASE64) && m_bodyIsBase64) {
                        tmp1 = ConvertUtils.data2utf8(m_body, m_codepage);
                    } else
                        tmp1 = ConvertUtils.data2utf8(m_body, m_codepage);
                    sbDig.write(tmp1);
                }
            }
        }
        tmp1 = null;
        // don't need to canonicalize base64 content !
        if (m_contentType.equals(CONTENT_EMBEDDED_BASE64)) {
            // VS: DF temp file base64 decoding fix
            if (!bUse64ByteLines && m_fDfCache == null) {
                tmp2 = sbDig.toByteArray();
                if (tmp2 != null && tmp2.length > 0) {
                    sha.update(tmp2);
                    if (os != null)
                        os.write(tmp2);
                }
            } else if (m_body != null && sbDig.size() > 0) {
                tmp2 = sbDig.toByteArray();
                if (tmp2 != null && tmp2.length > 0) {
                    sha.update(tmp2);
                    if (os != null)
                        os.write(tmp2);
                }
            }
        } else {
            // canonicalize body
            tmp2 = sbDig.toByteArray();
            if (tmp2 != null && tmp2.length > 0) {
                if (tmp2[0] == '<')
                    tmp2 = canonicalizeXml(tmp2);
                if (tmp2 != null && tmp2.length > 0) {
                    sha.update(tmp2); // crash
                    if (os != null)
                        os.write(tmp2);
                }
            }
        }
        tmp2 = null;
        sbDig = null;
        // trailer         
        tmp1 = xmlTrailer();
        sha.update(tmp1);
        if (os != null)
            os.write(tmp1);
        // now calculate the digest
        byte[] digest = sha.digest();
        setDigest(digest);
        if (m_logger.isDebugEnabled())
            m_logger.debug("DataFile: \'" + getId() + "\' length: " + getSize() + " digest: "
                    + Base64Util.encode(digest));
        m_fileName = longFileName;
    } catch (Exception ex) {
        DigiDocException.handleException(ex, DigiDocException.ERR_READ_FILE);
    } finally {
        try {
            if (fis != null)
                fis.close();
        } catch (Exception ex) {
            m_logger.error("Error closing file: " + ex);
        }
    }
}

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

@Override
public Object getPortfolio(MimeType outMimeType, String portfolioUuid, int userId, int groupId, String label,
        String resource, String files) throws Exception {
    String rootNodeUuid = getPortfolioRootNode(portfolioUuid);
    String header = "";
    String footer = "";
    NodeRight nodeRight = credential.getPortfolioRight(userId, groupId, portfolioUuid, Credential.READ);
    if (!nodeRight.read)
        return "faux";

    if (outMimeType.getSubType().equals("xml")) {
        //         header = "<portfolio xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' schemaVersion='1.0'>";
        //         footer = "</portfolio>";

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder;
        Document document = null;
        try {/* www. j  a  va 2  s  . c  o m*/
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
            document = documentBuilder.newDocument();
            document.setXmlStandalone(true);
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Element root = document.createElement("portfolio");
        root.setAttribute("id", portfolioUuid);
        root.setAttribute("code", "0");

        //// Noeuds supplmentaire pour WAD
        // Version
        Element verNode = document.createElement("version");
        Text version = document.createTextNode("3");
        verNode.appendChild(version);
        root.appendChild(verNode);
        // metadata-wad
        Element metawad = document.createElement("metadata-wad");
        metawad.setAttribute("prog", "main.jsp");
        metawad.setAttribute("owner", "N");
        root.appendChild(metawad);

        //          root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        //          root.setAttribute("schemaVersion", "1.0");
        document.appendChild(root);

        getLinearXml(portfolioUuid, rootNodeUuid, root, true, null, userId, groupId);

        StringWriter stw = new StringWriter();
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.transform(new DOMSource(document), new StreamResult(stw));

        if (resource != null && files != null) {

            if (resource.equals("true") && files.equals("true")) {
                String adressedufichier = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".xml";
                String adresseduzip = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".zip";

                File file = null;
                PrintWriter ecrire;
                PrintWriter ecri;
                try {
                    file = new File(adressedufichier);
                    ecrire = new PrintWriter(new FileOutputStream(adressedufichier));
                    ecrire.println(stw.toString());
                    ecrire.flush();
                    ecrire.close();
                    System.out.print("fichier cree ");
                } catch (IOException ioe) {
                    System.out.print("Erreur : ");
                    ioe.printStackTrace();
                }

                try {
                    String fileName = portfolioUuid + ".zip";

                    ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(adresseduzip));
                    zip.setMethod(ZipOutputStream.DEFLATED);
                    zip.setLevel(Deflater.BEST_COMPRESSION);
                    File dataDirectories = new File(file.getName());
                    FileInputStream fis = new FileInputStream(dataDirectories);
                    byte[] bytes = new byte[fis.available()];
                    fis.read(bytes);

                    ZipEntry entry = new ZipEntry(file.getName());
                    entry.setTime(dataDirectories.lastModified());
                    zip.putNextEntry(entry);
                    zip.write(bytes);
                    zip.closeEntry();
                    fis.close();
                    //zipDirectory(dataDirectories, zip);
                    zip.close();

                    file.delete();

                    return adresseduzip;

                } catch (FileNotFoundException fileNotFound) {
                    fileNotFound.printStackTrace();

                } catch (IOException io) {

                    io.printStackTrace();
                }
            }
        }

        return stw.toString();

    } else if (outMimeType.getSubType().equals("json")) {
        header = "{\"portfolio\": { \"-xmlns:xsi\": \"http://www.w3.org/2001/XMLSchema-instance\",\"-schemaVersion\": \"1.0\",";
        footer = "}}";
    }

    return header + getNode(outMimeType, rootNodeUuid, true, userId, groupId, label).toString() + footer;
}

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

@Override
public Object getPortfolio(MimeType outMimeType, String portfolioUuid, int userId, int groupId, String label,
        String resource, String files, int substid) throws Exception {
    String rootNodeUuid = getPortfolioRootNode(portfolioUuid);
    String header = "";
    String footer = "";
    NodeRight nodeRight = credential.getPortfolioRight(userId, groupId, portfolioUuid, Credential.READ);
    if (!nodeRight.read) {
        userId = credential.getPublicUid();
        //         NodeRight nodeRight = new NodeRight(false,false,false,false,false,false);
        /// Vrifie les droits avec le compte publique (dernire chance)
        nodeRight = credential.getPublicRight(userId, 123, rootNodeUuid, "dummy");
        if (!nodeRight.read)
            return "faux";
    }//from   w  w w  .  j a va 2s  .  com

    if (outMimeType.getSubType().equals("xml")) {
        //         header = "<portfolio xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' schemaVersion='1.0'>";
        //         footer = "</portfolio>";

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder;
        Document document = null;
        try {
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
            document = documentBuilder.newDocument();
            document.setXmlStandalone(true);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }

        Element root = document.createElement("portfolio");
        root.setAttribute("id", portfolioUuid);
        root.setAttribute("code", "0");

        //// Noeuds supplmentaire pour WAD
        // Version
        Element verNode = document.createElement("version");
        Text version = document.createTextNode("4");
        verNode.appendChild(version);
        root.appendChild(verNode);
        // metadata-wad
        //         Element metawad = document.createElement("metadata-wad");
        //         metawad.setAttribute("prog", "main.jsp");
        //         metawad.setAttribute("owner", "N");
        //         root.appendChild(metawad);
        int owner = credential.getOwner(userId, portfolioUuid);
        String isOwner = "N";
        if (owner == userId)
            isOwner = "Y";
        root.setAttribute("owner", isOwner);

        //          root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        //          root.setAttribute("schemaVersion", "1.0");
        document.appendChild(root);

        getLinearXml(portfolioUuid, rootNodeUuid, root, true, null, userId, nodeRight.groupId,
                nodeRight.groupLabel);

        StringWriter stw = new StringWriter();
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.transform(new DOMSource(document), new StreamResult(stw));

        if (resource != null && files != null) {
            if (resource.equals("true") && files.equals("true")) {
                String adressedufichier = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".xml";
                String adresseduzip = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".zip";

                File file = null;
                PrintWriter ecrire;
                try {
                    file = new File(adressedufichier);
                    ecrire = new PrintWriter(new FileOutputStream(adressedufichier));
                    ecrire.println(stw.toString());
                    ecrire.flush();
                    ecrire.close();
                    System.out.print("fichier cree ");
                } catch (IOException ioe) {
                    System.out.print("Erreur : ");
                    ioe.printStackTrace();
                }

                try {
                    ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(adresseduzip));
                    zip.setMethod(ZipOutputStream.DEFLATED);
                    zip.setLevel(Deflater.BEST_COMPRESSION);
                    File dataDirectories = new File(file.getName());
                    FileInputStream fis = new FileInputStream(dataDirectories);
                    byte[] bytes = new byte[fis.available()];
                    fis.read(bytes);

                    ZipEntry entry = new ZipEntry(file.getName());
                    entry.setTime(dataDirectories.lastModified());
                    zip.putNextEntry(entry);
                    zip.write(bytes);
                    zip.closeEntry();
                    fis.close();
                    //zipDirectory(dataDirectories, zip);
                    zip.close();

                    file.delete();

                    return adresseduzip;
                } catch (FileNotFoundException fileNotFound) {
                    fileNotFound.printStackTrace();
                } catch (IOException io) {
                    io.printStackTrace();
                }
            }
        }

        return stw.toString();
    } else if (outMimeType.getSubType().equals("json")) {
        header = "{\"portfolio\": { \"-xmlns:xsi\": \"http://www.w3.org/2001/XMLSchema-instance\",\"-schemaVersion\": \"1.0\",";
        footer = "}}";
    }

    return header + getNode(outMimeType, rootNodeUuid, true, userId, groupId, label).toString() + footer;
}