_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q167800
TableServiceEntity.setReflectedEntityCacheDisabled
validation
public static void setReflectedEntityCacheDisabled(boolean disableReflectedEntityCache) { if (TableServiceEntity.reflectedEntityCache != null && disableReflectedEntityCache) { TableServiceEntity.reflectedEntityCache.clear(); } TableServiceEntity.disableReflectedEntityCache = disableReflectedEntityCache; }
java
{ "resource": "" }
q167801
BaseResponse.getDate
validation
public static String getDate(final HttpURLConnection request) { final String retString = request.getHeaderField("Date"); return retString == null ? request.getHeaderField(Constants.HeaderConstants.DATE) : retString; }
java
{ "resource": "" }
q167802
BaseResponse.getMetadata
validation
public static HashMap<String, String> getMetadata(final HttpURLConnection request) { return getValuesByHeaderPrefix(request, Constants.HeaderConstants.PREFIX_FOR_STORAGE_METADATA); }
java
{ "resource": "" }
q167803
BaseResponse.isServerRequestEncrypted
validation
public static boolean isServerRequestEncrypted(HttpURLConnection request) { return Constants.TRUE.equals(request.getHeaderField(Constants.HeaderConstants.SERVER_REQUEST_ENCRYPTED)); }
java
{ "resource": "" }
q167804
TableStorageErrorDeserializer.getExtendedErrorInformation
validation
public static StorageExtendedErrorInformation getExtendedErrorInformation(final Reader reader, final TablePayloadFormat format) throws JsonParseException, IOException { JsonFactory jsonFactory = new JsonFactory(); JsonParser parser = jsonFactory.createParser(reader); try { final StorageExtendedErrorInformation errorInfo = new StorageExtendedErrorInformation(); if (!parser.hasCurrentToken()) { parser.nextToken(); } JsonUtilities.assertIsStartObjectJsonToken(parser); parser.nextToken(); JsonUtilities.assertIsFieldNameJsonToken(parser); JsonUtilities.assertIsExpectedFieldName(parser, "odata.error"); // start getting extended error information parser.nextToken(); JsonUtilities.assertIsStartObjectJsonToken(parser); // get code parser.nextValue(); JsonUtilities.assertIsExpectedFieldName(parser, TableConstants.ErrorConstants.ERROR_CODE); errorInfo.setErrorCode(parser.getValueAsString()); // get message parser.nextToken(); JsonUtilities.assertIsFieldNameJsonToken(parser); JsonUtilities.assertIsExpectedFieldName(parser, TableConstants.ErrorConstants.ERROR_MESSAGE); parser.nextToken(); JsonUtilities.assertIsStartObjectJsonToken(parser); parser.nextValue(); JsonUtilities.assertIsExpectedFieldName(parser, "lang"); parser.nextValue(); JsonUtilities.assertIsExpectedFieldName(parser, "value"); errorInfo.setErrorMessage(parser.getValueAsString()); parser.nextToken(); JsonUtilities.assertIsEndObjectJsonToken(parser); parser.nextToken(); // get innererror if it exists if (parser.getCurrentToken() == JsonToken.FIELD_NAME) { JsonUtilities.assertIsExpectedFieldName(parser, TableConstants.ErrorConstants.INNER_ERROR); errorInfo.getAdditionalDetails().putAll(parseJsonErrorException(parser)); parser.nextToken(); } // end code object JsonUtilities.assertIsEndObjectJsonToken(parser); // end odata.error object parser.nextToken(); JsonUtilities.assertIsEndObjectJsonToken(parser); return errorInfo; } finally { parser.close(); } }
java
{ "resource": "" }
q167805
TableStorageErrorDeserializer.parseErrorDetails
validation
public static StorageExtendedErrorInformation parseErrorDetails(StorageRequest<CloudTableClient, ?, ?> request) { try { if (request == null || request.getConnection().getErrorStream() == null) { return null; } return getExtendedErrorInformation(new InputStreamReader( request.getConnection().getErrorStream()), TablePayloadFormat.Json); } catch (Exception e) { return null; } }
java
{ "resource": "" }
q167806
TableStorageErrorDeserializer.parseJsonErrorException
validation
private static HashMap<String, String[]> parseJsonErrorException(JsonParser parser) throws JsonParseException, IOException { HashMap<String, String[]> additionalDetails = new HashMap<String, String[]>(); parser.nextToken(); JsonUtilities.assertIsStartObjectJsonToken(parser); parser.nextToken(); JsonUtilities.assertIsFieldNameJsonToken(parser); while (parser.getCurrentToken() != JsonToken.END_OBJECT) { if (parser.getCurrentName().equals(TableConstants.ErrorConstants.ERROR_MESSAGE)) { parser.nextToken(); additionalDetails.put(TableConstants.ErrorConstants.ERROR_MESSAGE, new String[] { parser.getValueAsString() }); } else if (parser.getCurrentName().equals(TableConstants.ErrorConstants.ERROR_EXCEPTION_TYPE)) { parser.nextToken(); additionalDetails.put(TableConstants.ErrorConstants.ERROR_EXCEPTION_TYPE, new String[] { parser.getValueAsString() }); } else if (parser.getCurrentName().equals(TableConstants.ErrorConstants.ERROR_EXCEPTION_STACK_TRACE)) { parser.nextToken(); additionalDetails .put(Constants.ERROR_EXCEPTION_STACK_TRACE, new String[] { parser.getValueAsString() }); } parser.nextToken(); } return additionalDetails; }
java
{ "resource": "" }
q167807
SharedAccessPolicyHandler.getAccessIdentifiers
validation
public static <T extends SharedAccessPolicy> HashMap<String, T> getAccessIdentifiers(final InputStream stream, final Class<T> cls) throws ParserConfigurationException, SAXException, IOException { SAXParser saxParser = Utility.getSAXParser(); SharedAccessPolicyHandler<T> handler = new SharedAccessPolicyHandler<T>(cls); saxParser.parse(stream, handler); return handler.policies; }
java
{ "resource": "" }
q167808
FileResponse.getCopyState
validation
public static CopyState getCopyState(final HttpURLConnection request) throws URISyntaxException, ParseException { String copyStatusString = request.getHeaderField(Constants.HeaderConstants.COPY_STATUS); if (!Utility.isNullOrEmpty(copyStatusString)) { final CopyState copyState = new CopyState(); copyState.setStatus(CopyStatus.parse(copyStatusString)); copyState.setCopyId(request.getHeaderField(Constants.HeaderConstants.COPY_ID)); copyState.setStatusDescription(request.getHeaderField(Constants.HeaderConstants.COPY_STATUS_DESCRIPTION)); final String copyProgressString = request.getHeaderField(Constants.HeaderConstants.COPY_PROGRESS); if (!Utility.isNullOrEmpty(copyProgressString)) { String[] progressSequence = copyProgressString.split("/"); copyState.setBytesCopied(Long.parseLong(progressSequence[0])); copyState.setTotalBytes(Long.parseLong(progressSequence[1])); } final String copySourceString = request.getHeaderField(Constants.HeaderConstants.COPY_SOURCE); if (!Utility.isNullOrEmpty(copySourceString)) { copyState.setSource(new URI(copySourceString)); } final String copyCompletionTimeString = request.getHeaderField(Constants.HeaderConstants.COPY_COMPLETION_TIME); if (!Utility.isNullOrEmpty(copyCompletionTimeString)) { copyState.setCompletionTime(Utility.parseRFC1123DateFromStringInGMT(copyCompletionTimeString)); } return copyState; } else { return null; } }
java
{ "resource": "" }
q167809
FileResponse.getFileShareAttributes
validation
public static FileShareAttributes getFileShareAttributes(final HttpURLConnection request, final boolean usePathStyleUris) throws StorageException { final FileShareAttributes shareAttributes = new FileShareAttributes(); final FileShareProperties shareProperties = shareAttributes.getProperties(); shareProperties.setEtag(BaseResponse.getEtag(request)); shareProperties.setShareQuota(parseShareQuota(request)); shareProperties.setLastModified(new Date(request.getLastModified())); shareAttributes.setMetadata(getMetadata(request)); return shareAttributes; }
java
{ "resource": "" }
q167810
FileResponse.getFileDirectoryAttributes
validation
public static FileDirectoryAttributes getFileDirectoryAttributes(final HttpURLConnection request, final boolean usePathStyleUris) throws StorageException { final FileDirectoryAttributes directoryAttributes = new FileDirectoryAttributes(); URI tempURI; try { tempURI = PathUtility.stripSingleURIQueryAndFragment(request.getURL().toURI()); } catch (final URISyntaxException e) { final StorageException wrappedUnexpectedException = Utility.generateNewUnexpectedStorageException(e); throw wrappedUnexpectedException; } directoryAttributes.setName(PathUtility.getDirectoryNameFromURI(tempURI, usePathStyleUris)); final FileDirectoryProperties directoryProperties = directoryAttributes.getProperties(); directoryProperties.setEtag(BaseResponse.getEtag(request)); directoryProperties.setLastModified(new Date(request.getLastModified())); directoryAttributes.setMetadata(getMetadata(request)); directoryProperties.setServerEncrypted( Constants.TRUE.equals(request.getHeaderField(Constants.HeaderConstants.SERVER_ENCRYPTED))); return directoryAttributes; }
java
{ "resource": "" }
q167811
FileResponse.getFileAttributes
validation
public static FileAttributes getFileAttributes(final HttpURLConnection request, final StorageUri resourceURI) throws URISyntaxException, ParseException { final FileAttributes fileAttributes = new FileAttributes(); final FileProperties properties = fileAttributes.getProperties(); properties.setCacheControl(request.getHeaderField(Constants.HeaderConstants.CACHE_CONTROL)); properties.setContentDisposition(request.getHeaderField(Constants.HeaderConstants.CONTENT_DISPOSITION)); properties.setContentEncoding(request.getHeaderField(Constants.HeaderConstants.CONTENT_ENCODING)); properties.setContentLanguage(request.getHeaderField(Constants.HeaderConstants.CONTENT_LANGUAGE)); // For range gets, only look at 'x-ms-content-md5' for overall MD5 if (!Utility.isNullOrEmpty(request.getHeaderField(Constants.HeaderConstants.CONTENT_RANGE))) { properties.setContentMD5(request.getHeaderField(FileConstants.FILE_CONTENT_MD5_HEADER)); } else { properties.setContentMD5(request.getHeaderField(Constants.HeaderConstants.CONTENT_MD5)); } properties.setContentType(request.getHeaderField(Constants.HeaderConstants.CONTENT_TYPE)); properties.setEtag(BaseResponse.getEtag(request)); properties.setCopyState(FileResponse.getCopyState(request)); properties.setServerEncrypted( Constants.TRUE.equals(request.getHeaderField(Constants.HeaderConstants.SERVER_ENCRYPTED))); final Calendar lastModifiedCalendar = Calendar.getInstance(Utility.LOCALE_US); lastModifiedCalendar.setTimeZone(Utility.UTC_ZONE); lastModifiedCalendar.setTime(new Date(request.getLastModified())); properties.setLastModified(lastModifiedCalendar.getTime()); final String rangeHeader = request.getHeaderField(Constants.HeaderConstants.CONTENT_RANGE); final String xContentLengthHeader = request.getHeaderField(FileConstants.CONTENT_LENGTH_HEADER); if (!Utility.isNullOrEmpty(rangeHeader)) { properties.setLength(Long.parseLong(rangeHeader.split("/")[1])); } else if (!Utility.isNullOrEmpty(xContentLengthHeader)) { properties.setLength(Long.parseLong(xContentLengthHeader)); } else { // using this instead of the request property since the request // property only returns an int. final String contentLength = request.getHeaderField(Constants.HeaderConstants.CONTENT_LENGTH); if (!Utility.isNullOrEmpty(contentLength)) { properties.setLength(Long.parseLong(contentLength)); } } fileAttributes.setStorageUri(resourceURI); fileAttributes.setMetadata(BaseResponse.getMetadata(request)); return fileAttributes; }
java
{ "resource": "" }
q167812
MimePart.getHttpVerbForOperation
validation
static String getHttpVerbForOperation(final TableOperationType operationType) { if (operationType == TableOperationType.INSERT) { return "POST"; } else if (operationType == TableOperationType.DELETE) { return "DELETE"; } else if (operationType == TableOperationType.MERGE || operationType == TableOperationType.INSERT_OR_MERGE) { return "MERGE"; } else if (operationType == TableOperationType.REPLACE || operationType == TableOperationType.INSERT_OR_REPLACE) { return "PUT"; } else if (operationType == TableOperationType.RETRIEVE) { return "GET"; } else { throw new IllegalArgumentException(SR.UNKNOWN_TABLE_OPERATION); } }
java
{ "resource": "" }
q167813
StorageEventMultiCaster.fireEvent
validation
public void fireEvent(final EVENT_TYPE event) { for (final StorageEvent<EVENT_TYPE> listener : this.listeners) { listener.eventOccurred(event); } }
java
{ "resource": "" }
q167814
ExecutionEngine.fireSendingRequestEvent
validation
private static void fireSendingRequestEvent(OperationContext opContext, HttpURLConnection request, RequestResult result) { if (opContext.getSendingRequestEventHandler().hasListeners() || OperationContext.getGlobalSendingRequestEventHandler().hasListeners()) { SendingRequestEvent event = new SendingRequestEvent(opContext, request, result); opContext.getSendingRequestEventHandler().fireEvent(event); OperationContext.getGlobalSendingRequestEventHandler().fireEvent(event); } }
java
{ "resource": "" }
q167815
ExecutionEngine.fireResponseReceivedEvent
validation
private static void fireResponseReceivedEvent(OperationContext opContext, HttpURLConnection request, RequestResult result) { if (opContext.getResponseReceivedEventHandler().hasListeners() || OperationContext.getGlobalResponseReceivedEventHandler().hasListeners()) { ResponseReceivedEvent event = new ResponseReceivedEvent(opContext, request, result); opContext.getResponseReceivedEventHandler().fireEvent(event); OperationContext.getGlobalResponseReceivedEventHandler().fireEvent(event); } }
java
{ "resource": "" }
q167816
ExecutionEngine.fireErrorReceivingResponseEvent
validation
private static void fireErrorReceivingResponseEvent(OperationContext opContext, HttpURLConnection request, RequestResult result) { if (opContext.getErrorReceivingResponseEventHandler().hasListeners() || OperationContext.getGlobalErrorReceivingResponseEventHandler().hasListeners()) { ErrorReceivingResponseEvent event = new ErrorReceivingResponseEvent(opContext, request, result); opContext.getErrorReceivingResponseEventHandler().fireEvent(event); OperationContext.getGlobalErrorReceivingResponseEventHandler().fireEvent(event); } }
java
{ "resource": "" }
q167817
ExecutionEngine.fireRequestCompletedEvent
validation
private static void fireRequestCompletedEvent(OperationContext opContext, HttpURLConnection request, RequestResult result) { if (opContext.getRequestCompletedEventHandler().hasListeners() || OperationContext.getGlobalRequestCompletedEventHandler().hasListeners()) { RequestCompletedEvent event = new RequestCompletedEvent(opContext, request, result); opContext.getRequestCompletedEventHandler().fireEvent(event); OperationContext.getGlobalRequestCompletedEventHandler().fireEvent(event); } }
java
{ "resource": "" }
q167818
ExecutionEngine.fireRetryingEvent
validation
private static void fireRetryingEvent(OperationContext opContext, HttpURLConnection request, RequestResult result, RetryContext retryContext) { if (opContext.getRetryingEventHandler().hasListeners() || OperationContext.getGlobalRetryingEventHandler().hasListeners()) { RetryingEvent event = new RetryingEvent(opContext, request, result, retryContext); opContext.getRetryingEventHandler().fireEvent(event); OperationContext.getGlobalRetryingEventHandler().fireEvent(event); } }
java
{ "resource": "" }
q167819
Utility.assertContinuationType
validation
public static void assertContinuationType(final ResultContinuation continuationToken, final ResultContinuationType continuationType) { if (continuationToken != null) { if (!(continuationToken.getContinuationType() == ResultContinuationType.NONE || continuationToken .getContinuationType() == continuationType)) { final String errorMessage = String.format(Utility.LOCALE_US, SR.UNEXPECTED_CONTINUATION_TYPE, continuationToken.getContinuationType(), continuationType); throw new IllegalArgumentException(errorMessage); } } }
java
{ "resource": "" }
q167820
Utility.assertInBounds
validation
public static void assertInBounds(final String param, final long value, final long min, final long max) { if (value < min || value > max) { throw new IllegalArgumentException(String.format(SR.PARAMETER_NOT_IN_RANGE, param, min, max)); } }
java
{ "resource": "" }
q167821
Utility.assertGreaterThanOrEqual
validation
public static void assertGreaterThanOrEqual(final String param, final long value, final long min) { if (value < min) { throw new IllegalArgumentException(String.format(SR.PARAMETER_SHOULD_BE_GREATER_OR_EQUAL, param, min)); } }
java
{ "resource": "" }
q167822
Utility.validateMaxExecutionTimeout
validation
public static boolean validateMaxExecutionTimeout(Long operationExpiryTimeInMs, long additionalInterval) { if (operationExpiryTimeInMs != null) { long currentTime = new Date().getTime(); return operationExpiryTimeInMs < currentTime + additionalInterval; } return false; }
java
{ "resource": "" }
q167823
Utility.getRemainingTimeout
validation
public static int getRemainingTimeout(Long operationExpiryTimeInMs, Integer timeoutIntervalInMs) throws StorageException { if (operationExpiryTimeInMs != null) { long remainingTime = operationExpiryTimeInMs - new Date().getTime(); if (remainingTime > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } else if (remainingTime > 0) { return (int) remainingTime; } else { TimeoutException timeoutException = new TimeoutException(SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION); StorageException translatedException = new StorageException( StorageErrorCodeStrings.OPERATION_TIMED_OUT, SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION, Constants.HeaderConstants.HTTP_UNUSED_306, null, timeoutException); throw translatedException; } } else if (timeoutIntervalInMs != null) { return timeoutIntervalInMs + Constants.DEFAULT_READ_TIMEOUT; } else { return Constants.DEFAULT_READ_TIMEOUT; } }
java
{ "resource": "" }
q167824
Utility.determinePathStyleFromUri
validation
public static boolean determinePathStyleFromUri(final URI baseURI) { String path = baseURI.getPath(); if (path != null && path.startsWith("/")) { path = path.substring(1); } // if the path is null or empty, this is not path-style if (Utility.isNullOrEmpty(path)) { return false; } // if this contains a port or has a host which is not DNS, this is path-style return pathStylePorts.contains(baseURI.getPort()) || !isHostDnsName(baseURI); }
java
{ "resource": "" }
q167825
Utility.isHostDnsName
validation
private static boolean isHostDnsName(URI uri) { String host = uri.getHost(); for (int i = 0; i < host.length(); i++) { char hostChar = host.charAt(i); if (!Character.isDigit(hostChar) && !(hostChar == '.')) { return true; } } return false; }
java
{ "resource": "" }
q167826
Utility.formatETag
validation
public static String formatETag(final String etag) { if (etag.startsWith("\"") && etag.endsWith("\"")) { return etag; } else { return String.format("\"%s\"", etag); } }
java
{ "resource": "" }
q167827
Utility.generateNewUnexpectedStorageException
validation
public static StorageException generateNewUnexpectedStorageException(final Exception cause) { final StorageException exceptionRef = new StorageException(StorageErrorCode.NONE.toString(), "Unexpected internal storage client error.", 306, // unused null, null); exceptionRef.initCause(cause); return exceptionRef; }
java
{ "resource": "" }
q167828
Utility.getStandardHeaderValue
validation
public static String getStandardHeaderValue(final HttpURLConnection conn, final String headerName) { final String headerValue = conn.getRequestProperty(headerName); // Coalesce null value return headerValue == null ? Constants.EMPTY_STRING : headerValue; }
java
{ "resource": "" }
q167829
Utility.parseDateFromString
validation
public static Date parseDateFromString(final String value, final String pattern, final TimeZone timeZone) throws ParseException { final DateFormat rfc1123Format = new SimpleDateFormat(pattern, Utility.LOCALE_US); rfc1123Format.setTimeZone(timeZone); return rfc1123Format.parse(value); }
java
{ "resource": "" }
q167830
Utility.parseRFC1123DateFromStringInGMT
validation
public static Date parseRFC1123DateFromStringInGMT(final String value) throws ParseException { final DateFormat format = new SimpleDateFormat(RFC1123_GMT_PATTERN, Utility.LOCALE_US); format.setTimeZone(GMT_ZONE); return format.parse(value); }
java
{ "resource": "" }
q167831
Utility.safeRelativize
validation
public static String safeRelativize(final URI baseURI, final URI toUri) throws URISyntaxException { // For compatibility followed // http://msdn.microsoft.com/en-us/library/system.uri.makerelativeuri.aspx // if host and scheme are not identical return from uri if (!baseURI.getHost().equals(toUri.getHost()) || !baseURI.getScheme().equals(toUri.getScheme())) { return toUri.toString(); } final String basePath = baseURI.getPath(); String toPath = toUri.getPath(); int truncatePtr = 1; // Seek to first Difference // int maxLength = Math.min(basePath.length(), toPath.length()); int m = 0; int ellipsesCount = 0; for (; m < basePath.length(); m++) { if (m >= toPath.length()) { if (basePath.charAt(m) == '/') { ellipsesCount++; } } else { if (basePath.charAt(m) != toPath.charAt(m)) { break; } else if (basePath.charAt(m) == '/') { truncatePtr = m + 1; } } } // ../containername and ../containername/{path} should increment the truncatePtr // otherwise toPath will incorrectly begin with /containername if (m < toPath.length() && toPath.charAt(m) == '/') { // this is to handle the empty directory case with the '/' delimiter // for example, ../containername/ and ../containername// should not increment the truncatePtr if (!(toPath.charAt(m - 1) == '/' && basePath.charAt(m - 1) == '/')) { truncatePtr = m + 1; } } if (m == toPath.length()) { // No path difference, return query + fragment return new URI(null, null, null, toUri.getQuery(), toUri.getFragment()).toString(); } else { toPath = toPath.substring(truncatePtr); final StringBuilder sb = new StringBuilder(); while (ellipsesCount > 0) { sb.append("../"); ellipsesCount--; } if (!Utility.isNullOrEmpty(toPath)) { sb.append(toPath); } if (!Utility.isNullOrEmpty(toUri.getQuery())) { sb.append("?"); sb.append(toUri.getQuery()); } if (!Utility.isNullOrEmpty(toUri.getFragment())) { sb.append("#"); sb.append(toUri.getRawFragment()); } return sb.toString(); } }
java
{ "resource": "" }
q167832
Utility.logHttpError
validation
public static void logHttpError(StorageException ex, OperationContext opContext) { if (Logger.shouldLog(opContext, Log.DEBUG)) { try { StringBuilder bld = new StringBuilder(); bld.append("Error response received. "); bld.append("HttpStatusCode= "); bld.append(ex.getHttpStatusCode()); bld.append(", HttpStatusMessage= "); bld.append(ex.getMessage()); bld.append(", ErrorCode= "); bld.append(ex.getErrorCode()); StorageExtendedErrorInformation extendedError = ex.getExtendedErrorInformation(); if (extendedError != null) { bld.append(", ExtendedErrorInformation= {ErrorMessage= "); bld.append(extendedError.getErrorMessage()); HashMap<String, String[]> details = extendedError.getAdditionalDetails(); if (details != null) { bld.append(", AdditionalDetails= { "); for (Entry<String, String[]> detail : details.entrySet()) { bld.append(detail.getKey()); bld.append("= "); for (String value : detail.getValue()) { bld.append(value); } bld.append(","); } bld.setCharAt(bld.length() - 1, '}'); } bld.append("}"); } Logger.debug(opContext, bld.toString()); } catch (Exception e) { // Do nothing } } }
java
{ "resource": "" }
q167833
Utility.logHttpResponse
validation
public static void logHttpResponse(HttpURLConnection conn, OperationContext opContext) throws IOException { if (Logger.shouldLog(opContext, Log.VERBOSE)) { try { StringBuilder bld = new StringBuilder(); // This map's null key will contain the response code and message for (Map.Entry<String, List<String>> header : conn.getHeaderFields().entrySet()) { if (header.getKey() != null) { bld.append(header.getKey()); bld.append(": "); } for (int i = 0; i < header.getValue().size(); i++) { bld.append(header.getValue().get(i)); if (i < header.getValue().size() - 1) { bld.append(","); } } bld.append('\n'); } Logger.verbose(opContext, bld.toString()); } catch (Exception e) { // Do nothing } } }
java
{ "resource": "" }
q167834
Utility.trimEnd
validation
protected static String trimEnd(final String value, final char trimChar) { int stopDex = value.length() - 1; while (stopDex > 0 && value.charAt(stopDex) == trimChar) { stopDex--; } return stopDex == value.length() - 1 ? value : value.substring(stopDex); }
java
{ "resource": "" }
q167835
Utility.trimStart
validation
public static String trimStart(final String value) { int spaceDex = 0; while (spaceDex < value.length() && value.charAt(spaceDex) == ' ') { spaceDex++; } return value.substring(spaceDex); }
java
{ "resource": "" }
q167836
Utility.parseDate
validation
public static Date parseDate(String dateString) { String pattern = MAX_PRECISION_PATTERN; switch(dateString.length()) { case 28: // "yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"-> [2012-01-04T23:21:59.1234567Z] length = 28 case 27: // "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'"-> [2012-01-04T23:21:59.123456Z] length = 27 case 26: // "yyyy-MM-dd'T'HH:mm:ss.SSSSS'Z'"-> [2012-01-04T23:21:59.12345Z] length = 26 case 25: // "yyyy-MM-dd'T'HH:mm:ss.SSSS'Z'"-> [2012-01-04T23:21:59.1234Z] length = 25 case 24: // "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"-> [2012-01-04T23:21:59.123Z] length = 24 dateString = dateString.substring(0, MAX_PRECISION_DATESTRING_LENGTH); break; case 23: // "yyyy-MM-dd'T'HH:mm:ss.SS'Z'"-> [2012-01-04T23:21:59.12Z] length = 23 // SS is assumed to be milliseconds, so a trailing 0 is necessary dateString = dateString.replace("Z", "0"); break; case 22: // "yyyy-MM-dd'T'HH:mm:ss.S'Z'"-> [2012-01-04T23:21:59.1Z] length = 22 // S is assumed to be milliseconds, so trailing 0's are necessary dateString = dateString.replace("Z", "00"); break; case 20: // "yyyy-MM-dd'T'HH:mm:ss'Z'"-> [2012-01-04T23:21:59Z] length = 20 pattern = Utility.ISO8601_PATTERN; break; case 17: // "yyyy-MM-dd'T'HH:mm'Z'"-> [2012-01-04T23:21Z] length = 17 pattern = Utility.ISO8601_PATTERN_NO_SECONDS; break; default: throw new IllegalArgumentException(String.format(SR.INVALID_DATE_STRING, dateString)); } final DateFormat format = new SimpleDateFormat(pattern, Utility.LOCALE_US); format.setTimeZone(UTC_ZONE); try { return format.parse(dateString); } catch (final ParseException e) { throw new IllegalArgumentException(String.format(SR.INVALID_DATE_STRING, dateString), e); } }
java
{ "resource": "" }
q167837
Utility.getListingLocationMode
validation
public static RequestLocationMode getListingLocationMode(ResultContinuation token) { if ((token != null) && token.getTargetLocation() != null) { switch (token.getTargetLocation()) { case PRIMARY: return RequestLocationMode.PRIMARY_ONLY; case SECONDARY: return RequestLocationMode.SECONDARY_ONLY; default: throw new IllegalArgumentException(String.format(SR.ARGUMENT_OUT_OF_RANGE_ERROR, "token", token.getTargetLocation())); } } return RequestLocationMode.PRIMARY_OR_SECONDARY; }
java
{ "resource": "" }
q167838
QueueRequestOptions.populateAndApplyDefaults
validation
protected static final QueueRequestOptions populateAndApplyDefaults(QueueRequestOptions options, final CloudQueueClient client) { QueueRequestOptions modifiedOptions = new QueueRequestOptions(options); RequestOptions.populateRequestOptions(modifiedOptions, client.getDefaultRequestOptions(), true /* setStartTime */); QueueRequestOptions.applyDefaults(modifiedOptions); return modifiedOptions; }
java
{ "resource": "" }
q167839
LogRecordStreamReader.readString
validation
public String readString() throws IOException { String temp = this.readField(false /* isQuotedString */); if (Utility.isNullOrEmpty(temp)) { return null; } else { return temp; } }
java
{ "resource": "" }
q167840
LogRecordStreamReader.readQuotedString
validation
public String readQuotedString() throws IOException { String temp = this.readField(true /* isQuotedString */); if (Utility.isNullOrEmpty(temp)) { return null; } else { return temp; } }
java
{ "resource": "" }
q167841
LogRecordStreamReader.readBoolean
validation
public Boolean readBoolean() throws IOException { String temp = this.readField(false /* isQuotedString */); if (Utility.isNullOrEmpty(temp)) { return null; } else { return Boolean.parseBoolean(temp); } }
java
{ "resource": "" }
q167842
LogRecordStreamReader.readDate
validation
public Date readDate(DateFormat format) throws IOException, ParseException { String temp = this.readField(false /* isQuotedString */); if (Utility.isNullOrEmpty(temp)) { return null; } else { return format.parse(temp); } }
java
{ "resource": "" }
q167843
LogRecordStreamReader.readDouble
validation
public Double readDouble() throws IOException { String temp = this.readField(false /* isQuotedString */); if (Utility.isNullOrEmpty(temp)) { return null; } else { return Double.parseDouble(temp); } }
java
{ "resource": "" }
q167844
LogRecordStreamReader.readUuid
validation
public UUID readUuid() throws IOException { String temp = this.readField(false /* isQuotedString */); if (Utility.isNullOrEmpty(temp)) { return null; } else { return UUID.fromString(temp); } }
java
{ "resource": "" }
q167845
LogRecordStreamReader.readInteger
validation
public Integer readInteger() throws IOException { String temp = this.readField(false /* isQuotedString */); if (Utility.isNullOrEmpty(temp)) { return null; } else { return Integer.parseInt(temp); } }
java
{ "resource": "" }
q167846
LogRecordStreamReader.readLong
validation
public Long readLong() throws IOException { String temp = this.readField(false /* isQuotedString */); if (Utility.isNullOrEmpty(temp)) { return null; } else { return Long.parseLong(temp); } }
java
{ "resource": "" }
q167847
LogRecordStreamReader.readUri
validation
public URI readUri() throws URISyntaxException, IOException { String temp = this.readField(true /* isQuotedString */); if (Utility.isNullOrEmpty(temp)) { return null; } else { return new URI(Html.fromHtml(temp).toString()); } }
java
{ "resource": "" }
q167848
LogRecordStreamReader.readDelimiter
validation
private void readDelimiter(char delimiter) throws IOException { if (this.isEndOfFile()) { throw new EOFException(SR.LOG_STREAM_END_ERROR); } else { int read = this.read(); if (read == -1 || (char) read != delimiter) { throw new IllegalStateException(SR.LOG_STREAM_DELIMITER_ERROR); } } }
java
{ "resource": "" }
q167849
LogRecordStreamReader.tryPeekDelimiter
validation
private boolean tryPeekDelimiter(char delimiter) throws IOException { if (this.isEndOfFile()) { throw new EOFException(SR.LOG_STREAM_END_ERROR); } else { if ((char) this.peek() != delimiter) { return false; } else { return true; } } }
java
{ "resource": "" }
q167850
LogRecordStreamReader.readField
validation
private String readField(boolean isQuotedString) throws IOException { if (!this.isFirstFieldInRecord) { this.readDelimiter(LogRecordStreamReader.FIELD_DELIMITER); } else { this.isFirstFieldInRecord = false; } // Read a field, handling field/record delimiters in quotes and not counting them, // and also check that there are no record delimiters since they are only expected // outside of a field. // Note: We only need to handle strings that are quoted once from the beginning, // (e.g. "mystring"). We do not need to handle nested quotes or anything because // we control the string format. StringBuilder fieldBuilder = new StringBuilder(); boolean hasSeenQuoteForQuotedString = false; boolean isExpectingDelimiterForNextCharacterForQuotedString = false; while (true) { // If EOF when we haven't read the delimiter; unexpected. if (this.isEndOfFile()) { throw new EOFException(SR.LOG_STREAM_END_ERROR); } // Since we just checked isEndOfFile above, we know this is a char. char c = (char) this.peek(); // If we hit a delimiter that is not quoted or we hit the delimiter for // a quoted string or we hit the empty value string and hit a delimiter, // then we have finished reading the field. // Note: The empty value string is the only string that we don't require // quotes for for a quoted string. if ((!isQuotedString || isExpectingDelimiterForNextCharacterForQuotedString || fieldBuilder.length() == 0) && (c == LogRecordStreamReader.FIELD_DELIMITER || c == LogRecordStreamReader.RECORD_DELIMITER)) { // The delimiter character was peeked but not read -- they'll be consumed // on either the next call to readField or to EndCurrentRecord. break; } if (isExpectingDelimiterForNextCharacterForQuotedString) { // We finished reading a quoted string but found no delimiter following it. throw new IllegalStateException(SR.LOG_STREAM_QUOTE_ERROR); } // The character was not a delimiter, so consume and add to builder. this.read(); fieldBuilder.append(c); // We need to handle quotes specially since quoted delimiters // do not count since they are considered to be part of the // quoted string and not actually a delimiter. // Note: We use a specific quote character since we control the format // and we only allow non-encoded quote characters at the beginning/end // of the string. if (c == LogRecordStreamReader.QUOTE_CHAR) { if (!isQuotedString) { // Non-encoded quote character only allowed for quoted strings. throw new IllegalStateException(SR.LOG_STREAM_QUOTE_ERROR); } else if (fieldBuilder.length() == 1) { // Opening quote for a quoted string. hasSeenQuoteForQuotedString = true; } else if (hasSeenQuoteForQuotedString) { // Closing quote for a quoted string. isExpectingDelimiterForNextCharacterForQuotedString = true; } else { // Unexpected non-encoded quote. throw new IllegalStateException(SR.LOG_STREAM_QUOTE_ERROR); } } } String field; // Note: For quoted strings we remove the quotes. // We do not do this for the empty value string since it represents empty // and we don't write that out in quotes even for quoted strings. if (isQuotedString && fieldBuilder.length() != 0) { field = fieldBuilder.substring(1, fieldBuilder.length() - 1); } else { field = fieldBuilder.toString(); } return field; }
java
{ "resource": "" }
q167851
RetryExponentialRetry.createInstance
validation
@Override public RetryPolicy createInstance(final OperationContext opContext) { return new RetryExponentialRetry(this.resolvedMinBackoff, this.deltaBackoffIntervalInMs, this.resolvedMaxBackoff, this.maximumAttempts); }
java
{ "resource": "" }
q167852
LazySegmentedIterator.hasNext
validation
@Override @DoesServiceRequest public boolean hasNext() { while (this.currentSegment == null || (!this.currentSegmentIterator.hasNext() && this.currentSegment != null && this.currentSegment .getHasMoreResults())) { try { this.currentSegment = ExecutionEngine.executeWithRetry(this.client, this.parentObject, this.segmentGenerator, this.policyFactory, this.opContext); } catch (final StorageException e) { final NoSuchElementException ex = new NoSuchElementException(SR.ENUMERATION_ERROR); ex.initCause(e); throw ex; } this.currentSegmentIterator = this.currentSegment.getResults().iterator(); if (!this.currentSegmentIterator.hasNext() && !this.currentSegment.getHasMoreResults()) { return false; } } return this.currentSegmentIterator.hasNext(); }
java
{ "resource": "" }
q167853
QueryTableOperation.setClazzType
validation
protected void setClazzType(final Class<? extends TableEntity> clazzType) { Utility.assertNotNull("clazzType", clazzType); Utility.checkNullaryCtor(clazzType); this.clazzType = clazzType; }
java
{ "resource": "" }
q167854
QueryTableOperation.setResolver
validation
protected void setResolver(final EntityResolver<?> resolver) { Utility.assertNotNull(SR.QUERY_REQUIRES_VALID_CLASSTYPE_OR_RESOLVER, resolver); this.resolver = resolver; }
java
{ "resource": "" }
q167855
MimeHelper.writeMIMEBoundary
validation
private static void writeMIMEBoundary(final OutputStreamWriter outWriter, final String boundaryID) throws IOException { outWriter.write(String.format("--%s\r\n", boundaryID)); }
java
{ "resource": "" }
q167856
MimeHelper.writeMIMEBoundaryClosure
validation
private static void writeMIMEBoundaryClosure(final OutputStreamWriter outWriter, final String boundaryID) throws IOException { outWriter.write(String.format("--%s--\r\n", boundaryID)); }
java
{ "resource": "" }
q167857
MimeHelper.writeMIMEContentType
validation
private static void writeMIMEContentType(final OutputStreamWriter outWriter, final String boundaryName) throws IOException { outWriter.write(String.format("Content-Type: multipart/mixed; boundary=%s\r\n", boundaryName)); }
java
{ "resource": "" }
q167858
UriQueryBuilder.add
validation
public void add(final String name, final String value) throws StorageException { if (Utility.isNullOrEmpty(name)) { throw new IllegalArgumentException(SR.QUERY_PARAMETER_NULL_OR_EMPTY); } this.insertKeyValue(name, value); }
java
{ "resource": "" }
q167859
UriQueryBuilder.addToURI
validation
public URI addToURI(final URI uri) throws URISyntaxException, StorageException { final String origRawQuery = uri.getRawQuery(); final String rawFragment = uri.getRawFragment(); final String uriString = uri.resolve(uri).toASCIIString(); final HashMap<String, String[]> origQueryMap = PathUtility.parseQueryString(origRawQuery); // Try/Insert original queries to map for (final Entry<String, String[]> entry : origQueryMap.entrySet()) { for (final String val : entry.getValue()) { this.insertKeyValue(entry.getKey(), val); } } final StringBuilder retBuilder = new StringBuilder(); // has a fragment if (Utility.isNullOrEmpty(origRawQuery) && !Utility.isNullOrEmpty(rawFragment)) { final int bangDex = uriString.indexOf('#'); retBuilder.append(uriString.substring(0, bangDex)); } else if (!Utility.isNullOrEmpty(origRawQuery)) { // has a query final int queryDex = uriString.indexOf('?'); retBuilder.append(uriString.substring(0, queryDex)); } else { // no fragment or query retBuilder.append(uriString); if (uri.getRawPath().length() <= 0) { retBuilder.append("/"); } } final String finalQuery = this.toString(); if (finalQuery.length() > 0) { retBuilder.append("?"); retBuilder.append(finalQuery); } if (!Utility.isNullOrEmpty(rawFragment)) { retBuilder.append("#"); retBuilder.append(rawFragment); } return new URI(retBuilder.toString()); }
java
{ "resource": "" }
q167860
BaseRequest.addOptionalHeader
validation
public static void addOptionalHeader(final HttpURLConnection request, final String name, final String value) { if (value != null && !value.equals(Constants.EMPTY_STRING)) { request.setRequestProperty(name, value); } }
java
{ "resource": "" }
q167861
BaseRequest.createURLConnection
validation
public static HttpURLConnection createURLConnection(final URI uri, final RequestOptions options, UriQueryBuilder builder, final OperationContext opContext) throws IOException, URISyntaxException, StorageException { if (builder == null) { builder = new UriQueryBuilder(); } if (options.getTimeoutIntervalInMs() != null && options.getTimeoutIntervalInMs() != 0) { builder.add(TIMEOUT, String.valueOf(options.getTimeoutIntervalInMs() / 1000)); } final URL resourceUrl = builder.addToURI(uri).toURL(); // Get the proxy settings Proxy proxy = OperationContext.getDefaultProxy(); if (opContext != null && opContext.getProxy() != null) { proxy = opContext.getProxy(); } // Set up connection, optionally with proxy settings final HttpURLConnection retConnection; if (proxy != null) { retConnection = (HttpURLConnection) resourceUrl.openConnection(proxy); } else { retConnection = (HttpURLConnection) resourceUrl.openConnection(); } /* * ReadTimeout must be explicitly set to avoid a bug in JDK 6. In certain cases, this bug causes an immediate * read timeout exception to be thrown even if ReadTimeout is not set. * * Both connect and read timeout are set to the same value as we have no way of knowing how to partition * the remaining time between these operations. The user can override these timeouts using the SendingRequest * event handler if more control is desired. */ int timeout = Utility.getRemainingTimeout(options.getOperationExpiryTimeInMs(), options.getTimeoutIntervalInMs()); retConnection.setReadTimeout(timeout); retConnection.setConnectTimeout(timeout); // Note : by default sends Accept behavior as text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2 retConnection.setRequestProperty(Constants.HeaderConstants.ACCEPT, Constants.HeaderConstants.XML_TYPE); retConnection.setRequestProperty(Constants.HeaderConstants.ACCEPT_CHARSET, Constants.UTF8_CHARSET); // Note: by default sends Accept-Encoding as gzip retConnection.setRequestProperty(Constants.HeaderConstants.ACCEPT_ENCODING, Constants.EMPTY_STRING); // Note : by default sends Content-type behavior as application/x-www-form-urlencoded for posts. retConnection.setRequestProperty(Constants.HeaderConstants.CONTENT_TYPE, Constants.EMPTY_STRING); retConnection.setRequestProperty(Constants.HeaderConstants.STORAGE_VERSION_HEADER, Constants.HeaderConstants.TARGET_STORAGE_VERSION); retConnection.setRequestProperty(Constants.HeaderConstants.USER_AGENT, getUserAgent()); retConnection.setRequestProperty(Constants.HeaderConstants.CLIENT_REQUEST_ID_HEADER, opContext.getClientRequestID()); return retConnection; }
java
{ "resource": "" }
q167862
BaseRequest.delete
validation
public static HttpURLConnection delete(final URI uri, final RequestOptions options, UriQueryBuilder builder, final OperationContext opContext) throws IOException, URISyntaxException, StorageException { if (builder == null) { builder = new UriQueryBuilder(); } final HttpURLConnection retConnection = createURLConnection(uri, options, builder, opContext); retConnection.setRequestMethod(Constants.HTTP_DELETE); return retConnection; }
java
{ "resource": "" }
q167863
BaseRequest.getServiceProperties
validation
public static HttpURLConnection getServiceProperties(final URI uri, final RequestOptions options, UriQueryBuilder builder, final OperationContext opContext) throws IOException, URISyntaxException, StorageException { if (builder == null) { builder = new UriQueryBuilder(); } builder.add(Constants.QueryConstants.COMPONENT, Constants.QueryConstants.PROPERTIES); builder.add(Constants.QueryConstants.RESOURCETYPE, SERVICE); final HttpURLConnection retConnection = createURLConnection(uri, options, builder, opContext); retConnection.setRequestMethod(Constants.HTTP_GET); return retConnection; }
java
{ "resource": "" }
q167864
BaseRequest.getUserAgent
validation
public static String getUserAgent() { if (userAgent == null) { String userAgentComment = String.format(Utility.LOCALE_US, "(Android %s; %s; %s)", android.os.Build.VERSION.RELEASE, android.os.Build.BRAND, android.os.Build.MODEL); userAgent = String.format("%s/%s %s", Constants.HeaderConstants.USER_AGENT_PREFIX, Constants.HeaderConstants.USER_AGENT_VERSION, userAgentComment); } return userAgent; }
java
{ "resource": "" }
q167865
BaseRequest.setMetadata
validation
public static HttpURLConnection setMetadata(final URI uri, final RequestOptions options, UriQueryBuilder builder, final OperationContext opContext) throws IOException, URISyntaxException, StorageException { if (builder == null) { builder = new UriQueryBuilder(); } builder.add(Constants.QueryConstants.COMPONENT, METADATA); final HttpURLConnection retConnection = createURLConnection(uri, options, builder, opContext); retConnection.setFixedLengthStreamingMode(0); retConnection.setDoOutput(true); retConnection.setRequestMethod(Constants.HTTP_PUT); return retConnection; }
java
{ "resource": "" }
q167866
BaseRequest.setServiceProperties
validation
public static HttpURLConnection setServiceProperties(final URI uri, final RequestOptions options, UriQueryBuilder builder, final OperationContext opContext) throws IOException, URISyntaxException, StorageException { if (builder == null) { builder = new UriQueryBuilder(); } builder.add(Constants.QueryConstants.COMPONENT, Constants.QueryConstants.PROPERTIES); builder.add(Constants.QueryConstants.RESOURCETYPE, SERVICE); final HttpURLConnection retConnection = createURLConnection(uri, options, builder, opContext); retConnection.setDoOutput(true); retConnection.setRequestMethod(Constants.HTTP_PUT); return retConnection; }
java
{ "resource": "" }
q167867
FileOutputStream.close
validation
@Override @DoesServiceRequest public void close() throws IOException { try { // if the user has already closed the stream, this will throw a STREAM_CLOSED exception // if an exception was thrown by any thread in the threadExecutor, realize it now this.checkStreamState(); // flush any remaining data this.flush(); // shut down the ExecutorService. this.threadExecutor.shutdown(); // try to commit the file try { this.commit(); } catch (final StorageException e) { throw Utility.initIOException(e); } catch (URISyntaxException e) { throw Utility.initIOException(e); } } finally { // if close() is called again, an exception will be thrown synchronized (this.lastErrorLock) { this.streamFaulted = true; this.lastError = new IOException(SR.STREAM_CLOSED); } // if an exception was thrown and the executor was not yet closed, call shutDownNow() to cancel all tasks // and shutdown the ExecutorService if (!this.threadExecutor.isShutdown()) { this.threadExecutor.shutdownNow(); } } }
java
{ "resource": "" }
q167868
FileOutputStream.commit
validation
@DoesServiceRequest private void commit() throws StorageException, URISyntaxException { if (this.options.getStoreFileContentMD5()) { this.parentFileRef.getProperties().setContentMD5(Base64.encode(this.md5Digest.digest())); } this.parentFileRef.uploadProperties(this.accessCondition, this.options, this.opContext); }
java
{ "resource": "" }
q167869
FileOutputStream.dispatchWrite
validation
@DoesServiceRequest private synchronized void dispatchWrite(final int writeLength) throws IOException { if (writeLength == 0) { return; } Callable<Void> worker = null; if (this.outstandingRequests > this.options.getConcurrentRequestCount() * 2) { this.waitForTaskToComplete(); } final ByteArrayInputStream bufferRef = new ByteArrayInputStream(this.outBuffer.toByteArray()); final CloudFile fileRef = this.parentFileRef; long tempOffset = this.currentOffset; long tempLength = writeLength; final long opWriteLength = tempLength; final long opOffset = tempOffset; this.currentOffset += writeLength; worker = new Callable<Void>() { @Override public Void call() { try { fileRef.uploadRange(bufferRef, opOffset, opWriteLength, FileOutputStream.this.accessCondition, FileOutputStream.this.options, FileOutputStream.this.opContext); } catch (final IOException e) { synchronized (FileOutputStream.this.lastErrorLock) { FileOutputStream.this.streamFaulted = true; FileOutputStream.this.lastError = e; } } catch (final StorageException e) { synchronized (FileOutputStream.this.lastErrorLock) { FileOutputStream.this.streamFaulted = true; FileOutputStream.this.lastError = Utility.initIOException(e); } } catch (URISyntaxException e) { synchronized (FileOutputStream.this.lastErrorLock) { FileOutputStream.this.streamFaulted = true; FileOutputStream.this.lastError = Utility.initIOException(e); } } return null; } }; // Do work and reset buffer. this.completionService.submit(worker); this.outstandingRequests++; this.currentBufferedBytes = 0; this.outBuffer = new ByteArrayOutputStream(); }
java
{ "resource": "" }
q167870
FileOutputStream.flush
validation
@Override @DoesServiceRequest public synchronized void flush() throws IOException { this.checkStreamState(); // Dispatch a write for the current bytes in the buffer this.dispatchWrite(this.currentBufferedBytes); // Waits for all submitted tasks to complete while (this.outstandingRequests > 0) { // Wait for a task to complete this.waitForTaskToComplete(); // If that task threw an error, fail fast this.checkStreamState(); } }
java
{ "resource": "" }
q167871
FileOutputStream.waitForTaskToComplete
validation
private void waitForTaskToComplete() throws IOException { try { final Future<Void> future = this.completionService.take(); future.get(); } catch (final InterruptedException e) { throw Utility.initIOException(e); } catch (final ExecutionException e) { throw Utility.initIOException(e); } this.outstandingRequests--; }
java
{ "resource": "" }
q167872
FileOutputStream.write
validation
@Override @DoesServiceRequest public void write(final byte[] data, final int offset, final int length) throws IOException { if (offset < 0 || length < 0 || length > data.length - offset) { throw new IndexOutOfBoundsException(); } this.writeInternal(data, offset, length); }
java
{ "resource": "" }
q167873
FileOutputStream.write
validation
@DoesServiceRequest public void write(final InputStream sourceStream, final long writeLength) throws IOException, StorageException { Utility.writeToOutputStream(sourceStream, this, writeLength, false, false, this.opContext, this.options, false); }
java
{ "resource": "" }
q167874
FileOutputStream.writeInternal
validation
@DoesServiceRequest private synchronized void writeInternal(final byte[] data, int offset, int length) throws IOException { while (length > 0) { this.checkStreamState(); final int availableBufferBytes = this.internalWriteThreshold - this.currentBufferedBytes; final int nextWrite = Math.min(availableBufferBytes, length); // If we need to set MD5 then update the digest accordingly if (this.options.getStoreFileContentMD5()) { this.md5Digest.update(data, offset, nextWrite); } this.outBuffer.write(data, offset, nextWrite); this.currentBufferedBytes += nextWrite; offset += nextWrite; length -= nextWrite; if (this.currentBufferedBytes == this.internalWriteThreshold) { this.dispatchWrite(this.internalWriteThreshold); } } }
java
{ "resource": "" }
q167875
CloudStorageAccount.getDNS
validation
private static String getDNS(String service, String base) { if (base == null) { base = DEFAULT_DNS; } return String.format(DNS_NAME_FORMAT, service, base); }
java
{ "resource": "" }
q167876
CloudStorageAccount.tryConfigureDevStore
validation
private static CloudStorageAccount tryConfigureDevStore(final Map<String, String> settings) throws URISyntaxException { if (matchesSpecification( settings, allRequired(USE_DEVELOPMENT_STORAGE_NAME), optional(DEVELOPMENT_STORAGE_PROXY_URI_NAME))) { if (!Boolean.parseBoolean(settings.get(USE_DEVELOPMENT_STORAGE_NAME))) { throw new IllegalArgumentException(SR.INVALID_CONNECTION_STRING_DEV_STORE_NOT_TRUE); } URI devStoreProxyUri = null; if (settings.containsKey(DEVELOPMENT_STORAGE_PROXY_URI_NAME)) { devStoreProxyUri = new URI(settings.get(DEVELOPMENT_STORAGE_PROXY_URI_NAME)); } return getDevelopmentStorageAccount(devStoreProxyUri); } else { return null; } }
java
{ "resource": "" }
q167877
CloudStorageAccount.tryConfigureServiceAccount
validation
private static CloudStorageAccount tryConfigureServiceAccount(final Map<String, String> settings) throws URISyntaxException, InvalidKeyException { ConnectionStringFilter endpointsOptional = optional( BLOB_ENDPOINT_NAME, BLOB_SECONDARY_ENDPOINT_NAME, QUEUE_ENDPOINT_NAME, QUEUE_SECONDARY_ENDPOINT_NAME, TABLE_ENDPOINT_NAME, TABLE_SECONDARY_ENDPOINT_NAME, FILE_ENDPOINT_NAME, FILE_SECONDARY_ENDPOINT_NAME ); ConnectionStringFilter primaryEndpointRequired = atLeastOne( BLOB_ENDPOINT_NAME, QUEUE_ENDPOINT_NAME, TABLE_ENDPOINT_NAME, FILE_ENDPOINT_NAME ); ConnectionStringFilter secondaryEndpointsOptional = optional( BLOB_SECONDARY_ENDPOINT_NAME, QUEUE_SECONDARY_ENDPOINT_NAME, TABLE_SECONDARY_ENDPOINT_NAME, FILE_SECONDARY_ENDPOINT_NAME ); ConnectionStringFilter automaticEndpointsMatchSpec = matchesExactly(matchesAll( matchesOne( matchesAll(allRequired(ACCOUNT_KEY_NAME)), // Key + Name, Endpoints optional allRequired(SHARED_ACCESS_SIGNATURE_NAME) // SAS + Name, Endpoints optional ), allRequired(ACCOUNT_NAME_NAME), // Name required to automatically create URIs endpointsOptional, optional(DEFAULT_ENDPOINTS_PROTOCOL_NAME, ENDPOINT_SUFFIX_NAME) )); ConnectionStringFilter explicitEndpointsMatchSpec = matchesExactly(matchesAll( // Any Credentials, Endpoints must be explicitly declared validCredentials, primaryEndpointRequired, secondaryEndpointsOptional )); Boolean matchesAutomaticEndpointsSpec = matchesSpecification(settings, automaticEndpointsMatchSpec); Boolean matchesExplicitEndpointsSpec = matchesSpecification(settings, explicitEndpointsMatchSpec); if (matchesAutomaticEndpointsSpec || matchesExplicitEndpointsSpec) { if (matchesAutomaticEndpointsSpec && !settings.containsKey(DEFAULT_ENDPOINTS_PROTOCOL_NAME)) { settings.put(DEFAULT_ENDPOINTS_PROTOCOL_NAME, "https"); } String blobEndpoint = settingOrDefault(settings, BLOB_ENDPOINT_NAME); String queueEndpoint = settingOrDefault(settings, QUEUE_ENDPOINT_NAME); String tableEndpoint = settingOrDefault(settings, TABLE_ENDPOINT_NAME); String fileEndpoint = settingOrDefault(settings, FILE_ENDPOINT_NAME); String blobSecondaryEndpoint = settingOrDefault(settings, BLOB_SECONDARY_ENDPOINT_NAME); String queueSecondaryEndpoint = settingOrDefault(settings, QUEUE_SECONDARY_ENDPOINT_NAME); String tableSecondaryEndpoint = settingOrDefault(settings, TABLE_SECONDARY_ENDPOINT_NAME); String fileSecondaryEndpoint = settingOrDefault(settings, FILE_SECONDARY_ENDPOINT_NAME); // if secondary is specified, primary must also be specified if ( isValidEndpointPair(blobEndpoint, blobSecondaryEndpoint) && isValidEndpointPair(queueEndpoint, queueSecondaryEndpoint) && isValidEndpointPair(tableEndpoint, tableSecondaryEndpoint) && isValidEndpointPair(fileEndpoint, fileSecondaryEndpoint) ) { CloudStorageAccount accountInformation = new CloudStorageAccount( StorageCredentials.tryParseCredentials(settings), getStorageUri(settings, SR.BLOB, BLOB_ENDPOINT_NAME, BLOB_SECONDARY_ENDPOINT_NAME, matchesAutomaticEndpointsSpec), getStorageUri(settings, SR.QUEUE, QUEUE_ENDPOINT_NAME, QUEUE_SECONDARY_ENDPOINT_NAME, matchesAutomaticEndpointsSpec), getStorageUri(settings, SR.TABLE, TABLE_ENDPOINT_NAME, TABLE_SECONDARY_ENDPOINT_NAME, matchesAutomaticEndpointsSpec), getStorageUri(settings, SR.FILE, FILE_ENDPOINT_NAME, FILE_SECONDARY_ENDPOINT_NAME, matchesAutomaticEndpointsSpec) ); accountInformation.isBlobEndpointDefault = blobEndpoint == null; accountInformation.isFileEndpointDefault = fileEndpoint == null; accountInformation.isQueueEndpointDefault = queueEndpoint == null; accountInformation.isTableEndpointDefault = tableEndpoint == null; accountInformation.endpointSuffix = settingOrDefault(settings, ENDPOINT_SUFFIX_NAME); accountInformation.accountName = settingOrDefault(settings, ACCOUNT_NAME_NAME); return accountInformation; } } return null; }
java
{ "resource": "" }
q167878
CloudStorageAccount.createCloudAnalyticsClient
validation
public CloudAnalyticsClient createCloudAnalyticsClient() { if (this.getBlobStorageUri() == null) { throw new IllegalArgumentException(SR.BLOB_ENDPOINT_NOT_CONFIGURED); } if (this.getTableStorageUri() == null) { throw new IllegalArgumentException(SR.TABLE_ENDPOINT_NOT_CONFIGURED); } if (this.credentials == null) { throw new IllegalArgumentException(SR.MISSING_CREDENTIALS); } return new CloudAnalyticsClient(this.getBlobStorageUri(), this.getTableStorageUri(), this.getCredentials()); }
java
{ "resource": "" }
q167879
CloudStorageAccount.createCloudBlobClient
validation
public CloudBlobClient createCloudBlobClient() { if (this.getBlobStorageUri() == null) { throw new IllegalArgumentException(SR.BLOB_ENDPOINT_NOT_CONFIGURED); } if (this.credentials == null) { throw new IllegalArgumentException(SR.MISSING_CREDENTIALS); } return new CloudBlobClient(this.getBlobStorageUri(), this.getCredentials()); }
java
{ "resource": "" }
q167880
CloudStorageAccount.createCloudFileClient
validation
public CloudFileClient createCloudFileClient() { if (this.getFileStorageUri() == null) { throw new IllegalArgumentException(SR.FILE_ENDPOINT_NOT_CONFIGURED); } if (this.credentials == null) { throw new IllegalArgumentException(SR.MISSING_CREDENTIALS); } if (!StorageCredentialsHelper.canCredentialsGenerateClient(this.credentials)) { throw new IllegalArgumentException(SR.CREDENTIALS_CANNOT_SIGN_REQUEST); } return new CloudFileClient(this.getFileStorageUri(), this.getCredentials()); }
java
{ "resource": "" }
q167881
CloudStorageAccount.createCloudQueueClient
validation
public CloudQueueClient createCloudQueueClient() { if (this.getQueueStorageUri() == null) { throw new IllegalArgumentException(SR.QUEUE_ENDPOINT_NOT_CONFIGURED); } if (this.credentials == null) { throw new IllegalArgumentException(SR.MISSING_CREDENTIALS); } if (!StorageCredentialsHelper.canCredentialsGenerateClient(this.credentials)) { throw new IllegalArgumentException(SR.CREDENTIALS_CANNOT_SIGN_REQUEST); } return new CloudQueueClient(this.getQueueStorageUri(), this.getCredentials()); }
java
{ "resource": "" }
q167882
CloudStorageAccount.createCloudTableClient
validation
public CloudTableClient createCloudTableClient() { if (this.getTableStorageUri() == null) { throw new IllegalArgumentException(SR.TABLE_ENDPOINT_NOT_CONFIGURED); } if (this.credentials == null) { throw new IllegalArgumentException(SR.MISSING_CREDENTIALS); } if (!StorageCredentialsHelper.canCredentialsGenerateClient(this.credentials)) { throw new IllegalArgumentException(SR.CREDENTIALS_CANNOT_SIGN_REQUEST); } return new CloudTableClient(this.getTableStorageUri(), this.getCredentials()); }
java
{ "resource": "" }
q167883
CloudStorageAccount.generateSharedAccessSignature
validation
public String generateSharedAccessSignature(SharedAccessAccountPolicy policy) throws InvalidKeyException, StorageException { if (!StorageCredentialsHelper.canCredentialsSignRequest(this.getCredentials())) { throw new IllegalArgumentException(SR.CANNOT_CREATE_SAS_WITHOUT_ACCOUNT_KEY); } final String sig = SharedAccessSignatureHelper.generateSharedAccessSignatureHashForAccount( this.credentials.getAccountName(), policy, this.getCredentials()); final UriQueryBuilder sasBuilder = SharedAccessSignatureHelper.generateSharedAccessSignatureForAccount(policy, sig); return sasBuilder.toString(); }
java
{ "resource": "" }
q167884
TableOperation.generateRequestIdentity
validation
protected String generateRequestIdentity(boolean isSingleIndexEntry, final String entryName) throws StorageException { if (isSingleIndexEntry) { return String.format("'%s'", entryName.replace("'", "''")); } if (this.opType == TableOperationType.INSERT) { return Constants.EMPTY_STRING; } else { String pk = null; String rk = null; if (this.opType == TableOperationType.RETRIEVE) { final QueryTableOperation qOp = (QueryTableOperation) this; pk = qOp.getPartitionKey(); rk = qOp.getRowKey(); } else { pk = this.getEntity().getPartitionKey(); rk = this.getEntity().getRowKey(); } return String.format("%s='%s',%s='%s'", TableConstants.PARTITION_KEY, pk.replace("'", "''"), TableConstants.ROW_KEY, rk.replace("'", "''")); } }
java
{ "resource": "" }
q167885
TableOperation.generateRequestIdentityWithTable
validation
protected String generateRequestIdentityWithTable(final String tableName) throws StorageException { return String.format("%s(%s)", tableName, generateRequestIdentity(false, null)); }
java
{ "resource": "" }
q167886
StorageRequest.initialize
validation
protected final void initialize(OperationContext opContext) { RequestResult currResult = new RequestResult(); this.setResult(currResult); opContext.appendRequestResult(currResult); this.setException(null); this.setNonExceptionedRetryableFailure(false); this.setIsSent(false); }
java
{ "resource": "" }
q167887
StorageRequest.materializeException
validation
protected final StorageException materializeException(final OperationContext opContext) { if (this.getException() != null) { return this.getException(); } return StorageException.translateException(this, null, opContext); }
java
{ "resource": "" }
q167888
StorageRequest.postProcessResponse
validation
public R postProcessResponse(HttpURLConnection connection, P parentObject, C client, OperationContext context, R storageObject) throws Exception { return storageObject; }
java
{ "resource": "" }
q167889
StorageRequest.parseErrorDetails
validation
public StorageExtendedErrorInformation parseErrorDetails() { try { if (this.getConnection() == null || this.getConnection().getErrorStream() == null) { return null; } return StorageErrorHandler.getExtendedErrorInformation(this.getConnection().getErrorStream()); } catch (final Exception e) { return null; } }
java
{ "resource": "" }
q167890
TableBatchOperation.delete
validation
public void delete(final TableEntity entity) { this.lockToPartitionKey(entity.getPartitionKey()); this.add(TableOperation.delete(entity)); }
java
{ "resource": "" }
q167891
TableBatchOperation.insert
validation
public void insert(final TableEntity entity, boolean echoContent) { this.lockToPartitionKey(entity.getPartitionKey()); this.add(TableOperation.insert(entity, echoContent)); }
java
{ "resource": "" }
q167892
TableBatchOperation.insertOrMerge
validation
public void insertOrMerge(final TableEntity entity) { this.lockToPartitionKey(entity.getPartitionKey()); this.add(TableOperation.insertOrMerge(entity)); }
java
{ "resource": "" }
q167893
TableBatchOperation.insertOrReplace
validation
public void insertOrReplace(final TableEntity entity) { this.lockToPartitionKey(entity.getPartitionKey()); this.add(TableOperation.insertOrReplace(entity)); }
java
{ "resource": "" }
q167894
TableBatchOperation.merge
validation
public void merge(final TableEntity entity) { this.lockToPartitionKey(entity.getPartitionKey()); this.add(TableOperation.merge(entity)); }
java
{ "resource": "" }
q167895
TableBatchOperation.remove
validation
@Override public TableOperation remove(int index) { TableOperation op = super.remove(index); checkResetEntityLocks(); return op; }
java
{ "resource": "" }
q167896
TableBatchOperation.removeAll
validation
@Override public boolean removeAll(java.util.Collection<?> c) { boolean ret = super.removeAll(c); checkResetEntityLocks(); return ret; }
java
{ "resource": "" }
q167897
TableBatchOperation.replace
validation
public void replace(final TableEntity entity) { this.lockToPartitionKey(entity.getPartitionKey()); this.add(TableOperation.replace(entity)); }
java
{ "resource": "" }
q167898
TableBatchOperation.checkSingleQueryPerBatch
validation
private void checkSingleQueryPerBatch(final TableOperation op, final int size) { // if this has a query then no other operations can be added. if (this.hasQuery) { throw new IllegalArgumentException(SR.RETRIEVE_MUST_BE_ONLY_OPERATION_IN_BATCH); } if (op.getOperationType() == TableOperationType.RETRIEVE) { if (size > 0) { throw new IllegalArgumentException(SR.RETRIEVE_MUST_BE_ONLY_OPERATION_IN_BATCH); } else { this.hasQuery = true; } } this.containsWrites = op.getOperationType() != TableOperationType.RETRIEVE; }
java
{ "resource": "" }
q167899
TableBatchOperation.lockToPartitionKey
validation
private void lockToPartitionKey(final String partitionKey) { if (this.partitionKey == null) { this.partitionKey = partitionKey; } else { if (partitionKey.length() != partitionKey.length() || !this.partitionKey.equals(partitionKey)) { throw new IllegalArgumentException(SR.OPS_IN_BATCH_MUST_HAVE_SAME_PARTITION_KEY); } } }
java
{ "resource": "" }