List of usage examples for java.util Arrays copyOfRange
public static boolean[] copyOfRange(boolean[] original, int from, int to)
From source file:com.denimgroup.threadfix.framework.util.CommonPathFinder.java
@Nullable private static String[] getCommonParts(@Nullable String[] soFar, @Nonnull String[] newParts) { String[] returnParts = newParts; if (soFar != null && soFar.length == 0) { returnParts = soFar;/*from ww w. j ava 2 s.co m*/ } else if (soFar != null) { int endIndex = 0; for (int i = 0; i < soFar.length && i < newParts.length; i++) { if (!soFar[i].equalsIgnoreCase(newParts[i])) { break; } else { endIndex += 1; } } if (endIndex == 0) { returnParts = new String[] {}; } else if (endIndex == soFar.length) { returnParts = soFar; } else { returnParts = Arrays.copyOfRange(soFar, 0, endIndex); } } return returnParts; }
From source file:com.ms.commons.udas.impl.commons.MemcachedKeyStore.java
/** * @param allStoedKey Key?//from w w w .jav a 2 s . c o m * @param oldIndexSize */ private void restoreToRemote(Set<String> allStoedKey) { // long t1 = System.currentTimeMillis(); // ??? String[] allStoredKeyArray = allStoedKey.toArray(new String[0]); // long t2 = System.currentTimeMillis(); // logger.warn(nameSpace + "restoreToRemote: toArray() " + (t2 - t1)); // int newBundleCount = calIndexSize(allStoredKeyArray); // ?N-1? // long t3 = System.currentTimeMillis(); for (int i = 0; i < newBundleCount - 1; i++) { // String[] newKeyArray = Arrays.copyOfRange(allStoredKeyArray, 0, key_bundle_size); String[] remainKeyArray = Arrays.copyOfRange(allStoredKeyArray, key_bundle_size, allStoredKeyArray.length); allStoredKeyArray = remainKeyArray; // ? Set<String> newSet = new HashSet<String>(Arrays.asList(newKeyArray)); store(createIndexKey(i), newSet); } // long t4 = System.currentTimeMillis(); // logger.warn(nameSpace + "restoreToRemote: copyOfRange() " + newBundleCount + " " + (t4 - t3)); // ? Set<String> newSet = new HashSet<String>(Arrays.asList(allStoredKeyArray)); store(createIndexKey(newBundleCount - 1), newSet); // ??Key int currentIndex = getIndexSize(); if (newBundleCount < currentIndex) { for (int i = newBundleCount; i < currentIndex; i++) { String keyId = createIndexKey(i); deleteFromMemcached(keyId); } } // Keysize store(memcached_key_second_index_size, newBundleCount); }
From source file:net.netheos.pcsapi.BytesIOTest.java
private void checkFileByteSink(byte[] dataToWrite, boolean abort, ByteSink fbs, File file, boolean withTempName, boolean deleteOnAbort) throws IOException { File actualFile = file;// w w w . j a v a 2 s.c o m if (withTempName) { actualFile = new File(file.getPath() + ".part"); } ByteSinkStream stream = fbs.openStream(); try { // check file exists : assertTrue(actualFile.exists()); fbs.setExpectedLength(dataToWrite.length); // write not all bytes, only beginning of data : stream.write(Arrays.copyOfRange(dataToWrite, 0, 10)); stream.flush(); assertEquals(10, actualFile.length()); if (abort) { LOGGER.info("Aborting stream of byte sink !"); stream.abort(); } } finally { IOUtils.closeQuietly(stream); } boolean fileStillExists = file.exists(); boolean tempFileStillExists = actualFile.exists(); if (!abort) { // operation has not been aborted : so file never deleted assertTrue(fileStillExists); } else { // operation has been aborted : // if a temp file is used and not deleted, it has not been renamed : assertTrue(tempFileStillExists != deleteOnAbort); } }
From source file:com.intellectualcrafters.plot.commands.FlagCmd.java
@Override public boolean execute(final PlotPlayer player, final String... args) { /*/*from w w w.j av a 2 s. co m*/ * plot flag set fly true * plot flag remove fly * plot flag remove use 1,3 * plot flag add use 2,4 * plot flag list */ if (args.length == 0) { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag <set|remove|add|list|info>"); return false; } final Location loc = player.getLocation(); final Plot plot = MainUtil.getPlot(loc); if (plot == null) { MainUtil.sendMessage(player, C.NOT_IN_PLOT); return false; } if (!plot.hasOwner()) { sendMessage(player, C.PLOT_NOT_CLAIMED); return false; } if (!plot.isAdded(player.getUUID()) && !Permissions.hasPermission(player, "plots.set.flag.other")) { MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.set.flag.other"); return false; } if (args.length > 1 && FlagManager.isReserved(args[1])) { MainUtil.sendMessage(player, C.NOT_VALID_FLAG); return false; } switch (args[0].toLowerCase()) { case "info": { if (!Permissions.hasPermission(player, "plots.set.flag")) { MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.flag.info"); return false; } if (args.length != 2) { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag info <flag>"); return false; } final AbstractFlag af = FlagManager.getFlag(args[1]); if (af == null) { MainUtil.sendMessage(player, C.NOT_VALID_FLAG); MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag info <flag>"); return false; } // flag key MainUtil.sendMessage(player, C.FLAG_KEY, af.getKey()); // flag type MainUtil.sendMessage(player, C.FLAG_TYPE, af.value.getClass().getSimpleName()); // Flag type description MainUtil.sendMessage(player, C.FLAG_DESC, af.getValueDesc()); return true; } case "set": { if (!Permissions.hasPermission(player, "plots.set.flag")) { MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.set.flag"); return false; } if (args.length < 3) { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag set <flag> <value>"); return false; } final AbstractFlag af = FlagManager.getFlag(args[1].toLowerCase()); if (af == null) { MainUtil.sendMessage(player, C.NOT_VALID_FLAG); return false; } if (!Permissions.hasPermission(player, "plots.set.flag." + args[1].toLowerCase())) { MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.set.flag." + args[1].toLowerCase()); return false; } final String value = StringUtils.join(Arrays.copyOfRange(args, 2, args.length), " "); final Object parsed = af.parseValueRaw(value); if (parsed == null) { MainUtil.sendMessage(player, "&c" + af.getValueDesc()); return false; } final Flag flag = new Flag(FlagManager.getFlag(args[1].toLowerCase(), true), parsed); final boolean result = FlagManager.addPlotFlag(plot, flag); if (!result) { MainUtil.sendMessage(player, C.FLAG_NOT_ADDED); return false; } MainUtil.sendMessage(player, C.FLAG_ADDED); APlotListener.manager.plotEntry(player, plot); return true; } case "remove": { if (!Permissions.hasPermission(player, "plots.flag.remove")) { MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.flag.remove"); return false; } if ((args.length != 2) && (args.length != 3)) { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag remove <flag> [values]"); return false; } final AbstractFlag af = FlagManager.getFlag(args[1].toLowerCase()); if (af == null) { MainUtil.sendMessage(player, C.NOT_VALID_FLAG); return false; } if (!Permissions.hasPermission(player, "plots.set.flag." + args[1].toLowerCase())) { MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.set.flag." + args[1].toLowerCase()); return false; } final Flag flag = FlagManager.getPlotFlagAbs(plot, args[1].toLowerCase()); if (flag == null) { MainUtil.sendMessage(player, C.FLAG_NOT_IN_PLOT); return false; } if ((args.length == 3) && flag.getAbstractFlag().isList()) { final String value = StringUtils.join(Arrays.copyOfRange(args, 2, args.length), " "); ((FlagValue.ListValue) flag.getAbstractFlag().value).remove(flag.getValue(), value); DBFunc.setFlags(plot.world, plot, plot.settings.flags.values()); } else { final boolean result = FlagManager.removePlotFlag(plot, flag.getKey()); if (!result) { MainUtil.sendMessage(player, C.FLAG_NOT_REMOVED); return false; } } MainUtil.sendMessage(player, C.FLAG_REMOVED); APlotListener.manager.plotEntry(player, plot); return true; } case "add": { if (!Permissions.hasPermission(player, "plots.flag.add")) { MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.flag.add"); return false; } if (args.length < 3) { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag add <flag> <values>"); return false; } final AbstractFlag af = FlagManager.getFlag(args[1].toLowerCase()); if (af == null) { MainUtil.sendMessage(player, C.NOT_VALID_FLAG); return false; } if (!Permissions.hasPermission(player, "plots.set.flag." + args[1].toLowerCase())) { MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.set.flag." + args[1].toLowerCase()); return false; } final String value = StringUtils.join(Arrays.copyOfRange(args, 2, args.length), " "); final Object parsed = af.parseValueRaw(value); if (parsed == null) { MainUtil.sendMessage(player, "&c" + af.getValueDesc()); return false; } Flag flag = FlagManager.getPlotFlag(plot, args[1].toLowerCase()); if ((flag == null) || !flag.getAbstractFlag().isList()) { flag = new Flag(FlagManager.getFlag(args[1].toLowerCase(), true), parsed); } else { ((FlagValue.ListValue) flag.getAbstractFlag().value).add(flag.getValue(), value); } final boolean result = FlagManager.addPlotFlag(plot, flag); if (!result) { MainUtil.sendMessage(player, C.FLAG_NOT_ADDED); return false; } DBFunc.setFlags(plot.world, plot, plot.settings.flags.values()); MainUtil.sendMessage(player, C.FLAG_ADDED); APlotListener.manager.plotEntry(player, plot); return true; } case "list": { if (!Permissions.hasPermission(player, "plots.flag.list")) { MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.flag.list"); return false; } if (args.length != 1) { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag list"); return false; } final HashMap<String, ArrayList<String>> flags = new HashMap<>(); for (final AbstractFlag af : FlagManager.getFlags()) { final String type = af.value.getClass().getSimpleName().replaceAll("Value", ""); if (!flags.containsKey(type)) { flags.put(type, new ArrayList<String>()); } flags.get(type).add(af.getKey()); } String message = ""; String prefix = ""; for (final String flag : flags.keySet()) { message += prefix + "&6" + flag + ": &7" + StringUtils.join(flags.get(flag), ", "); prefix = "\n"; } MainUtil.sendMessage(player, message); return true; } } MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag <set|remove|add|list|info>"); return false; }
From source file:com.clustercontrol.infra.util.JschUtil.java
private static byte[] getByteArray(ChannelExec channel, InputStream in, int maxSize, int timeout) throws IOException, HinemosUnknown { int pos = 0;/* w w w.j a v a 2 s . c om*/ byte[] buffer = new byte[maxSize]; boolean loop = true; long start = HinemosTime.currentTimeMillis(); while (loop) { while (in.available() > 0 && pos < maxSize) { int len = in.read(buffer, pos, maxSize - pos); if (len < 0) { loop = false; break; } pos += len; start = HinemosTime.currentTimeMillis(); } if (pos >= maxSize) { loop = false; } else if (channel.isClosed()) { if (in.available() <= 0) { loop = false; } } else { if ((HinemosTime.currentTimeMillis() - start) > timeout) throw new HinemosUnknown("Jsch command is spent too much time."); try { Thread.sleep(500); } catch (Exception ee) { } } } return pos >= maxSize ? buffer : Arrays.copyOfRange(buffer, 0, pos); }
From source file:dev.maisentito.suca.commands.BotCommands.java
@Override public boolean onMessage(MessageEvent event) throws Throwable { if (event.getMessage().startsWith(COMMAND_PREFIX) && !event.getUser().equals(event.getBot().getUserBot())) { String[] parts = event.getMessage().substring(1).split("\\s+"); if ((parts.length > 0) && (mCommandHandlers.containsKey(parts[0]))) { CommandHandler handler = mCommandHandlers.get(parts[0]); BotCommand attrs = handler.getClass().getAnnotation(BotCommand.class); if ((attrs != null) && (parts.length <= attrs.minArgc())) { event.respond(COMMAND_PREFIX + parts[0] + ": not enough arguments"); return true; }//from ww w .ja va 2 s.c o m if (parts.length > 1) { handler.handleCommand(event, Arrays.copyOfRange(parts, 1, parts.length)); } else { handler.handleCommand(event, new String[] {}); } return true; } } return false; }
From source file:com.serotonin.modbus4j.ip.listener.TcpListener.java
@Override synchronized public ModbusResponse sendImpl(ModbusRequest request) throws ModbusTransportException { if (!connected) { LOG.debug("No connection in Port: " + ipParameters.getPort()); throw new ModbusTransportException(new Exception("TCP Listener has no active connection!"), request.getSlaveId());// ww w . ja v a2s.co m } if (!initialized) { LOG.debug("Listener already terminated " + ipParameters.getPort()); return null; } // Wrap the modbus request in a ip request. OutgoingRequestMessage ipRequest; if (ipParameters.isEncapsulated()) { ipRequest = new EncapMessageRequest(request); StringBuilder sb = new StringBuilder(); for (byte b : Arrays.copyOfRange(ipRequest.getMessageData(), 0, ipRequest.getMessageData().length)) { sb.append(String.format("%02X ", b)); } LOG.debug("Encap Request: " + sb.toString()); } else { ipRequest = new XaMessageRequest(request, getNextTransactionId()); StringBuilder sb = new StringBuilder(); for (byte b : Arrays.copyOfRange(ipRequest.getMessageData(), 0, ipRequest.getMessageData().length)) { sb.append(String.format("%02X ", b)); } LOG.debug("Xa Request: " + sb.toString()); } // Send the request to get the response. IpMessageResponse ipResponse; try { // Send data via handler! handler.conn.DEBUG = true; ipResponse = (IpMessageResponse) handler.conn.send(ipRequest); if (ipResponse == null) { throw new ModbusTransportException(new Exception("No valid response from slave!"), request.getSlaveId()); } StringBuilder sb = new StringBuilder(); for (byte b : Arrays.copyOfRange(ipResponse.getMessageData(), 0, ipResponse.getMessageData().length)) { sb.append(String.format("%02X ", b)); } LOG.debug("Response: " + sb.toString()); return ipResponse.getModbusResponse(); } catch (Exception e) { LOG.debug(e.getLocalizedMessage() + ", Port: " + ipParameters.getPort() + ", retries: " + retries); if (retries < 10 && !e.getLocalizedMessage().contains("Broken")) { retries++; } else { /* * To recover from a Broken Pipe, the only way is to restart serverSocket */ LOG.debug("Restarting Socket, Port: " + ipParameters.getPort() + ", retries: " + retries); // Close the serverSocket first to prevent new messages. try { if (serverSocket != null) serverSocket.close(); } catch (IOException e2) { LOG.debug("Error closing socket" + e2.getLocalizedMessage(), e); getExceptionHandler().receivedException(e2); } // Close all open connections. if (handler != null) { handler.closeConnection(); terminateListener(); } if (!initialized) { LOG.debug("Listener already terminated " + ipParameters.getPort()); return null; } executorService = Executors.newCachedThreadPool(); try { startListener(); } catch (Exception e2) { LOG.warn("Error trying to restart socket" + e2.getLocalizedMessage(), e); throw new ModbusTransportException(e2, request.getSlaveId()); } retries = 0; } LOG.warn("Error sending request, Port: " + ipParameters.getPort() + ", msg: " + e.getMessage()); // Simple send error! throw new ModbusTransportException(e, request.getSlaveId()); } }
From source file:com.jfolson.hive.serde.RTypedBytesWritableOutput.java
public void writeRawBytes(BytesWritable bw) throws IOException { //LOG.info("Writing a plain BytesWritable"); byte[] bytes = Arrays.copyOfRange(bw.getBytes(), 0, bw.getLength()); out.writeRawBytes(bytes);//from w ww . j av a 2s. co m }
From source file:com.streamsets.pipeline.lib.parser.avro.AvroDataParserFactory.java
@Override public DataParser getParser(String id, byte[] data) throws DataParserException { if (schemaSource == OriginAvroSchemaSource.REGISTRY) { Optional<Integer> detectedSchemaId = schemaHelper.detectSchemaId(data); byte[] remaining; Schema recordSchema = schema; try {/*from w w w.j a va 2 s . co m*/ if (detectedSchemaId.isPresent()) { // Load the schema for this id from cache recordSchema = schemas.get(detectedSchemaId.get()); // Strip the embedded ID remaining = Arrays.copyOfRange(data, MAGIC_BYTE_SIZE + ID_SIZE, data.length); } else { remaining = data; } return new AvroMessageParser(getSettings().getContext(), recordSchema, remaining, id, schemaSource); } catch (IOException | ExecutionException e) { throw new DataParserException(Errors.DATA_PARSER_03, e.toString(), e); } } try { return new AvroMessageParser(getSettings().getContext(), schema, data, id, schemaSource); } catch (IOException e) { throw new DataParserException(Errors.DATA_PARSER_01, e.toString(), e); } }
From source file:com.cloudera.sqoop.Sqoop.java
/** * Entry-point that parses the correct SqoopTool to use from the args, * but does not call System.exit() as main() will. *//*from w w w . ja va2 s .com*/ public static int runTool(String[] args) { // Expand the options String[] expandedArgs = null; try { expandedArgs = OptionsFileUtil.expandArguments(args); } catch (Exception ex) { LOG.error("Error while expanding arguments", ex); System.err.println(ex.getMessage()); System.err.println("Try 'sqoop help' for usage."); return 1; } String toolName = expandedArgs[0]; SqoopTool tool = SqoopTool.getTool(toolName); if (null == tool) { System.err.println("No such sqoop tool: " + toolName + ". See 'sqoop help'."); return 1; } Sqoop sqoop = new Sqoop(tool); return runSqoop(sqoop, Arrays.copyOfRange(expandedArgs, 1, expandedArgs.length)); }