code
stringlengths
73
34.1k
label
stringclasses
1 value
@SuppressWarnings("UnusedReturnValue") public static String webread(URL url) throws IOException { StringBuilder result = new StringBuilder(); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); BufferedReader rd = new BufferedReader(new In...
java
public static void openInDefaultBrowser(URL url) throws IOException { Runtime rt = Runtime.getRuntime(); if (SystemUtils.IS_OS_WINDOWS) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (SystemUtils.IS_OS_MAC) { rt.exec("open" + url); } else { ...
java
public String format(Object expression, Object objPattern) { if (objPattern instanceof String) { final String pattern = filterPattern((String) objPattern); if (expression == null) { return null; } if (expression instanceof LocalDate) { ...
java
private NodeMetadata enrich(NodeMetadata nodeMetadata, Template template) { final NodeMetadataBuilder nodeMetadataBuilder = NodeMetadataBuilder .fromNodeMetadata(nodeMetadata); if (nodeMetadata.getHardware() == null) { nodeMetadataBuilder.hardware(template.getHardware()); } if (nodeMetad...
java
protected org.jclouds.compute.options.TemplateOptions modifyTemplateOptions( VirtualMachineTemplate originalVirtualMachineTemplate, org.jclouds.compute.options.TemplateOptions originalTemplateOptions) { return originalTemplateOptions; }
java
public boolean verify() { this.errors = new LinkedList<>(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(generator.generate(spaceId, ManifestFormat.TSV)))) { WriteOnlyStringSet snapshotManifest = ManifestFileHelper.loadManifestSetFromFile(this.md5Ma...
java
@Nullable private static Identifiers handleIdentifiers(String domainIdOrName, String projectIdOrName, String endpoint, String userId, String password) { //we try all four cases and return the one that works Set<Identifiers> possibleIdentifiers = new HashSet<Identifiers>() {{ add(new Identifiers(I...
java
@Override protected void configure() { bind(DiscoveryService.class).to(BaseDiscoveryService.class); bind(OperatingSystemDetectionStrategy.class) .to(NameSubstringBasedOperatingSystemDetectionStrategy.class); }
java
public static Update update(String key, Object value) { return new Update().set(key, value); }
java
public static void encryptFields(Object object, CollectionMetaData cmd, ICipher cipher) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { for (String secretAnnotatedFieldName: cmd.getSecretAnnotatedFieldNames()) { Method getterMethod = cmd.getGetterMethodForFieldName(...
java
public static void decryptFields(Object object, CollectionMetaData cmd, ICipher cipher) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { for (String secretAnnotatedFieldName: cmd.getSecretAnnotatedFieldNames()) { Method getterMethod = cmd.getGetterMethodForFieldName...
java
public static String generate128BitKey(String password, String salt) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException { SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.g...
java
public static CollectionSchemaUpdate update(String key, IOperation operation) { return new CollectionSchemaUpdate().set(key, operation); }
java
public CollectionSchemaUpdate set(String key, IOperation operation) { collectionUpdateData.put(key, operation); return this; }
java
public Map<String, AddOperation> getAddOperations() { Map<String, AddOperation> addOperations = new TreeMap<String, AddOperation>(); for (Entry<String, IOperation> entry : collectionUpdateData.entrySet()) { String key = entry.getKey(); IOperation op = entry.getValue(); if (op.getOperationType(...
java
public Map<String, RenameOperation> getRenameOperations() { Map<String, RenameOperation> renOperations = new TreeMap<String, RenameOperation>(); for (Entry<String, IOperation> entry : collectionUpdateData.entrySet()) { String key = entry.getKey(); IOperation op = entry.getValue(); if (op.getOp...
java
public Map<String, DeleteOperation> getDeleteOperations() { Map<String, DeleteOperation> delOperations = new TreeMap<String, DeleteOperation>(); for (Entry<String, IOperation> entry : collectionUpdateData.entrySet()) { String key = entry.getKey(); IOperation op = entry.getValue(); if (op.getOp...
java
protected static Object getIdForEntity(Object document, Method getterMethodForId) { Object id = null; if (null != getterMethodForId) { try { id = getterMethodForId.invoke(document); } catch (IllegalAccessException e) { logger.error("Failed to invoke getter method for a idAnnotated fi...
java
protected static Object deepCopy(Object fromBean) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); XMLEncoder out = new XMLEncoder(bos); out.writeObject(fromBean); out.close(); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); XMLDecoder in = new XMLDecoder(bis, ...
java
public static boolean stampVersion(JsonDBConfig dbConfig, File f, String version) { FileOutputStream fos = null; OutputStreamWriter osr = null; BufferedWriter writer = null; try { fos = new FileOutputStream(f); osr = new OutputStreamWriter(fos, dbConfig.getCharset()); writer = new Buf...
java
@Override public String decrypt(String cipherText) { this.decryptionLock.lock(); try{ String decryptedValue = null; try { byte[] bytes = Base64.getDecoder().decode(cipherText); decryptedValue = new String(decryptCipher.doFinal(bytes), charset); } catch (UnsupportedEncodingExc...
java
@Override public int compare(String expected, String actual) { String[] vals1 = expected.split("\\."); String[] vals2 = actual.split("\\."); int i = 0; while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])) { i++; } if (i < vals1.length && i < vals2.length) { i...
java
public static Keyword keyword(Object o) { if (o instanceof Keyword) return (Keyword) o; else if (o instanceof String) { String s = (String) o; if (s.charAt(0) == ':') return new KeywordImpl(s.substring(1)); else return new K...
java
public static Symbol symbol(Object o) { if (o instanceof Symbol) return (Symbol) o; else if (o instanceof String) { String s = (String) o; if (s.charAt(0) == ':') return new SymbolImpl(s.substring(1)); else return new Symbol...
java
public static <T> TaggedValue<T> taggedValue(String tag, T rep) { return new TaggedValueImpl<T>(tag, rep); }
java
private long readNumber(int firstChar, boolean isNeg) throws IOException { out.unsafeWrite(firstChar); // unsafe OK since we know output is big enough // We build up the number in the negative plane since it's larger (by one) than // the positive plane. long v = '0' - firstChar; // can't overflow...
java
private int readFrac(CharArr arr, int lim) throws IOException { nstate = HAS_FRACTION; // deliberate set instead of '|' while(--lim>=0) { int ch = getChar(); if (ch>='0' && ch<='9') { arr.write(ch); } else if (ch=='e' || ch=='E') { arr.write(ch); return readExp(arr,lim...
java
private int readExp(CharArr arr, int lim) throws IOException { nstate |= HAS_EXPONENT; int ch = getChar(); lim--; if (ch=='+' || ch=='-') { arr.write(ch); ch = getChar(); lim--; } // make sure at least one digit is read. if (ch<'0' || ch>'9') { throw err("missing exponent num...
java
private int readExpDigits(CharArr arr, int lim) throws IOException { while (--lim>=0) { int ch = getChar(); if (ch>='0' && ch<='9') { arr.write(ch); } else { if (ch!=-1) start--; // back up return NUMBER; } } return BIGNUMBER; }
java
private char readEscapedChar() throws IOException { int ch = getChar(); switch (ch) { case '"' : return '"'; case '\'' : return '\''; case '\\' : return '\\'; case '/' : return '/'; case 'n' : return '\n'; case 'r' : return '\r'; case 't' : return '\t'; case 'f' :...
java
private void readStringChars2(CharArr arr, int middle) throws IOException { if (stringTerm == 0) { readStringBare(arr); return; } char terminator = (char) stringTerm; for (;;) { if (middle>=end) { arr.write(buf,start,middle-start); start=middle; getMore(); ...
java
public void getNumberChars(CharArr output) throws IOException { int ev=0; if (valstate==0) ev=nextEvent(); if (valstate == LONG || valstate == NUMBER) output.write(this.out); else if (valstate==BIGNUMBER) { continueNumber(output); } else { throw err("Unexpected " + ev); } valstat...
java
public long parseLong(char[] arr, int start, int end) { long x = 0; boolean negative = arr[start] == '-'; for (int i=negative ? start+1 : start; i<end; i++) { // If constructing the largest negative number, this will overflow // to the largest negative number. This is OK since the negation of ...
java
protected SocketFactory createSocketFactory(InetAddress address, int port, InetAddress localAddr, int localPort, long timeout) ...
java
public String encodeIntArray(int[] input) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); int length = input.length; dos.writeInt(length); for (int i=0; i < length; i++) { dos.writeInt(inp...
java
public int[] decodeIntArray(String input) throws IOException { int[] result = null; ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decodeBase64(input)); DataInputStream dis = new DataInputStream(bis); int length = dis.readInt(); result = new int[length]; ...
java
public String decodeHexToString(String str) throws DecoderException { String result = null; byte[] bytes = Hex.decodeHex(str.toCharArray()); if (bytes != null && bytes.length > 0) { result = new String(bytes); } return result; }
java
public String getName() { FeatureDescriptor fd = getFeatureDescriptor(); if (fd == null) { return null; } return fd.getName(); }
java
public String getDescription() { FeatureDescriptor fd = getFeatureDescriptor(); if (fd == null) { return ""; } return getTeaToolsUtils().getDescription(fd); }
java
public String getQualifiedTypeNameForFile() { String typeName = getTypeNameForFile(); String qualifiedTypeName = mDoc.qualifiedTypeName(); int packageLength = qualifiedTypeName.length() - typeName.length(); if (packageLength <= 0) { return typeName; } Strin...
java
public MethodDoc getMatchingMethod(MethodDoc method) { MethodDoc[] methods = getMethods(); for (int i = 0; i < methods.length; i++) { if (method.getName().equals(methods[i].getName()) && method.getSignature().equals(methods[i].getSignature())) { return meth...
java
public MethodDoc getMatchingMethod(MethodDoc method, MethodFinder mf) { MethodDoc md = getMatchingMethod(method); if (md != null) { if (mf.checkMethod(md)) { return md; } } return null; }
java
public MethodDoc findMatchingMethod(MethodDoc method, MethodFinder mf) { // Look in this class's interface set MethodDoc md = findMatchingInterfaceMethod(method, mf); if (md != null) { return md; } // Look in this class's superclass ancestry ClassDoc superC...
java
public String getTagValue(String tagName) { Tag[] tags = getTagMap().get(tagName); if (tags == null || tags.length == 0) { return null; } return tags[tags.length - 1].getText(); }
java
public static Map<String, PropertyDescriptor> getAllProperties(GenericType root) throws IntrospectionException { Map<String, PropertyDescriptor> properties = cPropertiesCache.get(root); if (properties == null) { GenericType rootType = root.getRootType(); ...
java
public static String findTemplateName(org.teatrove.tea.compiler.Scanner scanner) { // System.out.println("<-- findTemplateName -->"); Token token; String name = null; try { while (((token = scanner.readToken()).getID()) != Token.EOF) { /* Syste...
java
public Template parseTeaTemplate(String templateName) throws IOException { if (templateName == null) { return null; } preserveParseTree(templateName); compile(templateName); CompilationUnit unit = getCompilationUnit(templateName, null); if (unit == null) { ...
java
public boolean isValueKnown() { Type type = getType(); if (type != null) { Class<?> clazz = type.getObjectClass(); return Number.class.isAssignableFrom(clazz) || clazz.isAssignableFrom(Number.class); } else { return false; } ...
java
public Object[] cloneArray(Object[] array) { Class<?> clazz = array.getClass().getComponentType(); Object newArray = Array.newInstance(clazz, array.length); System.arraycopy(array, 0, newArray, 0, array.length); return (Object[]) newArray; }
java
public HttpClient setHeader(String name, Object value) { if (mHeaders == null) { mHeaders = new HttpHeaderMap(); } mHeaders.put(name, value); return this; }
java
public HttpClient addHeader(String name, Object value) { if (mHeaders == null) { mHeaders = new HttpHeaderMap(); } mHeaders.add(name, value); return this; }
java
public Response getResponse(PostData postData) throws ConnectException, SocketException { CheckedSocket socket = mFactory.getSocket(mSession); try { CharToByteBuffer request = new FastCharToByteBuffer (new DefaultByteBuffer(), "8859_1"); request = new...
java
public void addRootLogListener(LogListener listener) { if (mParent == null) { addLogListener(listener); } else { mParent.addRootLogListener(listener); } }
java
public void debug(String s) { if (isEnabled() && isDebugEnabled()) { dispatchLogMessage(new LogEvent(this, LogEvent.DEBUG_TYPE, s)); } }
java
public void debug(Throwable t) { if (isEnabled() && isDebugEnabled()) { dispatchLogException(new LogEvent(this, LogEvent.DEBUG_TYPE, t)); } }
java
public void info(String s) { if (isEnabled() && isInfoEnabled()) { dispatchLogMessage(new LogEvent(this, LogEvent.INFO_TYPE, s)); } }
java
public void info(Throwable t) { if (isEnabled() && isInfoEnabled()) { dispatchLogException(new LogEvent(this, LogEvent.INFO_TYPE, t)); } }
java
public void warn(String s) { if (isEnabled() && isWarnEnabled()) { dispatchLogMessage(new LogEvent(this, LogEvent.WARN_TYPE, s)); } }
java
public void warn(Throwable t) { if (isEnabled() && isWarnEnabled()) { dispatchLogException(new LogEvent(this, LogEvent.WARN_TYPE, t)); } }
java
public void error(String s) { if (isEnabled() && isErrorEnabled()) { dispatchLogMessage(new LogEvent(this, LogEvent.ERROR_TYPE, s)); } }
java
public void error(Throwable t) { if (isEnabled() && isErrorEnabled()) { dispatchLogException(new LogEvent(this, LogEvent.ERROR_TYPE, t)); } }
java
public Log[] getChildren() { Collection copy; synchronized (mChildren) { copy = new ArrayList(mChildren.size()); Iterator it = mChildren.iterator(); while (it.hasNext()) { Log child = (Log)((WeakReference)it.next()).get(); if (child ==...
java
public void setEnabled(boolean enabled) { setEnabled(enabled, ENABLED_MASK); if (enabled) { Log parent; if ((parent = mParent) != null) { parent.setEnabled(true); } } }
java
public void applyProperties(Map properties) { if (properties.containsKey("enabled")) { setEnabled(!"false".equalsIgnoreCase ((String)properties.get("enabled"))); } if (properties.containsKey("debug")) { setDebugEnabled(!"false".equalsIgnoreCase ...
java
private static PropertyDescriptor[][] getBeanProperties(Class<?> beanType) { List<PropertyDescriptor> readProperties = new ArrayList<PropertyDescriptor>(); List<PropertyDescriptor> writeProperties = new ArrayList<PropertyDescriptor>(); try { Map<?,...
java
static void writeShort(OutputStream out, int i) throws IOException { out.write((byte)i); out.write((byte)(i >> 8)); }
java
void appendCompressed(ByteData compressed, ByteData original) throws IOException { mCompressedSegments++; mBuffer.appendSurrogate(new CompressedData(compressed, original)); }
java
public static int toDecimalDigits(float v, char[] digits, int offset, int maxDigits, int maxFractDigits, int roundMode) { int bits = Float.floatToIntBits(v); int f = bits & 0x7fffff; int e = (bits >> 23) & 0xff; ...
java
public static int toDecimalDigits(double v, char[] digits, int offset, int maxDigits, int maxFractDigits, int roundMode) { // NOTE: The value 144115188075855872 is converted to // 144115188075855870, which is as correct as p...
java
public TransactionQueueData add(TransactionQueueData data) { return new TransactionQueueData (null, Math.min(mSnapshotStart, data.mSnapshotStart), Math.max(mSnapshotEnd, data.mSnapshotEnd), mQueueSize + data.mQueueSize, mThreadCount + data.mThreadC...
java
public Object get(Object key) { Object value = mCacheMap.get(key); if (value != null || mCacheMap.containsKey(key)) { return value; } value = mBackingMap.get(key); if (value != null || mBackingMap.containsKey(key)) { mCacheMap.put(key, value); } ...
java
public Object put(Object key, Object value) { mCacheMap.put(key, value); return mBackingMap.put(key, value); }
java
public Object remove(Object key) { mCacheMap.remove(key); return mBackingMap.remove(key); }
java
public Plugin getPlugin(String name) { if (mPluginContext != null) { return mPluginContext.getPlugin(name); } return null; }
java
public Plugin[] getPlugins() { if (mPluginContext != null) { Collection c = mPluginContext.getPlugins().values(); if (c != null) { return (Plugin[])c.toArray(new Plugin[c.size()]); } } return new Plugin[0]; }
java
public boolean isOwnedBy(String possibleOwner) { boolean retval = false; if (this.owner != null) { retval = (this.owner.compareTo(possibleOwner) == 0); } return retval; }
java
public void deleteAtManagementGroup(String policySetDefinitionName, String managementGroupId) { deleteAtManagementGroupWithServiceResponseAsync(policySetDefinitionName, managementGroupId).toBlocking().single().body(); }
java
public void delete(String resourceGroupName, String workflowName) { deleteWithServiceResponseAsync(resourceGroupName, workflowName).toBlocking().single().body(); }
java
public Observable<Page<WorkflowInner>> listByResourceGroupNextAsync(final String nextPageLink) { return listByResourceGroupNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<WorkflowInner>>, Page<WorkflowInner>>() { @Override public Page<Wo...
java
public Observable<Page<ClusterInner>> listByResourceGroupAsync(String resourceGroupName) { return listByResourceGroupWithServiceResponseAsync(resourceGroupName).map(new Func1<ServiceResponse<List<ClusterInner>>, Page<ClusterInner>>() { @Override public Page<ClusterInner> call(ServiceResp...
java
public static EntityGetOperation<AssetDeliveryPolicyInfo> get(String assetDeliveryPolicyId) { return new DefaultGetOperation<AssetDeliveryPolicyInfo>(ENTITY_SET, assetDeliveryPolicyId, AssetDeliveryPolicyInfo.class); }
java
public static DefaultListOperation<AssetDeliveryPolicyInfo> list(LinkInfo<AssetDeliveryPolicyInfo> link) { return new DefaultListOperation<AssetDeliveryPolicyInfo>(link.getHref(), new GenericType<ListResult<AssetDeliveryPolicyInfo>>() { }); }
java
public Observable<AdvisorListResultInner> listByDatabaseAsync(String resourceGroupName, String serverName, String databaseName) { return listByDatabaseWithServiceResponseAsync(resourceGroupName, serverName, databaseName).map(new Func1<ServiceResponse<AdvisorListResultInner>, AdvisorListResultInner>() { ...
java
public AdvisorInner createOrUpdate(String resourceGroupName, String serverName, String databaseName, String advisorName, AutoExecuteStatus autoExecuteValue) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, databaseName, advisorName, autoExecuteValue).toBlocking().single().body(); ...
java
public static MSICredentials getMSICredentials(String managementEndpoint) { //check if we are running in a web app String websiteName = System.getenv("WEBSITE_SITE_NAME"); if (websiteName != null && !websiteName.isEmpty()) { // We are in a web app... MSIConfigurationForA...
java
T unsafeGetIfOpened() { if (innerObject != null && innerObject.getState() == IOObject.IOObjectState.OPENED) { return innerObject; } return null; }
java
public void delete(String resourceGroupName, String registryName, String taskName) { deleteWithServiceResponseAsync(resourceGroupName, registryName, taskName).toBlocking().last().body(); }
java
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException { // The connection string value can be obtained by going to your App Configuration instance in the Azure portal // and navigating to "Access Keys" page under the "Settings" section. final String connect...
java
public ConnectionStringBuilder setEndpoint(String namespaceName, String domainName) { try { this.endpoint = new URI(String.format(Locale.US, END_POINT_FORMAT, namespaceName, domainName)); } catch (URISyntaxException exception) { throw new IllegalConnectionStringFormatException( ...
java
public void marshalEntry(Object content, OutputStream stream) throws JAXBException { marshaller.marshal(createEntry(content), stream); }
java
public Observable<Page<VaultInner>> listByResourceGroupAsync(final String resourceGroupName, final Integer top) { return listByResourceGroupWithServiceResponseAsync(resourceGroupName, top) .map(new Func1<ServiceResponse<Page<VaultInner>>, Page<VaultInner>>() { @Override ...
java
public void setData(String key, Object value) { this.data = this.data.addData(key, value); }
java
private void resetInputStreams() throws IOException, MessagingException { for (int ix = 0; ix < this.getCount(); ix++) { BodyPart part = this.getBodyPart(ix); if (part.getContent() instanceof MimeMultipart) { MimeMultipart subContent = (MimeMultipart) part.getContent(); ...
java
public Observable<Page<IntegrationAccountSessionInner>> listByIntegrationAccountsNextAsync(final String nextPageLink) { return listByIntegrationAccountsNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<IntegrationAccountSessionInner>>, Page<IntegrationAccountSessionInner...
java
public static JWSObject deserialize(String json) throws IOException { ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(json, JWSObject.class); }
java
public KeyIdentifier keyIdentifier() { if (key() == null || key().kid() == null || key().kid().length() == 0) { return null; } return new KeyIdentifier(key().kid()); }
java
public Map<String, String> getCachedChallenge(HttpUrl url) { if (url == null) { return null; } String authority = getAuthority(url); authority = authority.toLowerCase(Locale.ENGLISH); return cachedChallenges.get(authority); }
java
public void addCachedChallenge(HttpUrl url, Map<String, String> challenge) { if (url == null || challenge == null) { return; } String authority = getAuthority(url); authority = authority.toLowerCase(Locale.ENGLISH); cachedChallenges.put(authority, challenge); }
java
public String getAuthority(HttpUrl url) { String scheme = url.scheme(); String host = url.host(); int port = url.port(); StringBuilder builder = new StringBuilder(); if (scheme != null) { builder.append(scheme).append("://"); } builder.append(host); ...
java
static Mono<Object> decode(HttpResponse httpResponse, SerializerAdapter serializer, HttpResponseDecodeData decodeData) { Type headerType = decodeData.headersType(); if (headerType == null) { return Mono.empty(); } else { return Mono.defer(() -> { try { ...
java