code
stringlengths
73
34.1k
label
stringclasses
1 value
public static int deepHashCode(final Object obj) { if (obj == null) { return 0; } if (obj.getClass().isArray()) { return typeOf(obj.getClass()).deepHashCode(obj); } return obj.hashCode(); }
java
public static String deepToString(final Object obj) { if (obj == null) { return NULL_STRING; } if (obj.getClass().isArray()) { return typeOf(obj.getClass()).deepToString(obj); } return obj.toString(); }
java
public static <T> List<T> repeatEach(final Collection<T> c, final int n) { N.checkArgNotNegative(n, "n"); if (n == 0 || isNullOrEmpty(c)) { return new ArrayList<T>(); } final List<T> result = new ArrayList<>(c.size() * n); for (T e : c) { for ...
java
public static <T> List<T> repeatEachToSize(final Collection<T> c, final int size) { N.checkArgNotNegative(size, "size"); checkArgument(size == 0 || notNullOrEmpty(c), "Collection can not be empty or null when size > 0"); if (size == 0 || isNullOrEmpty(c)) { return new ArrayList...
java
public static <T> T max(final Collection<? extends T> c, final int from, final int to, Comparator<? super T> cmp) { checkFromToIndex(from, to, size(c)); if (N.isNullOrEmpty(c) || to - from < 1 || from >= c.size()) { throw new IllegalArgumentException("The size of collection can not be n...
java
private synchronized PoolableConnection newConnection() { synchronized (xpool) { if (xpool.size() >= maxActive) { return null; } try { PoolableConnection conn = null; if (xpool.size() < minIdle) { ...
java
private void initPool() { if (logger.isWarnEnabled()) { logger.warn("Start to initialize connection pool with url: " + url + " ..."); } for (int i = 0; (i < initialSize) && (xpool.size() < initialSize); i++) { pool.lock(); try { if (...
java
public static void registerXMLBindingClassForPropGetSetMethod(final Class<?> cls) { if (registeredXMLBindingClassList.containsKey(cls)) { return; } synchronized (entityDeclaredPropGetMethodPool) { registeredXMLBindingClassList.put(cls, false); if (en...
java
public static Set<Class<?>> getAllInterfaces(final Class<?> cls) { final Set<Class<?>> interfacesFound = new LinkedHashSet<>(); getAllInterfaces(cls, interfacesFound); return interfacesFound; }
java
public static List<String> getPropNameList(final Class<?> cls) { List<String> propNameList = entityDeclaredPropNameListPool.get(cls); if (propNameList == null) { loadPropGetSetMethodList(cls); propNameList = entityDeclaredPropNameListPool.get(cls); } ret...
java
public int totalCountOfValues() { int count = 0; for (V v : valueMap.values()) { count += v.size(); } return count; }
java
public static long skip(final InputStream input, final long toSkip) throws UncheckedIOException { if (toSkip < 0) { throw new IllegalArgumentException("Skip count must be non-negative, actual: " + toSkip); } else if (toSkip == 0) { return 0; } final byte[]...
java
private static long estimateLineCount(final File file, final int byReadingLineNum) throws UncheckedIOException { final Holder<ZipFile> outputZipFile = new Holder<>(); InputStream is = null; BufferedReader br = null; try { is = openFile(outputZipFile, file); ...
java
public static long merge(final Collection<File> sourceFiles, final File destFile) throws UncheckedIOException { final byte[] buf = Objectory.createByteArrayBuffer(); long totalCount = 0; OutputStream output = null; try { output = new FileOutputStream(destFile); ...
java
private static String decodeUrl(final String url) { String decoded = url; if (url != null && url.indexOf('%') >= 0) { final int n = url.length(); final StringBuffer buffer = new StringBuffer(); final ByteBuffer bytes = ByteBuffer.allocate(n); for (in...
java
public static <R> Stream<R> zip(final ShortStream a, final ShortStream b, final ShortBiFunction<R> zipFunction) { return zip(a.iteratorEx(), b.iteratorEx(), zipFunction).onClose(newCloseHandler(N.asList(a, b))); }
java
static URLSpec getReleaseDownloadUrl(String path, MavenSettings settings) throws IOException { String url = settings.mCentralUrl; if (settings.mMirrorUrl != null) url = settings.mMirrorUrl; return new URLSpec(url + path, settings.mProxyHost, settings.mProxyPort); }
java
static URLSpec getSnapshotDownloadUrl(String path, MavenSettings settings) throws IOException { String url = settings.mSnapshotUrl; return new URLSpec(url + path, settings.mProxyHost, settings.mProxyPort); }
java
static MavenSettings getMavenSettings() { try { String homeDir = System.getProperty("user.home"); return parseMavenSettings(new File(homeDir, ".m2/settings.xml")); } catch (Exception e) { log(e); } return new MavenSettings(); }
java
static MavenSettings parseMavenSettings(File settingsFile) throws IOException { MavenSettings settings = new MavenSettings(); try { DocumentBuilder xmlBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document xmlDoc = xmlBuilder.parse(settingsFile); NodeList mirrorList = xmlDoc.getD...
java
static String parseSnapshotExeName(File mdFile) throws IOException { String exeName = null; try { String clsStr = Protoc.getPlatformClassifier(); DocumentBuilder xmlBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document xmlDoc = xmlBuilder.parse(mdFile); NodeList versions = xmlDoc...
java
public static void assertSelectCount(long expectedSelectCount) { QueryCount queryCount = QueryCountHolder.getGrandTotal(); long recordedSelectCount = queryCount.getSelect(); if (expectedSelectCount != recordedSelectCount) { throw new SQLSelectCountMismatchException(expectedSelectCoun...
java
public static void assertInsertCount(long expectedInsertCount) { QueryCount queryCount = QueryCountHolder.getGrandTotal(); long recordedInsertCount = queryCount.getInsert(); if (expectedInsertCount != recordedInsertCount) { throw new SQLInsertCountMismatchException(expectedInsertCoun...
java
public static void assertUpdateCount(long expectedUpdateCount) { QueryCount queryCount = QueryCountHolder.getGrandTotal(); long recordedUpdateCount = queryCount.getUpdate(); if (expectedUpdateCount != recordedUpdateCount) { throw new SQLUpdateCountMismatchException(expectedUpdateCoun...
java
public static void assertDeleteCount(long expectedDeleteCount) { QueryCount queryCount = QueryCountHolder.getGrandTotal(); long recordedDeleteCount = queryCount.getDelete(); if (expectedDeleteCount != recordedDeleteCount) { throw new SQLDeleteCountMismatchException(expectedDeleteCoun...
java
public void login(String username, String passwd, String domain) { this.login = getPerformedAction(new PostLogin(username, passwd, domain)).getLoginData(); loginChangeUserInfo = true; if (getVersion() == Version.UNKNOWN) { loginChangeVersion = true; } }
java
public void delete(String title, String reason) { getPerformedAction(new PostDelete(getUserinfo(), title, reason)); }
java
private EditType getEditType(String typeName) { for (EditType type : EditType.values()) { if (type.toString().equals(typeName)) { return type; } } return null; }
java
@Override protected ImmutableList<String> parseElements(String s) { ImmutableList.Builder<String> titles = ImmutableList.builder(); Optional<XmlElement> child = XmlConverter.getChildOpt(s, "query", "allpages"); if (child.isPresent()) { for (XmlElement pageElement : child.get().getChildren("p")) { ...
java
static Optional<XmlElement> getErrorElement(XmlElement rootXmlElement) { Optional<XmlElement> elem = rootXmlElement.getChildOpt("error"); if (elem.isPresent()) { ApiException error = elem.transform(toApiException()).get(); log.error(error.getCode() + ": " + error.getValue()); } return elem; ...
java
@Deprecated protected Optional<String> parseXmlHasMore( String xml, String elementName, String attributeKey, String newContinueKey) { XmlElement rootElement = XmlConverter.getRootElement(xml); Optional<XmlElement> aContinue = rootElement.getChildOpt("continue"); if (aContinue.isPresent()) { re...
java
public synchronized @Nullable <Z> Z map(Function<T, Z> f) { if (ref == null) { return f.apply(null); } else { return f.apply(ref.get()); } }
java
public @Nullable <Z> Z mapWithCopy(Function<T, Z> f) throws IOException { final @Nullable SharedReference<T> localRef = getCopy(); try { if (localRef == null) { return f.apply(null); } else { return f.apply(localRef.get()); } } ...
java
@Nonnull private static File writeDataToTempFileOrDie(@Nonnull final OutputStreamCallback callback, @Nonnull final File targetFile, @Nonnull final Logger log) throws IOException { Preconditions.checkNotNull...
java
@Deprecated public static boolean writeObjectToFile(Object obj, String file) { try { writeObjectToFileOrDie(obj, file, LOGGER); return true; } catch (Exception e) { LOGGER.error(e.getClass() + ": writeObjectToFile(" + file + ") encountered exception: " + e.g...
java
private static boolean arrayCompare(byte[] a, int offset1, byte[] a2, int offset2, int length) { for (int i = 0; i < length; i++) { if (a[offset1++] != a2[offset2++]) return false; } return true; }
java
public static long parseTimestampFromUIDString(String s, final int start, final int end) { long ret = 0; for (int i = start; i < end && i < start + 9; i++) { ret <<= 5; char c = s.charAt(i); if (c >= '0' && c <= '9') { ret |= c - '0'; } els...
java
public void advise(long position, long length) throws IOException { final long ap = address+position; final long a = (ap)/PAGE_SIZE*PAGE_SIZE; final long l = Math.min(length+(ap-a), address+memory.length()-ap); final int err = madvise(a, l); if (err != 0) { throw new ...
java
@Deprecated public static void madviseDontNeedTrackedBuffers() { if (openBuffersTracker == null) { return; } openBuffersTracker.forEachOpenTrackedBuffer(new Function<MMapBuffer, Void>() { @Override public Void apply(final MMapBuffer b) { /...
java
public boolean isLoadedDataSuccessfullyRecently() { final Integer timeSinceLastError = getSecondsSinceLastFailedLoad(); final Integer timeSinceLastSuccess = getSecondsSinceLastLoad(); if (timeSinceLastSuccess == null) { return false; // never loaded data, so must be FAIL } ...
java
public static Quicksortable getQuicksortableIntArray(final int [] array) { return new Quicksortable() { public void swap(int i, int j) { int t = array[i]; array[i] = array[j]; array[j] = t; } public int compare(int a, int b) { ...
java
private static void sort1(Quicksortable q, int off, int k, int len) { // we don't care about anything >= to k if (off >= k) return; // Insertion sort on smallest arrays if (len < 7) { for (int i = off; i < len + off; i++) for (int j = i; j > off &&...
java
public static void heapSort(Quicksortable q, int size) { q = reverseQuicksortable(q); makeHeap(q, size); sortheap(q, size); }
java
private static void sortheap(Quicksortable q, int size) { for (int i = size-1; i >= 1; i--) { q.swap(0, i); heapifyDown(q, 0, i); } }
java
public static void partialSortUsingHeap(Quicksortable q, int k, int size) { Quicksortable revq = reverseQuicksortable(q); makeHeap(revq, k); for (int i = k; i < size; i++) { if (q.compare(0, i) > 0) { q.swap(0, i); heapifyDown(revq, 0, k); ...
java
public static void partialHeapSort(Quicksortable q, int k, int size) { makeHeap(q, size); for (int i = 0; i < k; i++) { q.swap(0, size-i-1); heapifyDown(q, 0, size-i-1); } vecswap(q, 0, size-k, k); reverse(q, k); }
java
public static void makeHeap(Quicksortable q, int size) { for (int i = (size-1)/2; i >= 0; i--) { heapifyDown(q, i, size); } }
java
public static void popHeap(Quicksortable q, int size) { q.swap(0, size-1); heapifyDown(q, 0, size-1); }
java
public static void topK(Quicksortable qs, int totalSize, int k) { if (k > totalSize) k = totalSize; makeHeap(qs, k); for (int i = k; i < totalSize; i++) { // compare each element to the root of the heap if (qs.compare(i, 0) > 0) { // if it's greater, swap ...
java
public static int binarySearch(Quicksortable qs, int size) { int low = 0; int high = size-1; while (low <= high) { int mid = (low + high) >> 1; int cmp = qs.compare(mid, -1); if (cmp < 0) low = mid + 1; else if (cmp > 0) h...
java
public final long plus(final long value, @Nonnull final TimeUnit timeUnit) { return this.millis.addAndGet(timeUnit.toMillis(value)); }
java
private static long findMaxTime(Node n) { long max = Long.MIN_VALUE; for (Map.Entry<String, Node> entry : n.children.entrySet()) { max = Math.max(max, entry.getValue().time); } return max; }
java
public final void and(ThreadSafeBitSet other) { if (other.size != size) throw new IllegalArgumentException("BitSets must be of equal size"); for (int i = 0; i < bits.length; i++) { bits[i] &= other.bits[i]; } }
java
public final void or(ThreadSafeBitSet other) { if (other.size != size) throw new IllegalArgumentException("BitSets must be of equal size"); for (int i = 0; i < bits.length; i++) { bits[i] |= other.bits[i]; } }
java
public final void xor(ThreadSafeBitSet other) { if (other.size != size) throw new IllegalArgumentException("BitSets must be of equal size"); for (int i = 0; i < bits.length; i++) { bits[i] ^= other.bits[i]; } }
java
@Nonnegative public static int count(@Nonnull final Path dir) throws IOException { try (final DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { return Iterables.size(stream); } catch (DirectoryIteratorException ex) { // I/O error encounted during the iteration, ...
java
public static void rename(final Path oldName, final Path newName) throws IOException { checkNotNull(oldName); checkNotNull(newName); final boolean sameDir = Files.isSameFile(oldName.getParent(), newName.getParent()); // rename the file Files.move(oldName, newName, StandardCopyO...
java
public static void ensureDirectoryExists(final Path path) throws IOException { if (Files.exists(path)) { if (!Files.isDirectory(path)) { throw new IOException("path is not a directory: " + path); } // probably should fsync parent here just to be sure, but that...
java
@Nonnegative public static int fsyncRecursive(final Path root) throws IOException { final FsyncingSimpleFileVisitor visitor = new FsyncingSimpleFileVisitor(); Files.walkFileTree(root, visitor); return visitor.getFileCount(); }
java
public static void fsync(final Path path) throws IOException { if (! Files.isDirectory(path) && ! Files.isRegularFile(path)) { throw new IllegalArgumentException("fsync is only supported for regular files and directories: " + path); } try (final FileChannel channel = FileChannel.ope...
java
private static void fsyncLineage(final Path path) throws IOException { Path cursor = path.toRealPath(); while (cursor != null) { fsync(cursor); cursor = cursor.getParent(); } }
java
public static void writeUTF8(final String value, final Path path) throws IOException { write(value.getBytes(Charsets.UTF_8), path); }
java
public static void write(final byte[] data, final Path path) throws IOException { try (final SafeOutputStream out = createAtomicFile(path)) { out.write(ByteBuffer.wrap(data)); out.commit(); } }
java
@Nonnull public static String determineHostName() throws UnknownHostException { if (!OPT_HOSTNAME.isPresent()) { final String hostName = InetAddress.getLocalHost().getHostName(); if (Strings.isNullOrEmpty(hostName)) { throw new UnknownHostException("Unable to lookup l...
java
@Nonnull public static String determineHostName(@Nonnull final String defaultValue) { checkNotNull(defaultValue, "Unable to use default value of null for hostname"); if (!OPT_HOSTNAME.isPresent()) { try { return determineHostName(); // this will get and save it. ...
java
@Nullable public static String determineIpAddress() throws SocketException { SocketException caughtException = null; for (final Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); networkInterfaces.hasMoreElements();) { try { final N...
java
public static synchronized VarExporter forNamespace(@Nonnull final Class<?> clazz, final boolean declaredFieldsOnly) { return getInstance(clazz.getSimpleName(), clazz, declaredFieldsOnly); }
java
@SuppressWarnings("unchecked") public <T> T getValue(final String variableName) { final Variable variable = getVariable(variableName); return (variable == null) ? null : (T) variable.getValue(); }
java
@Override @SuppressWarnings("unchecked") public <T> Variable<T> getVariable(final String variableName) { final String[] subTokens = getSubVariableTokens(variableName); if (subTokens != null) { final Variable<T> sub = getSubVariable(subTokens[0], subTokens[1]); if (sub != ...
java
@Override public void visitVariables(VariableVisitor visitor) { // build a collection of live variables in a synchronized block final List<Variable> variablesCopy; synchronized (variables) { variablesCopy = Lists.newArrayListWithExpectedSize(variables.size()); final I...
java
public void dumpJson(final PrintWriter out) { out.append("{"); visitVariables(new Visitor() { int count = 0; public void visit(Variable var) { if (count++ > 0) { out.append(", "); } out.append(var.getName()).append("='").append(String.valueOf(var....
java
@Override public void merge(final Object from, final Object target, final NullHandlingPolicy nullPolicy) { if (from == null || target == null) { return; } final BeanWrapper fromWrapper = beanWrapper(from); final BeanWrapper targetWrapper = beanWrapper(target); f...
java
public List getOptions(int code) { if (options == null) return Collections.EMPTY_LIST; List list = Collections.EMPTY_LIST; for (Iterator it = options.iterator(); it.hasNext(); ) { EDNSOption opt = (EDNSOption) it.next(); if (opt.getCode() == code) { if (list == Collections.EMPTY_LIST) list = new ArrayLi...
java
public RRset findExactMatch(Name name, int type) { Object types = exactName(name); if (types == null) return null; return oneRRset(types, type); }
java
public void addRRset(RRset rrset) { Name name = rrset.getName(); addRRset(name, rrset); }
java
public void addRecord(Record r) { Name name = r.getName(); int rtype = r.getRRsetType(); synchronized (this) { RRset rrset = findRRset(name, rtype); if (rrset == null) { rrset = new RRset(r); addRRset(name, rrset); } else { rrset.addRR(r); } } }
java
public void removeRecord(Record r) { Name name = r.getName(); int rtype = r.getRRsetType(); synchronized (this) { RRset rrset = findRRset(name, rtype); if (rrset == null) return; if (rrset.size() == 1 && rrset.first().equals(r)) removeRRset(name, rtype); else rrset.deleteRR(r); } }
java
public synchronized String toMasterFile() { Iterator zentries = data.entrySet().iterator(); StringBuffer sb = new StringBuffer(); nodeToString(sb, originNode); while (zentries.hasNext()) { Map.Entry entry = (Map.Entry) zentries.next(); if (!origin.equals(entry.getKey())) nodeToString(sb, entry.getValue()); ...
java
public static String formatString(byte [] b, int lineLength, String prefix, boolean addClose) { String s = toString(b); StringBuffer sb = new StringBuffer(); for (int i = 0; i < s.length(); i += lineLength) { sb.append (prefix); if (i + lineLength >= s.length()) { sb.append(s.substring(i)); if (addClose) ...
java
public static byte [] fromString(String str) { ByteArrayOutputStream bs = new ByteArrayOutputStream(); byte [] raw = str.getBytes(); for (int i = 0; i < raw.length; i++) { if (!Character.isWhitespace((char)raw[i])) bs.write(raw[i]); } byte [] in = bs.toByteArray(); if (in.length % 4 != 0) { return null; }...
java
public static long parse(String s, boolean clamp) { if (s == null || s.length() == 0 || !Character.isDigit(s.charAt(0))) throw new NumberFormatException(); long value = 0; long ttl = 0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); long oldvalue = value; if (Character.isDigit(c)) { value =...
java
public static Message newQuery(Record r) { Message m = new Message(); m.header.setOpcode(Opcode.QUERY); m.header.setFlag(Flags.RD); m.addRecord(r, Section.QUESTION); return m; }
java
public void addRecord(Record r, int section) { if (sections[section] == null) sections[section] = new LinkedList(); header.incCount(section); sections[section].add(r); }
java
public boolean removeRecord(Record r, int section) { if (sections[section] != null && sections[section].remove(r)) { header.decCount(section); return true; } else return false; }
java
public boolean findRecord(Record r, int section) { return (sections[section] != null && sections[section].contains(r)); }
java
public boolean findRecord(Record r) { for (int i = Section.ANSWER; i <= Section.ADDITIONAL; i++) if (sections[i] != null && sections[i].contains(r)) return true; return false; }
java
public boolean findRRset(Name name, int type, int section) { if (sections[section] == null) return false; for (int i = 0; i < sections[section].size(); i++) { Record r = (Record) sections[section].get(i); if (r.getType() == type && name.equals(r.getName())) return true; } return false; }
java
public boolean findRRset(Name name, int type) { return (findRRset(name, type, Section.ANSWER) || findRRset(name, type, Section.AUTHORITY) || findRRset(name, type, Section.ADDITIONAL)); }
java
public Record getQuestion() { List l = sections[Section.QUESTION]; if (l == null || l.size() == 0) return null; return (Record) l.get(0); }
java
public TSIGRecord getTSIG() { int count = header.getCount(Section.ADDITIONAL); if (count == 0) return null; List l = sections[Section.ADDITIONAL]; Record rec = (Record) l.get(count - 1); if (rec.type != Type.TSIG) return null; return (TSIGRecord) rec; }
java
public OPTRecord getOPT() { Record [] additional = getSectionArray(Section.ADDITIONAL); for (int i = 0; i < additional.length; i++) if (additional[i] instanceof OPTRecord) return (OPTRecord) additional[i]; return null; }
java
public Record [] getSectionArray(int section) { if (sections[section] == null) return emptyRecordArray; List l = sections[section]; return (Record []) l.toArray(new Record[l.size()]); }
java
public RRset [] getSectionRRsets(int section) { if (sections[section] == null) return emptyRRsetArray; List sets = new LinkedList(); Record [] recs = getSectionArray(section); Set hash = new HashSet(); for (int i = 0; i < recs.length; i++) { Name name = recs[i].getName(); boolean newset = true; if (hash.co...
java
public byte [] toWire() { DNSOutput out = new DNSOutput(); toWire(out); size = out.current(); return out.toByteArray(); }
java
public void setTSIG(TSIG key, int error, TSIGRecord querytsig) { this.tsigkey = key; this.tsigerror = error; this.querytsig = querytsig; }
java
public String sectionToString(int i) { if (i > 3) return null; StringBuffer sb = new StringBuffer(); Record [] records = getSectionArray(i); for (int j = 0; j < records.length; j++) { Record rec = records[j]; if (i == Section.QUESTION) { sb.append(";;\t" + rec.name); sb.append(", type = " + Type.strin...
java
String rrToString() { StringBuffer sb = new StringBuffer(); Iterator it = strings.iterator(); while (it.hasNext()) { byte [] array = (byte []) it.next(); sb.append(byteArrayToString(array, true)); if (it.hasNext()) sb.append(" "); } return sb.toString(); }
java
public boolean isCurrent() { BasicHandler handler = getBasicHandler(); return (handler.axfr == null && handler.ixfr == null); }
java
public void apply(Message m, int error, TSIGRecord old) { Record r = generate(m, m.toWire(), error, old); m.addRecord(r, Section.ADDITIONAL); m.tsigState = Message.TSIG_SIGNED; }
java
public static Integer toInteger(int val) { if (val >= 0 && val < cachedInts.length) return (cachedInts[val]); return new Integer(val); }
java