Example usage for java.nio CharBuffer toString

List of usage examples for java.nio CharBuffer toString

Introduction

In this page you can find the example usage for java.nio CharBuffer toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representing the current remaining chars of this buffer.

Usage

From source file:org.geppetto.frontend.controllers.GeppettoMessageInbound.java

/**
 * Receives message(s) from client.//  w  ww.j  a  v  a2 s  .  com
 * 
 * @throws JsonProcessingException
 */
@Override
protected void onTextMessage(CharBuffer message) throws JsonProcessingException {
    String msg = message.toString();

    // de-serialize JSON
    GeppettoTransportMessage gmsg = new Gson().fromJson(msg, GeppettoTransportMessage.class);

    String requestID = gmsg.requestID;

    // switch on message type
    // NOTE: each message handler knows how to interpret the GeppettoMessage data field
    switch (INBOUND_MESSAGE_TYPES.valueOf(gmsg.type.toUpperCase())) {
    case GEPPETTO_VERSION: {
        _servletController.getVersionNumber(requestID, this);
        break;
    }
    case INIT_URL: {
        String urlString = gmsg.data;
        URL url;
        try {
            url = new URL(urlString);
            _servletController.load(requestID, urlString, this);
        } catch (MalformedURLException e) {
            _servletController.messageClient(requestID, this, OUTBOUND_MESSAGE_TYPES.ERROR_LOADING_SIMULATION);
        }
        break;
    }
    case INIT_SIM: {
        String simulation = gmsg.data;
        _servletController.load(requestID, simulation, this);
        break;
    }
    case RUN_SCRIPT: {
        String urlString = gmsg.data;
        URL url = null;
        try {
            url = new URL(urlString);

            _servletController.sendScriptData(requestID, url, this);

        } catch (MalformedURLException e) {
            _servletController.messageClient(requestID, this, OUTBOUND_MESSAGE_TYPES.ERROR_READING_SCRIPT);
        }
        break;
    }
    case SIM: {
        String url = gmsg.data;
        _servletController.getSimulationConfiguration(requestID, url, this);
        break;
    }
    case START: {
        _servletController.startSimulation(requestID, this);
        break;
    }
    case PAUSE: {
        _servletController.pauseSimulation(requestID, this);
        break;
    }
    case STOP: {
        _servletController.stopSimulation(requestID, this);
        break;
    }
    case OBSERVE: {
        _servletController.observeSimulation(requestID, this);
        break;
    }
    case SET_WATCH: {
        String watchListsString = gmsg.data;

        try {
            _servletController.setWatchedVariables(requestID, watchListsString, this);
        } catch (GeppettoExecutionException e) {
            _servletController.messageClient(requestID, this,
                    OUTBOUND_MESSAGE_TYPES.ERROR_SETTING_WATCHED_VARIABLES);
        } catch (GeppettoInitializationException e) {
            _servletController.messageClient(requestID, this,
                    OUTBOUND_MESSAGE_TYPES.ERROR_SETTING_WATCHED_VARIABLES);
        }

        break;
    }
    case CLEAR_WATCH: {
        _servletController.clearWatchLists(requestID, this);
        break;
    }
    case IDLE_USER: {
        _servletController.disableUser(requestID, this);
        break;
    }
    case GET_MODEL_TREE: {
        String instancePath = gmsg.data;

        _servletController.getModelTree(requestID, instancePath, this);
        break;
    }
    case GET_SIMULATION_TREE: {
        String instancePath = gmsg.data;

        _servletController.getSimulationTree(requestID, instancePath, this);
        break;
    }
    case GET_SUPPORTED_OUTPUTS: {
        //            String instancePath = gmsg.data;
        //            
        //            _servletController.getModelTree(requestID,instancePath,this);
        break;
    }
    case WRITE_MODEL: {

        Map<String, String> parameters = new Gson().fromJson(gmsg.data,
                new TypeToken<HashMap<String, String>>() {
                }.getType());
        _servletController.writeModel(requestID, parameters.get("instancePath"), parameters.get("format"),
                this);

    }
    default: {
        // NOTE: no other messages expected for now
    }
    }
}

From source file:org.springframework.web.reactive.resource.CssLinkResourceTransformer.java

@Override
public Mono<Resource> transform(ServerWebExchange exchange, Resource inputResource,
        ResourceTransformerChain transformerChain) {

    return transformerChain.transform(exchange, inputResource).flatMap(ouptputResource -> {
        String filename = ouptputResource.getFilename();
        if (!"css".equals(StringUtils.getFilenameExtension(filename))
                || inputResource instanceof GzipResourceResolver.GzippedResource) {
            return Mono.just(ouptputResource);
        }//ww w. j  a  va 2 s .  c  o m

        if (logger.isTraceEnabled()) {
            logger.trace("Transforming resource: " + ouptputResource);
        }

        DataBufferFactory bufferFactory = exchange.getResponse().bufferFactory();
        Flux<DataBuffer> flux = DataBufferUtils.read(ouptputResource, bufferFactory, StreamUtils.BUFFER_SIZE);
        return DataBufferUtils.join(flux).flatMap(dataBuffer -> {
            CharBuffer charBuffer = DEFAULT_CHARSET.decode(dataBuffer.asByteBuffer());
            DataBufferUtils.release(dataBuffer);
            String cssContent = charBuffer.toString();
            return transformContent(cssContent, ouptputResource, transformerChain, exchange);
        });
    });
}

From source file:info.dolezel.fatrat.plugins.UloztoDownload.java

@Override
public void processLink(String link) {

    //if (link.contains("/live/"))
    //    link = link.replace("/live/", "/");
    if (link.startsWith("http://uloz.to") || link.startsWith("https://uloz.to"))
        link = link.replace("https?://uloz.to", "https://www.uloz.to");
    if (link.startsWith("http://m.uloz.to") || link.startsWith("https://m.uloz.to"))
        link = link.replace("https?://m.uloz.to", "https://www.uloz.to");

    if (!logIn(link))
        return;//from  www . j av  a2  s.com

    final String downloadLink = link; // I can't make 'link' final

    fetchPage(link, new PageFetchListener() {

        @Override
        public void onCompleted(ByteBuffer buf, Map<String, String> headers) {
            try {
                if (headers.containsKey("location")) {
                    String location = headers.get("location");
                    if (location.contains("smazano") || location.contains("nenalezeno"))
                        setFailed("The file has been removed");
                    else
                        processLink(location);
                    return;
                }

                CharBuffer cb = charsetUtf8.decode(buf);

                if (cb.toString().contains("?disclaimer=1")) {
                    processLink(downloadLink + "?disclaimer=1");
                    return;
                }

                final Document doc = Jsoup.parse(cb.toString());
                final Element freeForm = doc.getElementById("frm-download-freeDownloadTab-freeDownloadForm");
                final Element premiumLink = doc.getElementById("#quickDownloadButton");

                boolean usePremium = usePremium(downloadLink);

                if (cb.toString().contains("Nem dostatek kreditu"))
                    setMessage("Credit depleted, using FREE download");
                else if (usePremium && premiumLink != null) {
                    String msg = "Using premium download";

                    Elements aCredits = doc.getElementsByAttributeValue("href", "/kredit");

                    if (!aCredits.isEmpty())
                        msg += " (" + aCredits.get(0).ownText() + " left)";

                    setMessage(msg);

                    startDownload("http://www.uloz.to" + premiumLink.attr("href"));
                    return;

                } else if (loggedIn)
                    setMessage("Login failed, using FREE download");

                Elements aNames = doc.getElementsByClass("jsShowDownload");
                if (!aNames.isEmpty())
                    reportFileName(aNames.get(0).ownText());

                final PostQuery pq = new PostQuery();
                final Map<String, String> hdr = new HashMap<String, String>();
                Elements eHiddens = freeForm.select("input[type=hidden]");

                hdr.put("X-Requested-With", "XMLHttpRequest");
                hdr.put("Referer", downloadLink);
                hdr.put("Accept", "application/json, text/javascript, */*; q=0.01");

                for (Element e : eHiddens)
                    pq.add(e.attr("name"), e.attr("value"));

                fetchPage("https://uloz.to/reloadXapca.php?rnd=" + Math.abs(new Random().nextInt()),
                        new PageFetchListener() {

                            @Override
                            public void onCompleted(ByteBuffer buf, Map<String, String> headers) {
                                CharBuffer cb = charsetUtf8.decode(buf);
                                String captchaUrl;

                                try {
                                    JSONObject json = new JSONObject(cb.toString());
                                    captchaUrl = "https:" + json.getString("image");
                                    pq.add("hash", json.getString("hash"));
                                    pq.add("timestamp", "" + json.getInt("timestamp"));
                                    pq.add("salt", "" + json.getInt("salt"));
                                } catch (JSONException e) {
                                    setFailed("Error parsing captcha JSON");
                                    return;
                                }

                                solveCaptcha(captchaUrl, new CaptchaListener() {

                                    @Override
                                    public void onFailed() {
                                        setFailed("Failed to decode the captcha code");
                                    }

                                    @Override
                                    public void onSolved(String text) {

                                        String action = freeForm.attr("action");
                                        pq.add("captcha_value", text);

                                        fetchPage("https://www.uloz.to" + action, new PageFetchListener() {

                                            @Override
                                            public void onCompleted(ByteBuffer buf,
                                                    Map<String, String> headers) {
                                                try {
                                                    CharBuffer cb = charsetUtf8.decode(buf);
                                                    JSONObject obj = new JSONObject(cb.toString());

                                                    startDownload(obj.getString("url"));
                                                } catch (Exception e) {
                                                    setFailed("" + e);
                                                }
                                            }

                                            @Override
                                            public void onFailed(String error) {
                                                setFailed(error);
                                            }

                                        }, pq.toString(), hdr);

                                    }
                                });
                            }

                            @Override
                            public void onFailed(String error) {
                                setFailed("Failed to load captcha AJAX page");
                            }

                        });

            } catch (Exception e) {
                e.printStackTrace();
                setFailed(e.toString());
            }
        }

        @Override
        public void onFailed(String error) {
            setFailed("Failed to load the initial page");
        }
    }, null);
}

From source file:org.paxle.core.doc.impl.AParserDocumentTest.java

protected void appendData(File source, IParserDocument target) throws IOException {
    final StringBuilder sourceText = new StringBuilder();

    // writing Data
    final CharBuffer buffer = CharBuffer.allocate(50);
    final InputStreamReader sourceReader = new InputStreamReader(new FileInputStream(source),
            Charset.forName("UTF-8"));
    while (sourceReader.read(buffer) != -1) {
        buffer.flip();/*w  ww  .  j av  a 2s.c om*/
        sourceText.append(buffer);
        target.append(buffer.toString());
        buffer.clear();
    }

    sourceReader.close();
    target.flush();
}

From source file:com.all.networking.AbstractNetworkingService.java

@Override
public final void messageReceived(IoSession session, Object message) {
    String json = null;/*from w ww.j  a  v a  2 s.c  om*/
    try {
        byte[] decodedBytes = Base64.decode(message.toString().getBytes());
        CharBuffer charBuff = UTF_DECODER.decode(ByteBuffer.wrap(decodedBytes));
        json = charBuff.toString();
    } catch (Exception e) {
        LOG.warn("Could not decode message with UTF-8.");
        json = new String(Base64.decode(message.toString().getBytes()));
    }
    NetworkingMessage networkingMessage = JsonConverter.toBean(json, NetworkingMessage.class);
    if (networkingMessage.isSplit()) {
        networkingMessage = mergeNetworkingMessageChunk(networkingMessage);
    }
    if (networkingMessage != null) {
        AllMessage<?> actualMessage = networkingMessage.getBody();
        InetSocketAddress remoteAddress = (InetSocketAddress) session.getRemoteAddress();
        actualMessage.putProperty(MESSAGE_SENDER_PUBLIC_ADDRESS, remoteAddress.getAddress().getHostAddress());
        actualMessage.putProperty(MESSAGE_SENDER, networkingMessage.getSender());
        actualMessage.putProperty(NETWORKING_SESSION_ID, Long.toString(session.getId()));
        sessionUpdated(session, networkingMessage);
        onAllMessage(actualMessage);
    }
}

From source file:test.PBEncryptLink.java

/**
 * Given an array of bytes, treat them as an array of ISO8859_1 characters
 * and convert them to a Java String./*  w w  w  .j ava  2s.c o  m*/
 * 
 * @param input
 *            array of bytes to convert.
 * @return String representing the array of bytes
 */
public String iso8859_1_BytesToString(byte[] input) {
    Charset charSet = Charset.forName("ISO-8859-1");
    ByteBuffer bb = ByteBuffer.wrap(input);
    CharBuffer cb = charSet.decode(bb);
    String output = cb.toString();
    return output;
}

From source file:com.metawiring.load.generators.LineExtractGenerator.java

private void loadLines(String filename) {

    InputStream stream = LineExtractGenerator.class.getClassLoader().getResourceAsStream(filename);
    if (stream == null) {
        throw new RuntimeException(filename + " was missing.");
    }//from w w w  . j  a  v a 2  s.  c o  m

    CharBuffer linesImage;
    try {
        InputStreamReader isr = new InputStreamReader(stream);
        linesImage = CharBuffer.allocate(1024 * 1024);
        isr.read(linesImage);
        isr.close();
    } catch (IOException e) {
        logger.error(e.getMessage());
        throw new RuntimeException(e);
    }
    linesImage.flip();
    Collections.addAll(lines, linesImage.toString().split("\n"));
}

From source file:org.tolven.security.password.PasswordHolder.java

public boolean isPasswordStoreUpToDate() {
    Passwords initialPasswords = loadPasswords();
    HashMap<String, PasswordInfo> passwordMapCopy = new HashMap<String, PasswordInfo>(getPasswordMap());
    passwordMapCopy.remove(getAdminGroupId());
    if (passwordMapCopy.size() != initialPasswords.getPasswordInfo().size()) {
        return false;
    }//from w  w  w .j  a  va  2 s .c o m
    char[] password = null;
    PasswordInfo passwordInfo = null;
    for (PasswordDetail passwordDetail : initialPasswords.getPasswordInfo()) {
        passwordInfo = passwordMapCopy.get(passwordDetail.getRefId());
        if (passwordInfo == null) {
            return false;
        }
        password = getPassword(passwordInfo.getRefId());
        CharBuffer passwordBuff = CharBuffer.wrap(password);
        if (!passwordBuff.toString().equals(passwordDetail.getPassword()))
            return false;
    }
    return true;
}

From source file:org.alfresco.extension.wcmdeployment.NaiveFilesystemDeploymentTarget.java

/**
 * @see org.alfresco.deployment.DeploymentTarget#getCurrentVersion(java.lang.String, java.lang.String)
 *//*from  w  w  w  . j a v a2s  .c o  m*/
public int getCurrentVersion(final String target, final String storeName) {
    log.trace("NaiveFilesystemDeploymentTarget.getCurrentVersion(" + target + ", " + storeName + ")");
    int result = 0;

    File targetMetaDirectory = new File(metadataDirectory, target);
    File storeMetaDirectory = new File(targetMetaDirectory, storeName);
    File versionFile = new File(storeMetaDirectory, VERSION_FILENAME);

    if (versionFile.exists()) {
        CharBuffer buffer = CharBuffer.allocate(16);
        Reader reader = null;

        try {
            reader = new InputStreamReader(new FileInputStream(versionFile));
            reader.read(buffer);

            result = Integer.valueOf(buffer.toString().trim());
        } catch (final IOException ioe) {
            log.warn("Unable to retrieve version infomation from '" + getPath(versionFile) + "'.", ioe);
        } catch (final NumberFormatException nfe) {
            log.warn("Unable to parse version number '" + buffer.toString() + "'.", nfe);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ioe) {
                    // *Gulp* - if this occurs there's not a lot else we can do but swallow it...
                }
            }
        }
    }

    return (result);
}

From source file:esg.node.components.monitoring.MonitorDAO.java

private void setDiskInfo(MonitorInfo info) {
    if (info.diskInfo == null) {
        info.diskInfo = new HashMap<String, Map<String, String>>();
    }//from  www.  j ava 2 s .  c  om

    info.diskInfo.clear();

    if (disk_info_byte_buffer == null) {
        log.warn("Disk Info Byte Buffer is : [" + disk_info_byte_buffer + "] cannot provide disk information!");
        return;
    }

    //"thredds_dataset_roots"
    Map<String, File> datasetRoots = new HashMap<String, File>();

    try {
        Charset cs = Charset.forName("8859_1");
        CharBuffer cb = cs.newDecoder().decode(disk_info_byte_buffer);

        //Flatten the file...
        String data = cb.toString().replaceAll("[\n]+", " ");

        Matcher m = disk_info_dsroot_pat.matcher(data);
        String key_vals = null;
        Matcher m2 = null;

        while (m.find()) {
            key_vals = m.group(1);
            m2 = disk_info_dsroot_keyval_pat.matcher(key_vals);
            while (m2.find()) {
                log.trace("Checking... dataset_root [" + m2.group(1) + "] dir [" + m2.group(2) + "]");
                datasetRoots.put(m2.group(1), new File(m2.group(2)));
            }
        }
        disk_info_byte_buffer.flip();

        Map<String, String> statsMap = null;
        for (String rootLabel : datasetRoots.keySet()) {
            Long total, free = 0L;
            statsMap = new HashMap<String, String>();
            log.trace("rootLabel: " + rootLabel);
            File f = datasetRoots.get(rootLabel);
            log.trace("value : " + f);
            statsMap.put(MonitorInfo.TOTAL_SPACE,
                    "" + (total = (datasetRoots.get(rootLabel).getTotalSpace()) / 1024L));
            statsMap.put(MonitorInfo.FREE_SPACE,
                    "" + (free = (datasetRoots.get(rootLabel).getFreeSpace()) / 1024L));
            statsMap.put(MonitorInfo.USED_SPACE, "" + (total - free));
            info.diskInfo.put(rootLabel, statsMap);
        }
    } catch (java.nio.charset.CharacterCodingException e) {
        log.error(e);
    }
}