Example usage for java.io InputStream available

List of usage examples for java.io InputStream available

Introduction

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

Prototype

public int available() throws IOException 

Source Link

Document

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking, which may be 0, or 0 when end of stream is detected.

Usage

From source file:com.novartis.pcs.ontology.service.graph.DOTProcessImpl.java

@Override
@SuppressWarnings("unused")
public String submit(String dot) {
    OutputStream stdin = process.getOutputStream();
    InputStream stdout = process.getInputStream();
    InputStream stderr = process.getErrorStream();

    // the dot process only starts writing to stdout after
    // receiving the terminating '}' character on stdin.
    // We need to ensure that '}' is at the end of the input string
    // so we don't cause a deadlock. Note: because of dot's well defined
    // behavior we don't need multiple threads to wait on the dot process
    // stdout and stderr. BTW, creating threads in a SLSB is illegal!
    if (!dot.endsWith("}\n")) {
        throw new IllegalArgumentException("Invalid DOT syntax: must end with '}\\n'");
    }//from   w w  w  .  j  av a  2 s.  c  o m

    try {
        stdin.write(dot.getBytes(CHARSET));
        stdin.flush();

        for (int spin = 0; stdout.available() == 0; spin++) {
            if (stderr.available() > 0) {
                int n = stderr.read(buffer);
                String msg = new String(buffer, 0, n, "UTF-8");
                logger.severe("dot process stderr: " + msg);
                throw new RuntimeException(msg);
            }
        }

        copy(stdout);

        return substr(SVG_START, SVG_END);
    } catch (IOException e) {
        String msg = "IO error occured while interacting with dot process";
        logger.log(Level.SEVERE, msg, e);
        throw new RuntimeException(msg, e);
    }
}

From source file:org.duracloud.client.ContentStoreImplTest.java

@Test
public void testGetContentWithMidstreamNetworkFailureAndRecovery() throws Exception {
    String streamContent = "content";
    byte[] bytes = streamContent.getBytes();
    InputStream stream = EasyMock.createMock(InputStream.class);
    EasyMock.expect(stream.available()).andReturn(0).anyTimes();
    EasyMock.expect(stream.read((byte[]) EasyMock.anyObject(), anyInt(), anyInt()))
            .andDelegateTo(new InputStream() {
                @Override// w  w w.  ja  v a  2s  .  c  o m
                public int read() throws IOException {
                    return bytes[0];
                }

                @Override
                public int read(byte[] bytes1, int offset, int length) throws IOException {
                    bytes1[0] = bytes[0];
                    return 1;
                }

                @Override
                public int available() {
                    return 0;
                }
            });

    EasyMock.expect(stream.read((byte[]) EasyMock.anyObject(), anyInt(), anyInt())).andThrow(new IOException());

    String fullURL = baseURL + "/" + spaceId + "/" + contentId + "?storeID=" + storeId;
    EasyMock.expect(response.getStatusCode()).andReturn(200);
    EasyMock.expect(response.getResponseHeaders()).andReturn(new Header[0]).times(2);
    EasyMock.expect(response.getResponseStream()).andReturn(stream);
    EasyMock.expect(restHelper.get(fullURL)).andReturn(response);

    EasyMock.expect(response.getStatusCode()).andReturn(206);
    Capture<Map<String, String>> captureHeaders = Capture.newInstance();
    EasyMock.expect(restHelper.get(eq(fullURL), capture(captureHeaders))).andReturn(response);
    EasyMock.expect(response.getResponseStream())
            .andReturn(new ByteArrayInputStream(Arrays.copyOfRange(bytes, 1, bytes.length)));

    replayMocks();
    EasyMock.replay(stream);

    Content content = contentStore.getContent(spaceId, contentId);
    Assert.assertNotNull(content);
    Assert.assertEquals(contentId, content.getId());
    Assert.assertEquals(streamContent, IOUtils.toString(content.getStream()));

    Map<String, String> headers = captureHeaders.getValue();
    Assert.assertEquals("Range header value is incorrect.", "bytes=1-", headers.get("Range"));
    EasyMock.verify(stream);
}

From source file:com.bean.ImagenLogica.java

/**
 * Metodo encargado de guardar la imagen perteneciente a una determinada publicacion
 * @return El nombre de la imagen que ha sido guardada en el servidor
 **///from www .  jav a 2s.c om
public String guardarImgPost() {

    File archivo = null;//Objeto para el manejo de os archivos
    InputStream in = null;//Objeto para el manejo del stream de datos del archivo
    //Se obtiene el codigo de usuario de la sesion actual
    String codUsuario = codUsuario = String
            .valueOf(new SessionLogica().obtenerUsuarioSession().getCodUsuario());
    //Se obtiene un codigo producto de la combinacion del codigo del usuario y de un numero aleatorio
    String codGenerado = new Utiles().generar(codUsuario);
    String extension = "";
    int i = 0;
    //Extension del archivo ha subir
    extension = "." + FilenameUtils.getExtension(this.getObjImagen().getImagen().getFileName());

    try {
        //Pasa el buffer de datos en un array de bytes , finalmente lee cada uno de los bytes
        in = this.getObjImagen().getImagen().getInputstream();
        byte[] data = new byte[in.available()];
        in.read(data);

        //Crea un archivo en la ruta de publicacion
        archivo = new File(this.rutaImgPublicacion + codGenerado + extension);
        FileOutputStream out = new FileOutputStream(archivo);
        //Escribe los datos en el nuevo archivo creado
        out.write(data);

        System.out.println("Ruta de Path Absolute");
        System.out.println(archivo.getAbsolutePath());

        //Cierra todas las conexiones
        in.close();
        out.flush();
        out.close();
    } catch (IOException ex) {
        System.out.println(ex.getMessage());
        return "none.jpg";
    }
    //Retorna el nombre de la iamgen almacenada
    return codGenerado + extension;
}

From source file:io.cslinmiso.line.model.LineBase.java

/**
 * Send image.//from  ww  w .  j ava  2 s .  c  om
 * 
 * @param is the is
 * @return true, if successful
 * @throws Exception the exception
 */
public boolean sendImage(InputStream is) throws Exception {
    try {
        LineMessage message = new LineMessage();
        message.setTo(getId());
        message.setText("");
        message.setContentType(ContentType.IMAGE);

        Message sendMessage = client.sendMessage(0, message);
        String messageId = sendMessage.getId();

        // preparing params which is detail of image to upload server
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode objectNode = objectMapper.createObjectNode();
        objectNode.put("name", "media");
        objectNode.put("oid", messageId);
        objectNode.put("size", is.available());
        objectNode.put("type", "image");
        objectNode.put("ver", "1.0");

        Map<String, Object> data = new HashMap<String, Object>();
        // data.put("file", file);
        data.put("params", objectMapper.writeValueAsString(objectNode));

        String url = LineApi.LINE_UPLOADING_URL;
        LineApiImpl api = (LineApiImpl) client.getApi();
        boolean isUploaded = api.postContent(url, data, is);

        if (isUploaded == false) {
            throw new Exception("Fail to upload image.");
        }
        return true;
    } catch (Exception e) {
        throw e;
    }
}

From source file:com.twinsoft.convertigo.engine.Engine.java

public static synchronized void start() throws EngineException {
    if (Engine.theApp == null) {
        System.out.println("Starting Convertigo Enterprise Mobility Server");

        // If the engine has been stopped by the admin, we must reload
        // properties
        EnginePropertiesManager.loadProperties();

        boolean bProjectsDataCompatibilityMode = Boolean.parseBoolean(
                EnginePropertiesManager.getProperty(PropertyName.PROJECTS_DATA_COMPATIBILITY_MODE));

        if (bProjectsDataCompatibilityMode) {
            System.out.println("Projects data compatibility mode required");
            try {
                Engine.PROJECTS_PATH = new File(Engine.WEBAPP_PATH + "/projects").getCanonicalPath();
                File projectsDir = new File(Engine.PROJECTS_PATH);
                projectsDir.mkdir();//from w  w  w .  j  av a  2 s. c  o m
            } catch (IOException e) {
                throw new EngineException("Unable to update projects path for compatibility mode", e);
            }
        }

        isStarted = false;
        isStartFailed = false;
        RequestableObject.nbCurrentWorkerThreads = 0;

        Engine.startStopDate = System.currentTimeMillis();

        System.out.println("Creating/updating loggers");

        String logFile = EnginePropertiesManager.getProperty(PropertyName.LOG4J_APPENDER_CEMSAPPENDER_FILE);
        System.out.println("Log file: " + logFile);

        // Main loggers
        Engine.logConvertigo = Logger.getLogger("cems");
        Engine.logEngine = Logger.getLogger("cems.Engine");
        Engine.logAdmin = Logger.getLogger("cems.Admin");
        Engine.logBeans = Logger.getLogger("cems.Beans");
        Engine.logBillers = Logger.getLogger("cems.Billers");
        Engine.logEmulators = Logger.getLogger("cems.Emulators");
        Engine.logContext = Logger.getLogger("cems.Context");
        Engine.logUser = Logger.getLogger("cems.Context.User");
        Engine.logUsageMonitor = Logger.getLogger("cems.UsageMonitor");
        Engine.logStatistics = Logger.getLogger("cems.Statistics");
        Engine.logScheduler = Logger.getLogger("cems.Scheduler");
        Engine.logSiteClipper = Logger.getLogger("cems.SiteClipper");
        /** #3437 : Disabled ExternalBrowser feature because it's not terminated
        Engine.logExternalBrowser = Logger.getLogger("cems.ExternalBrowser");
        */
        Engine.logAudit = Logger.getLogger("cems.Context.Audit");

        // Managers
        Engine.logContextManager = Logger.getLogger("cems.ContextManager");
        Engine.logCacheManager = Logger.getLogger("cems.CacheManager");
        Engine.logTracePlayerManager = Logger.getLogger("cems.TracePlayerManager");
        Engine.logJobManager = Logger.getLogger("cems.JobManager");
        Engine.logCertificateManager = Logger.getLogger("cems.CertificateManager");
        Engine.logDatabaseObjectManager = Logger.getLogger("cems.DatabaseObjectManager");
        Engine.logProxyManager = Logger.getLogger("cems.ProxyManager");
        Engine.logDevices = Logger.getLogger("cems.Devices");
        Engine.logCouchDbManager = Logger.getLogger("cems.CouchDbManager");
        Engine.logSecurityTokenManager = Logger.getLogger("cems.SecurityTokenManager");

        // Logger for compatibility issues
        Engine.log = new LogWrapper(Engine.logConvertigo);
        LogWrapper.initWrapper(Engine.logEmulators);

        try {
            Engine.logEngine.info("===========================================================");
            Engine.logEngine.info("Web app home: " + Engine.WEBAPP_PATH);
            Engine.logEngine.info("User workspace: " + Engine.USER_WORKSPACE_PATH);
            Engine.logEngine.info("Configuration path: " + Engine.CONFIGURATION_PATH);

            Engine.logEngine.info("Projects path: " + Engine.PROJECTS_PATH);
            if (bProjectsDataCompatibilityMode) {
                Engine.logEngine.warn("Projects data compatibility mode required");
            }

            Engine.logEngine.info("Log: " + Engine.LOG_PATH);

            if (cloud_customer_name != null) {
                Engine.logEngine.info("Cloud customer: " + cloud_customer_name);
            }

            // Check environment and native dependencies
            if (!isStudioMode()) {
                StartupDiagnostics.run();
            }

            // Initializing the engine
            Engine.theApp = new Engine();

            CachedIntrospector.prefetchDatabaseObjectsAsync();

            try {
                Engine.theApp.usageMonitor = new UsageMonitor();
                Engine.theApp.usageMonitor.init();

                Thread vulture = new Thread(Engine.theApp.usageMonitor);
                vulture.setName("UsageMonitor");
                vulture.setDaemon(true);
                vulture.start();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to launch the usage monitor.", e);
            }

            Engine.theApp.eventManager = new EventManager();
            Engine.theApp.eventManager.init();

            Engine.theApp.databaseObjectsManager = new DatabaseObjectsManager();
            Engine.theApp.databaseObjectsManager.init();

            Engine.theApp.sqlConnectionManager = new JdbcConnectionManager();
            Engine.theApp.sqlConnectionManager.init();

            Engine.theApp.filePropertyManager = new FilePropertyManager();
            Engine.theApp.filePropertyManager.init();

            try {
                Engine.theApp.proxyManager = new ProxyManager();
                Engine.theApp.proxyManager.init();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to launch the proxy manager.", e);
            }

            try {
                Engine.theApp.billingManager = new BillingManager();
                Engine.theApp.billingManager.init();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to launch the billing manager.", e);
            }

            // Initialization of the trace player
            try {
                Engine.theApp.tracePlayerManager = new TracePlayerManager();
                Engine.theApp.tracePlayerManager.init();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to run the trace player.", e);
            }

            try {
                Engine.theApp.minificationManager = new MinificationManager();
                Engine.theApp.minificationManager.init();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to run the minification manager.", e);
            }

            try {
                Engine.theApp.couchDbManager = new CouchDbManager();
                Engine.theApp.couchDbManager.init();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to run the couchDbProxy manager.", e);
            }

            try {
                Engine.theApp.pluginsManager = new PluginsManager();
                Engine.theApp.pluginsManager.init();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to run the plugins manager.", e);
            }

            try {
                Engine.theApp.restApiManager = RestApiManager.getInstance();
                Engine.theApp.restApiManager.init();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to run the rest api manager.", e);
            }

            Engine.logEngine.info("Current working directory is '" + System.getProperty("user.dir") + "'.");

            // Creating the Carioca Authentication objects
            Engine.logEngine.debug("Creating the Carioca Authentication objects");
            String cariocaUserName = EnginePropertiesManager
                    .getProperty(PropertyName.CARIOCA_DEFAULT_USER_NAME);
            String cariocaPassword = EnginePropertiesManager
                    .getProperty(PropertyName.CARIOCA_DEFAULT_USER_PASSWORD);
            Engine.theApp.authentications = new HashMap<String, Authentication>();

            // Initialization of the default TAS properties
            try {
                KeyManager.log = new LogWrapper(Engine.logEngine);
                Authentication auth = Engine.theApp.getAuthenticationObject("", null);
                auth.login(cariocaUserName, cariocaPassword);
            } catch (Exception e) {
                Engine.logEngine.error("The authentication to Carioca has failed (user name: \""
                        + cariocaUserName + "\", user password: \"" + cariocaPassword + "\").", e);
            }

            // TODO : retrieve SOA flag from KeyManager
            isSOA = true;

            // Creation of the session manager
            Engine.theApp.sessionManager = new SessionManager();
            Engine.theApp.sessionManager.setLog(new LogWrapper(Engine.logEngine));
            Engine.theApp.sessionManager.setProductCode(SessionManager.CONVERTIGO);

            String s = EnginePropertiesManager.getProperty(PropertyName.CONNECTORS_MONITORING);
            Engine.theApp.setMonitored(s.equalsIgnoreCase("true"));

            // Create Projects directory if needed
            File projectsDirFile = new File(Engine.PROJECTS_PATH);
            try {
                if (!projectsDirFile.exists())
                    projectsDirFile.mkdirs();
            } catch (Exception e) {
                Engine.logEngine.error("An error occured while creating projects directory.", e);
            }

            // Starts projects migration process
            MigrationManager.performProjectsMigration();

            // Security providers registration
            try {
                File dir = new File(Engine.CERTIFICATES_PATH);
                String[] files = dir.list(new FilenameFilter() {
                    public boolean accept(File dir, String name) {
                        return name.endsWith((".pkcs11"));
                    }
                });

                if (files != null && files.length > 0) {
                    Engine.logEngine.info("Registering security providers...");
                    try {
                        Class<?> sunPKCS11Class = Class.forName("sun.security.pkcs11.SunPKCS11");
                        String file;

                        for (int i = 0; i < files.length; i++) {
                            file = Engine.CERTIFICATES_PATH + "/" + files[i];
                            try {
                                Constructor<?> constructor = sunPKCS11Class
                                        .getConstructor(new Class[] { String.class });
                                Provider provider = (Provider) constructor.newInstance(new Object[] { file });
                                Security.addProvider(provider);
                                Engine.logEngine.info("Provider '" + provider.getName()
                                        + "' has been successfully registered.");
                            } catch (Exception e) {
                                Engine.logEngine.error("Unable to register security provider from file: " + file
                                        + " . Please check that the implementation library is in the Java lib path.");
                            }
                        }
                    } catch (ClassNotFoundException e) {
                        Engine.logEngine.error(
                                "Unable to find sun.security.pkcs11.SunPKCS11 class! PKCS#11 authentication won't be available. You must use JVM 1.5 or higher in order to use PKCS#11 authentication.");
                    }
                }

                Provider[] providers = Security.getProviders();
                String sProviders = "";
                for (int i = 0; i < providers.length; i++) {
                    sProviders += providers[i].getName() + ", ";
                }
                Engine.logEngine.debug("Registered providers: " + sProviders);
            } catch (Exception e) {
                Engine.logEngine.error("Unable to register security providers.", e);
            }

            // Launch the cache manager
            try {
                String cacheManagerClassName = EnginePropertiesManager
                        .getProperty(PropertyName.CACHE_MANAGER_CLASS);
                Engine.logEngine.debug("Cache manager class: " + cacheManagerClassName);
                Engine.theApp.cacheManager = (CacheManager) Class.forName(cacheManagerClassName).newInstance();
                Engine.theApp.cacheManager.init();

                Thread vulture = new Thread(Engine.theApp.cacheManager);
                Engine.theApp.cacheManager.executionThread = vulture;
                vulture.setName("CacheManager");
                vulture.setDaemon(true);
                vulture.start();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to launch the cache manager.", e);
            }

            // Launch the thread manager
            try {
                Engine.theApp.threadManager = new ThreadManager();
                Engine.theApp.threadManager.init();

                Thread vulture = new Thread(Engine.theApp.threadManager);
                Engine.theApp.threadManager.executionThread = vulture;
                vulture.setName("ThreadManager");
                vulture.setDaemon(true);
                vulture.start();
            } catch (Exception e) {
                Engine.theApp.threadManager = null;
                Engine.logEngine.error("Unable to launch the thread manager.", e);
            }

            // Launch the context manager
            try {
                Engine.theApp.contextManager = new ContextManager();
                Engine.theApp.contextManager.init();

                Thread vulture = new Thread(Engine.theApp.contextManager);
                Engine.theApp.contextManager.executionThread = vulture;
                vulture.setName("ContextManager");
                vulture.setDaemon(true);
                vulture.start();
            } catch (Exception e) {
                Engine.theApp.contextManager = null;
                Engine.logEngine.error("Unable to launch the context manager.", e);
            }

            // Launch the security token manager
            Engine.theApp.securityTokenManager = new SecurityTokenManager();
            Engine.theApp.securityTokenManager.init();

            // Initialize the HttpClient
            try {
                Engine.logEngine.debug("HttpClient initializing...");

                Engine.theApp.httpClient = HttpUtils.makeHttpClient3(true);
                Engine.theApp.httpClient4 = HttpUtils.makeHttpClient4(true);

                Engine.logEngine.debug("HttpClient initialized!");
            } catch (Exception e) {
                Engine.logEngine.error("Unable to initialize the HttpClient.", e);
            }

            // Initialization of the schedule manager
            Engine.theApp.schedulerManager = new SchedulerManager(true);

            // Initialization of the RSA manager
            Engine.theApp.rsaManager = new RsaManager();
            Engine.theApp.rsaManager.init();

            // Initialization of the External Browser manager
            /** #3437 : Disabled ExternalBrowser feature because it's not terminated
            Engine.theApp.externalBrowserManager = new ExternalBrowserManager();
            Engine.theApp.externalBrowserManager.init();
            */

            // Initialization of the Schema manager
            Engine.theApp.schemaManager = new SchemaManager();
            Engine.theApp.schemaManager.init();

            // XUL initialization
            String xulrunner_url = System.getProperty("org.eclipse.swt.browser.XULRunnerPath");
            if (xulrunner_url == null || xulrunner_url.equals("")) {
                xulrunner_url = EnginePropertiesManager.getProperty(PropertyName.XULRUNNER_URL);
            }

            File f = new File(xulrunner_url);
            if (f.exists()) {
                xulrunner_url = f.getAbsolutePath();
                Engine.logEngine
                        .debug("initMozillaSWT: org.eclipse.swt.browser.XULRunnerPath=" + xulrunner_url);
                System.setProperty("org.eclipse.swt.browser.XULRunnerPath", xulrunner_url);
            } else {
                Engine.logEngine.error("Error in initMozillaSWT: " + xulrunner_url
                        + " doesn't exist, fix it with xulrunner.url");
            }

            if (Engine.isEngineMode() && Engine.isLinux()
                    && "true".equals(EnginePropertiesManager.getProperty(PropertyName.LINUX_LAUNCH_XVNC))) {

                Engine.logEngine
                        .debug("initMozillaSWT: org.eclipse.swt.browser.XULRunnerPath=" + xulrunner_url);
                final String display = System.getenv("DISPLAY");
                if (display != null) {
                    try {
                        String port = System.getProperty("xvnc.port");
                        if (port == null) {
                            port = "" + (Integer.parseInt(display.replaceAll(".*:(\\d*)", "$1")) + 5900);
                            System.setProperty("xvnc.port", port);
                        }
                        Engine.logEngine.debug("Xvnc should listen on " + port + " port");
                    } catch (Exception e) {
                    }
                    try {
                        File vncDir = new File(Engine.WEBAPP_PATH + "/WEB-INF/xvnc");
                        File Xvnc = new File(vncDir, "/Xvnc");
                        File fonts = new File(vncDir, "/fonts");
                        File wm = new File(vncDir, "/matchbox-window-manager");
                        if (vncDir.exists() && Xvnc.exists() && fonts.exists() && wm.exists()) {
                            for (File file : GenericUtils.<File>asList(Xvnc, wm)) {
                                new ProcessBuilder("/bin/chmod", "u+x", file.getAbsolutePath()).start()
                                        .waitFor();
                            }
                            String depth = EnginePropertiesManager.getProperty(PropertyName.LINUX_XVNC_DEPTH);
                            String geometry = EnginePropertiesManager
                                    .getProperty(PropertyName.LINUX_XVNC_GEOMETRY);
                            Engine.logEngine
                                    .debug("Xvnc will use depth " + depth + " and geometry " + geometry);
                            Process pr_xvnc = new ProcessBuilder(Xvnc.getAbsolutePath(), display, "-fp",
                                    fonts.getAbsolutePath(), "-depth", depth, "-geometry", geometry).start();
                            Thread.sleep(500);
                            try {
                                int exit = pr_xvnc.exitValue();
                                InputStream err = pr_xvnc.getErrorStream();
                                byte[] buf = new byte[err.available()];
                                err.read(buf);
                                Engine.logEngine.debug("Xvnc failed to run with exit code " + exit
                                        + " and this error : <<" + new String(buf, "UTF-8") + ">>");
                            } catch (Exception e) {
                                new ProcessBuilder(wm.getAbsolutePath()).start();
                                Engine.logEngine.debug("Xvnc successfully started !");
                            }
                        } else {
                            Engine.logEngine.info(
                                    vncDir.getAbsolutePath() + " not found or incomplet, cannot start Xvnc");
                        }
                    } catch (Exception e) {
                        Engine.logEngine.info("failed to launch Xvnc (maybe already launched", e);
                    }
                } else
                    Engine.logEngine
                            .warn("Trying to start Xvnc on Linux without DISPLAY environment variable !");
            }

            // SAP provider registration
            try {
                SapJcoDestinationDataProvider.init();
                Engine.logEngine.debug("SAP destination provider successfully registered");
            } catch (Throwable e) {
                Engine.logEngine.error("Error while registering SAP destination provider", e);
            }

            isStarted = true;

            Engine.logEngine.info("Convertigo engine started");
        } catch (Throwable e) {
            isStartFailed = true;
            Engine.logEngine.error("Unable to successfully start the engine.", e);
        }
    } else {
        Engine.logEngine.info("Convertigo engine already started");
    }
}

From source file:net.solarnetwork.node.io.rxtx.SerialPortSupport.java

private boolean handleSerialEventWithoutTimeout(SerialPortEvent event, InputStream in,
        ByteArrayOutputStream sink, byte[] magicBytes, byte[] eofBytes) {
    int sinkSize = sink.size();
    boolean append = sinkSize > 0;
    byte[] buf = new byte[1024];
    if (eventLog.isTraceEnabled()) {
        eventLog.trace("Sink contains {} bytes: {}", sinkSize, asciiDebugValue(sink.toByteArray()));
    }/*w w w.j  a  v a 2s  . co  m*/
    try {
        int len = -1;
        final int max = Math.min(in.available(), buf.length);
        eventLog.trace("Attempting to read {} bytes from serial port", max);
        while (max > 0 && (len = in.read(buf, 0, max)) > 0) {
            sink.write(buf, 0, len);
            sinkSize += len;

            if (append) {
                // look for eofBytes, starting where we last appended
                if (findEOFBytes(sink, len, eofBytes)) {
                    if (eventLog.isDebugEnabled()) {
                        eventLog.debug("Found desired EOF bytes: {}", asciiDebugValue(eofBytes));
                    }
                    return true;
                }
                eventLog.debug("Looking for EOF bytes {}", asciiDebugValue(eofBytes));
                return false;
            } else {
                eventLog.trace("Looking for {} magic bytes {} in buffer {}", new Object[] { magicBytes.length,
                        asciiDebugValue(magicBytes), asciiDebugValue(sink.toByteArray()) });
            }

            // look for magic in the buffer
            int magicIdx = 0;
            byte[] sinkBuf = sink.toByteArray();
            boolean found = false;
            for (; magicIdx < (sinkBuf.length - magicBytes.length + 1); magicIdx++) {
                found = true;
                for (int j = 0; j < magicBytes.length; j++) {
                    if (sinkBuf[magicIdx + j] != magicBytes[j]) {
                        found = false;
                        break;
                    }
                }
                if (found) {
                    break;
                }
            }

            if (found) {
                // magic found!
                if (eventLog.isTraceEnabled()) {
                    eventLog.trace("Found magic bytes " + asciiDebugValue(magicBytes) + " at buffer index "
                            + magicIdx);
                }

                int count = buf.length;
                count = Math.min(buf.length, sinkBuf.length - magicIdx);
                sink.reset();
                sink.write(sinkBuf, magicIdx, count);
                sinkSize = count;
                if (eventLog.isTraceEnabled()) {
                    eventLog.trace("Sink contains {} bytes: {}", sinkSize, asciiDebugValue(sink.toByteArray()));
                }
                if (findEOFBytes(sink, len, eofBytes)) {
                    // we got all the data here... we're done
                    return true;
                }
                append = true;
            } else if (sinkBuf.length > magicBytes.length) {
                // haven't found the magic yet, and the sink is larger than magic size, so 
                // trim sink down to just magic size
                sink.reset();
                sink.write(sinkBuf, sinkBuf.length - magicBytes.length, magicBytes.length);
                sinkSize = magicBytes.length;
            }
        }
    } catch (IOException e) {
        log.error("Error reading from serial port: {}", e.getMessage());
        throw new RuntimeException(e);
    }

    if (eventLog.isTraceEnabled()) {
        eventLog.debug("Looking for bytes {}, buffer: {}",
                (append ? asciiDebugValue(eofBytes) : asciiDebugValue(magicBytes)),
                asciiDebugValue(sink.toByteArray()));
    }
    return false;
}

From source file:org.musa.payload.MechanicusTeleportReceiver.java

public SpaceMarine deserialize(InputStream in) throws IOException {

    String name = readString(in);

    System.out.println("name == " + name);

    String chapter = readString(in);

    System.out.println("chapter == " + chapter);

    int kills = Integer.parseInt(readString(in));

    System.out.println("kills == " + kills);

    SMRank rank = SMRank.valueOf(readString(in));

    System.out.println("rank == " + rank.name());

    SMLoyalty loyalty = SMLoyalty.valueOf(readString(in));
    System.out.println("loyalty == " + loyalty.name());

    SMStatus status = SMStatus.valueOf(readString(in));
    System.out.println("status == " + status.name());
    //public SpaceMarine(String name, String chapter, int kills, SMRank rank, SMLoyalty loyalty, int damage)
    int damage = Integer.parseInt(readString(in));

    System.out.println("damage == " + damage);

    SpaceMarine spacemarine = new SpaceMarine(name, chapter, kills, rank, loyalty, damage);

    int b = in.available();
    in.skip(b);/*from   ww w  . j  a v  a 2 s. com*/

    return spacemarine;

}

From source file:com.zimbra.common.mime.MimeDetect.java

public void parseMagic(String fileList) throws IOException {
    final String MAGIC_MAGIC = "MIME-Magic\0";

    if (fileList == null || fileList.length() == 0) {
        magics.clear();/*from  w ww  .  j a  v  a  2s .c  o m*/
        return;
    }
    ArrayList<String> files = new ArrayList<String>();
    for (String file : fileList.split(":")) {
        files.add(file);
        files.add(file + ".zimbra");
    }
    for (String file : files) {
        InputStream is = null;
        try {
            is = new BufferedInputStream(new FileInputStream(new File(file)));
        } catch (FileNotFoundException e) {
            continue;
        }
        String line = readLine(is);

        if (line == null || !line.equals(MAGIC_MAGIC)) {
            ZimbraLog.system.warn("invalid magic file %s", file);
            continue;
        }
        if (is.read() != '[') {
            ZimbraLog.system.warn("invalid magic section in %s", file);
            continue;
        }
        while (is.available() > 0) {
            Magic magic = new Magic(is);

            magics.put(magic, magic.type);
        }
    }
}

From source file:net.chaosserver.timelord.swingui.Timelord.java

/**
 * Check if there is a newer version of the timelord application
 * available and if so, prompt the user to download the new version.
 * //from   ww w  .  j a v  a  2 s.  c o  m
 * @return if the user wants to download a new version
 */
public boolean isUpgradeRequested() {
    boolean result = false;
    Properties appProperties = getAppProperties();

    if (appProperties != null) {
        String pomUrlString = appProperties.getProperty("pomurl");
        String appVersion = appProperties.getProperty("implementation.version");

        if (pomUrlString != null) {
            InputStream pomStream = null;

            try {
                URL pomUrl = new URL(pomUrlString);
                pomStream = pomUrl.openStream();

                if (log.isDebugEnabled()) {
                    log.debug("Opened URL [" + pomUrl + "] with result ["
                            + (pomStream != null ? pomStream.available() : "null") + "]");
                }

                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                factory.setNamespaceAware(true);
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(pomStream);

                if (log.isTraceEnabled()) {
                    log.trace("Loaded document: " + doc.getDocumentElement());
                }

                Element pomversionElement = doc.getElementById("pomversion");
                String pomVersion = "";
                if (pomversionElement != null) {
                    pomVersion = pomversionElement.getNodeValue();
                }

                if (appVersion == null) {
                    appVersion = "";
                }

                if (log.isDebugEnabled()) {
                    log.debug("Testinv version of app [" + appVersion + "] against version of pom ["
                            + pomVersion + "]");
                }

                if (!pomVersion.equals(appVersion)) {

                }

            } catch (ParserConfigurationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SAXException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (pomStream != null) {
                    try {
                        pomStream.close();
                    } catch (IOException e) {
                        if (log.isInfoEnabled()) {
                            log.info("failed to close pomstream", e);
                        }
                    }
                }
            }

        } else {
            if (log.isWarnEnabled()) {
                log.warn("Got back blank pomurl, so not checking " + "for upgrade.");
            }
        }
    } else {
        if (log.isWarnEnabled()) {
            log.warn("Got back blank properties, so not checking " + "for upgrade.");
        }
    }

    return result;
}

From source file:net.solarnetwork.node.io.rxtx.SerialPortSupport.java

private boolean handleSerialEventWithoutTimeout(SerialPortEvent event, InputStream in,
        ByteArrayOutputStream sink, byte[] magicBytes, int readLength) {
    int sinkSize = sink.size();
    boolean append = sinkSize > 0;
    byte[] buf = new byte[Math.min(readLength, 1024)];
    if (eventLog.isTraceEnabled()) {
        eventLog.trace("Sink contains {} bytes: {}", sinkSize, asciiDebugValue(sink.toByteArray()));
    }/*from  w  w w.  ja  va 2 s  . c o  m*/
    try {
        int len = -1;
        final int max = Math.min(in.available(), buf.length);
        eventLog.trace("Attempting to read {} bytes from serial port", max);
        while (max > 0 && (len = in.read(buf, 0, max)) > 0) {
            sink.write(buf, 0, len);
            sinkSize += len;

            if (append) {
                // if we've collected at least desiredSize bytes, we're done
                if (sinkSize >= readLength) {
                    if (eventLog.isDebugEnabled()) {
                        eventLog.debug("Got desired {}  bytes of data: {}", readLength,
                                asciiDebugValue(sink.toByteArray()));
                    }
                    return true;
                }
                eventLog.debug("Looking for {} more bytes of data", (readLength - sinkSize));
                return false;
            } else {
                eventLog.trace("Looking for {} magic bytes 0x{}", magicBytes.length,
                        Hex.encodeHexString(magicBytes));
            }

            // look for magic in the buffer
            int magicIdx = 0;
            byte[] sinkBuf = sink.toByteArray();
            boolean found = false;
            for (; magicIdx < (sinkBuf.length - magicBytes.length + 1); magicIdx++) {
                found = true;
                for (int j = 0; j < magicBytes.length; j++) {
                    if (sinkBuf[magicIdx + j] != magicBytes[j]) {
                        found = false;
                        break;
                    }
                }
                if (found) {
                    break;
                }
            }

            if (found) {
                // magic found!
                if (eventLog.isTraceEnabled()) {
                    eventLog.trace("Found magic bytes " + asciiDebugValue(magicBytes) + " at buffer index "
                            + magicIdx);
                }

                // skip over magic bytes
                magicIdx += magicBytes.length;

                int count = readLength;
                count = Math.min(readLength, sinkBuf.length - magicIdx);
                sink.reset();
                sink.write(sinkBuf, magicIdx, count);
                sinkSize = count;
                if (eventLog.isTraceEnabled()) {
                    eventLog.trace("Sink contains {} bytes: {}", sinkSize, asciiDebugValue(sink.toByteArray()));
                }
                if (sinkSize >= readLength) {
                    // we got all the data here... we're done
                    return true;
                }
                eventLog.trace("Need {} more bytes of data", (readLength - sinkSize));
                append = true;
            } else if (sinkBuf.length > magicBytes.length) {
                // haven't found the magic yet, and the sink is larger than magic size, so 
                // trim sink down to just magic size
                sink.reset();
                sink.write(sinkBuf, sinkBuf.length - magicBytes.length - 1, magicBytes.length);
                sinkSize = magicBytes.length;
            }
        }
    } catch (IOException e) {
        log.error("Error reading from serial port: {}", e.getMessage());
        throw new RuntimeException(e);
    }

    if (eventLog.isTraceEnabled()) {
        eventLog.trace("Need {} more bytes of data, buffer: {}", (readLength - sinkSize),
                asciiDebugValue(sink.toByteArray()));
    }
    return false;
}