javatips.net counter

Java Examples for java.io.IOException

The following java examples will help you to understand the usage of java.io.IOException. These source code samples are taken from different open source projects.

Example 1
Project: IKVM.NET-cvs-clone-master  File: InputStreamWrapper.java View source code
public int read() throws java.io.IOException {
    try {
        if (false)
            throw new cli.System.IO.IOException();
        if (false)
            throw new cli.System.ObjectDisposedException(null);
        int i = stream.ReadByte();
        if (i == -1) {
            atEOF = true;
        }
        return i;
    } catch (cli.System.IO.IOException x) {
        java.io.IOException ex = new java.io.IOException();
        ex.initCause(x);
        throw ex;
    } catch (cli.System.ObjectDisposedException x) {
        java.io.IOException ex = new java.io.IOException();
        ex.initCause(x);
        throw ex;
    }
}
Example 2
Project: eclipse.jdt.ui-master  File: Catch2.java View source code
public void foo(int a, IOException second) throws Exception {
    try {
        if (a < 10)
            throw new FileNotFoundException();
        else if (a < 20)
            throw new InterruptedIOException();
    } catch (FileNotFoundExceptionInterruptedIOException |  ex) {
        second.printStackTrace();
    }
}
Example 3
Project: ARTPart-master  File: IOExceptionTest.java View source code
/**
     * java.io.IOException#IOException(java.lang.String,
     *java.lang.Throwable)
     * @since 1.6
     */
public void test_ConstructorLString_LThrowable() {
    // Test for constructor java.io.IOException(java.lang.String, java.lang.Throwable)
    IOException ioException = new IOException("A dummy IOException", //$NON-NLS-1$//$NON-NLS-2$
    new Throwable("A dummy Throwable"));
    //$NON-NLS-1$
    assertEquals("A dummy IOException", ioException.getMessage());
    try {
        throw new IOException("A dummy error", //$NON-NLS-1$ //$NON-NLS-2$
        new Throwable("Some error message"));
    } catch (IOException e) {
        return;
    } catch (Exception e) {
        fail("Exception during IOException test" + e.toString());
    }
    //$NON-NLS-1$
    fail("Failed to generate exception");
}
Example 4
Project: ikvm-openjdk-master  File: RMIConnectionImpl_Stub.java View source code
// methods from remote interfaces
// implementation of addNotificationListener(ObjectName, ObjectName, MarshalledObject, MarshalledObject, Subject)
public void addNotificationListener(javax.management.ObjectName $param_ObjectName_1, javax.management.ObjectName $param_ObjectName_2, java.rmi.MarshalledObject $param_MarshalledObject_3, java.rmi.MarshalledObject $param_MarshalledObject_4, javax.security.auth.Subject $param_Subject_5) throws java.io.IOException, javax.management.InstanceNotFoundException {
    try {
        ref.invoke(this, $method_addNotificationListener_0, new java.lang.Object[] { $param_ObjectName_1, $param_ObjectName_2, $param_MarshalledObject_3, $param_MarshalledObject_4, $param_Subject_5 }, -8578317696269497109L);
    } catch (java.lang.RuntimeException e) {
        throw e;
    } catch (java.io.IOException e) {
        throw e;
    } catch (javax.management.InstanceNotFoundException e) {
        throw e;
    } catch (java.lang.Exception e) {
        throw new java.rmi.UnexpectedException("undeclared checked exception", e);
    }
}
Example 5
Project: openjdk8-jdk-master  File: ForceLogSnapshot_Skel.java View source code
public void dispatch(java.rmi.Remote obj, java.rmi.server.RemoteCall call, int opnum, long hash) throws java.lang.Exception {
    if (opnum < 0) {
        if (hash == 8484760490859430950L) {
            opnum = 0;
        } else if (hash == -1519179153769139224L) {
            opnum = 1;
        } else {
            throw new java.rmi.UnmarshalException("invalid method hash");
        }
    } else {
        if (hash != interfaceHash)
            throw new java.rmi.server.SkeletonMismatchException("interface hash mismatch");
    }
    ForceLogSnapshot server = (ForceLogSnapshot) obj;
    switch(opnum) {
        case // crash()
        0:
            {
                call.releaseInputStream();
                server.crash();
                try {
                    call.getResultStream(true);
                } catch (java.io.IOException e) {
                    throw new java.rmi.MarshalException("error marshalling return", e);
                }
                break;
            }
        case // ping(int, String)
        1:
            {
                int $param_int_1;
                java.lang.String $param_String_2;
                try {
                    java.io.ObjectInput in = call.getInputStream();
                    $param_int_1 = in.readInt();
                    $param_String_2 = (java.lang.String) in.readObject();
                } catch (java.io.IOException e) {
                    throw new java.rmi.UnmarshalException("error unmarshalling arguments", e);
                } catch (java.lang.ClassNotFoundException e) {
                    throw new java.rmi.UnmarshalException("error unmarshalling arguments", e);
                } finally {
                    call.releaseInputStream();
                }
                server.ping($param_int_1, $param_String_2);
                try {
                    call.getResultStream(true);
                } catch (java.io.IOException e) {
                    throw new java.rmi.MarshalException("error marshalling return", e);
                }
                break;
            }
        default:
            throw new java.rmi.UnmarshalException("invalid method number");
    }
}
Example 6
Project: schach-master  File: NXTSamba.java View source code
/**
     * Open the specified USB device and check that it is in SAM-BA mode. We
     * switch the device into "quiet" mode and also download the FlashWrite
     * program.
     * @param nxt Device to open.
     * @return true if the device is now open, false otherwise.
     * @throws java.io.IOException
     */
public boolean open(NXTInfo nxt) throws IOException {
    if (nxtComm.open(nxt, NXTComm.RAW)) {
        try {
            // We first set the device to interactive/text mode verbose mode
            // (which is the default) and wait for the prompt. This is safe no matter
            // whether the device originally is in interactive or quiet mode.
            // Then we switch back to quiet mode and ask for the version string.
            // This matches the behavior of the original SAM-BA software
            // Switch into quiet mode, NXT may answer with line-feed if in verbose mode
            sendInitCommand(CMD_TEXT);
            while (!endsWithPrompt(read())) {
            /* wait for prompt */
            }
            // Switch into quiet mode, NXT may answer with line-feed if in verbose mode
            sendInitCommand(CMD_NON_TEXT);
            //discard response
            readLine();
            // Ask for version number, terminated by line-feed
            sendInitCommand(CMD_VERSION);
            // Example version string: "v1.4 Nov 10 2004 14:49:33"
            version = readLine().trim();
            // strip everything after the first whitespace 
            version = version.replaceAll("\\s.*", "");
            // Check that we are all in sync
            System.out.println("Connected to SAM-BA " + version);
            // Now upload the flash writer helper routine
            writeBytes(HELPER_CODEADR, getModifiedHelper());
            // And set the the clock into PLL/2 mode ready for writing
            writeWord(0xfffffc30, 0x7);
            return true;
        } catch (IOException e) {
        }
        // Unable to sync things make sure the device is closed.
        nxtComm.close();
    }
    return false;
}
Example 7
Project: jeboorker-master  File: TextUtils.java View source code
public static StringBuilder removePageNumbers(String text) {
    StringBuilder result = new StringBuilder();
    try (BufferedReader textReader = new BufferedReader(new StringReader(text))) {
        String line;
        for (int i = 1; (line = trim(textReader.readLine())) != null; ) {
            int num = NumberUtils.toInt(line, -1);
            if (num == i) {
                i++;
                continue;
            }
            result.append(line).append(StringUtil.NEW_LINE);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return result;
}
Example 8
Project: jeql-master  File: DbfFile.java View source code
/**
            * Fetches a part column of Integers from the database file.
            * @param int col - the column to fetch
            * @param int start - the row to start fetching from
            * @param int end - the row to stop fetching at.
            * @exception java.io.IOException - on read error
            * @exception DbfFileException - column is not an Integer.
            */
public Integer[] getIntegerCol(int col, int start, int end) throws java.io.IOException, DbfFileException {
    Integer[] column = new Integer[end - start];
    String record = new String();
    StringBuffer sb = new StringBuffer(numfields);
    int k = 0;
    int i = 0;
    if (col >= numfields) {
        throw new DbfFileException("DbFi>No Such Column in file: " + col);
    }
    if (fielddef[col].fieldtype != 'N') {
        throw new DbfFileException("DbFi>Column " + col + " is not Integer");
    }
    // move to start of data
    try {
        rFile.seek(data_offset + (rec_size * start));
        for (i = start; i < end; i++) {
            sb.setLength(0);
            for (k = 0; k < rec_size; k++) sb.append((char) rFile.readUnsignedByte());
            record = sb.toString();
            try {
                column[i - start] = new Integer(record.substring(fielddef[col].fieldstart, fielddef[col].fieldstart + fielddef[col].fieldlen));
            } catch (java.lang.NumberFormatException e) {
                column[i - start] = new Integer(0);
            }
        }
    } catch (java.io.EOFException e) {
        System.err.println("DbFi>" + e);
        System.err.println("DbFi>record " + i + " byte " + k + " file pos " + rFile.getFilePointer());
    } catch (java.io.IOException e) {
        System.err.println("DbFi>" + e);
        System.err.println("DbFi>record " + i + " byte " + k + " file pos " + rFile.getFilePointer());
    }
    return column;
}
Example 9
Project: gpu-garbage-collection-master  File: TestSerialization.java View source code
public static void main(String[] args) throws Exception {
    //Uncomment when need to generate serialized data from jdk again
    /*
    try {
      final ObjectOutputStream output = new ObjectOutputStream(new java.io.FileOutputStream("MySerializationData.dat"));
      output.writeObject(new SerializationData());
      output.close();
    } catch (java.io.IOException e) {
      e.printStackTrace(System.out);
    }
*/
    final byte[] data = loadData();
    try {
        final ObjectInputStream input = new ObjectInputStream(new ByteArrayInputStream(data));
        System.out.println("Attemping read");
        final SerializationData ts = (SerializationData) input.readObject();
        System.out.println("Existing serialization read");
        System.out.println(ts);
    } catch (java.io.IOException e) {
        e.printStackTrace(System.out);
    } catch (ClassNotFoundException e) {
        e.printStackTrace(System.out);
    }
    byte[] bytes = new byte[0];
    try {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final ObjectOutputStream output = new ObjectOutputStream(baos);
        System.out.println("Attemping write");
        SerializationData sd = new SerializationData();
        sd.jitter();
        output.writeObject(sd);
        output.flush();
        output.close();
        bytes = baos.toByteArray();
        System.out.println("write success. Checking consistency of data written ...");
        System.out.println("actual.length (" + bytes.length + ") vs expected.length (" + data.length);
        for (int i = 0; i < data.length && i < bytes.length; i++) {
            if (data[i] != bytes[i]) {
                System.out.println("data differs at " + i);
                break;
            }
        }
    } catch (java.io.IOException e) {
        e.printStackTrace(System.out);
    }
    try {
        final ObjectInputStream input = new ObjectInputStream(new ByteArrayInputStream(bytes));
        System.out.println("Attemping read of output data");
        final SerializationData ts = (SerializationData) input.readObject();
        System.out.println("Existing serialization read");
        System.out.println(ts);
    } catch (java.io.IOException e) {
        e.printStackTrace(System.out);
    } catch (ClassNotFoundException e) {
        e.printStackTrace(System.out);
    }
}
Example 10
Project: android_packages_apps-master  File: NdefPushProtocol.java View source code
public byte[] toByteArray() {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream(1024);
    DataOutputStream output = new DataOutputStream(buffer);
    try {
        output.writeByte(VERSION);
        output.writeInt(mNumMessages);
        for (int i = 0; i < mNumMessages; i++) {
            output.writeByte(mActions[i]);
            byte[] bytes = mMessages[i].toByteArray();
            output.writeInt(bytes.length);
            output.write(bytes);
        }
    } catch (java.io.IOException e) {
        return null;
    }
    return buffer.toByteArray();
}
Example 11
Project: sonar-java-master  File: FileCreateTempFileCheck_no_version.java View source code
private void noncompliant() throws IOException {
    File tempDir;
    tempDir = (File.createTempFile("", "."));
    tempDir.delete();
    // Noncompliant [[sc=13;ec=18]] {{Use "Files.createTempDirectory" or a library function to create this directory instead. (sonar.java.source not set. Assuming 7 or greater.)}}
    tempDir.mkdir();
    File tempDir2 = File.createTempFile("", ".");
    tempDir2.delete();
    // Noncompliant
    tempDir2.mkdir();
    // issue already raised
    tempDir2.mkdir();
    b = File.createTempFile("", ".");
    b.delete();
    A a = new A() {

        private void noncompliant() throws IOException {
            b = File.createTempFile("", ".");
            b.delete();
            // Noncompliant
            b.mkdir();
        }
    };
    // Noncompliant
    b.mkdir();
    // issue already raised
    b.mkdir();
}
Example 12
Project: openjdk-master  File: ImplicitFinal.java View source code
public static void main(String... args) {
    try (ImplicitFinal r = new ImplicitFinal()) {
        //disallowed
        r = null;
    } catch (// Not reachable
    IOException // Not reachable
    ioe) {
        throw new AssertionError("Shouldn't reach here", ioe);
    }
    try (@SuppressWarnings("unchecked") ImplicitFinal r1 = new ImplicitFinal()) {
        //disallowed
        r1 = null;
    } catch (// Not reachable
    IOException // Not reachable
    ioe) {
        throw new AssertionError("Shouldn't reach here", ioe);
    }
    try (final ImplicitFinal r2 = new ImplicitFinal()) {
        //disallowed
        r2 = null;
    } catch (// Not reachable
    IOException // Not reachable
    ioe) {
        throw new AssertionError("Shouldn't reach here", ioe);
    }
    try (@SuppressWarnings("unchecked") final ImplicitFinal r3 = new ImplicitFinal()) {
        //disallowed
        r3 = null;
    } catch (// Not reachable
    IOException // Not reachable
    ioe) {
        throw new AssertionError("Shouldn't reach here", ioe);
    }
}
Example 13
Project: oobd-master  File: JcaCRLStore.java View source code
private static Collection convertCRLs(Collection collection) throws CRLException {
    List list = new ArrayList(collection.size());
    for (Iterator it = collection.iterator(); it.hasNext(); ) {
        Object crl = it.next();
        if (crl instanceof X509CRL) {
            try {
                list.add(new X509CRLHolder(((X509CRL) crl).getEncoded()));
            } catch (IOException e) {
                throw new CRLException("cannot read encoding: " + e.getMessage());
            }
        } else {
            list.add((X509CRLHolder) crl);
        }
    }
    return list;
}
Example 14
Project: bixie-master  File: MainClassTest.java View source code
@Test
public void test() {
    final File source_file = new File(testRoot + "ic_java/true_positives/TruePositives02.java");
    File classFileDir = null;
    try {
        classFileDir = compileJavaFile(source_file);
        Bixie.main(new String[] { "-j", classFileDir.getAbsolutePath(), "-logProver", "test" });
    } catch (IOException e) {
        e.printStackTrace();
        fail("Not yet implemented");
    } finally {
        if (classFileDir != null) {
            try {
                delete(classFileDir);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
Example 15
Project: android-platform-tools-base-master  File: Lib2b.java View source code
private static String getContent() {
    InputStream input = Lib2b.class.getResourceAsStream("Lib2b.txt");
    if (input == null) {
        return "FAILED TO FIND Lib2b.txt";
    }
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
        return reader.readLine();
    } catch (IOException e) {
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
            }
        }
    }
    return "FAILED TO READ CONTENT";
}
Example 16
Project: FTL-Hyperion-master  File: ReconnectTest.java View source code
public void testReconnect() throws IOException {
    final Timer timer = new Timer();
    final Server server = new Server();
    startEndPoint(server);
    server.bind(tcpPort);
    server.addListener(new Listener() {

        public void connected(final Connection connection) {
            timer.schedule(new TimerTask() {

                public void run() {
                    System.out.println("Disconnecting after 2 seconds.");
                    connection.close();
                }
            }, 2000);
        }
    });
    // ----
    final AtomicInteger reconnetCount = new AtomicInteger();
    final Client client = new Client();
    startEndPoint(client);
    client.addListener(new Listener() {

        public void disconnected(Connection connection) {
            if (reconnetCount.getAndIncrement() == 2) {
                stopEndPoints();
                return;
            }
            new Thread() {

                public void run() {
                    try {
                        System.out.println("Reconnecting: " + reconnetCount.get());
                        client.reconnect();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }.start();
        }
    });
    client.connect(5000, host, tcpPort);
    waitForThreads(10000);
    assertEquals(3, reconnetCount.getAndIncrement());
}
Example 17
Project: geotools-old-master  File: TypeNameChooser.java View source code
public static String showTypeNameChooser(DataStore dataStore) {
    if (dataStore == null) {
        // could not connect
        return null;
    }
    String typeNames[];
    try {
        typeNames = dataStore.getTypeNames();
    } catch (IOException e) {
        return null;
    }
    if (typeNames.length == 0) {
        // could not connect
        return null;
    }
    if (typeNames.length == 1) {
        // no need to choose only one option
        return typeNames[0];
    } else {
        String typeName = (String) JOptionPane.showInputDialog(null, "Please select a type name.", "Type Name", JOptionPane.QUESTION_MESSAGE, null, typeNames, typeNames[0]);
        return typeName;
    }
}
Example 18
Project: hdt-java-master  File: HDTGenerateIndex.java View source code
public static void main(String[] args) {
    try {
        if (args.length != 1) {
            System.out.println("HDTGenerateIndex <hdtFile>");
            System.exit(-1);
        }
        String hdtFileName = args[0];
        HDT hdt = HDTManager.mapHDT(hdtFileName, null);
        if (hdtFileName.endsWith(".gz")) {
            hdtFileName = hdtFileName.substring(0, hdtFileName.length() - 3);
        }
        System.out.println("Generating " + hdtFileName + ".index");
        HDTManager.indexedHDT(hdt, new ProgressListener() {

            @Override
            public void notifyProgress(float level, String message) {
            //					System.out.println(message + "\t"+ Float.toString(level));
            }
        }).close();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(-1);
    }
    ;
}
Example 19
Project: checkstyle-master  File: InputFinalInTryWithResource.java View source code
public static void test() {
    try {
    } catch (RuntimeException e) {
    }
    try (@NotNull BufferedReader br = new BufferedReader(new InputStreamReader(null, "utf-8"))) {
    } catch (IOException e) {
    }
    try (final BufferedReader br = new BufferedReader(new InputStreamReader(null, "utf-8"))) {
    } catch (IOException e) {
    }
    try (final BufferedReader br = new BufferedReader(new InputStreamReader(null, "utf-8"));
        final BufferedReader br2 = new BufferedReader(new InputStreamReader(null, "utf-8"))) {
    } catch (IOException e) {
    }
}
Example 20
Project: metrics-master  File: InstrumentedResource.java View source code
@GET
@ExceptionMetered(cause = IOException.class)
@Path("/exception-metered")
public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) throws IOException {
    if (splode) {
        throw new IOException("AUGH");
    }
    return "fuh";
}
Example 21
Project: tapestry-facebook-master  File: Channel.java View source code
Object onActivate() {
    return new StreamResponse() {

        public String getContentType() {
            return "text/html";
        }

        public InputStream getStream() throws IOException {
            return new ByteArrayInputStream(response.getBytes());
        }

        public void prepareResponse(Response response) {
            Date date = new Date();
            response.setDateHeader("Expires", date.getTime() + (maxAge * 1000));
            response.setHeader("Cache-Control", "max-age=" + maxAge);
            response.setHeader("Pragma", "public");
        }
    };
}
Example 22
Project: my-ministry-assistant-master  File: DailyBackupService.java View source code
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    File intDB = getApplicationContext().getDatabasePath(MinistryDatabase.DATABASE_NAME);
    File extDB = FileUtils.getExternalDBFile(getApplicationContext(), "auto-daily.db");
    try {
        if (extDB != null) {
            if (!extDB.exists())
                extDB.createNewFile();
            FileUtils.copyFile(intDB, extDB);
        }
    } catch (IOException e) {
        Toast.makeText(getApplicationContext(), "Error during daily backup", Toast.LENGTH_LONG).show();
    }
    return Service.START_NOT_STICKY;
}
Example 23
Project: snap-desktop-master  File: DesktopHelper.java View source code
public static void browse(String uriString) {
    final Desktop desktop = Desktop.getDesktop();
    URI uri;
    try {
        uri = new URI(uriString);
    } catch (URISyntaxException e) {
        Dialogs.showError(String.format("Internal error: Invalid URI:\n%s", uriString));
        return;
    }
    try {
        desktop.browse(uri);
    } catch (IOException e) {
        Dialogs.showError(String.format("<html>Failed to open URL in browser:<br><a href=\"%s\">%s</a>", uriString, uriString));
    } catch (UnsupportedOperationException e) {
        Dialogs.showError("Sorry, it seems that there is no browser available.");
    }
}
Example 24
Project: download-manager-master  File: CheckedWriter.java View source code
@Override
public DownloadTask.State write(DownloadTask.State state, byte[] buffer, int count) throws StopRequestException {
    spaceVerifier.verifySpacePreemptively(count);
    boolean forceVerified = false;
    while (true) {
        try {
            state.gotData = true;
            outputStream.write(buffer, 0, count);
            state.currentBytes += count;
            return state;
        } catch (IOException ex) {
            if (!forceVerified) {
                spaceVerifier.verifySpace(count);
                forceVerified = true;
            } else {
                throw new StopRequestException(DownloadStatus.FILE_ERROR, "Failed to write data: " + ex);
            }
        }
    }
}
Example 25
Project: flare-spork-master  File: TableStorageParserTokenManager.java View source code
private int jjMoveStringLiteralDfa1_0(long active0) {
    try {
        curChar = input_stream.readChar();
    } catch (java.io.IOException e) {
        jjStopStringLiteralDfa_0(0, active0);
        return 1;
    }
    switch(curChar) {
        case 69:
        case 101:
            return jjMoveStringLiteralDfa2_0(active0, 0x13400L);
        case 73:
        case 105:
            return jjMoveStringLiteralDfa2_0(active0, 0xc000L);
        case 79:
        case 111:
            return jjMoveStringLiteralDfa2_0(active0, 0x200L);
        case 83:
        case 115:
            if ((active0 & 0x20000L) != 0L) {
                jjmatchedKind = 17;
                jjmatchedPos = 1;
            }
            return jjMoveStringLiteralDfa2_0(active0, 0x800L);
        default:
            break;
    }
    return jjStartNfa_0(0, active0);
}
Example 26
Project: RedReader-master  File: JsonBufferedArray.java View source code
public boolean hasNext() {
    synchronized (JsonBufferedArray.this) {
        while (getStatus() == STATUS_LOADING && items <= currentId) {
            try {
                JsonBufferedArray.this.wait();
            } catch (final InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        if (getStatus() == STATUS_FAILED) {
            try {
                throwFailReasonException();
            } catch (final IOException e) {
                throw new RuntimeException(e);
            }
        }
        return items > currentId;
    }
}
Example 27
Project: TextSecureSMP-master  File: EncryptingJobSerializer.java View source code
@Override
public Job deserialize(EncryptionKeys keys, boolean encrypted, String serialized) throws IOException {
    try {
        String plaintext;
        if (encrypted) {
            MasterSecret masterSecret = ParcelUtil.deserialize(keys.getEncoded(), MasterSecret.CREATOR);
            MasterCipher masterCipher = new MasterCipher(masterSecret);
            plaintext = masterCipher.decryptBody(serialized);
        } else {
            plaintext = serialized;
        }
        return delegate.deserialize(keys, encrypted, plaintext);
    } catch (InvalidMessageException e) {
        throw new IOException(e);
    }
}
Example 28
Project: Technomap-master  File: JavaCharStream.java View source code
static final int hexval(char c) throws java.io.IOException {
    switch(c) {
        case '0':
            return 0;
        case '1':
            return 1;
        case '2':
            return 2;
        case '3':
            return 3;
        case '4':
            return 4;
        case '5':
            return 5;
        case '6':
            return 6;
        case '7':
            return 7;
        case '8':
            return 8;
        case '9':
            return 9;
        case 'a':
        case 'A':
            return 10;
        case 'b':
        case 'B':
            return 11;
        case 'c':
        case 'C':
            return 12;
        case 'd':
        case 'D':
            return 13;
        case 'e':
        case 'E':
            return 14;
        case 'f':
        case 'F':
            return 15;
    }
    // Should never come here
    throw new java.io.IOException();
}
Example 29
Project: cloudtm-data-platform-master  File: XmlConfigurator.java View source code
public InputSource resolveEntity(String publicId, String systemId) throws IOException {
    if (systemId != null && systemId.startsWith("http://www.jgroups.org/schema/JGroups-")) {
        String schemaName = systemId.substring("http://www.jgroups.org/".length());
        InputStream schemaIs = getAsInputStreamFromClassLoader(schemaName);
        if (schemaIs == null) {
            throw new IOException("Schema not found from classloader: " + schemaName);
        }
        InputSource source = new InputSource(schemaIs);
        source.setPublicId(publicId);
        source.setSystemId(systemId);
        return source;
    }
    return null;
}
Example 30
Project: SimpleRep-master  File: DynAbcastReplacer.java View source code
public void interceptCall(DynAbcastCallParameters params, Message dmessage) {
    synchronized (this.parent) {
        try {
            dmessage.content = new SequencedMessage(dmessage.content, new TInteger(sendSeqNumber));
            undeliveredMessages.add((Message) deepClone(dmessage));
            undeliveredType.add(params.type);
            undeliveredPID.add(params.pid);
            forwardCall(params, dmessage);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException("Can not abcast this message!");
        } catch (IOException ex) {
            ex.printStackTrace();
            throw new RuntimeException("Can not abcast this message!" + ex.getMessage());
        }
    }
}
Example 31
Project: android_platform_libcore-master  File: Support_StringReader.java View source code
/**
     * Reads at most <code>count</code> characters from this StringReader and
     * stores them at <code>offset</code> in the character array
     * <code>buf</code>. Returns the number of characters actually read or -1
     * if the end of reader was encountered.
     *
     * @param buf
     *            character array to store the read characters
     * @param offset
     *            offset in buf to store the read characters
     * @param count
     *            maximum number of characters to read
     * @return the number of characters read or -1 if end of reader.
     *
     * @exception java.io.IOException
     *                If the StringReader is closed.
     */
@Override
public int read(char buf[], int offset, int count) throws IOException {
    // avoid int overflow
    if (0 <= offset && offset <= buf.length && 0 <= count && count <= buf.length - offset) {
        synchronized (lock) {
            if (isOpen()) {
                if (pos == this.count) {
                    return -1;
                }
                int end = pos + count > this.count ? this.count : pos + count;
                str.getChars(pos, end, buf, offset);
                int read = end - pos;
                pos = end;
                return read;
            }
            throw new IOException("StringReader is closed");
        }
    }
    throw new ArrayIndexOutOfBoundsException();
}
Example 32
Project: sosies-generator-master  File: TaggedIOExceptionTest.java View source code
public void testTaggedIOException() {
    fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(), this, "testTaggedIOException");
    Serializable tag = java.util.UUID.randomUUID();
    IOException exception = new IOException("foo");
    TaggedIOException tagged = new TaggedIOException(exception, tag);
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 5742, null, 5741, org.apache.commons.io.TaggedIOException.isTaggedWith(tagged, tag));
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 5744, null, 5743, org.apache.commons.io.TaggedIOException.isTaggedWith(tagged, java.util.UUID.randomUUID()));
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 5745, exception);
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 5747, tagged, 5746, tagged.getCause());
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 5749, exception, 5748, exception.getMessage());
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 5751, tagged, 5750, tagged.getMessage());
    fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread());
}
Example 33
Project: JBossAS51-master  File: ClientMBeanServerConnection.java View source code
/**
    * Add a notification listener to an MBean.
    *
    * @param name     the name of the MBean broadcasting notifications
    * @param listener the listener to add
    * @param filter   a filter to preprocess notifications
    * @param handback a object to add to any notifications
    * @throws javax.management.InstanceNotFoundException
    *                             if the broadcaster is not registered
    * @throws java.io.IOException for a communication problem during this operation
    */
public void addNotificationListener(ObjectName name, NotificationListener listener, NotificationFilter filter, Object handback) throws InstanceNotFoundException, IOException {
    ClientListenerHolder holder = new ClientListenerHolder(name, listener, filter, handback);
    // properly registered as a listener and can ignore call
    if (clientNotifier.exists(holder)) {
        return;
    } else {
        MarshalledObject marshalledFilter = null;
        if (filter != null) {
            try {
                marshalledFilter = new MarshalledObject(filter);
            } catch (IOException e) {
                holder.setFilterOnClient(true);
            }
        }
        Integer[] listenerIDs = connection.addNotificationListeners(new ObjectName[] { name }, new MarshalledObject[] { marshalledFilter }, new Subject[] { subject });
        clientNotifier.addNotificationListener(listenerIDs[0], holder);
    }
}
Example 34
Project: jade_agents-master  File: ACLParserTokenManager.java View source code
private final int jjMoveStringLiteralDfa1_4(long active0) {
    try {
        curChar = input_stream.readChar();
    } catch (java.io.IOException e) {
        jjStopStringLiteralDfa_4(0, active0);
        return 1;
    }
    switch(curChar) {
        case 65:
        case 97:
            return jjMoveStringLiteralDfa2_4(active0, 0x8000000000000L);
        case 69:
        case 101:
            return jjMoveStringLiteralDfa2_4(active0, 0x1800000000000L);
        case 71:
        case 103:
            return jjMoveStringLiteralDfa2_4(active0, 0x2000000000000L);
        case 78:
        case 110:
            return jjMoveStringLiteralDfa2_4(active0, 0x4000000000000L);
        case 82:
        case 114:
            return jjMoveStringLiteralDfa2_4(active0, 0x10000000000000L);
        default:
            break;
    }
    return jjStartNfa_4(0, active0);
}
Example 35
Project: cloudbees-api-client-master  File: CloudResourceProvider.java View source code
/**
     * Lists up all the cloud resources.
     */
public Iterator<CloudResource> iterator() {
    try {
        JsonNode res = getOwner().retrieve().get("resources");
        if (res == null || !res.isArray())
            throw new IllegalStateException("Expected a JSON array but " + getOwner() + " gave us " + res);
        ReferencedResource[] dto = CloudResource.MAPPER.readValue(res, ReferencedResource[].class);
        List<CloudResource> r = new ArrayList<CloudResource>(dto.length);
        for (ReferencedResource rr : dto) {
            r.add(rr.toCloudResource(getOwner()));
        }
        return r.iterator();
    } catch (IOException e) {
        throw new Error(e);
    }
}
Example 36
Project: openmap-master  File: PNG8ImageFormatter.java View source code
public byte[] formatImage(BufferedImage bi) {
    BufferedImage reducedImage = null;
    if (bi.getColorModel().hasAlpha()) {
        reducedImage = ColorReducer.reduce32(bi, 256);
    } else {
        reducedImage = ColorReducer.reduce24(bi, 256);
    }
    try {
        ByteArrayOutputStream byo = new ByteArrayOutputStream();
        ImageIO.write(reducedImage, getFormatName(), byo);
        return byo.toByteArray();
    } catch (java.io.IOException e) {
        Debug.error("ImageIOFormatter caught IOException formatting image!");
        return new byte[0];
    }
}
Example 37
Project: Mint-Programming-Language-master  File: ExecuteJava.java View source code
@Override
public Pointer apply(SmartList<Pointer> args) throws MintException {
    String programName = PointerTools.dereferenceString(args.get(0));
    programName = programName.trim();
    String className = programName.replace(".java", "");
    if (!programName.endsWith(".java")) {
        programName += ".java";
    }
    try {
        Process jv = Runtime.getRuntime().exec("javac " + programName);
        Process jv2 = Runtime.getRuntime().exec("java " + className);
        BufferedReader in = new BufferedReader(new InputStreamReader(jv2.getInputStream()));
        String line = null;
        int i = 0;
        int limit = Integer.MAX_VALUE >>> 1;
        while (i < limit) {
            line = in.readLine();
            if (line == null) {
                break;
            }
            System.out.println(line);
            i++;
        }
    } catch (IOException ex) {
    }
    return Constants.MINT_NULL;
}
Example 38
Project: SRE-RoboCode-master  File: FileWriteSize.java View source code
public void run() {
    out.println("Data directory: " + getDataDirectory());
    out.println("Data quota: " + getDataQuotaAvailable());
    byte[] buf = new byte[100000];
    File file = null;
    RobocodeFileOutputStream rfos = null;
    try {
        file = getDataFile("test");
        out.println("Data file: " + file.getCanonicalPath());
        file.delete();
        rfos = new RobocodeFileOutputStream(file);
        for (int i = 0; i < 3; i++) {
            rfos.write(buf);
        }
    } catch (IOException e) {
        e.printStackTrace(out);
    } finally {
        if (rfos != null) {
            try {
                rfos.close();
            } catch (IOException e) {
                e.printStackTrace(out);
            }
        }
        if (file != null) {
            if (!file.delete()) {
                out.println("Could not delete the file: " + file);
            }
        }
    }
}
Example 39
Project: MyDownload-master  File: Utils.java View source code
public static String getRawData(String string) {
    String dataString = "";
    try {
        URL url;
        url = new URL(string);
        URLConnection conn = url.openConnection();
        // conn.connect();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        byte buffer[] = new byte[1024];
        String readerString;
        while ((readerString = reader.readLine()) != null) {
            dataString += readerString;
        }
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
        log("IOException", "" + e);
    }
    log("getRawData", dataString);
    return dataString;
}
Example 40
Project: molgenis-master  File: XmlMolgenisUiLoader.java View source code
public Molgenis load() throws IOException {
    InputStream xsdStream = this.getClass().getResourceAsStream(UI_XSD);
    if (xsdStream == null)
        throw new IOException("unable to find " + UI_XSD);
    try {
        InputStream xmlStream = this.getClass().getResourceAsStream(UI_XML);
        if (xmlStream == null)
            throw new IOException("unable to find " + UI_XML);
        try {
            SchemaLoader schemaLoader = new SchemaLoader(xsdStream);
            Schema molgenisUiSchema = schemaLoader.getSchema();
            JAXBContext jaxbContext = JAXBContext.newInstance(Molgenis.class);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            unmarshaller.setSchema(molgenisUiSchema);
            return unmarshaller.unmarshal(new StreamSource(xmlStream), Molgenis.class).getValue();
        } catch (JAXBException e) {
            throw new IOException(e);
        } finally {
            IOUtils.closeQuietly(xmlStream);
        }
    } finally {
        IOUtils.closeQuietly(xsdStream);
    }
}
Example 41
Project: hank-master  File: Hank.java View source code
public static String getProperty(String property) {
    try {
        Enumeration<URL> manifestStream = Hank.class.getClassLoader().getResources("META-INF/MANIFEST.MF");
        if (!manifestStream.hasMoreElements()) {
            return "No Manifest";
        }
        while (manifestStream.hasMoreElements()) {
            Manifest manifest = new Manifest(manifestStream.nextElement().openStream());
            Attributes attributes = manifest.getMainAttributes();
            String title = attributes.getValue("Implementation-Title");
            if (title != null && isValidTitle(title)) {
                String temp = attributes.getValue(property);
                if (temp != null) {
                    return temp;
                } else {
                    return "Not in Manifest";
                }
            }
        }
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    return "Unknown";
}
Example 42
Project: MyFramework-master  File: FreeMarkerConfig.java View source code
/***�1�7
     * @param templateDirPath
     * @throws ConfigureException
     */
public void configureFreeMarker(String templateDirPath) throws Exception {
    if (null == templateDirPath || "".equals(templateDirPath)) {
        throw new Exception("FreeMarker template directory not exist:" + templateDirPath);
    }
    File templateDir = new File(templateDirPath);
    if (null == templateDir || !templateDir.exists() || !templateDir.isDirectory()) {
        throw new Exception("FreeMarker template directory not exist:" + templateDirPath);
    }
    // Configure the template engine
    Configuration templateCfg = new Configuration();
    try {
        BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
        wrapper.setSimpleMapWrapper(true);
        wrapper.setExposureLevel(BeansWrapper.EXPOSE_ALL);
        templateCfg.setEncoding(Locale.CHINA, "utf-8");
        templateCfg.setObjectWrapper(wrapper);
        templateCfg.setDirectoryForTemplateLoading(templateDir);
        templateCfg.setNumberFormat("######################.##");
    } catch (IOException e) {
        throw new Exception("IOException occured when loading freemarker template:" + templateDirPath);
    }
    templateCfg.setTemplateUpdateDelay(2);
    Configuration.setDefaultConfiguration(templateCfg);
}
Example 43
Project: LambdaDojo-master  File: S205LambdaForStrategy.java View source code
private void useContainer() {
    Container<String> container = new Container<>("Hello, World!");
    container.output(new Consumer<String>() {

        @Override
        public void accept(String value) {
            System.out.println(value);
        }
    });
    final String filename = "container.txt";
    container.output(new Consumer<String>() {

        @Override
        public void accept(String value) {
            try {
                Path path = Paths.get(filename);
                Files.write(path, value.getBytes());
            } catch (IOException ex) {
                System.err.println("printに失敗しました");
            }
        }
    });
}
Example 44
Project: liferay-ide-master  File: FindJavaProblemsHandler.java View source code
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    try {
        Liferay7UpgradeAssistantSettings settings = UpgradeAssistantSettingsUtil.getObjectFromStore(Liferay7UpgradeAssistantSettings.class);
        String[] projectLocations = settings.getJavaProjectLocations();
        List<IPath> locations = new ArrayList<>();
        for (String projectLocation : projectLocations) {
            locations.add(new Path(projectLocation));
        }
        new MigrateProjectHandler().findMigrationProblems(locations.toArray(new IPath[0]));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
Example 45
Project: jdroid-master  File: CacheParser.java View source code
/**
	 * @see Parser#parse(java.io.InputStream)
	 */
@Override
public Object parse(InputStream inputStream) {
    final InputStream inputStreamCopy = FileUtils.copy(inputStream);
    Object object = parser.parse(inputStreamCopy);
    ExecutorUtils.execute(new Runnable() {

        @Override
        public void run() {
            try {
                inputStreamCopy.reset();
            } catch (IOException e) {
                LoggerUtils.logHandledException(LOGGER, e);
            }
            FileUtils.copyStream(inputStreamCopy, cacheFile);
            LOGGER.debug("Saved http request to cache file: " + cacheFile.getAbsolutePath());
        }
    });
    return object;
}
Example 46
Project: AudioPlayer-master  File: QianQianParser.java View source code
public static List<LyricResults> parseXml(String xml) {
    List<LyricResults> list = new ArrayList<LyricResults>();
    try {
        XmlPullParser xrp = XmlPullParserFactory.newInstance().newPullParser();
        xrp.setInput(new StringReader(xml));
        // 直到文档的结尾处
        while (xrp.getEventType() != XmlResourceParser.END_DOCUMENT) {
            // 如果遇到了开始标签
            if (xrp.getEventType() == XmlResourceParser.START_TAG) {
                String // 获取标签的名字
                tagName = // 获取标签的名字
                xrp.getName();
                if (tagName.equals("lrc")) {
                    LyricResults result = new LyricResults();
                    result.id = Integer.valueOf(// 通过属性名来获取属性值
                    xrp.getAttributeValue(// 通过属性名来获取属性值
                    0));
                    result.artist = // 通过属性索引来获取属性值
                    xrp.getAttributeValue(// 通过属性索引来获取属性值
                    1);
                    result.track = xrp.getAttributeValue(2);
                    list.add(result);
                }
            }
            // 获取解析下一个事件
            xrp.next();
        }
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return list.size() == 0 ? null : list;
}
Example 47
Project: android-15-master  File: CarouselViewUtilities.java View source code
/**
     * Debug utility to write the given bitmap to a file.
     *
     * @param context calling context
     * @param bitmap the bitmap to write
     * @param filename the name of the file to write
     * @return
     */
public static boolean writeBitmapToFile(Context context, Bitmap bitmap, String filename) {
    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    File file = new File(path, filename);
    boolean result = false;
    try {
        path.mkdirs();
        OutputStream os = new FileOutputStream(file);
        MediaScannerConnection.scanFile(context, new String[] { file.toString() }, null, null);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
        result = true;
    } catch (IOException e) {
        Log.w("ExternalStorage", "Error writing " + file, e);
    }
    return result;
}
Example 48
Project: afwall-master  File: FAQFragment.java View source code
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    TextView text = (TextView) getActivity().findViewById(R.id.faq_afwall_title);
    text.setText(R.string.faq);
    WebView creditsWebView = (WebView) getActivity().findViewById(R.id.faq_webview);
    try {
        String data = Api.loadData(getActivity().getBaseContext(), "faq");
        creditsWebView.loadDataWithBaseURL(null, data, "text/html", "UTF-8", null);
    } catch (IOException ioe) {
        Log.e(TAG, "Error reading changelog file!", ioe);
    }
}
Example 49
Project: cafeUnoesc-master  File: ThreadTwitter.java View source code
@Override
public void run() {
    int i = 0;
    while (ativar) {
        try {
            System.out.println("........");
            System.out.println("Vericicação Nº " + i++);
            Util u = new Util();
            u.buscarTweet("@CafeUnoesc");
            Thread.sleep(5000);
        } catch (TwitterException ex) {
            Logger.getLogger(ThreadTwitter.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
            Logger.getLogger(ThreadTwitter.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnknownHostException ex) {
            Logger.getLogger(ThreadTwitter.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ThreadTwitter.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
Example 50
Project: tio_patinhas-master  File: CClienteSocket.java View source code
public CArquivosTeste RecebeArquivosTeste() {
    try {
        conCliente = new Socket(hostname, porta);
        // Pega Os Streams de Leitura e escrita
        // Essa parte deve ter algo parecido no servidor
        // na hora de receber/enviar os dados
        ois = new ObjectInputStream(conCliente.getInputStream());
        return (CArquivosTeste) ois.readObject();
    } catch (UnknownHostException ex) {
        Logger.getLogger(CClienteSocket.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(CClienteSocket.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(CClienteSocket.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}
Example 51
Project: classlib6-master  File: DGCImpl_Skel.java View source code
public void dispatch(java.rmi.Remote obj, java.rmi.server.RemoteCall call, int opnum, long hash) throws java.lang.Exception {
    if (opnum < 0) {
        if (hash == -5803803475088455571L) {
            opnum = 0;
        } else if (hash == -8139341527526761862L) {
            opnum = 1;
        } else {
            throw new java.rmi.server.SkeletonMismatchException("interface hash mismatch");
        }
    } else if (hash != interfaceHash) {
        throw new java.rmi.server.SkeletonMismatchException("interface hash mismatch");
    }
    gnu.java.rmi.dgc.DGCImpl server = (gnu.java.rmi.dgc.DGCImpl) obj;
    switch(opnum) {
        case 0:
            {
                java.rmi.server.ObjID[] $param_0;
                long $param_1;
                java.rmi.dgc.VMID $param_2;
                boolean $param_3;
                try {
                    java.io.ObjectInput in = call.getInputStream();
                    $param_0 = (java.rmi.server.ObjID[]) in.readObject();
                    $param_1 = (long) in.readLong();
                    $param_2 = (java.rmi.dgc.VMID) in.readObject();
                    $param_3 = (boolean) in.readBoolean();
                } catch (java.io.IOException e) {
                    throw new java.rmi.UnmarshalException("error unmarshalling arguments", e);
                } catch (java.lang.ClassCastException e) {
                    throw new java.rmi.UnmarshalException("error unmarshalling arguments", e);
                } finally {
                    call.releaseInputStream();
                }
                server.clean($param_0, $param_1, $param_2, $param_3);
                try {
                    java.io.ObjectOutput out = call.getResultStream(true);
                } catch (java.io.IOException e) {
                    throw new java.rmi.MarshalException("error marshalling return", e);
                }
                break;
            }
        case 1:
            {
                java.rmi.server.ObjID[] $param_0;
                long $param_1;
                java.rmi.dgc.Lease $param_2;
                try {
                    java.io.ObjectInput in = call.getInputStream();
                    $param_0 = (java.rmi.server.ObjID[]) in.readObject();
                    $param_1 = (long) in.readLong();
                    $param_2 = (java.rmi.dgc.Lease) in.readObject();
                } catch (java.io.IOException e) {
                    throw new java.rmi.UnmarshalException("error unmarshalling arguments", e);
                } catch (java.lang.ClassCastException e) {
                    throw new java.rmi.UnmarshalException("error unmarshalling arguments", e);
                } finally {
                    call.releaseInputStream();
                }
                java.rmi.dgc.Lease $result = server.dirty($param_0, $param_1, $param_2);
                try {
                    java.io.ObjectOutput out = call.getResultStream(true);
                    out.writeObject($result);
                } catch (java.io.IOException e) {
                    throw new java.rmi.MarshalException("error marshalling return", e);
                }
                break;
            }
        default:
            throw new java.rmi.UnmarshalException("invalid method number");
    }
}
Example 52
Project: Android_Blog_Demos-master  File: LargeImageViewSimpleBak.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_large_image_view);
    mImageView = (ImageView) findViewById(R.id.id_imageview);
    try {
        InputStream inputStream = getAssets().open("tangyan.jpg");
        //获得图片的宽、高
        BitmapFactory.Options tmpOptions = new BitmapFactory.Options();
        tmpOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(inputStream, null, tmpOptions);
        int width = tmpOptions.outWidth;
        int height = tmpOptions.outHeight;
        //设置显示图片的中心区域
        BitmapRegionDecoder bitmapRegionDecoder = BitmapRegionDecoder.newInstance(inputStream, false);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        Bitmap bitmap = bitmapRegionDecoder.decodeRegion(new Rect(width / 2 - 100, height / 2 - 100, width / 2 + 100, height / 2 + 100), options);
        mImageView.setImageBitmap(bitmap);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 53
Project: alien4cloud-master  File: ResetTopologyProcessor.java View source code
@Override
public void process(ResetTopologyOperation operation) {
    Topology topology = EditionContextManager.getTopology();
    Topology newTopology = new Topology();
    newTopology.setArchiveName(topology.getArchiveName());
    newTopology.setArchiveVersion(topology.getArchiveVersion());
    newTopology.setWorkspace(topology.getWorkspace());
    workflowBuilderService.initWorkflows(workflowBuilderService.buildTopologyContext(newTopology));
    try {
        EditionContextManager.get().reset(newTopology);
    } catch (IOException e) {
        log.error("Error occurs when trying to reset the topology <" + topology.getId() + ">", e);
    }
}
Example 54
Project: traffic-balance-master  File: JSONRPCSocketServer.java View source code
public void start() throws JSONRPCException {
    synchronized (this) {
        if (!socket.isOpened()) {
            try {
                socket.rebind();
                if (socket.isOpened()) {
                    return;
                }
            } catch (Exception e) {
                return;
            }
        }
    }
    try {
        byte[] buffer = socket.receiveData();
        while (buffer != null && buffer.length > 0) {
            BufferedReader reader = new BufferedReader(new StringReader(new String(buffer)));
            skeleton.processRequest(reader, new PrintWriter(new Writer() {

                @Override
                public void write(char[] cbuf, int off, int len) throws IOException {
                }

                @Override
                public void flush() throws IOException {
                }

                @Override
                public void close() throws IOException {
                }
            }));
            buffer = socket.receiveData();
        }
    } catch (IOException e) {
        throw new JSONRPCException("socket error", e);
    }
}
Example 55
Project: SpaceDefence-master  File: InThread.java View source code
@Override
public void run() {
    try {
        InputStream input = connection.getInputStream();
        while (!connection.isClosed()) {
            byte[] intBytes = new byte[4];
            for (int i = 0; i < 4; i++) {
                intBytes[i] = (byte) input.read();
            }
            int msgLen = ByteBuffer.wrap(intBytes).getInt();
            byte[] msg = new byte[msgLen];
            int read = 0, offset = 0, toRead = msgLen;
            while (toRead > 0 && (read = input.read(msg, offset, toRead)) > 0) {
                toRead -= read;
                offset += read;
            }
            if (read >= 0) {
                monitor.putArrayFromServer(msg);
            } else {
                break;
            // TODO: fix when server dies
            }
        }
    } catch (NegativeArraySizeException nsae) {
        Logger.log("NegativeArraySizeException when declaring msg.");
    } catch (SocketException se) {
        Logger.log("(inthread) insocket already closed");
    } catch (IOException e1) {
        Logger.log("Exception: ");
        e1.printStackTrace();
    } finally {
        monitor.closeConnection();
    }
}
Example 56
Project: adc-wildner-master  File: MainTestUApriori_saveToFile.java View source code
public static void main(String[] arg) throws IOException {
    // Loading the binary context
    UncertainTransactionDatabase context = new UncertainTransactionDatabase();
    try {
        context.loadFile(fileToPath("contextUncertain.txt"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    context.printDatabase();
    String output = ".//output.txt";
    // Applying the UApriori algorithm
    AlgoUApriori apriori = new AlgoUApriori(context);
    apriori.runAlgorithm(0.1, output);
    apriori.printStats();
}
Example 57
Project: astrid-master  File: RepeatTestsGtasksSyncRemote.java View source code
// Test logic in superclass
@Override
protected long setCompletionDate(boolean completeBefore, Task t, com.google.api.services.tasks.model.Task remoteModel, long dueDate) {
    long completionDate;
    if (completeBefore)
        completionDate = dueDate - DateUtilities.ONE_DAY;
    else
        completionDate = dueDate + DateUtilities.ONE_DAY;
    remoteModel.setCompleted(GtasksApiUtilities.unixTimeToGtasksCompletionTime(completionDate));
    remoteModel.setStatus("completed");
    try {
        gtasksService.updateGtask(DEFAULT_LIST, remoteModel);
    } catch (IOException e) {
        e.printStackTrace();
        fail("Exception in gtasks service");
    }
    return completionDate;
}
Example 58
Project: sqlpower-library-master  File: ZealousURLEncoder.java View source code
public static String zealousEncode(String s) {
    if (s == null) {
        return "";
    }
    int maxBytesPerChar = 10;
    StringBuffer out = new StringBuffer(s.length());
    ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar);
    OutputStreamWriter writer = new OutputStreamWriter(buf);
    for (int i = 0; i < s.length(); i++) {
        int c = (int) s.charAt(i);
        if (c == ' ') {
            c = '+';
            out.append((char) c);
        } else {
            // convert to external encoding before hex conversion
            try {
                writer.write(c);
                writer.flush();
            } catch (IOException e) {
                buf.reset();
                continue;
            }
            byte[] ba = buf.toByteArray();
            for (int j = 0; j < ba.length; j++) {
                out.append('%');
                char ch = Character.forDigit((ba[j] >> 4) & 0xF, 16);
                // the hex value if ch is a letter.
                if (Character.isLetter(ch)) {
                    ch -= caseDiff;
                }
                out.append(ch);
                ch = Character.forDigit(ba[j] & 0xF, 16);
                if (Character.isLetter(ch)) {
                    ch -= caseDiff;
                }
                out.append(ch);
            }
            buf.reset();
        }
    }
    return out.toString();
}
Example 59
Project: cdt-tests-runner-master  File: ProjectConverter.java View source code
public IBuildObject convert(IBuildObject buildObj, String fromId, String toId, boolean isConfirmed) {
    String tmpDir = System.getProperty("java.io.tmpdir");
    File outputFile = new File(tmpDir + "/converterOutput.txt");
    try {
        FileWriter out = new FileWriter(outputFile);
        out.write("---------- Start-------");
        out.write("Converter for the build object : '" + buildObj.getName() + "' is invoked.");
        out.write("From Id : " + fromId);
        out.write("To Id : " + toId);
        out.write("---------- End-------");
    } catch (IOException e) {
        System.out.println("Exception raised.");
    }
    return buildObj;
}
Example 60
Project: dcache-master  File: DumpSI.java View source code
public static void main(String[] args) {
    int rc = 1;
    if (args.length != 1) {
        System.err.println("Usage: DumpSI <SI file>");
        System.exit(rc);
    }
    String siFile = args[0];
    try {
        FileInputStream fis = new FileInputStream(siFile);
        ObjectInputStream ois = new ObjectInputStream(fis);
        StorageInfo si = (StorageInfo) ois.readObject();
        ois.close();
        System.out.println();
        System.out.println(si.toString());
        rc = 0;
    } catch (FileNotFoundException fe) {
        System.err.println("File not found : " + fe.getMessage());
    } catch (IOException ie) {
        System.err.println("IO exception : " + ie.getMessage());
    } catch (ClassNotFoundException ce) {
        System.err.println("Not a SI file : " + ce.getMessage());
    }
    System.exit(rc);
}
Example 61
Project: vlc-android-macbuild-master  File: StreamHelper.java View source code
public static String readStreamLineByLine(InputStream inputStream) {
    InputStreamReader reader = new InputStreamReader(inputStream);
    BufferedReader buffReader = new BufferedReader(reader);
    StringBuilder text = new StringBuilder();
    String resultText = null;
    try {
        String line;
        while ((line = buffReader.readLine()) != null) {
            text.append(line);
            text.append('\n');
        }
        resultText = text.toString();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            buffReader.close();
            reader.close();
        } catch (Exception e) {
        }
    }
    return resultText;
}
Example 62
Project: deb-kitkat-storage-access-framework-master  File: InputStreamResponseHandler.java View source code
@Override
public InputStream handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
    HttpEntity entity = response.getEntity();
    StatusLine statusLine = response.getStatusLine();
    boolean successfulResponse = (statusLine.getStatusCode() / 100) == 2;
    if (!successfulResponse) {
        // If it was not a successful response, the response body contains a
        // JSON error message body. Unfortunately, I have to adhere to the interface
        // and I am throwing an IOException in this case.
        String responseBody = EntityUtils.toString(entity);
        throw new IOException(responseBody);
    }
    return entity.getContent();
}
Example 63
Project: node-go-better-than-random-master  File: StreamCopy.java View source code
/** Run method.
        Exceptions caught are written to stderr. */
public void run() {
    try {
        byte buffer[] = new byte[1024];
        while (true) {
            int n = m_src.read(buffer);
            if (n < 0)
                break;
            if (m_verbose)
                System.err.write(buffer, 0, n);
            m_dest.write(buffer, 0, n);
            m_dest.flush();
        }
    } catch (Throwable e) {
        StringUtil.printException(e);
    } finally {
        if (m_close) {
            try {
                m_dest.close();
            } catch (IOException e) {
                StringUtil.printException(e);
            }
        }
    }
}
Example 64
Project: SecurePhoto-master  File: SecurePhotoBaseTests.java View source code
@Test(timeout = 10000)
public void testServerConnectivity() throws Exception {
    Socket clientSocket = null;
    PrintWriter outWriter = null;
    BufferedReader inReader = null;
    String response = null;
    try {
        clientSocket = new Socket("localhost", SPConstants.SERVER_DEFAULT_PORT);
        outWriter = new PrintWriter(clientSocket.getOutputStream(), true);
        inReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        outWriter.println("Testing connectivity");
        response = inReader.readLine();
    } catch (IOException e) {
        throw new Exception("Exception during writing to socket: " + e.getMessage());
    }
    Assert.assertEquals(SPConstants.SERVER_OK_MESSAGE, response);
}
Example 65
Project: castor-master  File: TestCastorReader.java View source code
public static void main(String[] args) {
    try {
        InputSource source = new InputSource(TestCastorReader.class.getResource("test.xsd").toExternalForm());
        SchemaReader schemaReader = new SchemaReader(source);
        schemaReader.setCacheIncludedSchemas(true);
        Schema schema = schemaReader.read();
        System.out.println("**** Schema is loaded successfully");
        int tnum = schema.getSimpleTypes().size();
        System.out.println("**** Total " + tnum + " simply types in the schema.");
        tnum = schema.getComplexTypes().size();
        System.out.println("**** Total " + tnum + " complex types in the schema.");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 66
Project: picard-tools-master  File: AbstractBAMFileIndexTest.java View source code
/**
     * @see <a href="https://github.com/samtools/htsjdk/issues/73">https://github.com/samtools/htsjdk/issues/73</a>
     */
@Test
public static void avoidDataExhaustionTest() {
    final AbstractBAMFileIndex.IndexStreamBuffer buffer = new AbstractBAMFileIndex.IndexStreamBuffer(new SeekableStream() {

        @Override
        public long length() {
            return 0;
        }

        @Override
        public long position() throws IOException {
            return 0;
        }

        @Override
        public void seek(final long position) throws IOException {
        }

        @Override
        public int read(final byte[] buffer, final int offset, final int length) throws IOException {
            // This is the important line; pretend we feed 2 bytes at a time, which is fewer than any downstream calls ultimately request
            return 2;
        }

        @Override
        public void close() throws IOException {
        }

        @Override
        public boolean eof() throws IOException {
            return false;
        }

        @Override
        public String getSource() {
            return null;
        }

        @Override
        public int read() throws IOException {
            return 0;
        }
    });
    // Ensure these throw no exceptions
    buffer.readLong();
    buffer.readInteger();
    buffer.readBytes(new byte[10000]);
}
Example 67
Project: ehour-master  File: LatestVersionFetcherHttpImplTest.java View source code
@Test
public void should_get_latest_version_number() throws Exception {
    Server server = new Server(8100);
    server.setHandler(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            response.setContentType("text/html;charset=utf-8");
            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            response.getWriter().println("1.2.1");
        }
    });
    server.start();
    LatestVersionFetcherHttpImpl fetcherHttp = new LatestVersionFetcherHttpImpl("http://localhost:8100/");
    Optional<String> latestVersionNumber = fetcherHttp.getLatestVersionNumber("1.3", true);
    server.stop();
    assertEquals("1.2.1", StringUtils.chomp(latestVersionNumber.get()));
}
Example 68
Project: tapestry-model-master  File: Blob.java View source code
protected StreamResponse onActivate(Class clazz, String id, String property) throws Exception {
    final Object bean = contextValueEncoder.toValue(clazz, id);
    final TynamoPropertyDescriptor propertyDescriptor = descriptorService.getClassDescriptor(clazz).getPropertyDescriptor(property);
    return new StreamResponse() {

        public String getContentType() {
            return filePersister.getContentType(propertyDescriptor, bean);
        }

        public InputStream getStream() throws IOException {
            return new ByteArrayInputStream(filePersister.getData(propertyDescriptor, bean));
        }

        public void prepareResponse(Response response) {
            String contentDisposition = propertyDescriptor.getExtension(BlobDescriptorExtension.class).getContentDisposition().getValue();
            String fileName = filePersister.getFileName(propertyDescriptor, bean);
            response.setHeader("Content-Disposition", contentDisposition + (fileName != null ? "; filename=" + fileName : ""));
        }
    };
}
Example 69
Project: ExcusePro-master  File: ServerResponse.java View source code
public synchronized byte[] getByteArray() throws CommunicationException {
    if (!alreadyRead) {
        alreadyRead = true;
        byte[] buffer = new byte[8192];
        int bytesRead;
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try {
            while ((bytesRead = responseStream.read(buffer)) != -1) {
                output.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            throw new CommunicationException(e);
        }
        return output.toByteArray();
    } else {
        throw new CommunicationException("Server Response has already been read!");
    }
}
Example 70
Project: bennu-master  File: FenixFrameworkProjectViewer.java View source code
@Override
public JsonElement view(Project project, JsonBuilder ctx) {
    String projectResource = "/" + project.getName() + "/project.properties";
    String url = FenixFrameworkProjectViewer.class.getResource(projectResource).toExternalForm();
    if (url.startsWith("jar")) {
        String jar = url.substring("jar:file:".length(), url.length() - projectResource.length() - 1);
        try (JarFile jarFile = new JarFile(jar)) {
            return ctx.view(jarFile);
        } catch (IOException e) {
            throw new Error(e);
        }
    }
    // webapp case
    JsonObject json = new JsonObject();
    json.addProperty("name", project.getName());
    return json;
}
Example 71
Project: ilarkesto-master  File: ServerSocketTask.java View source code
@Override
protected void perform() {
    try {
        serverSocket = new ServerSocket(port);
        serverSocket.setSoTimeout(1000);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    while (!isAbortRequested()) {
        Socket clientSocket;
        try {
            clientSocket = serverSocket.accept();
            LOG.debug("Client connected:", clientSocket.getInetAddress().getHostAddress() + ":" + clientSocket.getPort());
        } catch (SocketTimeoutException ex) {
            continue;
        } catch (IOException ex) {
            clientHandler.onIOException(ex);
            continue;
        }
        ClientHandlerTask clientHandlerTask = new ClientHandlerTask(clientSocket);
        clientHandlerTaskManager.start(clientHandlerTask);
    }
}
Example 72
Project: android-bankdroid-master  File: CertificateReader.java View source code
public static Certificate[] getCertificates(Context context, int... rawResCerts) {
    List<Certificate> certificates = new ArrayList<>();
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        for (int resId : rawResCerts) {
            InputStream is = new BufferedInputStream(context.getResources().openRawResource(resId));
            try {
                X509Certificate cert = (X509Certificate) cf.generateCertificate(is);
                certificates.add(cert);
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    Timber.w(e, "Failed to close input stream");
                }
            }
        }
    } catch (CertificateException e) {
        Timber.w(e, "Generating certificate failed");
    }
    return certificates.toArray(new Certificate[certificates.size()]);
}
Example 73
Project: Archimulator-master  File: CSVHelper.java View source code
/**
     * To CSV.
     *
     * @param outputCSVFileName the output CSV file name
     * @param results the list of results
     * @param fields the list of fields
     * @param <ResultT> the result type
     */
public static <ResultT> void toCsv(String outputCSVFileName, List<ResultT> results, List<CSVField<ResultT>> fields) {
    File resultDirFile = new File(outputCSVFileName).getParentFile();
    if (!resultDirFile.exists()) {
        if (!resultDirFile.mkdirs()) {
            throw new RuntimeException();
        }
    }
    CSVFormat format = CSVFormat.RFC4180.withHeader().withDelimiter(',').withQuoteMode(QuoteMode.ALL).withQuote('"');
    try {
        FileWriter writer = new FileWriter(outputCSVFileName);
        CSVPrinter printer = new CSVPrinter(writer, format);
        printer.printRecord(fields);
        for (ResultT result : results) {
            List<String> record = new ArrayList<>();
            for (CSVField<ResultT> field : fields) {
                record.add(field.getFunc().apply(result));
            }
            printer.printRecord(record);
        }
        printer.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Example 74
Project: openwayback-master  File: UniversalChardetSniffer.java View source code
@Override
public String sniff(Resource resource) {
    String charsetName = null;
    byte[] bbuffer = new byte[MAX_CHARSET_READAHEAD];
    // (1)
    UniversalDetector detector = new UniversalDetector(null);
    // (2)
    resource.mark(MAX_CHARSET_READAHEAD);
    try {
        int len = resource.read(bbuffer, 0, MAX_CHARSET_READAHEAD);
        resource.reset();
        detector.handleData(bbuffer, 0, len);
    } catch (IOException ex) {
    }
    // (3)
    detector.dataEnd();
    // (4)
    charsetName = detector.getDetectedCharset();
    // (5)
    detector.reset();
    if (isCharsetSupported(charsetName)) {
        return charsetName;
    }
    return null;
}
Example 75
Project: researchzilla-master  File: PicCrop.java View source code
public static void main(String[] args) {
    FileInputStream fileInputStream = null;
    ImageInputStream imageInputStream = null;
    try {
        fileInputStream = new FileInputStream("/home/yumingzhe/a.jpg");
        Iterator iterator = ImageIO.getImageReadersByFormatName("jpg");
        ImageReader imageReader = (ImageReader) iterator.next();
        imageInputStream = ImageIO.createImageInputStream(fileInputStream);
        imageReader.setInput(imageInputStream, true);
        ImageReadParam param = imageReader.getDefaultReadParam();
        Rectangle rect = new Rectangle(0, 0, 100, 100);
        param.setSourceRegion(rect);
        BufferedImage bi = imageReader.read(0, param);
        ImageIO.write(bi, "jpg", new File("/home/yumingzhe/b.jpg"));
        imageInputStream.close();
        fileInputStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 76
Project: park-alert-master  File: Debug.java View source code
public static void commit(HttpServlet servlet) {
    BufferedWriter out = null;
    try {
        FileWriter fileWritter = new FileWriter(new File("/root/apache-tomcat-5.5.34/webapps/backend/log-file.out").getName(), true);
        BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
        DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        Date date = new Date();
        String data = "[" + dateFormat.format(date) + "] " + buffer + "\n";
        bufferWritter.write(data);
        bufferWritter.close();
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        buffer = null;
    }
}
Example 77
Project: korsakow-editor-master  File: ServiceHTTPD.java View source code
public Response serveService(String uri, String method, Properties header, Properties parms) {
    int index = uri.lastIndexOf('/');
    String serviceName = uri.substring(index + 1);
    System.out.println("Service method: " + serviceName);
    Response response = serviceHandler.runService(serviceName, header, parms);
    String responseData = "";
    if (response.data instanceof ByteArrayInputStream) {
        try {
            response.data.mark(response.data.available());
            byte[] bytes = new byte[response.data.available()];
            response.data.read(bytes);
            responseData = new String(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.data.reset();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    System.out.println("Service response: " + response.status + ";" + responseData);
    return response;
}
Example 78
Project: SideScrollerGDW2012-Max-master  File: BroadcastresponseThread.java View source code
@SuppressWarnings("deprecation")
@Override
public void run() {
    while (!close) {
        DatagramPacket packet = new DatagramPacket(new byte[0], 0);
        try {
            this.socket.receive(packet);
            byte[] buf = this.ref.getBroadcastResponce().array();
            DatagramPacket responceDatagramPacket = new DatagramPacket(buf, buf.length, packet.getAddress(), packet.getPort());
            this.socket.send(responceDatagramPacket);
        } catch (IOException e) {
            e.printStackTrace();
            this.close = true;
        }
        GDWServerLogger.logMSG("Broadcastresponce gesendet");
    }
    this.socket.close();
}
Example 79
Project: Yhb-2.0-master  File: BitmapDecoderHttp.java View source code
@Override
public Bitmap decode(String fileName, Context context) {
    try {
        URL url = new URL(fileName);
        try {
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            InputStream input = connection.getInputStream();
            if (input != null) {
                try {
                    return BitmapFactory.decodeStream(input, null, OPTIONS);
                } catch (OutOfMemoryError oom) {
                } catch (Exception e) {
                }
            }
        } catch (IOException e) {
        }
    } catch (MalformedURLException e1) {
    }
    return null;
}
Example 80
Project: polly-master  File: PHCNPasteService.java View source code
@Override
public String doPaste(String message) throws IOException {
    Map<String, String> properties = new HashMap<String, String>(10);
    //$NON-NLS-1$ //$NON-NLS-2$
    properties.put("language", "");
    //$NON-NLS-1$ //$NON-NLS-2$
    properties.put("blppassword", "");
    //$NON-NLS-1$
    properties.put("input", message);
    //$NON-NLS-1$
    PostResult pr = this.postRequest(new URL("http://paste.phcn.ws/#"), properties);
    Matcher m = PATTERN.matcher(pr.getResultString());
    if (!m.find()) {
        //$NON-NLS-1$
        throw new IOException("invalid result");
    }
    return pr.getResultString().substring(m.start(), m.end());
}
Example 81
Project: fdroidclient-master  File: AssetUtils.java View source code
@Nullable
public static File copyAssetToDir(Context context, String assetName, File directory) {
    File tempFile = null;
    InputStream input = null;
    OutputStream output = null;
    try {
        tempFile = File.createTempFile(assetName, ".testasset", directory);
        Log.i(TAG, "Copying asset file " + assetName + " to directory " + directory);
        input = context.getAssets().open(assetName);
        output = new FileOutputStream(tempFile);
        Utils.copy(input, output);
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        Utils.closeQuietly(output);
        Utils.closeQuietly(input);
    }
    return tempFile;
}
Example 82
Project: ldbc_snb_datagen-master  File: EmpiricalDistribution.java View source code
@Override
public ArrayList<Bucket> getBuckets(Configuration conf) {
    fileName = conf.get("ldbc.snb.datagen.generator.distribution.EmpiricalDistribution.fileName");
    ArrayList<Pair<Integer, Integer>> histogram = new ArrayList<Pair<Integer, Integer>>();
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(fileName), "UTF-8"));
        String line;
        while ((line = reader.readLine()) != null) {
            String data[] = line.split(" ");
            histogram.add(new Pair<Integer, Integer>(Integer.parseInt(data[0]), Integer.parseInt(data[1])));
        }
        reader.close();
        return Bucket.bucketizeHistogram(histogram, 1000);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Example 83
Project: Desktop-master  File: CopyCiteKeyToClipboard.java View source code
public void actionPerformed(ActionEvent e) {
    Collection<NodeModel> nodes = Controller.getCurrentModeController().getMapController().getSelectedNodes();
    String strBuffer = CopyBibtexToClipboard.serializeStringSet(CopyBibtexToClipboard.getKeySet(nodes));
    final String citeKeys = "\\cite{" + strBuffer + "}";
    Transferable content = new Transferable() {

        public boolean isDataFlavorSupported(DataFlavor flavor) {
            return DataFlavor.stringFlavor.equals(flavor);
        }

        public DataFlavor[] getTransferDataFlavors() {
            return new DataFlavor[] { DataFlavor.stringFlavor };
        }

        public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
            if (DataFlavor.stringFlavor.equals(flavor)) {
                return citeKeys;
            }
            throw new UnsupportedFlavorException(flavor);
        }
    };
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(content, null);
}
Example 84
Project: many-ql-master  File: CommandLine.java View source code
/**
	 * The main method, which gets executed once this class is run. Enabled the user
	 * to enter a string, which is then parsed and shown as an AST.
	 */
public static void main(String[] args) {
    ErrorEnvironment errorEnvironment = new ErrorEnvironment();
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Press 'x' to stop");
        while (true) {
            System.out.print("Enter a statement:");
            String str = br.readLine();
            if ("x".equalsIgnoreCase(str)) {
                System.out.println("Stopped.");
                break;
            } else {
                QLNode tree = Parser.parse(str);
                if (tree instanceof Statement) {
                    errorEnvironment = TypeChecker.check((Statement) tree, null);
                    PrettyPrinter.print((Statement) tree, new ConsolePrinter());
                }
                if (errorEnvironment.hasErrors()) {
                    System.out.println(errorEnvironment.getErrors());
                    continue;
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 85
Project: MD-BiliBili-master  File: TopicApi.java View source code
@Override
public void call(Subscriber<? super Topic> subscriber) {
    Request request = new Request.Builder().url("http://www.bilibili.com/index/slideshow.json").build();
    try {
        Response response = new OkHttpClient().newCall(request).execute();
        if (response.isSuccessful()) {
            Topic topic = new Gson().fromJson(response.body().string(), Topic.class);
            subscriber.onNext(topic);
        } else {
            subscriber.onError(new Exception(response.message()));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 86
Project: mjprof-master  File: StreamDataSourcePluginBase.java View source code
protected String getStackStringFromReader() {
    StringBuilder linesOfStack = new StringBuilder();
    String line;
    try {
        while ((line = reader.readLine()) != null) {
            //  System.out.println(line);
            if (line.length() > 0 && Character.isDigit(line.charAt(0))) {
                //starting a new stack dump
                if (linesOfStack.length() > 0) {
                    return linesOfStack.toString();
                }
            }
            if (line.startsWith(ThreadDump.JNI_GLOBAL_REFS))
                // need this hack for later parsing
                linesOfStack.append("\"");
            linesOfStack.append(line).append("\n");
        }
    } catch (IOException e) {
        System.err.println("Error while parsing stdin" + e);
    }
    if (linesOfStack.length() > 0) {
        return linesOfStack.toString();
    }
    return null;
}
Example 87
Project: framework-master  File: LinkToPercentage.java View source code
@Override
protected void setup() {
    String filename = "110% Vaadin";
    Resource resource = new StreamResource(new StreamSource() {

        @Override
        public InputStream getStream() {
            return new InputStream() {

                boolean first = true;

                @Override
                public int read() throws IOException {
                    if (first) {
                        first = false;
                        return 'a';
                    } else {
                        return -1;
                    }
                }
            };
        }
    }, filename);
    Link link = new Link("The link", resource);
    addComponent(link);
}
Example 88
Project: solmix-master  File: TestHomeUtil.java View source code
private static void deleteDirectory(File file) throws IOException {
    if (!file.exists()) {
        return;
    }
    File[] children = file.listFiles();
    if (children != null) {
        for (File child : children) {
            if (child.isDirectory()) {
                deleteDirectory(child);
            } else {
                if (!child.delete()) {
                    throw new IOException("Failed to delete " + child.getAbsolutePath());
                }
            }
        }
    }
    if (!file.delete()) {
        throw new IOException("Failed to delete " + file.getAbsolutePath());
    }
}
Example 89
Project: violetumleditor-master  File: PDFGraphics2DStringWriter.java View source code
@Override
protected void writeString(String str, double x, double y) {
    Font oldFont = getFont();
    try {
        // workaround for Bug in PDFFontTable class (wrong order of Font constructor parameters)
        if (oldFont.isBold() && "SansSerif".equals(oldFont.getName())) {
            Font newFont = new Font("Helvetica", Font.BOLD, oldFont.getSize());
            setFont(newFont);
            // workaround for different between fonts width
            x = x + 8;
        }
        super.writeString(str, x, y);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        setFont(oldFont);
    }
}
Example 90
Project: NewsSpeakServer-master  File: ArticleParser.java View source code
private String getExtractedText(String alchemyApiUrl) {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    Result result = new Result();
    try {
        SAXParser parser = factory.newSAXParser();
        ExtractTextXMLHandler handler = new ExtractTextXMLHandler(result);
        parser.parse(alchemyApiUrl, handler);
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result.text;
}
Example 91
Project: jxta-master  File: Booter.java View source code
public static void main(String[] args) {
    try {
        final NetworkManager manager = new NetworkManager(NetworkManager.ConfigMode.SUPER, "i2peer");
        Runtime.getRuntime().addShutdownHook(new Thread() {

            @Override
            public void run() {
                super.run();
                manager.stopNetwork();
            }
        });
        manager.getConfigurator().addRdvSeedingURI(publicSeedingRdvURI);
        manager.getConfigurator().addRelaySeedingURI(publicSeedingRelayURI);
        PeerGroup pg = manager.startNetwork();
        pg.getRendezVousService().setAutoStart(false);
        if (manager.waitForRendezvousConnection(120000)) {
            System.out.println("Found server");
        } else {
            System.out.println("Not Found server");
        }
    } catch (PeerGroupException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 92
Project: hadoop-20-master  File: TestDFSClientMultipleClose.java View source code
@Test
public void testMultipleFileCloseDFS() throws Exception {
    String testFile = "/testMultipleFileCloseDFS";
    OutputStream stream = dfs.create(testFile, true);
    // This would ensure a close on the stream would fail.
    cluster.getNameNode().stop();
    try {
        stream.close();
    } catch (IOException e) {
        try {
            stream.close();
        } catch (IOException e1) {
            System.out.println("Test passed.");
            return;
        }
        fail("Second close did not throw an exception");
    }
    fail("Close did not throw an exception");
}
Example 93
Project: sinovoice-voicewake-master  File: AccountInfo.java View source code
/**
     * �����û���ע����Ϣ
     * @param context ������
     * @return ���سɹ�Ϊtrue��ʧ��Ϊfalse
     */
public boolean loadAccountInfo(Context context) {
    boolean isSuccess = true;
    try {
        InputStream ins = context.getResources().getAssets().open("AccountInfo.txt");
        Properties props = new Properties();
        props.load(ins);
        mAccountMap.put("appKey", props.getProperty("appKey"));
        mAccountMap.put("developerKey", props.getProperty("developerKey"));
        mAccountMap.put("cloudUrl", props.getProperty("cloudUrl"));
        mAccountMap.put("capKey", props.getProperty("capKey"));
    } catch (IOException e) {
        e.printStackTrace();
        isSuccess = false;
    }
    return isSuccess;
}
Example 94
Project: stickypunch-master  File: TestWebsite.java View source code
@Test
public void testSerializeWebsite() {
    String webServiceUrl = "http://webserviceurl/";
    String websiteName = "website name";
    String authenticationToken = UUID.randomUUID().toString();
    String urlFormatString = "http://urlformatstring/";
    List<String> allowedDomains = ImmutableList.of("http://domain1", "http://domain2", "http://domain3", "http://domain4", "http://domain5");
    String websitePushId = "com.website.push.id";
    Website website = new WebsiteBuilder().setWebServiceUrl(webServiceUrl).setWebsiteName(websiteName).setAuthenticationToken(authenticationToken).setUrlFormatString(urlFormatString).setAllowedDomains(allowedDomains).setWebsitePushId(websitePushId).build();
    try {
        String json = MAPPER.writeValueAsString(website);
        Website website1 = MAPPER.readValue(json, Website.class);
        assertEquals(website1.getAllowedDomains().get(0), website.getAllowedDomains().get(0));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 95
Project: mini-git-server-master  File: IoUtil.java View source code
public static void copyWithThread(final InputStream src, final OutputStream dst) {
    new Thread("IoUtil-Copy") {

        @Override
        public void run() {
            try {
                final byte[] buf = new byte[256];
                int n;
                while (0 < (n = src.read(buf))) {
                    dst.write(buf, 0, n);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    src.close();
                } catch (IOException e2) {
                }
            }
        }
    }.start();
}
Example 96
Project: nmonvisualizer-master  File: VersionInfo.java View source code
private static String loadVersion() {
    InputStream in = VersionInfo.class.getResourceAsStream("/com/ibm/nmon/" + "version.properties");
    if (in != null) {
        Properties properties = new Properties();
        try {
            properties.load(in);
            return properties.getProperty("version");
        } catch (IOException ioe) {
            LOGGER.warn("Error loading " + "version.properties" + " file", ioe);
            return "UNKNOWN";
        } finally {
            try {
                in.close();
            } catch (IOException ioe) {
                LOGGER.warn("Cannot close " + "version.properties");
            }
        }
    } else {
        LOGGER.debug("could not load " + "version.properties" + "; defaulting to '" + "development" + '\'');
        return "development";
    }
}
Example 97
Project: cms-ce-master  File: BinaryColumnReader.java View source code
public static byte[] readBinary(String columnName, ResultSet resultSet) throws SQLException {
    if (Environment.useStreamsForBinary()) {
        InputStream inputStream = resultSet.getBinaryStream(columnName);
        if (inputStream == null) {
            return null;
        }
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(2048);
        byte[] buffer = new byte[2048];
        try {
            while (true) {
                int amountRead = inputStream.read(buffer);
                if (amountRead == -1) {
                    break;
                }
                outputStream.write(buffer, 0, amountRead);
            }
            inputStream.close();
            outputStream.close();
        } catch (IOException e) {
            throw new HibernateException("Failed to read xml from stream", e);
        }
        return outputStream.toByteArray();
    } else {
        return resultSet.getBytes(columnName);
    }
}
Example 98
Project: dragome-sdk-master  File: DragomeDebugServerEndpoint.java View source code
public void onOpen(final Session session) {
    Receiver configuredReceiver = WebServiceLocator.getInstance().getServerToClientMessageChannel().getReceiver();
    if (!(configuredReceiver instanceof ChannelReceiverImpl))
        WebServiceLocator.getInstance().getServerToClientMessageChannel().setReceiver(new ChannelReceiverImpl());
    else
        configuredReceiver.reset();
    WebServiceLocator.getInstance().getServerToClientMessageChannel().setSender(new Sender() {

        public void send(String aMessage) {
            try {
                session.getBasicRemote().sendText(aMessage);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    });
    WebServiceLocator.getInstance().getServerToClientMessageChannel().getReceiver().reset();
}
Example 99
Project: edx-app-android-master  File: GzipRequestInterceptor.java View source code
private RequestBody gzip(final RequestBody body) {
    return new RequestBody() {

        @Override
        public MediaType contentType() {
            return body.contentType();
        }

        @Override
        public long contentLength() {
            // We don't know the compressed length in advance!
            return -1;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
            body.writeTo(gzipSink);
            gzipSink.close();
        }
    };
}
Example 100
Project: kanqiu_letv-master  File: LetvDomParser.java View source code
@Override
public T parse(String data) throws ParseException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    ByteArrayInputStream inputStream = null;
    //得到DocumentBuilder对象
    DocumentBuilder builder;
    try {
        builder = factory.newDocumentBuilder();
        inputStream = new ByteArrayInputStream(data.getBytes());
        Document document = builder.parse(inputStream);
        return handler(document);
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            inputStream = null;
        }
    }
    return null;
}
Example 101
Project: Campus-master  File: UserRecentFragment.java View source code
@SuppressWarnings("unchecked")
@Override
protected List<Message> load() {
    // TODO Auto-generated method stub
    int userId = ((UserActivity) getActivity()).getUserId();
    MessagePage page = null;
    if (userId == -1)
        page = (MessagePage) service.getUser();
    else {
        try {
            page = (MessagePage) service.getUserById(userId);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    if (page != null)
        return page.getResults();
    return null;
}