Example usage for java.io DataInputStream DataInputStream

List of usage examples for java.io DataInputStream DataInputStream

Introduction

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

Prototype

public DataInputStream(InputStream in) 

Source Link

Document

Creates a DataInputStream that uses the specified underlying InputStream.

Usage

From source file:org.openxdata.server.FormsServer.java

/**
 * Called when a new connection has been received. Failures are not handled
 * in this class as different servers (BT,SMS, etc) may want to handle them
 * differently./*from www.j a  v  a 2 s . c o m*/
 * 
 * @param dis - the stream to read from.
 * @param dos - the stream to write to.
 */
public void processConnection(InputStream disParam, OutputStream dosParam) {

    ZOutputStream gzip = new ZOutputStream(dosParam, JZlib.Z_BEST_COMPRESSION);
    DataOutputStream zdos = new DataOutputStream(gzip);

    byte responseStatus = ResponseStatus.STATUS_ERROR;

    try {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DataInputStream dis = new DataInputStream(disParam);

            String name = dis.readUTF();
            String password = dis.readUTF();
            String serializer = dis.readUTF();
            String locale = dis.readUTF();

            byte action = dis.readByte();

            User user = authenticationService.authenticate(name, password);
            if (user == null)
                responseStatus = ResponseStatus.STATUS_ACCESS_DENIED;
            else {
                DataOutputStream dosTemp = new DataOutputStream(baos);

                if (action == ACTION_DOWNLOAD_FORMS)
                    formDownloadService.downloadForms(dosTemp, serializer, locale);
                else if (action == ACTION_UPLOAD_DATA)
                    submitXforms(dis, dosTemp, serializer);
                else if (action == ACTION_DOWNLOAD_USERS)
                    formDownloadService.downloadUsers(dosTemp, serializer);
                else if (action == ACTION_DOWNLOAD_USERS_AND_FORMS)
                    downloadUsersAndForms(dis.readInt(), dosTemp, serializer, locale);
                else if (action == ACTION_DOWNLOAD_STUDY_LIST)
                    formDownloadService.downloadStudies(dosTemp, serializer, locale);
                else if (action == ACTION_DOWNLOAD_LANGUAGES)
                    formDownloadService.downloadLocales(dis, dosTemp, serializer);
                else if (action == ACTION_DOWNLOAD_MENU_TEXT)
                    formDownloadService.downloadMenuText(dis, dosTemp, serializer, locale);
                else if (action == ACTION_DOWNLOAD_STUDY_FORMS)
                    formDownloadService.downloadForms(dis.readInt(), zdos, serializer, locale);
                else if (action == ACTION_DOWNLOAD_USERS_AND_ALL_FORMS)
                    downloadUsersAndAllForms(dosTemp, serializer, locale);

                responseStatus = ResponseStatus.STATUS_SUCCESS;
            }

            zdos.writeByte(responseStatus);

            if (responseStatus == ResponseStatus.STATUS_SUCCESS) {
                zdos.write(baos.toByteArray());
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            zdos.writeByte(responseStatus);
        } finally {
            zdos.flush();
            gzip.finish();
        }
    } catch (IOException e) {
        // this is for exceptions occurring in the catch or finally clauses.
        log.error(e.getMessage(), e);
    }
}

From source file:com.rpgsheet.xcom.dao.SaveGameDaoImpl.java

private byte[] readIt(int saveSlot, String fileName) {
    File saveFile = ufoGameFileService.getSaveFile(saveSlot, fileName);
    byte[] data = new byte[(int) saveFile.length()];
    try {/*w w  w .  j ava2 s .c  o m*/
        FileInputStream fileInputStream = new FileInputStream(saveFile);
        DataInputStream dataInputStream = new DataInputStream(fileInputStream);
        dataInputStream.readFully(data);
    } catch (FileNotFoundException e) {
        // if we don't have it, we don't have it
        data = null;
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
    return data;
}

From source file:com.zack6849.alphabot.api.Utils.java

public static String checkServerStatus(InetAddress i, int port) {
    String returns = "Error.";
    try {/*from ww w. j  a  v  a 2  s .  c om*/
        //wow...i never actually used the port argument?
        Socket s = new Socket(i, port);
        DataInputStream SS_BF = new DataInputStream(s.getInputStream());
        DataOutputStream d = new DataOutputStream(s.getOutputStream());
        d.write(new byte[] { (byte) 0xFE, (byte) 0x01 });
        SS_BF.readByte();
        short length = SS_BF.readShort();
        StringBuilder sb = new StringBuilder();
        for (int in = 0; in < length; in++) {
            char ch = SS_BF.readChar();
            sb.append(ch);
        }
        String all = sb.toString().trim();
        System.out.println(all);
        String[] args1 = all.split("\u0000");
        if (args1[3].contains("")) {
            returns = "MOTD: " + args1[3].replaceAll("[a-m]", "").replaceAll("[1234567890]", "")
                    + "   players: [" + args1[4] + "/" + args1[5] + "]";
        } else {
            returns = "MOTD: " + args1[3] + "   players: [" + args1[4] + "/" + args1[5] + "]";
        }
    } catch (UnknownHostException e1) {
        returns = "the host you specified is unknown. check your settings.";
    } catch (IOException e1) {
        returns = "sorry, we couldn't reach this server, make sure that the server is up and has query enabled.";
    }
    return returns;
}

From source file:com.facebook.infrastructure.net.UdpConnection.java

public void read(SelectionKey key) {
    key.interestOps(key.interestOps() & (~SelectionKey.OP_READ));
    ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
    try {//from  w  ww .j  a  v a2s. c  o m
        SocketAddress sa = socketChannel_.receive(buffer);
        if (sa == null) {
            logger_.debug("*** No datagram packet was available to be read ***");
            return;
        }
        buffer.flip();

        byte[] bytes = gobbleHeaderAndExtractBody(buffer);
        if (bytes.length > 0) {
            DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes));
            Message message = Message.serializer().deserialize(dis);
            if (message != null) {
                MessagingService.receive(message);
            }
        }
    } catch (IOException ioe) {
        logger_.warn(LogUtil.throwableToString(ioe));
    } finally {
        key.interestOps(key_.interestOps() | SelectionKey.OP_READ);
    }
}

From source file:com.web.server.util.FarmWarFileTransfer.java

public void setState(InputStream input) throws Exception {
    List<String> list = (List<String>) Util.objectFromStream(new DataInputStream(input));
    synchronized (state) {
        state.clear();/*from   w w w  .  j a v a  2 s.c  o m*/
        state.addAll(list);
    }
    //System.out.println("received state (" + list.size() + " messages in chat history):");
    for (String str : list) {
        System.out.println(str);
    }
}

From source file:Util.PacketGenerator.java

public static void GenerateGraph() {
    try {//from w ww  .  j  a  v  a 2  s .  c om
        for (int j = 6; j <= 6; j++) {
            File real = new File("D:\\Mestrado\\SketchMatrix\\trunk\\Simulations\\Analise\\Scenario1\\Topology"
                    + j + "\\Real.csv");
            for (int k = 1; k <= 4; k++) {
                File simu = new File(
                        "D:\\Mestrado\\SketchMatrix\\trunk\\Simulations\\Analise\\Scenario1\\Topology" + j
                                + "\\SimulacaoInstancia" + k + ".csv");

                FileInputStream simuFIS = new FileInputStream(simu);
                DataInputStream simuDIS = new DataInputStream(simuFIS);
                BufferedReader simuBR = new BufferedReader(new InputStreamReader(simuDIS));

                FileInputStream realFIS = new FileInputStream(real);
                DataInputStream realDIS = new DataInputStream(realFIS);
                BufferedReader realBR = new BufferedReader(new InputStreamReader(realDIS));

                String lineSimu = simuBR.readLine();
                String lineReal = realBR.readLine();

                XYSeries matrix = new XYSeries("Matriz", false, true);
                while (lineSimu != null && lineReal != null) {

                    lineSimu = lineSimu.replaceAll(",", ".");
                    String[] simuMatriz = lineSimu.split(";");
                    String[] realMatriz = lineReal.split(";");

                    for (int i = 0; i < simuMatriz.length; i++) {
                        try {
                            Integer valorReal = Integer.parseInt(realMatriz[i]);
                            Float valorSimu = Float.parseFloat(simuMatriz[i]);
                            matrix.add(valorReal.doubleValue() / 1000.0, valorSimu.doubleValue() / 1000.0);
                        } catch (NumberFormatException ex) {

                        }
                    }
                    lineSimu = simuBR.readLine();
                    lineReal = realBR.readLine();
                }

                simuFIS.close();
                simuDIS.close();
                simuBR.close();

                realFIS.close();
                realDIS.close();
                realBR.close();

                double maxPlot = Double.max(matrix.getMaxX(), matrix.getMaxY()) * 1.1;
                XYSeries middle = new XYSeries("Referncia");
                ;
                middle.add(0, 0);
                middle.add(maxPlot, maxPlot);
                XYSeries max = new XYSeries("Superior 20%");
                max.add(0, 0);
                max.add(maxPlot, maxPlot * 1.2);
                XYSeries min = new XYSeries("Inferior 20%");
                min.add(0, 0);
                min.add(maxPlot, maxPlot * 0.8);

                XYSeriesCollection dataset = new XYSeriesCollection();
                dataset.addSeries(middle);
                dataset.addSeries(matrix);
                dataset.addSeries(max);
                dataset.addSeries(min);
                JFreeChart chart;
                if (k == 4) {
                    chart = ChartFactory.createXYLineChart("Matriz de Trfego", "Real", "CMO-MT", dataset);
                } else {
                    chart = ChartFactory.createXYLineChart("Matriz de Trfego", "CMO-MT", "Zhao", dataset);
                }
                chart.setBackgroundPaint(Color.WHITE);
                chart.getPlot().setBackgroundPaint(Color.WHITE);
                chart.getTitle().setFont(new Font("Times New Roman", Font.BOLD, 13));

                chart.getLegend().setItemFont(new Font("Times New Roman", Font.TRUETYPE_FONT, 10));

                chart.getXYPlot().getDomainAxis().setLabelFont(new Font("Times New Roman", Font.BOLD, 10));
                chart.getXYPlot().getDomainAxis()
                        .setTickLabelFont(new Font("Times New Roman", Font.TRUETYPE_FONT, 1));
                chart.getXYPlot().getRangeAxis().setLabelFont(new Font("Times New Roman", Font.BOLD, 10));
                chart.getXYPlot().getRangeAxis()
                        .setTickLabelFont(new Font("Times New Roman", Font.TRUETYPE_FONT, 1));

                XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();

                renderer.setSeriesLinesVisible(1, false);
                renderer.setSeriesShapesVisible(1, true);

                renderer.setSeriesStroke(0, new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
                        10.0f, new float[] { 0.1f }, 0.0f));
                renderer.setSeriesShape(1, new Ellipse2D.Float(-1.5f, -1.5f, 3f, 3f));
                renderer.setSeriesStroke(2, new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
                        10.0f, new float[] { 3.0f }, 0.0f));
                renderer.setSeriesStroke(3, new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
                        10.0f, new float[] { 3.0f }, 0.0f));

                renderer.setSeriesPaint(0, Color.BLACK);
                renderer.setSeriesPaint(1, Color.BLACK);
                renderer.setSeriesPaint(2, Color.BLACK);
                renderer.setSeriesPaint(3, Color.BLACK);

                int width = (int) (192 * 1.5f); /* Width of the image */

                int height = (int) (144 * 1.5f); /* Height of the image */

                File XYChart = new File(
                        "D:\\Mestrado\\SketchMatrix\\trunk\\Simulations\\Analise\\Scenario1\\Topology" + j
                                + "\\SimulacaoInstancia" + k + ".jpeg");
                ChartUtilities.saveChartAsJPEG(XYChart, chart, width, height);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.project.qrypto.keymanagement.KeyManager.java

/**
 * Load a Keystore. Uses either internal or external memory depending on settings.
 * @param context the context to use./*from  w  w  w  .  ja  v a 2s  .  c o  m*/
 * 
 * @throws IOException if the stream is bad
 * @throws InvalidCipherTextException if the key or data is bad
 */
public void load(Context context) throws IOException, InvalidCipherTextException {

    DataInputStream stream = null;
    if (passwordProtected) {
        byte[] data = AES.handle(false, IOUtils.toByteArray(getAssociatedInFileStream(context)), keyStoreKey);
        stream = new DataInputStream(new ByteArrayInputStream(data));
    } else {
        stream = new DataInputStream(getAssociatedInFileStream(context));
    }

    String type = stream.readUTF();
    if (type.equals("RCYTHR1")) {
        //Valid
        int count = stream.readInt();
        for (int i = 0; i < count; ++i) {
            String name = stream.readUTF();
            lookup.put(name, Key.readData(stream));
        }
    } else {
        throw new IOException("Bad Format");
    }

    storeLoaded = true;
}

From source file:com.kylinolap.common.persistence.ResourceStore.java

/**
 * read a resource, return null in case of not found
 *//* ww  w .  ja  va  2 s.co  m*/
final public <T extends RootPersistentEntity> T getResource(String resPath, Class<T> clz,
        Serializer<T> serializer) throws IOException {
    resPath = norm(resPath);
    InputStream in = getResourceImpl(resPath);
    if (in == null)
        return null;

    DataInputStream din = new DataInputStream(in);
    try {
        T r = serializer.deserialize(din);
        r.setLastModified(getResourceTimestamp(resPath));
        return r;
    } finally {
        IOUtils.closeQuietly(din);
        IOUtils.closeQuietly(in);
    }
}

From source file:bkampfbot.Instance.java

/**
 * Parst die Parameter und liest die Konfigurationsdatei aus.
 * /* w  w w  . j  a  v  a2s. co  m*/
 * @param args
 * @throws FatalError
 * @throws IOException
 * @throws RestartLater
 */
public Instance(String[] args) throws FatalError, IOException {

    // configure plans
    PlanBoeseBeute.initiate();
    PlanBoeseKrieg.initiate();
    PlanBoeseRespekt.initiate();
    PlanAngriff.initiate();

    // reset config
    new Config();

    // reset user
    new User();

    this.parseArguments(args);

    if (this.modus.equals(Modus.help)) {
        Output.help();
    }

    // read config file
    try {
        File f = new File(Config.getConfigFile());
        FileInputStream fstream = new FileInputStream(f.getAbsoluteFile());
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        String strLine, configString = "";

        // Read File Line By Line
        while ((strLine = br.readLine()) != null) {

            // Kommentare werden ausgelassen
            if (strLine.length() > 0 && strLine.substring(0, 1).equals("#")) {
                configString += "\n";
                continue;
            }
            configString += strLine + "\n";
        }

        // Close the input stream
        in.close();

        try {
            JSONObject config = new JSONObject(new JSONTokener(configString));
            Config.parseJsonConfig(config);
        } catch (JSONException e) {
            int lines = configString.substring(0, e.getIndex()).replaceAll("[^\n]", "").length();
            throw new FatalError(
                    "Die Struktur der Konfigurationsdatei " + "stimmt nicht. Versuche den Inhalt der "
                            + "Datei mit einem externen Werkzeug zu " + "reparieren. Dafr gibt es Webseiten, "
                            + "die JSON-Objekte validieren knnen. Vermutlich in der Zeile " + lines + "."
                            + "\n\nAls Hinweis hier noch die Fehlerausgabe:\n" + e.getMessage()
                            + "\n\nEingabe war:\n" + e.getInputString());
        }
    } catch (FileNotFoundException e) {
        throw new FatalError("Die Konfigurationsdatei konnte nicht gefunden/geffnet werden.\n Datei: "
                + Config.getConfigFile() + "\n Fehler: " + e.getMessage());
    }

    if (Config.getUserName() == null || Config.getUserPassword() == null || Config.getHost() == null) {
        throw new FatalError("Die Konfigurationsdatei ist nicht vollstndig. "
                + "Es wird mindestens der Benutzername, das " + "Passwort und der Hostname bentigt.");
    }

}

From source file:com.envirover.spl.SPLGroungControlTest.java

@Test
public void testMOMessagePipeline()
        throws URISyntaxException, ClientProtocolException, IOException, InterruptedException {
    System.out.println("MO TEST: Testing MO message pipeline...");

    Thread.sleep(1000);//from   ww  w .  j av  a2s  .c  o m

    Thread mavlinkThread = new Thread(new Runnable() {
        public void run() {
            Socket client = null;

            try {
                System.out.printf("MO TEST: Connecting to tcp://%s:%d",
                        InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort());
                System.out.println();

                client = new Socket(InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort());

                System.out.printf("MO TEST: Connected tcp://%s:%d", InetAddress.getLocalHost().getHostAddress(),
                        config.getMAVLinkPort());
                System.out.println();

                Parser parser = new Parser();
                DataInputStream in = new DataInputStream(client.getInputStream());
                while (true) {
                    MAVLinkPacket packet;
                    do {
                        int c = in.readUnsignedByte();
                        packet = parser.mavlink_parse_char(c);
                    } while (packet == null);

                    System.out.printf("MO TEST: MAVLink message received: msgid = %d", packet.msgid);
                    System.out.println();

                    Thread.sleep(100);
                }
            } catch (InterruptedException ex) {
                return;
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    mavlinkThread.start();

    HttpClient httpclient = HttpClients.createDefault();

    URIBuilder builder = new URIBuilder();
    builder.setScheme("http");
    builder.setHost(InetAddress.getLocalHost().getHostAddress());
    builder.setPort(config.getRockblockPort());
    builder.setPath(config.getHttpContext());

    URI uri = builder.build();
    HttpPost httppost = new HttpPost(uri);

    // Request parameters and other properties.
    List<NameValuePair> params = new ArrayList<NameValuePair>(2);
    params.add(new BasicNameValuePair("imei", config.getRockBlockIMEI()));
    params.add(new BasicNameValuePair("momsn", "12345"));
    params.add(new BasicNameValuePair("transmit_time", "12-10-10 10:41:50"));
    params.add(new BasicNameValuePair("iridium_latitude", "52.3867"));
    params.add(new BasicNameValuePair("iridium_longitude", "0.2938"));
    params.add(new BasicNameValuePair("iridium_cep", "9"));
    params.add(new BasicNameValuePair("data", Hex.encodeHexString(getSamplePacket().encodePacket())));
    httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    // Execute and get the response.
    System.out.printf("MO TEST: Sending test message to %s", uri.toString());
    System.out.println();

    HttpResponse response = httpclient.execute(httppost);

    if (response.getStatusLine().getStatusCode() != 200) {
        fail(String.format("RockBLOCK HTTP message handler status code = %d.",
                response.getStatusLine().getStatusCode()));
    }

    HttpEntity entity = response.getEntity();

    if (entity != null) {
        InputStream responseStream = entity.getContent();
        try {
            String responseString = IOUtils.toString(responseStream);
            System.out.println(responseString);
        } finally {
            responseStream.close();
        }
    }

    Thread.sleep(1000);

    mavlinkThread.interrupt();
    System.out.println("MO TEST: Complete.");
}