Example usage for java.util Arrays fill

List of usage examples for java.util Arrays fill

Introduction

In this page you can find the example usage for java.util Arrays fill.

Prototype

public static void fill(Object[] a, Object val) 

Source Link

Document

Assigns the specified Object reference to each element of the specified array of Objects.

Usage

From source file:Main.java

  public static void main(String[] argv) throws Exception {

  int[] intArr = new int[10];
  int intFillValue = -1;
  Arrays.fill(intArr, intFillValue);
}

From source file:Main.java

  public static void main(String[] argv) throws Exception {

  long[] longArr = new long[10];
  long longFillValue = -1;
  Arrays.fill(longArr, longFillValue);
}

From source file:Main.java

  public static void main(String[] argv) throws Exception {

  float[] floatArr = new float[10];
  float floatFillValue = -1;

  Arrays.fill(floatArr, floatFillValue);
}

From source file:Main.java

public static void main(String[] argv) throws Exception {

        double[] doubleArr = new double[10];
        double doubleFillValue = -1;
        Arrays.fill(doubleArr, doubleFillValue);
    }/*from  www . j a v  a  2s .  c  om*/

From source file:Password.java

public static void main(String args[]) throws IOException {

    Console c = System.console();
    if (c == null) {
        System.err.println("No console.");
        System.exit(1);//from   www. j  a v  a 2  s  .c  o  m
    }

    String login = c.readLine("Enter your login: ");
    char[] oldPassword = c.readPassword("Enter your old password: ");

    if (verify(login, oldPassword)) {
        boolean noMatch;
        do {
            char[] newPassword1 = c.readPassword("Enter your new password: ");
            char[] newPassword2 = c.readPassword("Enter new password again: ");
            noMatch = !Arrays.equals(newPassword1, newPassword2);
            if (noMatch) {
                c.format("Passwords don't match. Try again.%n");
            } else {
                change(login, newPassword1);
                c.format("Password for %s changed.%n", login);
            }
            Arrays.fill(newPassword1, ' ');
            Arrays.fill(newPassword2, ' ');
        } while (noMatch);
    }

    Arrays.fill(oldPassword, ' ');

}

From source file:CertificateSigner.java

public static void main(String[] args) {
    String ksname = null; // the keystore name
    String alias = null; // the private key alias
    String inname = null; // the input file name
    String outname = null; // the output file name
    for (int i = 0; i < args.length; i += 2) {
        if (args[i].equals("-keystore"))
            ksname = args[i + 1];//from   w  w w  .  j  a  v a2s .  com
        else if (args[i].equals("-alias"))
            alias = args[i + 1];
        else if (args[i].equals("-infile"))
            inname = args[i + 1];
        else if (args[i].equals("-outfile"))
            outname = args[i + 1];
        else
            usage();
    }

    if (ksname == null || alias == null || inname == null || outname == null)
        usage();

    try {
        Console console = System.console();
        if (console == null)
            error("No console");
        char[] password = console.readPassword("Keystore password: ");
        KeyStore store = KeyStore.getInstance("JKS", "SUN");
        InputStream in = new FileInputStream(ksname);
        store.load(in, password);
        Arrays.fill(password, ' ');
        in.close();

        char[] keyPassword = console.readPassword("Key password for %s: ", alias);
        PrivateKey issuerPrivateKey = (PrivateKey) store.getKey(alias, keyPassword);
        Arrays.fill(keyPassword, ' ');

        if (issuerPrivateKey == null)
            error("No such private key");

        in = new FileInputStream(inname);

        CertificateFactory factory = CertificateFactory.getInstance("X.509");

        X509Certificate inCert = (X509Certificate) factory.generateCertificate(in);
        in.close();
        byte[] inCertBytes = inCert.getTBSCertificate();

        X509Certificate issuerCert = (X509Certificate) store.getCertificate(alias);
        Principal issuer = issuerCert.getSubjectDN();
        String issuerSigAlg = issuerCert.getSigAlgName();

        FileOutputStream out = new FileOutputStream(outname);

        X509CertInfo info = new X509CertInfo(inCertBytes);
        info.set(X509CertInfo.ISSUER, new CertificateIssuerName((X500Name) issuer));

        X509CertImpl outCert = new X509CertImpl(info);
        outCert.sign(issuerPrivateKey, issuerSigAlg);
        outCert.derEncode(out);

        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:jsdp.app.control.clqg.univariate.CLQG.java

public static void main(String args[]) {

    /*******************************************************************
     * Problem parameters//ww w  .ja  va  2s  .  c  o m
     */

    int T = 20; // Horizon length
    double G = 1; // Input transition
    double Phi = 1; // State transition
    double R = 1; // Input cost
    double Q = 1; // State cost
    double Ulb = -1; // Action constraint
    double Uub = 20; // Action constraint
    double noiseStd = 5; // Standard deviation of the noise

    double[] noiseStdArray = new double[T];
    Arrays.fill(noiseStdArray, noiseStd);
    double truncationQuantile = 0.975;

    // Random variables

    Distribution[] distributions = IntStream.iterate(0, i -> i + 1).limit(noiseStdArray.length)
            .mapToObj(i -> new NormalDist(0, noiseStdArray[i]))

            .toArray(Distribution[]::new);
    double[] supportLB = IntStream.iterate(0, i -> i + 1).limit(T)
            .mapToDouble(i -> NormalDist.inverseF(0, noiseStdArray[i], 1 - truncationQuantile)).toArray();

    double[] supportUB = IntStream.iterate(0, i -> i + 1).limit(T)
            .mapToDouble(i -> NormalDist.inverseF(0, noiseStdArray[i], truncationQuantile)).toArray();

    double initialX = 0; // Initial state

    /*******************************************************************
     * Model definition
     */

    // State space

    double stepSize = 0.5; //Stepsize must be 1 for discrete distributions
    double minState = -25;
    double maxState = 100;
    StateImpl.setStateBoundaries(stepSize, minState, maxState);

    // Actions

    Function<State, ArrayList<Action>> buildActionList = (Function<State, ArrayList<Action>> & Serializable) s -> {
        StateImpl state = (StateImpl) s;
        ArrayList<Action> feasibleActions = new ArrayList<Action>();
        double maxAction = Math.min(Uub, (StateImpl.getMaxState() - Phi * state.getInitialState()) / G);
        double minAction = Math.max(Ulb, (StateImpl.getMinState() - Phi * state.getInitialState()) / G);
        for (double actionPointer = minAction; actionPointer <= maxAction; actionPointer += StateImpl
                .getStepSize()) {
            feasibleActions.add(new ActionImpl(state, actionPointer));
        }
        return feasibleActions;
    };

    Function<State, Action> idempotentAction = (Function<State, Action> & Serializable) s -> new ActionImpl(s,
            0.0);

    ImmediateValueFunction<State, Action, Double> immediateValueFunction = (initialState, action,
            finalState) -> {
        ActionImpl a = (ActionImpl) action;
        StateImpl fs = (StateImpl) finalState;
        double inputCost = Math.pow(a.getAction(), 2) * R;
        double stateCost = Math.pow(fs.getInitialState(), 2) * Q;
        return inputCost + stateCost;
    };

    // Random Outcome Function

    RandomOutcomeFunction<State, Action, Double> randomOutcomeFunction = (initialState, action, finalState) -> {
        double realizedNoise = ((StateImpl) finalState).getInitialState()
                - ((StateImpl) initialState).getInitialState() * Phi - ((ActionImpl) action).getAction() * G;
        return realizedNoise;
    };

    /*******************************************************************
     * Solve
     */

    // Sampling scheme

    SamplingScheme samplingScheme = SamplingScheme.NONE;
    int maxSampleSize = 50;
    double reductionFactorPerStage = 1;

    // Value Function Processing Method: backward recursion
    double discountFactor = 1.0;
    int stateSpaceLowerBound = 10000000;
    float loadFactor = 0.8F;
    BackwardRecursionImpl recursion = new BackwardRecursionImpl(OptimisationDirection.MIN, distributions,
            supportLB, supportUB, immediateValueFunction, randomOutcomeFunction, buildActionList,
            idempotentAction, discountFactor, samplingScheme, maxSampleSize, reductionFactorPerStage,
            stateSpaceLowerBound, loadFactor, HashType.THASHMAP);

    System.out.println("--------------Backward recursion--------------");
    StopWatch timer = new StopWatch();
    OperatingSystemMXBean osMBean;
    try {
        osMBean = ManagementFactory.newPlatformMXBeanProxy(ManagementFactory.getPlatformMBeanServer(),
                ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);
        long nanoBefore = System.nanoTime();
        long cpuBefore = osMBean.getProcessCpuTime();

        timer.start();
        recursion.runBackwardRecursionMonitoring();
        timer.stop();

        long cpuAfter = osMBean.getProcessCpuTime();
        long nanoAfter = System.nanoTime();

        long percent;
        if (nanoAfter > nanoBefore)
            percent = ((cpuAfter - cpuBefore) * 100L) / (nanoAfter - nanoBefore);
        else
            percent = 0;

        System.out.println(
                "Cpu usage: " + percent + "% (" + Runtime.getRuntime().availableProcessors() + " cores)");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println();
    double ETC = recursion.getExpectedCost(initialX);
    StateDescriptorImpl initialState = new StateDescriptorImpl(0, initialX);
    double action = recursion.getOptimalAction(initialState).getAction();
    System.out.println("Expected total cost (assuming an initial state " + initialX + "): " + ETC);
    System.out.println("Optimal initial action: " + action);
    System.out.println("Time elapsed: " + timer);
    System.out.println();
}

From source file:com.zimbra.cs.util.SmtpInject.java

public static void main(String[] args) {
    CliUtil.toolSetup();/*from ww w.  j av  a2s  . co  m*/
    CommandLine cl = parseArgs(args);

    if (cl.hasOption("h")) {
        usage(null);
    }

    String file = null;
    if (!cl.hasOption("f")) {
        usage("no file specified");
    } else {
        file = cl.getOptionValue("f");
    }
    try {
        ByteUtil.getContent(new File(file));
    } catch (IOException ioe) {
        usage(ioe.getMessage());
    }

    String host = null;
    if (!cl.hasOption("a")) {
        usage("no smtp server specified");
    } else {
        host = cl.getOptionValue("a");
    }

    String sender = null;
    if (!cl.hasOption("s")) {
        usage("no sender specified");
    } else {
        sender = cl.getOptionValue("s");
    }

    String recipient = null;
    if (!cl.hasOption("r")) {
        usage("no recipient specified");
    } else {
        recipient = cl.getOptionValue("r");
    }

    boolean trace = false;
    if (cl.hasOption("T")) {
        trace = true;
    }

    boolean tls = false;
    if (cl.hasOption("t")) {
        tls = true;
    }

    boolean auth = false;
    String user = null;
    String password = null;
    if (cl.hasOption("A")) {
        auth = true;
        if (!cl.hasOption("u")) {
            usage("auth enabled, no user specified");
        } else {
            user = cl.getOptionValue("u");
        }
        if (!cl.hasOption("p")) {
            usage("auth enabled, no password specified");
        } else {
            password = cl.getOptionValue("p");
        }
    }

    if (cl.hasOption("v")) {
        mLog.info("SMTP server: " + host);
        mLog.info("Sender: " + sender);
        mLog.info("Recipient: " + recipient);
        mLog.info("File: " + file);
        mLog.info("TLS: " + tls);
        mLog.info("Auth: " + auth);
        if (auth) {
            mLog.info("User: " + user);
            char[] dummyPassword = new char[password.length()];
            Arrays.fill(dummyPassword, '*');
            mLog.info("Password: " + new String(dummyPassword));
        }
    }

    Properties props = System.getProperties();

    props.put("mail.smtp.host", host);

    if (auth) {
        props.put("mail.smtp.auth", "true");
    } else {
        props.put("mail.smtp.auth", "false");
    }

    if (tls) {
        props.put("mail.smtp.starttls.enable", "true");
    } else {
        props.put("mail.smtp.starttls.enable", "false");
    }

    // Disable certificate checking so we can test against
    // self-signed certificates
    props.put("mail.smtp.ssl.socketFactory", SocketFactories.dummySSLSocketFactory());

    Session session = Session.getInstance(props, null);
    session.setDebug(trace);

    try {
        // create a message
        MimeMessage msg = new ZMimeMessage(session, new ZSharedFileInputStream(file));
        InternetAddress[] address = { new JavaMailInternetAddress(recipient) };
        msg.setFrom(new JavaMailInternetAddress(sender));

        // attach the file to the message
        Transport transport = session.getTransport("smtp");
        transport.connect(null, user, password);
        transport.sendMessage(msg, address);

    } catch (MessagingException mex) {
        mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
        }
        System.exit(1);
    }
}

From source file:jeffaschenk.tomcat.zuul.util.KeyFileUtils.java

/**
 * Utility Main to provide capabilities to generate a protected KeyFile for use with Zuul
 *
 * @param args - Incoming program Arguments
 * @throws Exception//from w  w w .  j  a va 2 s .c  o  m
 */
public static void main(String[] args) throws Exception {

    // Initialize our Ciphers
    KeyFileUtils keyFileUtils = new KeyFileUtils();
    keyFileUtils.InitCiphers();

    // Assume we our sole purpose in life is to prompt for a Password, which is the same,
    // ensure we have an argument to be out filename.
    if ((args == null) || (args.length != 1)) {
        System.out.println("Invalid number of Arguments specified!");
        System.out.println(
                "Usage: " + keyFileUtils.getClass().getName() + " <Fully Qualified Output Key Filename>");
        return;
    }

    // Validate Argument as a file.
    File outputKeyFile = new File(args[0]);
    if (outputKeyFile.exists()) {
        // Prompt to overwrite...
        char[] answer = readPassword("Specified Key File:[" + outputKeyFile + "], exists. Overwrite? (y/n)? ");
        if ((answer == null) || (answer.length == 0)
                || (!String.valueOf(answer).toUpperCase().startsWith("Y"))) {
            System.out.println(
                    "Existing Key File:[" + outputKeyFile + "], exists. Will not be Overwritten, Done.");
            return;
        } else {
            outputKeyFile.delete();
        }
    }

    // Prompt Operator for the Zuul Encryption Password to be encrypted in a file and saved for later access.
    // Prompt to overwrite...
    char[] password = obtainValidatedPassword("Enter Zuul Encryption Password: ");
    if (password == null) {
        System.out.println("Unable to obtain Password, Done.");
        return;
    }

    // Create our Input and Output Streams for the encryption of the Password.
    InputStream is = IOUtils.toInputStream(String.valueOf(password), "UTF-8");
    FileOutputStream fos = new FileOutputStream(outputKeyFile);

    // Encrypt
    keyFileUtils.CBCEncrypt(is, fos);

    // Now lets us Validate the file.
    keyFileUtils.ResetCiphers();
    keyFileUtils = new KeyFileUtils();
    keyFileUtils.InitCiphers();

    // Obtain the Decrypted Contents
    byte[] obtainedDecryptedData = keyFileUtils.CBCDecrypt(new FileInputStream(outputKeyFile));

    // Compare to validate...
    boolean valid = String.valueOf(password).equals(new String(obtainedDecryptedData));
    Arrays.fill(password, ' ');
    Arrays.fill(obtainedDecryptedData, (byte) 0x00);
    if (valid) {
        System.out.println("Key File:[" + outputKeyFile + "], validated and available for use, Done.");
        return;
    } else {
        System.out.println("Key File:[" + outputKeyFile + "], Did not Validate, very bad!");
        return;
    }
}

From source file:Main.java

private static void fillRowsWithZeros(double[][] a, int rows, int cols) {
    if (rows >= 0) {
        double[] row = new double[cols];
        Arrays.fill(row, 0.0);
        a[rows] = row;/*from  w  w w  .j av  a2  s  .c  o m*/
        fillRowsWithZeros(a, rows - 1, cols);
    }
}