Example usage for java.util Arrays copyOfRange

List of usage examples for java.util Arrays copyOfRange

Introduction

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

Prototype

public static boolean[] copyOfRange(boolean[] original, int from, int to) 

Source Link

Document

Copies the specified range of the specified array into a new array.

Usage

From source file:com.netflix.spinnaker.halyard.core.job.v1.JobExecutorLocal.java

@Override
public String startJob(JobRequest jobRequest, Map<String, String> env, InputStream stdIn,
        ByteArrayOutputStream stdOut, ByteArrayOutputStream stdErr) {
    List<String> tokenizedCommand = jobRequest.getTokenizedCommand();
    if (tokenizedCommand == null || tokenizedCommand.isEmpty()) {
        throw new IllegalArgumentException("JobRequest must include a tokenized command to run");
    }/*from w ww. ja v a  2s .c  o m*/

    final long timeoutMillis = jobRequest.getTimeoutMillis() == null ? ExecuteWatchdog.INFINITE_TIMEOUT
            : jobRequest.getTimeoutMillis();

    String jobId = UUID.randomUUID().toString();

    pendingJobSet.add(jobId);

    log.info("Scheduling job " + jobRequest.getTokenizedCommand() + " with id " + jobId);

    scheduler.createWorker().schedule(new Action0() {
        @Override
        public void call() {
            PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(stdOut, stdErr, stdIn);
            CommandLine commandLine;

            log.info("Executing " + jobId + "with tokenized command: " + tokenizedCommand);

            // Grab the first element as the command.
            commandLine = new CommandLine(jobRequest.getTokenizedCommand().get(0));

            // Treat the rest as arguments.
            String[] arguments = Arrays.copyOfRange(tokenizedCommand.toArray(new String[0]), 1,
                    tokenizedCommand.size());

            commandLine.addArguments(arguments, false);

            DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
            ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutMillis) {
                @Override
                public void timeoutOccured(Watchdog w) {
                    // If a watchdog is passed in, this was an actual time-out. Otherwise, it is likely
                    // the result of calling watchdog.destroyProcess().
                    if (w != null) {
                        log.warn("Job " + jobId + " timed-out after " + timeoutMillis + "ms.");

                        cancelJob(jobId);
                    }

                    super.timeoutOccured(w);
                }
            };

            Executor executor = new DefaultExecutor();
            executor.setStreamHandler(pumpStreamHandler);
            executor.setWatchdog(watchdog);
            try {
                executor.execute(commandLine, env, resultHandler);
            } catch (IOException e) {
                throw new RuntimeException("Execution of " + jobId + " failed ", e);
            }

            // Give the job some time to spin up.
            try {
                Thread.sleep(500);
            } catch (InterruptedException ignored) {
            }

            jobIdToHandlerMap.put(jobId, new ExecutionHandler().setResultHandler(resultHandler)
                    .setWatchdog(watchdog).setStdOut(stdOut).setStdErr(stdErr));

            if (pendingJobSet.contains(jobId)) {
                pendingJobSet.remove(jobId);
            } else {
                // If the job was removed from the set of pending jobs by someone else, its deletion was requested
                jobIdToHandlerMap.remove(jobId);
                watchdog.destroyProcess();
            }
        }
    });

    return jobId;
}

From source file:lucee.runtime.net.http.MultiPartResponseUtils.java

private static Struct extractHeaders(String rawHeaders) throws PageException {
    Struct result = new StructImpl();
    String[] headers = ListUtil.listToStringArray(rawHeaders, '\n');
    for (String rawHeader : headers) {
        String[] headerArray = ListUtil.listToStringArray(rawHeader, ':');
        String headerName = headerArray[0];
        if (!StringUtil.isEmpty(headerName, true)) {
            String value = StringUtils.join(Arrays.copyOfRange(headerArray, 1, headerArray.length), ":").trim();
            result.set(headerName, value);
        }//from  ww w  . j  a  va2 s  .  co m
    }
    return result;
}

From source file:co.foxdev.foxbot.utils.CommandManager.java

public boolean dispatchCommand(MessageEvent event, String commandLine) {
    String[] split = commandLine.split(" ");
    User sender = event.getUser();//from  w ww  .  j  av  a2 s.  c o  m
    String commandName = split[0].toLowerCase();
    Command command = commandMap.get(commandName);

    if (runCustomCommand(event.getChannel().getName(), commandName)) {
        return true;
    }

    if (command == null) {
        return false;
    }

    foxbot.getLogger()
            .info(String.format("Dispatching command '%s' used by %s", command.getName(), sender.getNick()));

    String permission = command.getPermission();

    if (permission != null && !permission.isEmpty()) {
        if (!foxbot.getPermissionManager().userHasPermission(sender, permission)) {
            foxbot.getLogger().warn(String.format("Permission denied for command '%s' used by %s",
                    command.getName(), sender.getNick()));
            sender.send().notice("You do not have permission to do that!");
            return false;
        }
    }

    String[] args = Arrays.copyOfRange(split, 1, split.length);

    try {
        command.execute(event, args);
    } catch (Exception ex) {
        sender.send()
                .notice("An internal error occurred whilst executing this command, please alert a bot admin.");
        foxbot.getLogger().error("Error dispatching command: " + command, ex);
    }
    return true;
}

From source file:com.itemanalysis.psychometrics.irt.model.IrmGRM.java

public double cumulativeProbability(double theta, double[] iparam, int category, double D) {
    if (category > maxCategory || category < minCategory)
        return 0;
    if (category == minCategory)
        return 1.0;

    double a = iparam[0];
    double[] s = Arrays.copyOfRange(iparam, 1, iparam.length);

    double Zk = D * a * (theta - s[category - 1]);
    double expZk = Math.exp(Zk);
    double prob = expZk / (1 + expZk);

    return prob;/*from  w w  w . j  ava2s.  c om*/
}

From source file:com.cloudera.sqoop.tool.JobTool.java

/**
 * Given an array of strings, return all elements of this
 * array up to (but not including) the first instance of "--".
 *//*  w  w  w .  j  av  a  2  s.  c  o  m*/
private String[] getElementsUpToDoubleDash(String[] array) {
    String[] parseableChildArgv = null;
    for (int i = 0; i < array.length; i++) {
        if ("--".equals(array[i])) {
            parseableChildArgv = Arrays.copyOfRange(array, 0, i);
            break;
        }
    }

    if (parseableChildArgv == null) {
        // Didn't find any nested '--'.
        parseableChildArgv = array;
    }

    return parseableChildArgv;
}

From source file:com.titankingdoms.dev.titanchat.command.defaults.BlacklistCommand.java

@Override
public void execute(CommandSender sender, Channel channel, String[] args) {
    if (args[0].equals("list")) {
        String list = StringUtils.join(channel.getBlacklist(), ", ");
        sendMessage(sender, "&6" + channel.getName() + " Blacklist: " + list);
        return;/*from   ww w  .  j  a v a2s . c o m*/

    } else {
        if (args.length < 2) {
            sendMessage(sender, "&4Invalid argument length");
            sendMessage(sender, "&6/titanchat [@<channel>] blacklist " + getUsage());
            return;
        }
    }

    Participant participant = plugin.getParticipantManager().getParticipant(args[1]);

    if (args[0].equalsIgnoreCase("add")) {
        if (channel.getBlacklist().contains(participant.getName())) {
            sendMessage(sender, participant.getDisplayName() + " &4is already on the blacklist");
            return;
        }

        channel.unlink(participant);
        channel.getBlacklist().add(participant.getName());
        participant.notice("&4You have been added to the blacklist of " + channel.getName());

        if (args.length > 2) {
            String reason = StringUtils.join(Arrays.copyOfRange(args, 2, args.length), " ").trim();
            participant.notice("&4Reason: " + reason);
        }

        if (!channel.isLinked(plugin.getParticipantManager().getParticipant(sender)))
            sendMessage(sender, participant.getDisplayName() + " &6has been added to the blacklist");

        channel.notice(participant.getDisplayName() + " &6has been added to the blacklist");

    } else if (args[0].equalsIgnoreCase("remove")) {
        if (!channel.getBlacklist().contains(participant.getName())) {
            sendMessage(sender, participant.getDisplayName() + " &4is not on the blacklist");
            return;
        }

        channel.getBlacklist().remove(participant.getName());
        participant.notice("&6You have been removed from the blacklist of " + channel.getName());

        if (args.length > 2) {
            String reason = StringUtils.join(Arrays.copyOfRange(args, 2, args.length), " ").trim();
            participant.notice("&6Reason: " + reason);
        }

        if (!channel.isLinked(plugin.getParticipantManager().getParticipant(sender)))
            sendMessage(sender, participant.getDisplayName() + " &6has been removed from the blacklist");

        channel.notice(participant.getDisplayName() + " &6has been removed from the blacklist");

    } else {
        sendMessage(sender, "&4Incorrect usage: /titanchat [@<channel>] blacklist " + getUsage());
    }
}

From source file:com.opengamma.analytics.math.interpolation.PolynomialInterpolator1D.java

@Override
public Double interpolate(final Interpolator1DDataBundle data, final Double value) {
    Validate.notNull(value, "value");
    Validate.notNull(data, "data bundle");
    final int n = data.size();
    final double[] keys = data.getKeys();
    final double[] values = data.getValues();
    if (n <= _degree) {
        throw new MathException("Need at least " + (_degree + 1)
                + " data points to perform polynomial interpolation of degree " + _degree);
    }//from ww w .ja v a2s . c o m
    if (data.getLowerBoundIndex(value) == n - 1) {
        return values[n - 1];
    }
    final int lower = data.getLowerBoundIndex(value);
    final int lowerBound = lower - _offset;
    final int upperBound = _degree + 1 + lowerBound;
    if (lowerBound < 0) {
        throw new MathException(
                "Could not get lower bound: index " + lowerBound + " must be greater than or equal to zero");
    }
    if (upperBound > n + 1) {
        throw new MathException(
                "Could not get upper bound: index " + upperBound + " must be less than or equal to " + (n + 1));
    }
    final double[] x = Arrays.copyOfRange(keys, lowerBound, upperBound);
    final double[] y = Arrays.copyOfRange(values, lowerBound, upperBound);
    try {
        final PolynomialFunctionLagrangeForm lagrange = _interpolator.interpolate(x, y);
        return CommonsMathWrapper.unwrap(lagrange).evaluate(value);
    } catch (final org.apache.commons.math.MathException e) {
        throw new MathException(e);
    }
}

From source file:gobblin.crypto.JCEKSKeystoreCredentialStoreCli.java

@Override
public void run(String[] args) {
    if (args.length < 2) {
        System.out.println("Must specify an action!");
        new HelpAction().run(args);
        return;/*from w w w .  j  av  a 2  s  .co m*/
    }

    String actionStr = args[1];
    Action action = actionMap.get(actionStr);
    if (action == null) {
        System.out.println("Action " + actionStr + " unknown!");
        new HelpAction().run(args);
        return;
    }

    action.run(Arrays.copyOfRange(args, 1, args.length));
}

From source file:my.adam.smo.EncryptionTest.java

@Test
public void symetricEncryptionLongMessage() {
    ApplicationContext clientContext = new ClassPathXmlApplicationContext("Context.xml");
    SymmetricEncryptionBox box = clientContext.getBean(SymmetricEncryptionBox.class);
    int plainTextLength = 17;

    byte[] plainText = new byte[plainTextLength];
    random.nextBytes(plainText);/* w w  w . java 2  s. co  m*/

    byte[] cryptogram = box.encrypt(plainText);
    Assert.assertFalse("plain text leaked!!!", Arrays.equals(plainText,
            Arrays.copyOfRange(cryptogram, SymmetricEncryptionBox.ivLength, cryptogram.length)));

    byte[] decrypted = box.decrypt(cryptogram);
    Assert.assertTrue("unable to decrypt", Arrays.equals(plainText, decrypted));
}

From source file:de.fichtelmax.asn1.ASN1PrinterTest.java

@Test
public void printHalfX509() throws IOException, CertificateException {
    byte[] x509Bytes = IOUtils.toByteArray(ASN1Printer.class.getResourceAsStream("/certificate.crt"));
    x509Bytes = Arrays.copyOfRange(x509Bytes, 0, x509Bytes.length / 2);

    cut.print(x509Bytes);//from  ww w .jav a 2 s  .  c o m

    verify(out).println(ASN1Printer.INCOMPLETE_MESSAGE);
}