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:it.marcoberri.mbmeteo.action.chart.GetLastTBar.java

/**
 * Processes requests for both HTTP//from  ww w.ja va2s.  c  om
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("start : " + this.getClass().getName());

    final HashMap<String, String> params = getParams(request.getParameterMap());
    final Integer dimy = Default.toInteger(params.get("dimy"), 600);
    final Integer dimx = Default.toInteger(params.get("dimx"), 800);

    Meteolog meteolog = ds.find(Meteolog.class).order("-time").limit(1).get();

    final DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    dataset.addValue(meteolog.getOutdoorTemperature(), ChartEnumMinMaxHelper.outdoorTemperatureMin.getUm(),
            DateTimeUtil.dateFormat("yyyy-MM-dd hh:mm:ss", meteolog.getTime()));

    final JFreeChart chart = ChartFactory.createBarChart("T", // chart title
            "", // domain axis label
            "", // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // orientation
            false, // include legend
            false, // tooltips?
            false // URLs?
    );

    final CategoryPlot xyPlot = (CategoryPlot) chart.getPlot();

    xyPlot.getRangeAxis().setRange(0, meteolog.getOutdoorTemperature() + 2);
    final File f = File.createTempFile("mbmeteo", ".jpg");
    ChartUtilities.saveChartAsJPEG(f, chart, dimx, dimy);

    response.setContentType("image/jpeg");
    response.setHeader("Content-Length", "" + f.length());
    response.setHeader("Content-Disposition", "inline; filename=\"" + f.getName() + "\"");
    final OutputStream out = response.getOutputStream();
    final FileInputStream in = new FileInputStream(f.toString());
    final int size = in.available();
    final byte[] content = new byte[size];
    in.read(content);
    out.write(content);
    in.close();
    out.close();

}

From source file:ict.servlet.UploadToServer.java

public static int upLoad2Server(String sourceFileUri) {
    String upLoadServerUri = "http://vbacdu.ddns.net:8080/WBS/newjsp.jsp";
    // String [] string = sourceFileUri;
    String fileName = sourceFileUri;
    int serverResponseCode = 0;

    HttpURLConnection conn = null;
    DataOutputStream dos = null;/* w  w w. j  ava  2  s  .c om*/
    DataInputStream inStream = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    String responseFromServer = "";

    File sourceFile = new File(sourceFileUri);
    if (!sourceFile.isFile()) {

        return 0;
    }
    try { // open a URL connection to the Servlet
        FileInputStream fileInputStream = new FileInputStream(sourceFile);
        URL url = new URL(upLoadServerUri);
        conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        conn.setRequestProperty("uploaded_file", fileName);
        dos = new DataOutputStream(conn.getOutputStream());

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fileName + "\""
                + lineEnd);
        dos.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available(); // create a buffer of  maximum size

        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

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

        while (bytesRead > 0) {
            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.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        // Responses from the server (code and message)
        serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();

        m_log.info("Upload file to server" + "HTTP Response is : " + serverResponseMessage + ": "
                + serverResponseCode);
        // close streams
        m_log.info("Upload file to server" + fileName + " File is written");
        fileInputStream.close();
        dos.flush();
        dos.close();
    } catch (MalformedURLException ex) {
        //         ex.printStackTrace();
        m_log.error("Upload file to server" + "error: " + ex.getMessage(), ex);
    } catch (Exception e) {
        //      e.printStackTrace();
    }
    //this block will give the response of upload link
    /* try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String line;
      while ((line = rd.readLine()) != null) {
      m_log.info("Huzza" + "RES Message: " + line);
      }
      rd.close();
      } catch (IOException ioex) {
      m_log.error("Huzza" + "error: " + ioex.getMessage(), ioex);
      }*/
    return serverResponseCode; // like 200 (Ok)

}

From source file:com.zokin.common.Application.java

public String ReadFileData(String fileName) {
    String res = "";
    try {/*from  w  ww.  j  a  v  a  2  s  .  c om*/
        FileInputStream fin = openFileInput(fileName);
        int length = fin.available();
        byte[] buffer = new byte[length];
        fin.read(buffer);
        res = EncodingUtils.getString(buffer, "UTF-8");
        fin.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return res;
}

From source file:com.ikon.util.impexp.RepositoryImporter.java

/**
 * Import mail./*from  w  w w  .j  a v a2 s.c  om*/
 */
private static ImpExpStats importMail(String token, File fs, String fldPath, String fileName, File fDoc,
        String metadata, Writer out, InfoDecorator deco) throws IOException, PathNotFoundException,
        AccessDeniedException, RepositoryException, DatabaseException, ExtensionException, AutomationException {
    FileInputStream fisContent = new FileInputStream(fDoc);
    MetadataAdapter ma = MetadataAdapter.getInstance(token);
    MailModule mm = ModuleManager.getMailModule();
    Properties props = System.getProperties();
    props.put("mail.host", "smtp.dummydomain.com");
    props.put("mail.transport.protocol", "smtp");
    ImpExpStats stats = new ImpExpStats();
    int size = fisContent.available();
    Mail mail = new Mail();
    Gson gson = new Gson();
    boolean api = false;

    try {
        // Metadata
        if (metadata.equals("JSON")) {
            // Read serialized document metadata
            File jsFile = new File(fDoc.getPath() + Config.EXPORT_METADATA_EXT);
            log.info("Document Metadata File: {}", jsFile.getPath());

            if (jsFile.exists() && jsFile.canRead()) {
                FileReader fr = new FileReader(jsFile);
                MailMetadata mmd = gson.fromJson(fr, MailMetadata.class);
                mail.setPath(fldPath + "/" + fileName);
                mmd.setPath(mail.getPath());
                IOUtils.closeQuietly(fr);
                log.info("Mail Metadata: {}", mmd);

                // Apply metadata
                ma.importWithMetadata(mmd);

                // Add attachments
                Session mailSession = Session.getDefaultInstance(props, null);
                MimeMessage msg = new MimeMessage(mailSession, fisContent);
                mail = MailUtils.messageToMail(msg);
                mail.setPath(fldPath + "/" + mmd.getName());
                MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser());

                FileLogger.info(BASE_NAME, "Created document ''{0}''", mail.getPath());
                log.info("Created document '{}'", mail.getPath());
            } else {
                log.warn("Unable to read metadata file: {}", jsFile.getPath());
                api = true;
            }
        } else {
            api = true;
        }

        if (api) {
            Session mailSession = Session.getDefaultInstance(props, null);
            MimeMessage msg = new MimeMessage(mailSession, fisContent);
            mail = MailUtils.messageToMail(msg);
            mail.setPath(fldPath + "/" + fileName);
            mm.create(token, mail);
            MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser());

            FileLogger.info(BASE_NAME, "Created mail ''{0}''", mail.getPath());
            log.info("Created mail ''{}''", mail.getPath());
        }

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), null));
            out.flush();
        }

        // Stats
        stats.setSize(stats.getSize() + size);
        stats.setMails(stats.getMails() + 1);
    } catch (UnsupportedMimeTypeException e) {
        log.warn("UnsupportedMimeTypeException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "UnsupportedMimeType"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "UnsupportedMimeTypeException ''{0}''", mail.getPath());
    } catch (FileSizeExceededException e) {
        log.warn("FileSizeExceededException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "FileSizeExceeded"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "FileSizeExceededException ''{0}''", mail.getPath());
    } catch (UserQuotaExceededException e) {
        log.warn("UserQuotaExceededException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "UserQuotaExceeded"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "UserQuotaExceededException ''{0}''", mail.getPath());
    } catch (VirusDetectedException e) {
        log.warn("VirusWarningException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "VirusWarningException"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "VirusWarningException ''{0}''", mail.getPath());
    } catch (ItemExistsException e) {
        log.warn("ItemExistsException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "ItemExists"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "ItemExistsException ''{0}''", mail.getPath());
    } catch (JsonParseException e) {
        log.warn("JsonParseException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "Json"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "JsonParseException ''{0}''", mail.getPath());
    } catch (MessagingException e) {
        log.warn("MessagingException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "Json"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "MessagingException ''{0}''", mail.getPath());
    } finally {
        IOUtils.closeQuietly(fisContent);
    }

    return stats;
}

From source file:com.openkm.util.impexp.RepositoryImporter.java

/**
 * Import mail./*from  w w  w.  j  av  a 2 s  .c  o m*/
 */
private static ImpExpStats importMail(String token, String fldPath, String fileName, File fDoc,
        boolean metadata, Writer out, InfoDecorator deco) throws IOException, PathNotFoundException,
        AccessDeniedException, RepositoryException, DatabaseException, ExtensionException, AutomationException {
    FileInputStream fisContent = new FileInputStream(fDoc);
    MetadataAdapter ma = MetadataAdapter.getInstance(token);
    MailModule mm = ModuleManager.getMailModule();
    Properties props = System.getProperties();
    props.put("mail.host", "smtp.dummydomain.com");
    props.put("mail.transport.protocol", "smtp");
    ImpExpStats stats = new ImpExpStats();
    int size = fisContent.available();
    Mail mail = new Mail();
    Gson gson = new Gson();
    boolean api = false;

    try {
        // Metadata
        if (metadata) {
            // Read serialized document metadata
            File jsFile = new File(fDoc.getPath() + Config.EXPORT_METADATA_EXT);
            log.info("Document Metadata File: {}", jsFile.getPath());

            if (jsFile.exists() && jsFile.canRead()) {
                FileReader fr = new FileReader(jsFile);
                MailMetadata mmd = gson.fromJson(fr, MailMetadata.class);
                mail.setPath(fldPath + "/" + fileName);
                mmd.setPath(mail.getPath());
                IOUtils.closeQuietly(fr);
                log.info("Mail Metadata: {}", mmd);

                // Apply metadata
                ma.importWithMetadata(mmd);

                // Add attachments
                if (fileName.endsWith(".eml")) {
                    Session mailSession = Session.getDefaultInstance(props, null);
                    MimeMessage msg = new MimeMessage(mailSession, fisContent);
                    mail = MailUtils.messageToMail(msg);
                    mail.setPath(fldPath + "/" + mmd.getName());
                    MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser());
                } else if (fileName.endsWith(".msg")) {
                    Message msg = new MsgParser().parseMsg(fisContent);
                    mail = MailUtils.messageToMail(msg);
                    mail.setPath(fldPath + "/" + mmd.getName());
                    MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser());
                } else {
                    throw new MessagingException("Unknown mail format");
                }

                FileLogger.info(BASE_NAME, "Created document ''{0}''", mail.getPath());
                log.info("Created document '{}'", mail.getPath());
            } else {
                log.warn("Unable to read metadata file: {}", jsFile.getPath());
                api = true;
            }
        } else {
            api = true;
        }

        if (api) {
            if (fileName.endsWith(".eml")) {
                Session mailSession = Session.getDefaultInstance(props, null);
                MimeMessage msg = new MimeMessage(mailSession, fisContent);
                mail = MailUtils.messageToMail(msg);
                mail.setPath(fldPath + "/" + UUID.randomUUID().toString() + "-"
                        + PathUtils.escape(mail.getSubject()));
                mm.create(token, mail);
                MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser());
            } else if (fileName.endsWith(".msg")) {
                Message msg = new MsgParser().parseMsg(fisContent);
                mail = MailUtils.messageToMail(msg);
                mail.setPath(fldPath + "/" + UUID.randomUUID().toString() + "-"
                        + PathUtils.escape(mail.getSubject()));
                mm.create(token, mail);
                MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser());
            } else {
                throw new MessagingException("Unknown mail format");
            }

            FileLogger.info(BASE_NAME, "Created mail ''{0}''", mail.getPath());
            log.info("Created mail ''{}''", mail.getPath());
        }

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), null));
            out.flush();
        }

        // Stats
        stats.setSize(stats.getSize() + size);
        stats.setMails(stats.getMails() + 1);
    } catch (UnsupportedMimeTypeException e) {
        log.warn("UnsupportedMimeTypeException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "UnsupportedMimeType"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "UnsupportedMimeTypeException ''{0}''", mail.getPath());
    } catch (FileSizeExceededException e) {
        log.warn("FileSizeExceededException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "FileSizeExceeded"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "FileSizeExceededException ''{0}''", mail.getPath());
    } catch (UserQuotaExceededException e) {
        log.warn("UserQuotaExceededException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "UserQuotaExceeded"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "UserQuotaExceededException ''{0}''", mail.getPath());
    } catch (VirusDetectedException e) {
        log.warn("VirusWarningException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "VirusWarningException"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "VirusWarningException ''{0}''", mail.getPath());
    } catch (ItemExistsException e) {
        log.warn("ItemExistsException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "ItemExists"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "ItemExistsException ''{0}''", mail.getPath());
    } catch (JsonParseException e) {
        log.warn("JsonParseException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "Json"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "JsonParseException ''{0}''", mail.getPath());
    } catch (MessagingException e) {
        log.warn("MessagingException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "Messaging"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "MessagingException ''{0}''", mail.getPath());
    } catch (Exception e) {
        log.warn("Exception: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "General"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "Exception ''{0}''", mail.getPath());
    } finally {
        IOUtils.closeQuietly(fisContent);
    }

    return stats;
}

From source file:cn.org.once.cstack.maven.plugin.utils.RestUtils.java

public Map<String, Object> sendPostForUpload(String url, String path, Log log) throws IOException {
    File file = new File(path);
    FileInputStream fileInputStream = new FileInputStream(file);
    fileInputStream.available();
    fileInputStream.close();//from w  w  w.j  av a 2s.c  o  m
    FileSystemResource resource = new FileSystemResource(file);
    Map<String, Object> params = new HashMap<>();
    params.put("file", resource);
    RestTemplate restTemplate = new RestTemplate();
    MultiValueMap<String, Object> postParams = new LinkedMultiValueMap<String, Object>();
    postParams.setAll(params);
    Map<String, Object> response = new HashMap<String, Object>();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Content-Type", "multipart/form-data");
    headers.set("Accept", "application/json");
    headers.add("Cookie", "JSESSIONID=" + localContext.getCookieStore().getCookies().get(0).getValue());
    org.springframework.http.HttpEntity<Object> request = new org.springframework.http.HttpEntity<Object>(
            postParams, headers);
    ResponseEntity<?> result = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
    String body = result.getBody().toString();
    MediaType contentType = result.getHeaders().getContentType();
    HttpStatus statusCode = result.getStatusCode();
    response.put("content-type", contentType);
    response.put("statusCode", statusCode);
    response.put("body", body);

    return response;
}

From source file:it.marcoberri.mbmeteo.action.chart.GetLastRDial.java

/**
 * Processes requests for both HTTP/*from  w  w w  .  j a  va  2 s.c  o  m*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("start : " + this.getClass().getName());

    final HashMap<String, String> params = getParams(request.getParameterMap());
    final Integer dimy = Default.toInteger(params.get("dimy"), 600);
    final Integer dimx = Default.toInteger(params.get("dimx"), 800);

    Meteolog meteolog = ds.find(Meteolog.class).order("-time").limit(1).get();

    DefaultValueDataset dataset = new DefaultValueDataset(meteolog.getDayRainfall());

    // get data for diagrams
    DialPlot plot = new DialPlot();
    plot.setView(0.0, 0.0, 1.0, 1.0);
    plot.setDataset(0, dataset);

    GradientPaint gp = new GradientPaint(new Point(), new Color(255, 255, 255), new Point(),
            new Color(170, 170, 220));

    DialBackground db = new DialBackground(gp);

    db.setGradientPaintTransformer(
            new StandardGradientPaintTransformer(GradientPaintTransformType.CENTER_HORIZONTAL));
    plot.setBackground(db);

    StandardDialScale scale = new StandardDialScale();
    scale.setLowerBound(0);
    scale.setUpperBound(50);
    scale.setTickLabelOffset(0.14);
    scale.setTickLabelFont(new Font("Dialog", Font.PLAIN, 10));
    plot.addScale(0, scale);

    DialPointer needle = new DialPointer.Pointer(0);

    plot.addLayer(needle);

    JFreeChart chart1 = new JFreeChart(plot);
    chart1.setTitle("Daily Rain mm");

    final File f = File.createTempFile("mbmeteo", ".jpg");
    ChartUtilities.saveChartAsJPEG(f, chart1, dimx, dimy);

    response.setContentType("image/jpeg");
    response.setHeader("Content-Length", "" + f.length());
    response.setHeader("Content-Disposition", "inline; filename=\"" + f.getName() + "\"");
    final OutputStream out = response.getOutputStream();
    final FileInputStream in = new FileInputStream(f.toString());
    final int size = in.available();
    final byte[] content = new byte[size];
    in.read(content);
    out.write(content);
    in.close();
    out.close();
}

From source file:it.marcoberri.mbmeteo.action.chart.GetLastTDial.java

/**
 * Processes requests for both HTTP// ww w.  ja  va2s  .  c o m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("start : " + this.getClass().getName());

    final HashMap<String, String> params = getParams(request.getParameterMap());
    final Integer dimy = Default.toInteger(params.get("dimy"), 600);
    final Integer dimx = Default.toInteger(params.get("dimx"), 800);

    Meteolog meteolog = ds.find(Meteolog.class).order("-time").limit(1).get();

    DefaultValueDataset dataset = new DefaultValueDataset(meteolog.getOutdoorTemperature());

    // get data for diagrams
    DialPlot plot = new DialPlot();
    plot.setView(0.0, 0.0, 1.0, 1.0);
    plot.setDataset(0, dataset);

    GradientPaint gp = new GradientPaint(new Point(), new Color(255, 255, 255), new Point(),
            new Color(170, 170, 220));

    DialBackground db = new DialBackground(gp);

    db.setGradientPaintTransformer(
            new StandardGradientPaintTransformer(GradientPaintTransformType.CENTER_HORIZONTAL));
    plot.setBackground(db);

    StandardDialScale scale = new StandardDialScale();
    scale.setLowerBound(-20);
    scale.setUpperBound(40);
    scale.setTickLabelOffset(0.14);
    scale.setTickLabelFont(new Font("Dialog", Font.PLAIN, 10));
    plot.addScale(0, scale);

    DialPointer needle = new DialPointer.Pointer(0);

    plot.addLayer(needle);

    JFreeChart chart1 = new JFreeChart(plot);
    chart1.setTitle("Temperature C");

    final File f = File.createTempFile("mbmeteo", ".jpg");
    ChartUtilities.saveChartAsJPEG(f, chart1, dimx, dimy);

    response.setContentType("image/jpeg");
    response.setHeader("Content-Length", "" + f.length());
    response.setHeader("Content-Disposition", "inline; filename=\"" + f.getName() + "\"");
    final OutputStream out = response.getOutputStream();
    final FileInputStream in = new FileInputStream(f.toString());
    final int size = in.available();
    final byte[] content = new byte[size];
    in.read(content);
    out.write(content);
    in.close();
    out.close();
}

From source file:org.lockss.util.TestDeferredTempFileOutputStream.java

/**
 * Verifies that the specified file contains the same data as the original
 * test data.//from   w w  w .  j  a  v  a2 s  . com
 *
 * @param testFile The file containing the test output.
 */
private void verifyResultFile(File testFile) throws IOException {
    assertTrue(testFile.exists());
    FileInputStream fis = new FileInputStream(testFile);
    assertTrue(fis.available() == testBytes.length);

    byte[] resultBytes = new byte[testBytes.length];
    assertTrue(fis.read(resultBytes) == testBytes.length);

    assertEquals(testBytes, resultBytes);
    assertTrue(fis.read(resultBytes) == -1);

    try {
        fis.close();
    } catch (IOException e) {
        // Ignore an exception on close
    }
}

From source file:it.marcoberri.mbmeteo.action.chart.GetLastUDial.java

/**
 * Processes requests for both HTTP/*from   w  ww .  j a  v  a 2  s . c om*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("start : " + this.getClass().getName());

    final HashMap<String, String> params = getParams(request.getParameterMap());
    final Integer dimy = Default.toInteger(params.get("dimy"), 600);
    final Integer dimx = Default.toInteger(params.get("dimx"), 800);

    Meteolog meteolog = ds.find(Meteolog.class).order("-time").limit(1).get();

    DefaultValueDataset dataset = new DefaultValueDataset(meteolog.getOutdoorHumidity());

    // get data for diagrams
    DialPlot plot = new DialPlot();
    plot.setInsets(RectangleInsets.ZERO_INSETS);
    //plot.setView(0.1, 0.1, 0.9, 0.9);
    // plot.set
    plot.setDataset(0, dataset);

    GradientPaint gp = new GradientPaint(new Point(), new Color(255, 255, 255), new Point(),
            new Color(170, 170, 220));

    DialBackground db = new DialBackground(gp);
    db.setGradientPaintTransformer(
            new StandardGradientPaintTransformer(GradientPaintTransformType.CENTER_HORIZONTAL));
    plot.setBackground(db);

    StandardDialScale scale = new StandardDialScale();
    scale.setLowerBound(0);
    scale.setUpperBound(100);
    scale.setTickLabelOffset(0.14);
    scale.setTickLabelFont(new Font("Dialog", Font.PLAIN, 10));
    plot.addScale(0, scale);
    plot.setInsets(RectangleInsets.ZERO_INSETS);

    DialPointer needle = new DialPointer.Pointer(0);

    plot.addLayer(needle);

    JFreeChart chart1 = new JFreeChart(plot);
    chart1.setTitle("Humidity %");

    final File f = File.createTempFile("mbmeteo", ".jpg");
    ChartUtilities.saveChartAsJPEG(f, chart1, dimx, dimy);

    response.setContentType("image/jpeg");
    response.setHeader("Content-Length", "" + f.length());
    response.setHeader("Content-Disposition", "inline; filename=\"" + f.getName() + "\"");
    final OutputStream out = response.getOutputStream();
    final FileInputStream in = new FileInputStream(f.toString());
    final int size = in.available();
    final byte[] content = new byte[size];
    in.read(content);
    out.write(content);
    in.close();
    out.close();
}