code
stringlengths
73
34.1k
label
stringclasses
1 value
private void clearRunLocks() { jobMetaService.runningJobs().forEach((RunningJob runningJob) -> { final Optional<JobInfo> jobInfoOptional = jobRepository.findOne(runningJob.jobId); if (jobInfoOptional.isPresent() && jobInfoOptional.get().isStopped()) { jobMetaService.relea...
java
public static VersionInfoProperties versionInfoProperties(final String version, final String commit, final String urlTemplate) { final VersionInfoProperties p = new VersionInfoProperties(); p.version = version; p.commit = commit; p.urlTemplate = urlTemplate; return p; }
java
public StatusDetail withDetail(final String key, final String value) { final LinkedHashMap<String, String> newDetails = new LinkedHashMap<>(details); newDetails.put(key, value); return statusDetail(name,status,message, newDetails); }
java
public StatusDetail withoutDetail(final String key) { final LinkedHashMap<String, String> newDetails = new LinkedHashMap<>(details); newDetails.remove(key); return statusDetail(name,status,message, newDetails); }
java
public static DatasourceDependencyBuilder mongoDependency(final List<Datasource> datasources) { return new DatasourceDependencyBuilder() .withDatasources(datasources) .withType(DatasourceDependency.TYPE_DB) .withSubtype(DatasourceDependency.SUBTYPE_MONGODB); }
java
public static DatasourceDependencyBuilder redisDependency(final List<Datasource> datasources) { return new DatasourceDependencyBuilder() .withDatasources(datasources) .withType(DatasourceDependency.TYPE_DB) .withSubtype(DatasourceDependency.SUBTYPE_REDIS); }
java
public static DatasourceDependencyBuilder cassandraDependency(final List<Datasource> datasources) { return new DatasourceDependencyBuilder() .withDatasources(datasources) .withType(DatasourceDependency.TYPE_DB) .withSubtype(DatasourceDependency.SUBTYPE_CASSANDRA);...
java
public static DatasourceDependencyBuilder elasticSearchDependency(final List<Datasource> datasources) { return new DatasourceDependencyBuilder() .withDatasources(datasources) .withType(DatasourceDependency.TYPE_DB) .withSubtype(DatasourceDependency.SUBTYPE_ELASTIC...
java
public static DatasourceDependencyBuilder kafkaDependency(final List<Datasource> datasources) { return new DatasourceDependencyBuilder() .withDatasources(datasources) .withType(DatasourceDependency.TYPE_QUEUE) .withSubtype(DatasourceDependency.SUBTYPE_KAFKA); ...
java
public static LdapProperties ldapProperties(final String host, final int port, final List<String> baseDn, final String roleBaseDn, ...
java
public static ServiceDependencyBuilder restServiceDependency(final String url) { return new ServiceDependencyBuilder() .withUrl(url) .withType(ServiceDependency.TYPE_SERVICE) .withSubtype(ServiceDependency.SUBTYPE_REST) .withMethods(singletonList("...
java
public static ServiceDependencyBuilder serviceDependency(final String url) { return new ServiceDependencyBuilder() .withUrl(url) .withType(ServiceDependency.TYPE_SERVICE) .withSubtype(ServiceDependency.SUBTYPE_OTHER); }
java
public static Datasource datasource(final String node, final int port, final String resource) { return new Datasource(node, port, resource); }
java
public static JobDefinition manuallyTriggerableJobDefinition(final String jobType, final String jobName, final String description, ...
java
@Override public byte[] getData() { byte[] data = new byte[frameData.length+2]; int first2 = (FRAME_SYNC<<2); if (blockSizeVariable) first2++; IOUtils.putInt2BE(data, 0, first2); System.arraycopy(frameData, 0, data, 2, frameData.length); return data; }
java
public void setUtc(String utc) { if (utc == null) { this.utc = null; } else { if (utc.length() != 20) { throw new IllegalArgumentException("Must be of the form YYYYMMDDTHHMMSS.sssZ"); } } }
java
public void processPacket(OggPacket packet) { SkeletonPacket skel = SkeletonPacketFactory.create(packet); // First packet must be the head if (packet.isBeginningOfStream()) { fishead = (SkeletonFishead)skel; } else if (skel instanceof SkeletonFisbone) { SkeletonF...
java
public SkeletonFisbone addBoneForStream(int sid) { SkeletonFisbone bone = new SkeletonFisbone(); bone.setSerialNumber(sid); fisbones.add(bone); if (sid == -1 || bonesByStream.containsKey(sid)) { throw new IllegalArgumentException("Invalid / duplicate sid " + sid); } ...
java
protected int addPacket(OggPacket packet, int offset) { if(packet.isBeginningOfStream()) { isBOS = true; } if(packet.isEndOfStream()) { isEOS = true; } // Add on in 255 byte chunks int size = packet.getData().length; for(int i = numLVs; i<...
java
public boolean isChecksumValid() { if(checksum == 0) return true; int crc = CRCUtils.getCRC(getHeader()); if(data != null && data.length > 0) { crc = CRCUtils.getCRC(data, crc); } return (checksum == crc); }
java
protected boolean hasSpaceFor(int bytes) { // Do we have enough lvs spare? // (Each LV holds up to 255 bytes, and we're // not allowed more than 255 of them) int reqLVs = (int)Math.ceil(bytes / 255.0); if(numLVs + reqLVs > 255) { return false; } retu...
java
public int getDataSize() { // Data size is given by lvs int size = 0; for(int i=0; i<numLVs; i++) { size += IOUtils.toInt(lvs[i]); } return size; }
java
protected byte[] getHeader() { byte[] header = new byte[MINIMUM_PAGE_SIZE + numLVs]; header[0] = (byte)'O'; header[1] = (byte)'g'; header[2] = (byte)'g'; header[3] = (byte)'S'; header[4] = 0; // Version byte flags = 0; if(isContinue) { flags ...
java
protected OggStreamPacket createNext(OggPacket packet) { if (type == OggStreamIdentifier.OGG_VORBIS) { return VorbisPacketFactory.create(packet); } else if (type == OggStreamIdentifier.SPEEX_AUDIO) { return SpeexPacketFactory.create(packet); } else if (type == OggStreamId...
java
public boolean populate(OggPacket packet) { // TODO Finish the flac support properly if (type == OggStreamIdentifier.OGG_FLAC) { if (tags == null) { tags = new FlacTags(packet); return true; } else { // TODO Finish FLAC support ...
java
public static long readUE7(InputStream stream) throws IOException { int i; long v = 0; while ((i = stream.read()) >= 0) { v = v << 7; if ((i & 128) == 128) { // Continues v += (i&127); } else { // Last value ...
java
public static String removeNullPadding(String str) { int idx = str.indexOf(0); if (idx == -1) { return str; } return str.substring(0, idx); }
java
public static void writeUTF8(OutputStream out, String str) throws IOException { byte[] s = str.getBytes(UTF8); out.write(s); }
java
public static boolean byteRangeMatches(byte[] wanted, byte[] within, int withinOffset) { for (int i=0; i<wanted.length; i++) { if (wanted[i] != within[i+withinOffset]) return false; } return true; }
java
protected static MediaType toMediaType(OggStreamType type) { if (type == OggStreamIdentifier.UNKNOWN) { // We don't have a specific type available to return return OGG_GENERAL; } else { // Say it's the specific type we found return MediaType.parse(type.mimetype)...
java
public int addSoundtrack(OggAudioHeaders audio) { if (w == null) { throw new IllegalStateException("Not in write mode"); } // If it doesn't have a sid yet, get it one OggPacketWriter aw = null; if (audio.getSid() == -1) { aw = ogg.getPacketWriter(); ...
java
public OggStreamAudioVisualData getNextAudioVisualPacket(Set<Integer> sids) throws IOException { OggStreamAudioVisualData data = null; while (data == null && !pendingPackets.isEmpty()) { AudioVisualDataAndSid avd = pendingPackets.removeFirst(); if (sids == null || sids.contains(...
java
public void close() throws IOException { if (r != null) { r = null; ogg.close(); ogg = null; } if (w != null) { // First, write the initial packet of each stream // Skeleton (if present) goes first, then video, then audio(s) ...
java
public int getNumberOfCodebooks() { byte[] data = getData(); int number = -1; if(data != null && data.length >= 10) { number = IOUtils.toInt(data[8]); } return (number+1); }
java
@Override public void populateMetadataHeader(byte[] b, int dataLength) { b[0] = FlacMetadataBlock.VORBIS_COMMENT; IOUtils.putInt3BE(b, 1, dataLength); }
java
public void calculate() throws IOException { OggStreamAudioData data; // Calculate the headers sizing OggAudioInfoHeader info = headers.getInfo(); handleHeader(info); handleHeader(headers.getTags()); handleHeader(headers.getSetup()); // Have each audio packet ha...
java
public void setGranulePosition(long position) { currentGranulePosition = position; for(OggPage p : buffer) { p.setGranulePosition(position); } }
java
public void bufferPacket(OggPacket packet, long granulePosition) { if(closed) { throw new IllegalStateException("Can't buffer packets on a closed stream!"); } if(! doneFirstPacket) { packet.setIsBOS(); doneFirstPacket = true; } int size = pack...
java
public int getCurrentPageSize() { if (buffer.isEmpty()) return OggPage.getMinimumPageSize(); OggPage p = buffer.get( buffer.size()-1 ); return p.getPageSize(); }
java
public void flush() throws IOException { if(closed) { throw new IllegalStateException("Can't flush packets on a closed stream!"); } // Write in one go OggPage[] pages = buffer.toArray(new OggPage[buffer.size()]); file.writePages(pages); // Get ready for nex...
java
public void close() throws IOException { if(buffer.size() > 0) { buffer.get( buffer.size()-1 ).setIsEOS(); } else { OggPacket p = new OggPacket(new byte[0]); p.setIsEOS(); bufferPacket(p); } flush(); closed = true; }
java
public OggPacketWriter getPacketWriter(int sid) { if(!writing) { throw new IllegalStateException("Can only write to a file opened with an OutputStream"); } seenSIDs.add(sid); return new OggPacketWriter(this, sid); }
java
protected int getUnusedSerialNumber() { while(true) { int sid = (int)(Math.random() * Short.MAX_VALUE); if(! seenSIDs.contains(sid)) { return sid; } } }
java
public static FlacFile open(File f) throws IOException, FileNotFoundException { // Open, in a way that we can skip backwards a few bytes InputStream inp = new BufferedInputStream(new FileInputStream(f), 8); FlacFile file = open(inp); return file; }
java
public List<String> getComments(String tag) { List<String> c = comments.get( normaliseTag(tag) ); if(c == null) { return new ArrayList<String>(); } else { return c; } }
java
public void addComment(String tag, String comment) { String nt = normaliseTag(tag); if(! comments.containsKey(nt)) { comments.put(nt, new ArrayList<String>()); } comments.get(nt).add(comment); }
java
public void setComments(String tag, List<String> comments) { String nt = normaliseTag(tag); if(this.comments.containsKey(nt)) { this.comments.remove(nt); } this.comments.put(nt, comments); }
java
static List<MethodParameter> extract(String path) { List<MethodParameter> output = new ArrayList<>(); List<String> items = split(path); if (items.size() > 0) { int pathIndex = 0; int index = 0; for (String item : items) { MethodParameter param = getParamFromPath(item, index, pathIndex); // set n...
java
private static String convertSub(String path) { if (isRestEasyPath(path)) { // remove {} path = path.substring(1, path.length() - 1); int index = path.lastIndexOf(":"); // check for regular expression if (index > 0 && index + 1 < path.length()) { return path.substring(index + 1); // make regular ex...
java
private static String removeMatrixFromPath(String path, RouteDefinition definition) { // simple removal ... we don't care what matrix attributes were given if (definition.hasMatrixParams()) { int index = path.indexOf(";"); if (index > 0) { return path.substring(0, index); } } return path; }
java
public static <T> Object constructType(Class<T> type, String fromValue) throws ClassFactoryException { Assert.notNull(type, "Missing type!"); // a primitive or "simple" type if (isSimpleType(type)) { return stringToPrimitiveType(fromValue, type); } // have a constructor that accepts a single argument (S...
java
private static <T> List<Method> getMethods(Class<T> type, String... names) { Assert.notNull(type, "Missing class to search for methods!"); Assert.notNullOrEmpty(names, "Missing method names to search for!"); Map<String, Method> candidates = new HashMap<>(); for (Method method : type.getMethods()) { if (Mo...
java
@SafeVarargs public final RestBuilder errorHandler(Class<? extends ExceptionHandler>... handlers) { Assert.notNullOrEmpty(handlers, "Missing exception handler(s)!"); exceptionHandlers.addAll(Arrays.asList(handlers)); return this; }
java
public <T> RestBuilder provide(ContextProvider<T> provider) { Assert.notNull(provider, "Missing context provider!"); contextProviders.add(provider); return this; }
java
private static MediaType parse(String mediaType) { Assert.notNullOrEmptyTrimmed(mediaType, "Missing media type!"); String type = null; String subType = null; Map<String, String> params = new HashMap<>(); String[] parts = mediaType.split(";"); for (int i = 0; i < parts.length; i++) { String part = Str...
java
public ValueReader get(MethodParameter parameter, Class<? extends ValueReader> byMethodDefinition, InjectionProvider provider, RoutingContext context, MediaType... mediaTypes) { // by type Class<?> readerType = null; ...
java
public void register(Class<? extends ValueReader> reader) { Assert.notNull(reader, "Missing reader class!"); boolean registered = false; Consumes found = reader.getAnnotation(Consumes.class); if (found != null) { MediaType[] consumes = MediaTypeHelper.getMediaTypes(found.value()); if (consumes != null &...
java
public static Map<RouteDefinition, Method> get(Class clazz) { Map<RouteDefinition, Method> out = new HashMap<>(); Map<RouteDefinition, Method> candidates = collect(clazz); // Final check if definitions are OK for (RouteDefinition definition : candidates.keySet()) { if (definition.getMethod() == null) { //...
java
private static RouteDefinition find(Map<RouteDefinition, Method> add, Method method) { if (add == null || add.size() == 0) { return null; } for (RouteDefinition additional : add.keySet()) { Method match = add.get(additional); if (isMatching(method, match)) { return additional; } } return n...
java
private static Map<RouteDefinition, Method> getDefinitions(Class clazz) { Assert.notNull(clazz, "Missing class with JAX-RS annotations!"); // base RouteDefinition root = new RouteDefinition(clazz); // go over methods ... Map<RouteDefinition, Method> output = new LinkedHashMap<>(); for (Method method : cl...
java
public static Object provideContext(Class<?> type, String defaultValue, RoutingContext context) throws ContextException { // vert.x context if (type.isAssignableFrom(HttpServerResponse.class)) { return context.response(); } if (type....
java
private static void checkWriterCompatibility(RouteDefinition definition) { try { // no way to know the accept content at this point getWriter(injectionProvider, definition.getReturnType(), definition, null, GenericResponseWriter.class); } catch (ClassFactoryException e) { // ignoring instance creation ... b...
java
public static void notFound(Router router, Class<? extends NotFoundResponseWriter> notFound) { notFound(router, null, notFound); }
java
public static void notFound(Router router, String regExPath, Class<? extends NotFoundResponseWriter> notFound) { Assert.notNull(router, "Missing router!"); Assert.notNull(notFound, "Missing not found handler!"); addLastHandler(router, regExPath, getNotFoundHandler(notFound)); }
java
public static void addProvider(Class<? extends ContextProvider> provider) { Class clazz = (Class) ClassFactory.getGenericType(provider); addProvider(clazz, provider); }
java
public HttpResponseWriter getResponseWriter(Class returnType, RouteDefinition definition, InjectionProvider provider, RoutingContext routeContext, ...
java
private static String createMessage(RouteDefinition definition, Set<? extends ConstraintViolation<?>> constraintViolations) { List<String> messages = new ArrayList<>(); for (ConstraintViolation<?> violation : constraintViolations) { StringBuilder message = new StringBuilder(); for (Path.Node next : violatio...
java
public static <T> Set<T> subSet(Set<T> original, int from, int to) { List<T> list = new ArrayList<>(original); if (to == -1) { to = original.size(); } return new LinkedHashSet<>(list.subList(from, to)); }
java
public static <T> Collection<T> intersect(Collection<T> first, Collection<T> second) { E.checkNotNull(first, "first"); E.checkNotNull(second, "second"); HashSet<T> results = null; if (first instanceof HashSet) { @SuppressWarnings...
java
public static <T> Collection<T> intersectWithModify(Collection<T> first, Collection<T> second) { E.checkNotNull(first, "first"); E.checkNotNull(second, "second"); first.retainAll(second); return first; }
java
public final Lock lock(Object key) { Lock lock = this.locks.get(key); lock.lock(); return lock; }
java
public final List<Lock> lockAll(Object... keys) { List<Lock> locks = new ArrayList<>(keys.length); for (Object key : keys) { Lock lock = this.locks.get(key); locks.add(lock); } Collections.sort(locks, (a, b) -> { int diff = a.hashCode() - b.hashCode();...
java
public final void unlockAll(List<Lock> locks) { for (int i = locks.size(); i > 0; i--) { assert this.indexOf(locks.get(i - 1)) != -1; locks.get(i - 1).unlock(); } }
java
public static boolean match(Version version, String begin, String end) { E.checkArgumentNotNull(version, "The version to match is null"); return version.compareTo(new Version(begin)) >= 0 && version.compareTo(new Version(end)) < 0; }
java
public static void check(Version version, String begin, String end, String component) { E.checkState(VersionUtil.match(version, begin, end), "The version %s of '%s' is not in [%s, %s)", version, component, begin, end); }
java
public static String getImplementationVersion(Class<?> clazz) { /* * We don't use Package.getImplementationVersion() due to * a duplicate package would override the origin package info. * https://stackoverflow.com/questions/1272648/reading-my-own-jars-manifest */ Stri...
java
public static String getPomVersion() { String cmd = "mvn help:evaluate -Dexpression=project.version " + "-q -DforceStdout"; Process process = null; InputStreamReader isr = null; try { process = Runtime.getRuntime().exec(cmd); process.waitFor()...
java
static void write(Command cmd, OutputStream out) throws UnsupportedEncodingException, IOException { encode(cmd.getCommand(), out); for (Parameter param : cmd.getParameters()) { encode(String.format("=%s=%s", param.getName(), param.hasValue() ? param.getValue() : ""), out); } ...
java
static String decode(InputStream in) throws ApiDataException, ApiConnectionException { StringBuilder res = new StringBuilder(); decode(in, res); return res.toString(); }
java
private static void decode(InputStream in, StringBuilder result) throws ApiDataException, ApiConnectionException { try { int len = readLen(in); if (len > 0) { byte buf[] = new byte[len]; for (int i = 0; i < len; ++i) { int c = in.read()...
java
static String hashMD5(String s) throws ApiDataException { MessageDigest algorithm = null; try { algorithm = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsae) { throw new ApiDataException("Cannot find MD5 digest algorithm"); } byte[]...
java
static String hexStrToStr(String s) { StringBuilder ret = new StringBuilder(); for (int i = 0; i < s.length(); i += 2) { ret.append((char) Integer.parseInt(s.substring(i, i + 2), 16)); } return ret.toString(); }
java
private static void encode(String word, OutputStream out) throws UnsupportedEncodingException, IOException { byte bytes[] = word.getBytes("UTF-8"); int len = bytes.length; if (len < 0x80) { out.write(len); } else if (len < 0x4000) { len = len | 0x8000; ...
java
private static int readLen(InputStream in) throws IOException { int c = in.read(); if (c > 0) { if ((c & 0x80) == 0) { } else if ((c & 0xC0) == 0x80) { c = c & ~0xC0; c = (c << 8) | in.read(); } else if ((c & 0xE0) == 0xC0) { ...
java
void addParameter(String name, String value) { params.add(new Parameter(name, value)); }
java
public static ApiConnection connect(SocketFactory fact, String host, int port, int timeout) throws MikrotikApiException { return ApiConnectionImpl.connect(fact, host, port, timeout); }
java
public static ApiConnection connect(String host) throws MikrotikApiException { return connect(SocketFactory.getDefault(), host, DEFAULT_PORT, DEFAULT_COMMAND_TIMEOUT); }
java
public static ApiConnection connect(SocketFactory fact, String host, int port, int timeOut) throws ApiConnectionException { ApiConnectionImpl con = new ApiConnectionImpl(); con.open(host, port, fact, timeOut); return con; }
java
private void open(String host, int port, SocketFactory fact, int conTimeout) throws ApiConnectionException { try { InetAddress ia = InetAddress.getByName(host.trim()); sock = fact.createSocket(); sock.connect(new InetSocketAddress(ia, port), conTimeout); in = new ...
java
Token next() throws ScanException { text = null; switch (c) { case '\n': return EOL; case ' ': case '\t': return whiteSpace(); case ',': nextChar(); return COMMA; case '/': ...
java
private Token name() throws ScanException { text = new StringBuilder(); while (!in(c, "[ \t\r\n=<>!]")) { text.append(c); nextChar(); } String val = text.toString().toLowerCase(Locale.getDefault()); switch (val) { case "where": ...
java
private Token quotedText(char quote) throws ScanException { nextChar(); // eat the '"' text = new StringBuilder(); while (c != quote) { if (c == '\n') { throw new ScanException("Unclosed quoted text, reached end of line."); } text.append(c); ...
java
private void nextChar() { if (pos < line.length()) { c = line.charAt(pos); pos++; } else { c = '\n'; } }
java
static Command parse(String text) throws ParseException { Parser parser = new Parser(text); return parser.parse(); }
java
private Command parse() throws ParseException { command(); while (!is(Token.WHERE, Token.RETURN, Token.EOL)) { param(); } if (token == Token.WHERE) { where(); } if (token == Token.RETURN) { returns(); } expect(Token.EOL...
java
private void next() throws ScanException { token = scanner.next(); while (token == Token.WS) { token = scanner.next(); } text = scanner.text(); }
java
public static double calcAverageDegree(HashMap<Character, String[]> keys) { double average = 0d; for (Map.Entry<Character, String[]> entry : keys.entrySet()) { average += neighborsNumber(entry.getValue()); } return average / (double) keys.size(); }
java
public static int neighborsNumber(String[] neighbors) { int sum = 0; for (String s : neighbors) { if (s != null) { sum++; } } return sum; }
java
public static Set<Character> getNeighbors(final AdjacencyGraph adjacencyGraph, final Character key) { final Set<Character> neighbors = new HashSet<>(); if (adjacencyGraph.getKeyMap().containsKey(key)) { String[] tmp_neighbors = adjacencyGraph.getKeyMap().get(key); fo...
java
public static int getTurns(final AdjacencyGraph adjacencyGraph, final String part) { int direction = 0; int turns = 1; char[] parts = part.toCharArray(); for (int i1 = 0; i1 < parts.length; i1++) { Character character = parts[i1]; if (i1 + 1 >= parts....
java