org.sandsoft.cymric.util.Commons.java Source code

Java tutorial

Introduction

Here is the source code for org.sandsoft.cymric.util.Commons.java

Source

/*
 * Copyright 2015 Sudipto Chandra.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.sandsoft.cymric.util;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import org.apache.commons.io.IOUtils;

/**
 * Common functions used everywhere.
 *
 * @author Sudipto Chandra
 */
public final class Commons {

    /**
     * Create a new custom pane from FXML data. <br>
     * Restraints: Name and package of FXML file should be the same as
     * <code>resourceClass</code>. <code>resourceClass</code> should extend
     * <code>BorderPane</code> or one of its descendents.
     *
     * @param resourceClass Pane class in which data to be loaded.
     * @return Pane type object containing loaded node.
     */
    public static Pane loadPaneFromFXML(Class resourceClass) throws IOException {
        //init loader           
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(resourceClass.getResource(resourceClass.getSimpleName() + ".fxml"));

        //load fxml
        Node node = (Node) loader.load();
        BorderPane control = (BorderPane) loader.getController();

        BorderPane.setAlignment(node, Pos.CENTER);
        control.setCenter(node);

        return control;
    }

    /**
     * Reads a input stream fully and converts it to string. <br>
     * <i>It uses <code>org.apache.commons.io.IOUtils.</code></i>
     *
     * @param is Input stream to convert into string.
     * @param encoding Encoding to use. For standard encoding set use
     * <code>java.nio.charset.StandardCharsets</code>. This can be null; if null
     * UTF-8 is used as default.
     * @return Converted string result; on error <code>null</code> value is
     * returned.
     */
    public static String readFullStream(InputStream is, Charset encoding) {
        try {
            if (encoding == null) {
                encoding = StandardCharsets.UTF_8;
            }
            return IOUtils.toString(is, encoding);
        } catch (Exception ex) {
            return null;
        }
    }

}