javax.ws.rs.core.UriBuilderException#com.microsoft.azure.storage.StorageException源码实例Demo

下面列出了javax.ws.rs.core.UriBuilderException#com.microsoft.azure.storage.StorageException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Test
public void testInsertEntityOver1MB() throws StorageException {
    TableRequestOptions options = new TableRequestOptions();
    options.setTablePayloadFormat(TablePayloadFormat.Json);

    Class1 ref = new Class1();
    ref.setA("foo_A");
    ref.setB("foo_B");
    ref.setC("foo_C");
    // 1mb right here
    ref.setD(new byte[1024 * 1024]);
    ref.setPartitionKey("jxscl_odata");
    ref.setRowKey(UUID.randomUUID().toString());

    try {
        this.table.execute(TableOperation.insert(ref), options, null);
        fail();
    } catch (TableServiceException ex) {
        assertEquals(ex.getMessage(), "Bad Request");
        assertTrue(ex.getExtendedErrorInformation().getErrorMessage()
                .startsWith("The entity is larger than the maximum allowed size (1MB)."));
        assertEquals(ex.getExtendedErrorInformation().getErrorCode(), "EntityTooLarge");
    }
}
 
源代码2 项目: azure-storage-android   文件: CloudQueueTests.java
@Test
@Category({ DevFabricTests.class, DevStoreTests.class })
public void testGetMetadata() throws StorageException {
    HashMap<String, String> metadata = new HashMap<String, String>();
    metadata.put("ExistingMetadata", "ExistingMetadataValue");
    this.queue.setMetadata(metadata);
    this.queue.uploadMetadata();
    this.queue.downloadAttributes();
    assertEquals(this.queue.getMetadata().get("ExistingMetadata"), "ExistingMetadataValue");
    assertTrue(this.queue.getMetadata().containsKey("ExistingMetadata"));

    HashMap<String, String> empytMetadata = null;
    this.queue.setMetadata(empytMetadata);
    this.queue.uploadMetadata();
    this.queue.downloadAttributes();
    assertTrue(this.queue.getMetadata().size() == 0);
}
 
源代码3 项目: azure-storage-android   文件: FileRequest.java
/**
 * Generates a web request to abort a copy operation.
 * 
 * @param uri
 *            A <code>java.net.URI</code> object that specifies the absolute URI.
 * @param fileOptions
 *            A {@link FileRequestOptions} object that specifies execution options such as retry policy and timeout
 *            settings for the operation. Specify <code>null</code> to use the request options specified on the
 *            {@link CloudFileClient}.
 * @param opContext
 *            An {@link OperationContext} object that represents the context for the current operation. This object
 *            is used to track requests to the storage service, and to provide additional runtime information about
 *            the operation.
 * @param accessCondition
 *            The access condition to apply to the request. Only lease conditions are supported for this operation.
 * @param copyId
 *            A <code>String</code> object that identifying the copy operation.
 * @return a <code>HttpURLConnection</code> configured for the operation.
 * @throws StorageException
 *             An exception representing any error which occurred during the operation.
 * @throws IllegalArgumentException
 * @throws IOException
 * @throws URISyntaxException
 */
public static HttpURLConnection abortCopy(final URI uri, final FileRequestOptions fileOptions,
        final OperationContext opContext, final AccessCondition accessCondition, final String copyId)
        throws StorageException, IOException, URISyntaxException {

    final UriQueryBuilder builder = new UriQueryBuilder();

    builder.add(Constants.QueryConstants.COMPONENT, Constants.QueryConstants.COPY);
    builder.add(Constants.QueryConstants.COPY_ID, copyId);

    final HttpURLConnection request = BaseRequest.createURLConnection(uri, fileOptions, builder, opContext);

    request.setFixedLengthStreamingMode(0);
    request.setDoOutput(true);
    request.setRequestMethod(Constants.HTTP_PUT);

    request.setRequestProperty(Constants.HeaderConstants.COPY_ACTION_HEADER,
            Constants.HeaderConstants.COPY_ACTION_ABORT);

    if (accessCondition != null) {
        accessCondition.applyConditionToRequest(request);
    }

    return request;
}
 
@Test
public void testNulls() throws StorageException {
    TableRequestOptions options = new TableRequestOptions();

    options.setTablePayloadFormat(TablePayloadFormat.JsonFullMetadata);
    testNulls(options, false);

    options.setTablePayloadFormat(TablePayloadFormat.Json);
    testNulls(options, false);

    options.setTablePayloadFormat(TablePayloadFormat.JsonNoMetadata);
    testNulls(options, false);

    options.setTablePayloadFormat(TablePayloadFormat.JsonNoMetadata);
    testNulls(options, true);
}
 
源代码5 项目: azure-storage-android   文件: CloudQueueTests.java
@Test
@Category({ DevFabricTests.class, DevStoreTests.class })
public void testUploadMetadataNullInput() throws URISyntaxException, StorageException {
    CloudQueue queueForGet =  this.queue.getServiceClient().getQueueReference(this.queue.getName());

    HashMap<String, String> metadata1 = new HashMap<String, String>();
    String key = "ExistingMetadata1" + UUID.randomUUID().toString().replace("-", "");
    metadata1.put(key, "ExistingMetadataValue1");
    this.queue.setMetadata(metadata1);

    queueForGet.downloadAttributes();
    assertFalse(queueForGet.getMetadata().containsKey(key));

    this.queue.uploadMetadata();
    queueForGet.downloadAttributes();
    assertTrue(queueForGet.getMetadata().containsKey(key));

    this.queue.setMetadata(null);
    this.queue.uploadMetadata();
    queueForGet.downloadAttributes();
    assertTrue(queueForGet.getMetadata().size() == 0);
}
 
@Test
public void testBlobEncryption() throws URISyntaxException, StorageException, IOException {
    this.requestFound = false;
    
    OperationContext ctxt = new OperationContext();
    ctxt.getRequestCompletedEventHandler().addListener(new StorageEvent<RequestCompletedEvent>() {
        @Override
        public void eventOccurred(RequestCompletedEvent eventArg) {
            assertTrue(eventArg.getRequestResult().isRequestServiceEncrypted());
            CloudBlobServerEncryptionTests.this.requestFound = true;
        }
    });

    this.blob.uploadText("test", null, null, null, ctxt);
    assertTrue(this.requestFound);
}
 
/**
 * Create a blob and try to download a range of its contents
 */
@Test
public void testAppendBlobDownloadRangeValidationTest()
        throws StorageException, URISyntaxException, IOException {
    final int length = 5 * 1024 * 1024;

    final String appendBlobName = BlobTestHelper
            .generateRandomBlobNameWithPrefix("testBlockBlob");
    final CloudAppendBlob appendBlobRef = this.container
            .getAppendBlobReference(appendBlobName);

    appendBlobRef
            .upload(BlobTestHelper.getRandomDataStream(length), length);

    // Download full blob
    appendBlobRef.download(new ByteArrayOutputStream());
    assertEquals(length, appendBlobRef.getProperties().getLength());

    // Download blob range.
    byte[] downloadBuffer = new byte[100];
    int downloadLength = appendBlobRef.downloadRangeToByteArray(0,
            (long) 100, downloadBuffer, 0);
    assertEquals(length, appendBlobRef.getProperties().getLength());
    assertEquals(100, downloadLength);
}
 
源代码8 项目: azure-storage-android   文件: CloudQueue.java
/**
 * Creates the queue if it does not already exist, using the specified request options and operation context.
 * 
 * @param options
 *            A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying
 *            <code>null</code> will use the default request options from the associated service client (
 *            {@link CloudQueueClient}).
 * @param opContext
 *            An {@link OperationContext} object that represents the context for the current operation. This object
 *            is used to track requests to the storage service, and to provide additional runtime information about
 *            the operation.
 * 
 * @return A value of <code>true</code> if the queue is created in the storage service, otherwise <code>false</code>
 *         .
 * 
 * @throws StorageException
 *             If a storage service error occurred during the operation.
 */
@DoesServiceRequest
public boolean createIfNotExists(QueueRequestOptions options, OperationContext opContext) throws StorageException {
    options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient);

    boolean exists = this.exists(true, options, opContext);
    if (exists) {
        return false;
    }
    else {
        try {
            this.create(options, opContext);
            return true;
        }
        catch (StorageException e) {
            if (e.getHttpStatusCode() == HttpURLConnection.HTTP_CONFLICT
                    && StorageErrorCodeStrings.QUEUE_ALREADY_EXISTS.equals(e.getErrorCode())) {
                return false;
            }
            else {
                throw e;
            }
        }
    }
}
 
源代码9 项目: front50   文件: AzureStorageService.java
private void logStorageException(StorageException storageException, String key) {
  String errorMsg = storageException.getExtendedErrorInformation().getErrorMessage();
  String errorCode = storageException.getExtendedErrorInformation().getErrorCode();
  if (key.isEmpty()) {
    log.error(
        "Exception occurred accessing object(s) from storage: HTTPStatusCode {} ErrorCode: {} {}",
        value("responseStatus", storageException.getHttpStatusCode()),
        value("errorCode", errorCode),
        value("errorMsg", errorMsg));
  } else {
    log.error(
        "Exception occurred accessing object(s) from storage: Key {} HTTPStatusCode {} ErrorCode: {} {}",
        value("key", key),
        value("responseStatus", storageException.getHttpStatusCode()),
        value("errorCode", errorCode),
        value("errorMsg", errorMsg));
  }
}
 
源代码10 项目: azure-storage-android   文件: TableClientTests.java
@Test
@Category( {CloudTests.class })
public void testGetServiceStats() throws StorageException {
    CloudTableClient tClient = TableTestHelper.createCloudTableClient();
    tClient.getDefaultRequestOptions().setLocationMode(LocationMode.SECONDARY_ONLY);
    TableTestHelper.verifyServiceStats(tClient.getServiceStats());
}
 
源代码11 项目: azure-storage-android   文件: CloudFileTests.java
/**
 * Test file resizing.
 * 
 * @throws URISyntaxException
 * @throws StorageException
 */
@Test
public void testCloudFileResize() throws URISyntaxException, StorageException {
    CloudFile file = this.share.getRootDirectoryReference().getFileReference("file1");
    CloudFile file2 = this.share.getRootDirectoryReference().getFileReference("file1");

    file.create(1024);
    assertEquals(1024, file.getProperties().getLength());
    file2.downloadAttributes();
    assertEquals(1024, file2.getProperties().getLength());
    file2.getProperties().setContentType("text/plain");
    file2.uploadProperties();
    file.resize(2048);
    assertEquals(2048, file.getProperties().getLength());
    file.downloadAttributes();
    assertEquals("text/plain", file.getProperties().getContentType());
    file2.downloadAttributes();
    assertEquals(2048, file2.getProperties().getLength());

    // Resize to 0 length
    file.resize(0);
    assertEquals(0, file.getProperties().getLength());
    file.downloadAttributes();
    assertEquals("text/plain", file.getProperties().getContentType());
    file2.downloadAttributes();
    assertEquals(0, file2.getProperties().getLength());
}
 
源代码12 项目: components   文件: AzureStorageDeleteRuntimeTest.java
@Test
public void testRunAtDriverValid() {
    properties.remoteBlobs.include.setValue(Arrays.asList(true));
    properties.remoteBlobs.prefix.setValue(Arrays.asList("block1"));
    ValidationResult validationResult = deleteBlock.initialize(runtimeContainer, properties);
    assertEquals(ValidationResult.OK.getStatus(), validationResult.getStatus());
    deleteBlock.azureStorageBlobService = blobService;
    try {
        final List<CloudBlockBlob> list = new ArrayList<>();
        list.add(new CloudBlockBlob(new URI("https://storagesample.blob.core.windows.net/mycontainer/blob1.txt")));

        when(blobService.listBlobs(anyString(), anyString(), anyBoolean())).thenReturn(new Iterable<ListBlobItem>() {

            @Override
            public Iterator<ListBlobItem> iterator() {
                return new DummyListBlobItemIterator(list);
            }
        });

        when(blobService.deleteBlobBlockIfExist(any(CloudBlockBlob.class))).thenReturn(true);

        deleteBlock.runAtDriver(runtimeContainer);
    } catch (StorageException | URISyntaxException | InvalidKeyException e) {
        fail("should not throw " + e.getMessage());
    }

}
 
源代码13 项目: azure-storage-android   文件: CloudPageBlobTests.java
@Test
public void testBlobUploadWithoutMD5Validation() throws URISyntaxException, StorageException, IOException {
    final String pageBlobName = BlobTestHelper.generateRandomBlobNameWithPrefix("testPageBlob");
    final CloudPageBlob pageBlobRef = this.container.getPageBlobReference(pageBlobName);

    final int length = 2 * 1024;
    ByteArrayInputStream srcStream = BlobTestHelper.getRandomDataStream(length);
    BlobRequestOptions options = new BlobRequestOptions();
    options.setDisableContentMD5Validation(false);
    options.setStoreBlobContentMD5(false);

    pageBlobRef.upload(srcStream, length, null, options, null);
    pageBlobRef.downloadAttributes();
    pageBlobRef.getProperties().setContentMD5("MDAwMDAwMDA=");
    pageBlobRef.uploadProperties(null, options, null);

    try {
        pageBlobRef.download(new ByteArrayOutputStream(), null, options, null);
        fail();
    }
    catch (StorageException ex) {
        assertEquals(306, ex.getHttpStatusCode());
        assertEquals("InvalidMd5", ex.getErrorCode());
    }

    options.setDisableContentMD5Validation(true);
    pageBlobRef.download(new ByteArrayOutputStream(), null, options, null);
    
    final CloudPageBlob pageBlobRef2 = this.container.getPageBlobReference(pageBlobName);
    assertNull(pageBlobRef2.getProperties().getContentMD5());

    byte[] target = new byte[4];
    pageBlobRef2.downloadRangeToByteArray(0L, 4L, target, 0);
    assertEquals("MDAwMDAwMDA=", pageBlobRef2.properties.getContentMD5());
}
 
源代码14 项目: hadoop   文件: SelfRenewingLease.java
/**
 * Free the lease and stop the keep-alive thread.
 * @throws StorageException
 */
public void free() throws StorageException {
  AccessCondition accessCondition = AccessCondition.generateEmptyCondition();
  accessCondition.setLeaseID(leaseID);
  try {
    blobWrapper.getBlob().releaseLease(accessCondition);
  } catch (StorageException e) {
    if (e.getErrorCode().equals("BlobNotFound")) {

      // Don't do anything -- it's okay to free a lease
      // on a deleted file. The delete freed the lease
      // implicitly.
    } else {

      // This error is not anticipated, so re-throw it.
      LOG.warn("Unanticipated exception when trying to free lease " + leaseID
          + " on " +  blobWrapper.getStorageUri());
      throw(e);
    }
  } finally {

    // Even if releasing the lease fails (e.g. because the file was deleted),
    // make sure to record that we freed the lease, to terminate the
    // keep-alive thread.
    leaseFreed = true;
    LOG.debug("Freed lease " + leaseID + " on " + blobWrapper.getUri()
        + " managed by thread " + renewer.getName());
  }
}
 
源代码15 项目: data-transfer-project   文件: AzureTableStore.java
@Override
public UUID findFirst(JobAuthorization.State jobState) {
  try {
    String partitionFilter =
        generateFilterCondition(
            "PartitionKey", TableQuery.QueryComparisons.EQUAL, configuration.getPartitionKey());
    String stateFilter =
        generateFilterCondition(
            "State",
            TableQuery.QueryComparisons.EQUAL,
            jobState.name()); // properties are converted to capitalized by the storage API

    String combinedFilter =
        TableQuery.combineFilters(partitionFilter, TableQuery.Operators.AND, stateFilter);

    TableQuery<DataWrapper> query =
        TableQuery.from(DataWrapper.class).where(combinedFilter).take(1);

    CloudTable table = tableClient.getTableReference(JOB_TABLE);
    Iterator<DataWrapper> iter = table.execute(query).iterator();
    if (!iter.hasNext()) {
      return null;
    }
    return UUID.fromString(iter.next().getRowKey());
  } catch (StorageException | URISyntaxException e) {
    throw new MicrosoftStorageException("Error finding first job", e);
  }
}
 
/**
 * Set and delete container permissions
 *
 * @throws URISyntaxException
 * @throws StorageException
 * @throws InterruptedException
 */
@Test
@Category({ SlowTests.class, DevFabricTests.class, DevStoreTests.class })
public void testCloudBlobContainerSetPermissions() throws  StorageException,
        InterruptedException, URISyntaxException {
    CloudBlobClient client = BlobTestHelper.createCloudBlobClient();
    this.container.create();

    BlobContainerPermissions permissions = this.container.downloadPermissions();
    assertTrue(BlobContainerPublicAccessType.OFF.equals(permissions.getPublicAccess()));
    assertEquals(0, permissions.getSharedAccessPolicies().size());

    final Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    final Date start = cal.getTime();
    cal.add(Calendar.MINUTE, 30);
    final Date expiry = cal.getTime();

    permissions.setPublicAccess(BlobContainerPublicAccessType.CONTAINER);
    SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
    policy.setPermissions(EnumSet.of(SharedAccessBlobPermissions.LIST, SharedAccessBlobPermissions.CREATE));
    policy.setSharedAccessStartTime(start);
    policy.setSharedAccessExpiryTime(expiry);
    permissions.getSharedAccessPolicies().put("key1", policy);

    this.container.uploadPermissions(permissions);
    Thread.sleep(30000);
    // Check if permissions were set
    CloudBlobContainer container2 = client.getContainerReference(this.container.getName());
    assertPermissionsEqual(permissions, container2.downloadPermissions());

    // Clear permissions
    permissions.getSharedAccessPolicies().clear();
    this.container.uploadPermissions(permissions);
    Thread.sleep(30000);

    // Check if permissions were cleared
    // Public access should still be the same
    permissions = container2.downloadPermissions();
    assertPermissionsEqual(permissions, container2.downloadPermissions());
}
 
源代码17 项目: azure-kusto-java   文件: AzureStorageClient.java
void postMessageToQueue(String queuePath, String content) throws StorageException, URISyntaxException {
    // Ensure
    Ensure.stringIsNotBlank(queuePath, "queuePath");
    Ensure.stringIsNotBlank(content, "content");

    CloudQueue queue = new CloudQueue(new URI(queuePath));
    CloudQueueMessage queueMessage = new CloudQueueMessage(content);
    queue.addMessage(queueMessage);
}
 
源代码18 项目: azure-kusto-java   文件: AzureStorageClient.java
CloudBlockBlob  uploadLocalFileToBlob(String filePath, String blobName, String storageUri, IngestionProperties.DATA_FORMAT dataFormat)
        throws URISyntaxException, StorageException, IOException {
    Ensure.fileExists(filePath);

    CompressionType sourceCompressionType = getCompression(filePath);
    return uploadLocalFileToBlob(filePath, blobName, storageUri, shouldCompress(sourceCompressionType, dataFormat.name()));
}
 
/**
 * Validate share references
 * 
 * @throws StorageException
 * @throws URISyntaxException
 */
@Test
public void testCloudFileShareReference() throws StorageException, URISyntaxException {
    CloudFileClient client = FileTestHelper.createCloudFileClient();
    CloudFileShare share = client.getShareReference("share");

    CloudFileDirectory directory = share.getRootDirectoryReference().getDirectoryReference("directory3");
    CloudFileDirectory directory2 = directory.getDirectoryReference("directory4");

    assertEquals(share.getStorageUri().toString(), directory.getShare().getStorageUri().toString());
    assertEquals(share.getStorageUri().toString(), directory2.getShare().getStorageUri().toString());
    assertEquals(share.getStorageUri().toString(), directory2.getParent().getShare().getStorageUri().toString());
}
 
源代码20 项目: nifi   文件: PutAzureQueueStorage.java
@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;
    }

    final long startNanos = System.nanoTime();

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    session.exportTo(flowFile, baos);
    final String flowFileContent = baos.toString();

    CloudQueueMessage message = new CloudQueueMessage(flowFileContent);
    CloudQueueClient cloudQueueClient;
    CloudQueue cloudQueue;

    final int ttl = context.getProperty(TTL).asTimePeriod(TimeUnit.SECONDS).intValue();
    final int delay = context.getProperty(VISIBILITY_DELAY).asTimePeriod(TimeUnit.SECONDS).intValue();
    final String queue = context.getProperty(QUEUE).evaluateAttributeExpressions(flowFile).getValue().toLowerCase();

    try {
        cloudQueueClient = createCloudQueueClient(context, flowFile);
        cloudQueue = cloudQueueClient.getQueueReference(queue);

        final OperationContext operationContext = new OperationContext();
        AzureStorageUtils.setProxy(operationContext, context);

        cloudQueue.addMessage(message, ttl, delay, null, operationContext);
    } catch (URISyntaxException | StorageException e) {
        getLogger().error("Failed to write the message to Azure Queue Storage due to {}", new Object[]{e});
        flowFile = session.penalize(flowFile);
        session.transfer(flowFile, REL_FAILURE);
        return;
    }

    session.transfer(flowFile, REL_SUCCESS);
    final long transmissionMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
    session.getProvenanceReporter().send(flowFile, cloudQueue.getUri().toString(), transmissionMillis);
}
 
源代码21 项目: azure-storage-android   文件: BlobOutputStream.java
/**
 * Closes this output stream and releases any system resources associated with this stream. If any data remains in
 * the buffer it is committed to the service.
 * 
 * @throws IOException
 *             If an I/O error occurs.
 */
@Override
@DoesServiceRequest
public synchronized 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 blob
        try {
            this.commit();
        }
        catch (final StorageException e) {
            throw Utility.initIOException(e);
        }
    }
    finally {
        // if close() is called again, an exception will be thrown
        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();
        }
    }
}
 
源代码22 项目: azure-kusto-java   文件: AzureStorageClientTest.java
@BeforeAll
static void setUp() throws StorageException, URISyntaxException {
    testFilePath = Paths.get("src", "test", "resources", "testdata.json").toString();
    testFile = new File(testFilePath);
    testFilePathCompressed = Paths.get("src", "test", "resources", "testdata.json.gz").toString();
    blob = new CloudBlockBlob(new URI("https://ms.com/storageUri"));
}
 
源代码23 项目: azure-storage-android   文件: CloudQueueTests.java
@Test
@Category({ DevFabricTests.class, DevStoreTests.class })
public void testDeleteQueueIfExists() throws URISyntaxException, StorageException {
    final CloudQueue queue = QueueTestHelper.getRandomQueueReference();

    assertFalse(queue.deleteIfExists());

    try {
        final OperationContext createQueueContext = new OperationContext();
        queue.create(null, createQueueContext);
        assertEquals(createQueueContext.getLastResult().getStatusCode(), HttpURLConnection.HTTP_CREATED);

        assertTrue(queue.deleteIfExists());
        assertFalse(queue.deleteIfExists());

        try {
            queue.create();
            fail("Queue CreateIfNotExists did not throw exception while trying to create a queue in BeingDeleted State");
        }
        catch (StorageException ex) {
            assertEquals("Expected 409 Exception, QueueBeingDeleted not thrown", ex.getHttpStatusCode(),
                    HttpURLConnection.HTTP_CONFLICT);
            assertEquals("Expected 409 Exception, QueueBeingDeleted not thrown", ex.getExtendedErrorInformation()
                    .getErrorCode(), StorageErrorCodeStrings.QUEUE_BEING_DELETED);
        }
    }
    finally {
        queue.delete();
    }
}
 
源代码24 项目: azure-storage-android   文件: CloudQueueTests.java
@Test
@Category({ DevFabricTests.class, DevStoreTests.class })
public void testQueueDelete() throws URISyntaxException, StorageException {
    final CloudQueueClient qClient = TestHelper.createCloudQueueClient();
    final String queueName = QueueTestHelper.generateRandomQueueName();
    CloudQueue queue = qClient.getQueueReference(queueName);
    assertEquals(queueName, queue.getName());

    try {
        OperationContext createQueueContext = new OperationContext();
        queue.create(null, createQueueContext);
        assertEquals(createQueueContext.getLastResult().getStatusCode(), HttpURLConnection.HTTP_CREATED);

        OperationContext deleteQueueContext = new OperationContext();
        queue.delete(null, deleteQueueContext);
        assertEquals(deleteQueueContext.getLastResult().getStatusCode(), HttpURLConnection.HTTP_NO_CONTENT);

        try {
            queue.downloadAttributes();
            fail();
        }
        catch (StorageException ex) {
            assertEquals("Expected 404 Exception", ex.getHttpStatusCode(), HttpURLConnection.HTTP_NOT_FOUND);
        }
    }
    finally {
        queue.deleteIfExists();
    }
}
 
源代码25 项目: azure-storage-android   文件: CloudQueue.java
/**
 * Get the message request base address (Used internally only).
 * 
 * @return The message request <code>URI</code>.
 * 
 * @throws URISyntaxException
 *             If the resource URI is invalid.
 * @throws StorageException
 */
private StorageUri getMessageRequestAddress(final OperationContext opContext) throws URISyntaxException,
        StorageException {
    if (this.messageRequestAddress == null) {
        this.messageRequestAddress = PathUtility.appendPathToUri(this.getTransformedAddress(opContext),
                QueueConstants.MESSAGES);
    }

    return this.messageRequestAddress;
}
 
源代码26 项目: big-c   文件: AzureNativeFileSystemStore.java
/**
 * Connect to Azure storage using account key credentials.
 */
private void connectUsingConnectionStringCredentials(
    final String accountName, final String containerName,
    final String accountKey) throws InvalidKeyException, StorageException,
    IOException, URISyntaxException {
  // If the account name is "acc.blob.core.windows.net", then the
  // rawAccountName is just "acc"
  String rawAccountName = accountName.split("\\.")[0];
  StorageCredentials credentials = new StorageCredentialsAccountAndKey(
      rawAccountName, accountKey);
  connectUsingCredentials(accountName, credentials, containerName);
}
 
源代码27 项目: components   文件: AzureStorageQueuePurgeRuntime.java
private boolean purgeAzureQueue(RuntimeContainer container) {
    Boolean purgeResult = false;
    try {
        int dataCount = (int) queueService.getApproximateMessageCount(queueName);
        LOGGER.debug(messages.getMessage("debug.Purgeing", dataCount, queueName));
        queueService.clear(queueName);
        purgeResult = true;
    } catch (InvalidKeyException | URISyntaxException | StorageException e) {
        LOGGER.error(e.getLocalizedMessage());
        if (dieOnError) {
            throw new ComponentException(e);
        }
    }
    return purgeResult;
}
 
@Test
@Category(SecondaryTests.class)
public void testBatchRemoveRange() throws StorageException {
    ArrayList<TableOperation> ops = allOpsList();

    TableBatchOperation batch = new TableBatchOperation();

    batch.addAll(ops);

    batch.removeRange(0, ops.size());
    assertEquals(0, batch.size());

    // should be able to add an entity with a different partition key
    Class1 baseEntity = TableTestHelper.generateRandomEntity("jxscl_odata_2");
    batch.insert(baseEntity);

    batch.removeRange(0, 1);

    batch.addAll(ops);
    batch.removeRange(0, ops.size() - 1);

    // should be not be able to add an entity with a different partition key
    baseEntity = TableTestHelper.generateRandomEntity("jxscl_odata_2");
    try {
        batch.insert(baseEntity);
        fail(SR.OPS_IN_BATCH_MUST_HAVE_SAME_PARTITION_KEY);
    }
    catch (IllegalArgumentException e) {
        assertEquals(SR.OPS_IN_BATCH_MUST_HAVE_SAME_PARTITION_KEY, e.getMessage());
    }

    batch.removeRange(0, 1);

    // should be able to add a retrieve to the batch
    Class1 ref = TableTestHelper.generateRandomEntity("jxscl_odata");
    TableOperation queryOp = TableOperation.retrieve(ref.getPartitionKey(), ref.getRowKey(), ref.getClass());
    batch.add(queryOp);
}
 
源代码29 项目: azure-storage-android   文件: QueueTestHelper.java
public static CloudQueue getRandomQueueReference() throws URISyntaxException, StorageException {
    String queueName = generateRandomQueueName();
    CloudQueueClient qClient = createCloudQueueClient();
    CloudQueue queue = qClient.getQueueReference(queueName);

    return queue;
}
 
源代码30 项目: cloudbreak   文件: AzureCloudBlobClientActions.java
private void createCloudBlobContainer(String containerName) {
    CloudBlobContainer cloudBlobContainer = null;

    try {
        int limit = 0;
        do {
            Thread.sleep(6000);
            try {
                cloudBlobContainer = createCloudBlobClient().getContainerReference(containerName);
                if (cloudBlobContainer.createIfNotExists()) {
                    Log.log(LOGGER, format(" Container with Name: %s has been created. ", containerName));
                } else {
                    Log.log(LOGGER, format(" Container with Name: %s already exists. ", containerName));
                }
                limit = 60;
            } catch (StorageException | URISyntaxException createAfterWaitException) {
                limit++;
                if (limit >= 60) {
                    LOGGER.error("Azure Adls Gen2 Blob Storage Container [{}] create cannot be succeed during 360000 ms!\n",
                            containerName, createAfterWaitException);
                }
            }
        } while (limit < 60);
    } catch (InterruptedException waitException) {
        LOGGER.error("Creation of Adls Gen2 Blob Storage Container [{}] has been timed out after 360000 ms!\n", containerName, waitException);
    }
}