List of usage examples for java.lang InterruptedException getCause
public synchronized Throwable getCause()
From source file:com.homeadvisor.kafdrop.service.CuratorKafkaMonitor.java
private Map<Integer, Long> getConsumerOffsets(String groupId, TopicVO topic) { try {// ww w.ja v a 2s . c o m // Kafka doesn't really give us an indication of whether a consumer is // using Kafka or Zookeeper based offset tracking. So look up the offsets // for both and assume that the largest offset is the correct one. ForkJoinTask<Map<Integer, Long>> kafkaTask = threadPool .submit(() -> getConsumerOffsets(groupId, topic, false)); ForkJoinTask<Map<Integer, Long>> zookeeperTask = threadPool .submit(() -> getConsumerOffsets(groupId, topic, true)); Map<Integer, Long> zookeeperOffsets = zookeeperTask.get(); Map<Integer, Long> kafkaOffsets = kafkaTask.get(); zookeeperOffsets.entrySet() .forEach(entry -> kafkaOffsets.merge(entry.getKey(), entry.getValue(), Math::max)); return kafkaOffsets; } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw Throwables.propagate(ex); } catch (ExecutionException ex) { throw Throwables.propagate(ex.getCause()); } }
From source file:com.homeadvisor.kafdrop.service.CuratorKafkaMonitor.java
private Map<Integer, Long> getTopicPartitionSizes(TopicVO topic, long time) { try {/* w ww .ja va2 s. c o m*/ PartitionOffsetRequestInfo requestInfo = new PartitionOffsetRequestInfo(time, 1); return threadPool.submit(() -> topic.getPartitions().parallelStream().filter(p -> p.getLeader() != null) .collect(Collectors.groupingBy(p -> p.getLeader().getId())) // Group partitions by leader broker id .entrySet().parallelStream().map(entry -> { final Integer brokerId = entry.getKey(); final List<TopicPartitionVO> brokerPartitions = entry.getValue(); try { // Get the size of the partitions for a topic from the leader. final OffsetResponse offsetResponse = sendOffsetRequest(brokerId, topic, requestInfo, brokerPartitions); // Build a map of partitionId -> topic size from the response return brokerPartitions.stream() .collect(Collectors.toMap(TopicPartitionVO::getId, partition -> Optional .ofNullable(offsetResponse.offsets(topic.getName(), partition.getId())) .map(Arrays::stream).orElse(LongStream.empty()).findFirst() .orElse(-1L))); } catch (Exception ex) { LOG.error("Unable to get partition log size for topic {} partitions ({})", topic.getName(), brokerPartitions.stream().map(TopicPartitionVO::getId) .map(String::valueOf).collect(Collectors.joining(",")), ex); // Map each partition to -1, indicating we got an error return brokerPartitions.stream() .collect(Collectors.toMap(TopicPartitionVO::getId, tp -> -1L)); } }).map(Map::entrySet).flatMap(Collection::stream) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))).get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Throwables.propagate(e); } catch (ExecutionException e) { throw Throwables.propagate(e.getCause()); } }
From source file:com.brienwheeler.lib.test.stepper.SteppableThreadTest.java
private void interruptInWait(SteppableThread stepper, TestMode mode) throws InterruptedException { final Thread testThread = Thread.currentThread(); Thread interruptThread = new Thread() { @Override/* w w w .j a v a 2 s . c o m*/ public void run() { try { Thread.sleep(10L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } testThread.interrupt(); } }; interruptThread.start(); try { if (mode == TestMode.RELEASE) stepper.release(); else if (mode == TestMode.WAITDONE) stepper.waitDone(); else if (mode == TestMode.JOIN) stepper.releaseAndJoin(); Assert.fail(); } catch (RuntimeException e) { Assert.assertTrue(Thread.interrupted()); // test and clear Assert.assertEquals(InterruptedException.class, e.getCause().getClass()); } interruptThread.join(); }
From source file:org.apache.phoenix.execute.HashJoinPlan.java
@Override public ResultIterator iterator(ParallelScanGrouper scanGrouper) throws SQLException { int count = subPlans.length; PhoenixConnection connection = getContext().getConnection(); ConnectionQueryServices services = connection.getQueryServices(); ExecutorService executor = services.getExecutor(); List<Future<Object>> futures = Lists.<Future<Object>>newArrayListWithExpectedSize(count); dependencies = Lists.newArrayList(); if (joinInfo != null) { hashClient = hashClient != null ? hashClient : new HashCacheClient(delegate.getContext().getConnection()); firstJobEndTime = new AtomicLong(0); keyRangeExpressions = new CopyOnWriteArrayList<Expression>(); }//w ww . j ava2s . c o m for (int i = 0; i < count; i++) { final int index = i; futures.add(executor.submit(new JobCallable<Object>() { @Override public Object call() throws Exception { return subPlans[index].execute(HashJoinPlan.this); } @Override public Object getJobId() { return HashJoinPlan.this; } @Override public TaskExecutionMetricsHolder getTaskExecutionMetric() { return NO_OP_INSTANCE; } })); } SQLException firstException = null; for (int i = 0; i < count; i++) { try { Object result = futures.get(i).get(); subPlans[i].postProcess(result, this); } catch (InterruptedException e) { if (firstException == null) { firstException = new SQLException("Sub plan [" + i + "] execution interrupted.", e); } } catch (ExecutionException e) { if (firstException == null) { firstException = new SQLException("Encountered exception in sub plan [" + i + "] execution.", e.getCause()); } } } if (firstException != null) { SQLCloseables.closeAllQuietly(dependencies); throw firstException; } Expression postFilter = null; boolean hasKeyRangeExpressions = keyRangeExpressions != null && !keyRangeExpressions.isEmpty(); if (recompileWhereClause || hasKeyRangeExpressions) { StatementContext context = delegate.getContext(); PTable table = context.getCurrentTable().getTable(); ParseNode viewWhere = table.getViewStatement() == null ? null : new SQLParser(table.getViewStatement()).parseQuery().getWhere(); context.setResolver(FromCompiler.getResolverForQuery((SelectStatement) (delegate.getStatement()), delegate.getContext().getConnection())); if (recompileWhereClause) { postFilter = WhereCompiler.compile(delegate.getContext(), delegate.getStatement(), viewWhere, null); } if (hasKeyRangeExpressions) { WhereCompiler.compile(delegate.getContext(), delegate.getStatement(), viewWhere, keyRangeExpressions, true, null); } } if (joinInfo != null) { Scan scan = delegate.getContext().getScan(); HashJoinInfo.serializeHashJoinIntoScan(scan, joinInfo); } ResultIterator iterator = joinInfo == null ? delegate.iterator(scanGrouper) : ((BaseQueryPlan) delegate).iterator(dependencies, scanGrouper); if (statement.getInnerSelectStatement() != null && postFilter != null) { iterator = new FilterResultIterator(iterator, postFilter); } return iterator; }
From source file:com.sillelien.dollar.api.types.DollarList.java
@NotNull @Override/* w ww . j ava 2 s .c o m*/ public var _fix(int depth, boolean parallel) { if (depth <= 1) { return this; } else { ImmutableList<var> result; if (parallel) { try { result = ImmutableList.copyOf(executor.submit(() -> $stream(parallel) .map(v -> v._fix(depth - 1, parallel)).collect(Collectors.toList())).get()); } catch (InterruptedException e) { Thread.interrupted(); result = ImmutableList.<var>of(DollarFactory.failure(ErrorType.INTERRUPTED, e, false)); } catch (ExecutionException e) { result = ImmutableList .of(DollarFactory.failure(ErrorType.EXECUTION_FAILURE, e.getCause(), false)); } return new DollarList(errors(), result); } else { return new DollarList(errors(), ImmutableList.copyOf( $stream(parallel).map(v -> v._fix(depth - 1, parallel)).collect(Collectors.toList()))); } } }
From source file:fr.dutra.confluence2wordpress.action.SyncAction.java
private void initSessionElements() throws WordpressXmlRpcException { if (getWordpressUsers() == null) { WordpressClient client = pluginSettingsManager.getWordpressClient(); Future<List<WordpressUser>> futureUsers = client.getUsers(); Future<List<WordpressCategory>> futureCategories = client.getCategories(); Future<List<WordpressTag>> futureTags = client.getTags(); Set<WordpressUser> users = new TreeSet<WordpressUser>(new Comparator<WordpressUser>() { @Override//from ww w .j av a2 s . co m public int compare(WordpressUser o1, WordpressUser o2) { return new CompareToBuilder() .append(StringUtils.lowerCase(o1.getNiceUsername()), StringUtils.lowerCase(o2.getNiceUsername())) .append(o1.getId(), o2.getId()).toComparison(); } }); Set<WordpressCategory> categories = new TreeSet<WordpressCategory>(new Comparator<WordpressCategory>() { @Override public int compare(WordpressCategory o1, WordpressCategory o2) { return new CompareToBuilder().append(StringUtils.lowerCase(o1.getCategoryName()), StringUtils.lowerCase(o2.getCategoryName())).toComparison(); } }); Set<WordpressTag> tags = new TreeSet<WordpressTag>(new Comparator<WordpressTag>() { @Override public int compare(WordpressTag o1, WordpressTag o2) { return new CompareToBuilder() .append(StringUtils.lowerCase(o1.getName()), StringUtils.lowerCase(o2.getName())) .toComparison(); } }); try { users.addAll(futureUsers.get(30, TimeUnit.SECONDS)); categories.addAll(futureCategories.get(30, TimeUnit.SECONDS)); tags.addAll(futureTags.get(30, TimeUnit.SECONDS)); } catch (InterruptedException e) { throw new WordpressXmlRpcException("Error contacting Wordpress server", e); } catch (ExecutionException e) { if (e.getCause() instanceof WordpressXmlRpcException) { throw (WordpressXmlRpcException) e.getCause(); } throw new WordpressXmlRpcException("Error contacting Wordpress server", e.getCause()); } catch (TimeoutException e) { throw new WordpressXmlRpcException("Connection to Wordpress timed out", e.getCause()); } setWordpressUsers(users); setWordpressCategories(categories); setWordpressTags(tags); } if (getAvailableMacros() == null) { Set<MacroMetadata> allMacroMetadata = macroMetadataManager.getAllMacroMetadata(); TreeSet<String> macros = new TreeSet<String>(); for (MacroMetadata macroMetadata : allMacroMetadata) { macros.add(macroMetadata.getMacroName()); } setAvailableMacros(macros); } }
From source file:org.yccheok.jstock.gui.OptionsAlertJPanel.java
private void signIn() { jCheckBox2.setEnabled(false);/* www . j av a 2 s.c om*/ SwingWorker swingWorker = new SwingWorker<Pair<Pair<Credential, String>, Boolean>, Void>() { @Override protected Pair<Pair<Credential, String>, Boolean> doInBackground() throws Exception { final Pair<Pair<Credential, String>, Boolean> pair = org.yccheok.jstock.google.Utils .authorizeGmail(); return pair; } @Override public void done() { Pair<Pair<Credential, String>, Boolean> pair = null; try { pair = this.get(); } catch (InterruptedException ex) { JOptionPane.showMessageDialog(OptionsAlertJPanel.this, ex.getMessage(), GUIBundle.getString("OptionsAlertJPanel_Alert"), JOptionPane.ERROR_MESSAGE); log.error(null, ex); } catch (ExecutionException ex) { Throwable throwable = ex.getCause(); if (throwable instanceof com.google.api.client.googleapis.json.GoogleJsonResponseException) { com.google.api.client.googleapis.json.GoogleJsonResponseException ge = (com.google.api.client.googleapis.json.GoogleJsonResponseException) throwable; for (GoogleJsonError.ErrorInfo errorInfo : ge.getDetails().getErrors()) { if ("insufficientPermissions".equals(errorInfo.getReason())) { org.yccheok.jstock.google.Utils.logoutGmail(); break; } } } JOptionPane.showMessageDialog(OptionsAlertJPanel.this, ex.getMessage(), GUIBundle.getString("OptionsAlertJPanel_Alert"), JOptionPane.ERROR_MESSAGE); log.error(null, ex); } if (pair != null) { credentialEx = pair.first; } else { jCheckBox2.setSelected(false); JStock.instance().getJStockOptions().setSendEmail(jCheckBox2.isSelected()); } updateGUIState(); } }; swingWorker.execute(); }
From source file:tauargus.model.batch.java
/** * Read the <SUPPRESS> command in a batch file with all its parameters * and calls the required suppression method * @throws ArgusException //from ww w . j av a 2 s .c o m */ static void suppressBatch() throws ArgusException { String SuppressType, token; int i; boolean linked; String[] tail = new String[1]; String hs; final TableSet tableset; SuppressType = tokenizer.nextField("(").toUpperCase(); tail[0] = tokenizer.getLine(); tokenizer.clearLine(); token = nextToken(tail); int n = Integer.parseInt(token); if (n < 0 || n > TableService.numberOfTables()) { throw new ArgusException("Wrong table number in Suppression"); } linked = (n == 0); if (linked) { if (!SuppressType.equals("GH") && !SuppressType.equals("MOD")) { throw new ArgusException("Linked tables is only possible for Modular or Hypercube"); } for (i = 0; i < TableService.numberOfTables(); i++) { TableService.undoSuppress(i); } tableset = tauargus.service.TableService.getTable(0); } else { tableset = tauargus.service.TableService.getTable(n - 1); TableService.undoSuppress(n - 1); } switch (SuppressType) { case "GH": {//TabNo, A priori Bounds Percentage, ModelSize, ApplySingleton) token = nextChar(tail); if (token.equals(",")) { token = nextToken(tail); tableset.ghMiterAprioryPercentage = Integer.parseInt(token); token = nextChar(tail); } if (token.equals(",")) { token = nextToken(tail); tableset.ghMiterSize = Integer.parseInt(token); token = nextChar(tail); } if (token.equals(",")) { token = nextToken(tail); tableset.ghMiterApplySingleton = token.equals("1"); token = nextChar(tail); } if (linked) { LinkedTables.buildCoverTable(); LinkedTables.runLinkedGHMiter(); hs = ""; TableSet ts; for (i = 0; i < TableService.numberOfTables(); i++) { ts = tauargus.service.TableService.getTable(i); hs = hs + ts.CountSecondaries() + " cells have been suppressed in table " + (i + 1) + "\n"; } hs = hs.substring(0, hs.length() - 1); } else { GHMiter.RunGHMiter(tableset); hs = tableset.CountSecondaries() + " cells have been suppressed"; } reportProgress("The hypercube procedure has been applied\n" + hs); break; } case "MOD": {//TabNo, MaxTimePerSubtable token = nextChar(tail); if (token.equals(",")) { token = nextToken(tail); tableset.maxHitasTime = Integer.parseInt(token); Application.generalMaxHitasTime = tableset.maxHitasTime; // The generalMAxHitasTime is used in the runModular procedure. token = nextChar(tail); } i = 0; while (token.equals(",") && (i < 3)) { i++; token = nextToken(tail); switch (i) { case 1: tableset.singletonSingletonCheck = token.equals("1"); break; case 2: tableset.singletonMultipleCheck = token.equals("1"); break; case 3: tableset.minFreqCheck = token.equals("1"); break; } token = nextChar(tail); } if (linked) { LinkedTables.buildCoverTable(); LinkedTables.runLinkedModular(null); } else { // single table if (token.equals(",")) { //MSC specified token = nextToken(tail); tableset.maxScaleCost = StrUtils.toDouble(token); if (tableset.maxScaleCost <= 0) { throw new ArgusException("Illegal Max Scaling Cost: " + token); } } try { // Make sure that PropertyChanges are not processed in batch-mode by overriding propertyChange to do nothing if (Application.batchType() == Application.BATCH_COMMANDLINE) { OptiSuppress.runModular(tableset, new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { } }); reportProgressInfo("The modular procedure has been applied\n" + tableset.CountSecondaries() + " cells have been suppressed"); } else { final SwingWorker<Integer, Void> worker = new ProgressSwingWorker<Integer, Void>( ProgressSwingWorker.DOUBLE, "Modular approach") { @Override protected Integer doInBackground() throws ArgusException, Exception { super.doInBackground(); OptiSuppress.runModular(tableset, getPropertyChangeListener()); reportProgressInfo("The modular procedure has been applied\n" + tableset.CountSecondaries() + " cells have been suppressed"); return null; } @Override protected void done() { super.done(); try { get(); tableset.undoAudit(); // Wat doet dit? Hoeft niet. Alleen voor GUI // ((AbstractTableModel)table.getModel()).fireTableDataChanged(); } catch (InterruptedException ex) { logger.log(Level.SEVERE, null, ex); } catch (ExecutionException ex) { JOptionPane.showMessageDialog(null, ex.getCause().getMessage()); } } }; worker.execute(); while (!worker.isDone()) { try { Thread.sleep(1000); } catch (InterruptedException ex) { } } } } catch (IOException ex) { throw new ArgusException("Modular failed\n" + ex.getMessage()); } } break; } case "OPT": {//TabNo, MaxComputingTime if (n == 0) { throw new ArgusException("Linked tables is not possible for Optimal"); } token = nextChar(tail); if (token.equals(",")) { token = nextToken(tail); tableset.maxHitasTime = Integer.parseInt(token); token = nextChar(tail); } if (Application.batchType() == Application.BATCH_COMMANDLINE) { try { OptiSuppress.runOptimal(tableset, new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { } }, false, false, 1); } catch (IOException ex) { } } else { // From menu with swingworker final SwingWorker<Integer, Void> worker = new ProgressSwingWorker<Integer, Void>( ProgressSwingWorker.DOUBLE, "Modular approach") { @Override protected Integer doInBackground() throws ArgusException, Exception { super.doInBackground(); try { OptiSuppress.runOptimal(tableset, new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { } }, false, false, 1); } catch (IOException ex) { } return null; } @Override protected void done() { super.done(); try { get(); } catch (InterruptedException ex) { logger.log(Level.SEVERE, null, ex); } catch (ExecutionException ex) { JOptionPane.showMessageDialog(null, ex.getCause().getMessage()); } } }; worker.execute(); while (!worker.isDone()) { try { Thread.sleep(1000); } catch (InterruptedException ex) { } } } //TODO reportProgressInfo("The optimal procedure has been applied\n" + tableset.CountSecondaries() + " cells have been suppressed"); break; } case "RND": {//TabNo, RoundingBase, Steps, Time, Partitions, StopRule // OK after Roundbase: Default Step = 0 (no step), time = 10, Nopartitions part = 0, stoprule = 2(optimal) if (n == 0) { throw new ArgusException("Linked tables is not possible for Rounding"); } if (Application.solverSelected == Application.SOLVER_CPLEX) //{throw new ArgusException("Controlled rounding cannot be used when Cplex is selected as solver");} { reportProgressInfo( "Whether controlled rounding can be used when Cplex is selected as solver, depends on your specific license.\n Incorrect license may cause errors."); } token = nextChar(tail); if (!token.equals(",")) { throw new ArgusException("a komma(,) expected"); } token = nextToken(tail); tableset.roundBase = Integer.parseInt(token); long mrb = TableSet.computeMinRoundBase(tableset); if (tableset.roundBase < mrb) { throw new ArgusException( "The rounding base is too small\n" + "A minimum of " + mrb + " is required"); } //set the defaults tableset.roundMaxStep = 0; tableset.roundMaxTime = 10; tableset.roundPartitions = 0; tableset.roundStoppingRule = 2; token = nextChar(tail); if (token.equals(",")) { //steps token = nextToken(tail); tableset.roundMaxStep = StrUtils.toInteger(token); token = nextChar(tail); } else { if (!token.equals(")")) throw new ArgusException("a komma(,) or \")\" expected"); } if (token.equals(",")) { //max time token = nextToken(tail); tableset.roundMaxTime = Integer.parseInt(token); if (tableset.roundMaxTime <= 0) { throw new ArgusException("Illegal value for max time: " + tableset.roundMaxTime); } token = nextChar(tail); } else { if (!token.equals(")")) throw new ArgusException("a komma(,) or \")\" expected"); } if (token.equals(",")) { //partitions token = nextToken(tail); tableset.roundPartitions = Integer.parseInt(token); if (tableset.roundPartitions < 0 || tableset.roundPartitions > 1) { throw new ArgusException("Illegal value for partitions: " + tableset.roundPartitions); } token = nextChar(tail); } else { if (!token.equals(")")) throw new ArgusException("a komma(,) or \")\" expected"); } if (token.equals(",")) { //Stop rule token = nextToken(tail); tableset.roundStoppingRule = Integer.parseInt(token); if (tableset.roundStoppingRule <= 0 || tableset.roundStoppingRule > 2) { throw new ArgusException("Illegal value for max time: " + tableset.roundStoppingRule); } token = nextChar(tail); } else { if (!token.equals(")")) throw new ArgusException("a komma(,) or \")\" expected"); } if (token.equals(",")) { //Unit cost function token = nextToken(tail); if (token.equals("1")) { tableset.roundUnitCost = true; } else if (token.equals("0")) { tableset.roundUnitCost = false; } else { throw new ArgusException("Illegal value UnitCost parameter: only 0 or 1 allowed"); } token = nextChar(tail); } else { if (!token.equals(")")) throw new ArgusException("a komma(,) or \")\" expected"); } // all parameters have been handeled. Run the rounder. if (Application.batchType() == Application.BATCH_COMMANDLINE) { try { OptiSuppress.runRounder(tableset, new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { } }); } catch (IOException ex) { throw new ArgusException(ex.getMessage()); } } else //batch run from menu { final SwingWorker<Integer, Void> worker = new ProgressSwingWorker<Integer, Void>( ProgressSwingWorker.ROUNDER, "Rounding") { @Override protected Integer doInBackground() throws ArgusException, Exception { super.doInBackground(); try { OptiSuppress.runRounder(tableset, new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { } }); } catch (IOException ex) { } return null; } @Override protected void done() { super.done(); try { get(); } catch (InterruptedException ex) { logger.log(Level.SEVERE, null, ex); } catch (ExecutionException ex) { JOptionPane.showMessageDialog(null, ex.getCause().getMessage()); } } }; worker.execute(); while (!worker.isDone()) { try { Thread.sleep(1000); } catch (InterruptedException ex) { } } } reportProgressInfo("The table has been rounded\n" + "Number of steps: " + tableset.roundMaxStep + "\n" + "Max step: " + StrUtils.formatDouble(tableset.roundMaxJump, tableset.respVar.nDecimals)); break; } case "CTA": { try { OptiSuppress.RunCTA(tableset, false); reportProgress("CTA run completed"); } catch (IOException ex) { throw new ArgusException(ex.getMessage()); } break; } case "NET": { OptiSuppress.TestNetwork(tableset); OptiSuppress.RunNetwork(tableset); break; } default: throw new ArgusException("Unknown suppression method (" + SuppressType + ") found"); } }
From source file:com.microsoft.azure.keyvault.cryptography.test.SymmetricKeyTest.java
@Test public void testSymmetricKeyAesKw192() { // Arrange/*from w ww.j av a2 s . com*/ byte[] KEK = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 }; byte[] CEK = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99, (byte) 0xAA, (byte) 0xBB, (byte) 0xCC, (byte) 0xDD, (byte) 0xEE, (byte) 0xFF }; byte[] EK = { (byte) 0x96, 0x77, (byte) 0x8B, 0x25, (byte) 0xAE, 0x6C, (byte) 0xA4, 0x35, (byte) 0xF9, 0x2B, 0x5B, (byte) 0x97, (byte) 0xC0, 0x50, (byte) 0xAE, (byte) 0xD2, 0x46, (byte) 0x8A, (byte) 0xB8, (byte) 0xA1, 0x7A, (byte) 0xD8, 0x4E, 0x5D }; boolean unlimited = hasUnlimitedCrypto(); SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); byte[] encrypted = null; try { encrypted = key.wrapKeyAsync(CEK, "A192KW").get().getLeft(); if (!unlimited) fail("Expected ExecutionException"); } catch (InterruptedException e) { fail("InterrupedException"); } catch (ExecutionException e) { // In the limited case, the failure should be InvalidKeyException // In the unlimited case, this should not fail if (!unlimited) { Throwable cause = e.getCause(); if (cause == null || !(cause instanceof InvalidKeyException)) fail("ExecutionException"); } else { fail("ExecutionException"); } } catch (NoSuchAlgorithmException e) { fail("NoSuchAlgorithmException"); } if (unlimited) { // Assert assertArrayEquals(EK, encrypted); byte[] decrypted = null; try { decrypted = key.unwrapKeyAsync(EK, "A192KW").get(); } catch (InterruptedException e) { fail("InterrupedException"); } catch (ExecutionException e) { fail("ExecutionException"); } catch (NoSuchAlgorithmException e) { fail("NoSuchAlgorithmException"); } // Assert assertArrayEquals(CEK, decrypted); } try { key.close(); } catch (IOException e) { fail("Key could not be closed"); } }
From source file:com.microsoft.azure.keyvault.cryptography.test.SymmetricKeyTest.java
@Test public void testSymmetricKeyAesKw192_ExcessKeyMaterial() { // Arrange/*from w w w . j a v a 2 s . co m*/ byte[] KEK = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; byte[] CEK = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99, (byte) 0xAA, (byte) 0xBB, (byte) 0xCC, (byte) 0xDD, (byte) 0xEE, (byte) 0xFF }; byte[] EK = { (byte) 0x96, 0x77, (byte) 0x8B, 0x25, (byte) 0xAE, 0x6C, (byte) 0xA4, 0x35, (byte) 0xF9, 0x2B, 0x5B, (byte) 0x97, (byte) 0xC0, 0x50, (byte) 0xAE, (byte) 0xD2, 0x46, (byte) 0x8A, (byte) 0xB8, (byte) 0xA1, 0x7A, (byte) 0xD8, 0x4E, 0x5D }; boolean unlimited = hasUnlimitedCrypto(); SymmetricKey key = new SymmetricKey("KEK", KEK, _provider); byte[] encrypted = null; try { encrypted = key.wrapKeyAsync(CEK, "A192KW").get().getLeft(); if (!unlimited) fail("Expected ExecutionException"); } catch (InterruptedException e) { fail("InterrupedException"); } catch (ExecutionException e) { // In the limited case, the failure should be InvalidKeyException // In the unlimited case, this should not fail if (!unlimited) { Throwable cause = e.getCause(); if (cause == null || !(cause instanceof InvalidKeyException)) fail("ExecutionException"); } else { fail("ExecutionException"); } } catch (NoSuchAlgorithmException e) { fail("NoSuchAlgorithmException"); } if (unlimited) { // Assert assertArrayEquals(EK, encrypted); byte[] decrypted = null; try { decrypted = key.unwrapKeyAsync(EK, "A192KW").get(); } catch (InterruptedException e) { fail("InterrupedException"); } catch (ExecutionException e) { fail("ExecutionException"); } catch (NoSuchAlgorithmException e) { fail("NoSuchAlgorithmException"); } // Assert assertArrayEquals(CEK, decrypted); } try { key.close(); } catch (IOException e) { fail("Key could not be closed"); } }