@Test public void testContinueOnSomeDbDirectoriesMissing() throws Exception { File targetDir1 = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); File targetDir2 = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); try { assertTrue(targetDir1.mkdirs()); assertTrue(targetDir2.mkdirs()); if (!targetDir1.setWritable(false, false)) { System.err.println( "Cannot execute 'testContinueOnSomeDbDirectoriesMissing' because cannot mark directory non-writable"); return; } RocksDBStateBackend rocksDbBackend = new RocksDBStateBackend(TEMP_URI); rocksDbBackend.setDbStoragePaths(targetDir1.getAbsolutePath(), targetDir2.getAbsolutePath()); try { rocksDbBackend.initializeForJob(getMockEnvironment(), "foobar", IntSerializer.INSTANCE); } catch (Exception e) { e.printStackTrace(); fail("Backend initialization failed even though some paths were available"); } } finally { //noinspection ResultOfMethodCallIgnored targetDir1.setWritable(true, false); FileUtils.deleteDirectory(targetDir1); FileUtils.deleteDirectory(targetDir2); } }
@Test(groups = "slow") public void testSetDefaultPaymentMethod() throws Exception { final PaymentPluginApi api = getTestApi(paymentPluginApiOSGIServiceRegistration, BUNDLE_TEST_RESOURCE_PREFIX); api.setDefaultPaymentMethod( UUID.randomUUID(), UUID.randomUUID(), ImmutableList.<PluginProperty>of(), callContext); }
@AfterReturning( pointcut = "execution(public String at.ac.tuwien.infosys.jcloudscale.server.JCloudScaleServer.createNewCloudObject(..))", returning = "ret") public void matchObjectCreated(JoinPoint jp, String ret) throws JCloudScaleException { try { ObjectCreatedEvent event = new ObjectCreatedEvent(); initializeBaseEventProperties(event); UUID objectId = UUID.fromString(ret); event.setObjectId(objectId); JCloudScaleServer server = (JCloudScaleServer) jp.getThis(); // XXX AbstractJCloudScaleServerRunner // UUID serverId = JCloudScaleServerRunner.getInstance().getId(); UUID serverId = AbstractJCloudScaleServerRunner.getInstance().getId(); event.setHostId(serverId); ClassLoader cl = server.getCloudObjectClassLoader(objectId); Class<?> theClazz = Class.forName((String) (jp.getArgs()[0]), true, cl); event.setObjectType(theClazz); getMqHelper().sendEvent(event); log.finer("Sent object created for object " + objectId.toString()); } catch (Exception e) { e.printStackTrace(); log.severe("Error while triggering ObjectCreatedEvent: " + e.getMessage()); } }
@Test public void shouldCountCarsWithFindCommand() throws Exception { String uniqueColorForTest = "color-shouldCountCarsWithFindCommand"; Car exampleCar = CarBuilder.aCar() .withManufacturer(UUID.randomUUID().toString()) .withColor(uniqueColorForTest) .build(); saveNewCopiesOfCarToRepository(exampleCar, 10); Car secondExampleCar = CarBuilder.aCar() .withManufacturer(UUID.randomUUID().toString()) .withColor(uniqueColorForTest) .build(); saveNewCopiesOfCarToRepository(secondExampleCar, 5); // Car searchByManufacturerExampleCar = new Car(null, 0, exampleCar.getManufacturer(), null); FindCommand<Car> findCommand = FindCommand.create(Car.class); findCommand.withSearchFilter("manufacturer", exampleCar.getManufacturer()); long foundCars = carRepository.findTotalItemCount(findCommand); assertThat(foundCars).isEqualTo(10); FindCommand<Car> findCommand2 = FindCommand.create(Car.class); findCommand2.withSearchFilter("color", uniqueColorForTest); long foundCarsByColor = carRepository.findTotalItemCount(findCommand2); assertThat(foundCarsByColor).isEqualTo(15); FindCommand<Car> findCommand3 = FindCommand.create(Car.class); findCommand3.withSearchFilter("manufacturer", exampleCar.getManufacturer()); findCommand3.withSearchFilter("color", uniqueColorForTest); long foundCarsByManufacturerAndColor = carRepository.findTotalItemCount(findCommand3); assertThat(foundCarsByManufacturerAndColor).isEqualTo(10); }
/** Make sure we can get a valid SAMLContextProvider. */ @Test public void canGetContextProvider() { final SAMLProperties properties = Mockito.mock(SAMLProperties.class); Mockito.when(properties.getLoadBalancer()).thenReturn(null); SAMLContextProvider provider = this.config.contextProvider(properties); Assert.assertNotNull(provider); Assert.assertFalse(provider instanceof SAMLContextProviderLB); final SAMLProperties.LoadBalancer loadBalancer = new SAMLProperties.LoadBalancer(); final String scheme = UUID.randomUUID().toString(); loadBalancer.setScheme(scheme); final String serverName = UUID.randomUUID().toString(); loadBalancer.setServerName(serverName); final int port = 443; loadBalancer.setServerPort(port); final String contextPath = UUID.randomUUID().toString(); loadBalancer.setContextPath(contextPath); Mockito.when(properties.getLoadBalancer()).thenReturn(loadBalancer); provider = this.config.contextProvider(properties); Assert.assertNotNull(provider); Assert.assertTrue(provider instanceof SAMLContextProviderLB); }
@Override protected void execute(CommandSender cs, String... args) { PlotBuild plotbuild = checkPlotBuild((Player) cs, 1, args); if (plotbuild == null) { return; } if (!hasPermissionsForPlotBuild((Player) cs, plotbuild)) { return; } OfflinePlayer removedStaff = BukkitUtil.matchPlayer(args[0]); if (removedStaff == null) { removedStaff = Bukkit.getOfflinePlayer(args[0]); } if (removedStaff.getLastPlayed() == 0) { sendPlayerNotFoundMessage(cs); return; } if (!plotbuild.isStaff(removedStaff)) { sendNotStaffMessage(cs, removedStaff, plotbuild.getName()); return; } plotbuild.removeStaff(removedStaff); sendRemoveStaffMessage(cs, removedStaff.getName(), plotbuild.getName()); if (removedStaff.getPlayer() != cs) { sendRemovedStaffPlayerMessage(cs, removedStaff, plotbuild.getName()); } for (UUID staff : plotbuild.getOfflineStaffList()) { if (!staff.equals(((Player) cs).getUniqueId()) && !staff.equals(removedStaff.getUniqueId())) { sendOtherStaffMessage( cs, Bukkit.getOfflinePlayer(staff), removedStaff, plotbuild.getName()); } } plotbuild.log(((Player) cs).getName() + " removed " + removedStaff.getName() + " from staff."); PluginData.saveData(); }
@Test public void shouldFindCarsByExample() throws Exception { String uniqueColor = "unique-color-" + UUID.randomUUID().toString(); Car exampleCar = CarBuilder.aCar() .withManufacturer(UUID.randomUUID().toString()) .withColor(uniqueColor) .build(); saveNewCopiesOfCarToRepository(exampleCar, 10); Car secondExampleCar = CarBuilder.aCar() .withManufacturer(UUID.randomUUID().toString()) .withColor(uniqueColor) .build(); saveNewCopiesOfCarToRepository(secondExampleCar, 5); Car searchByManufacturerExampleCar = new Car(null, 0, exampleCar.getManufacturer(), null); List<Car> foundCars = carRepository.findByExample(searchByManufacturerExampleCar); assertThat(foundCars).isNotNull().hasSize(10); Car searchByColorExampleCar = new Car(null, 0, null, uniqueColor); List<Car> foundCarsByColor = carRepository.findByExample(searchByColorExampleCar); assertThat(foundCarsByColor).isNotNull().hasSize(15); Car searchByManufacturerAndColorExampleCar = new Car(null, 0, exampleCar.getManufacturer(), uniqueColor); List<Car> foundCarsByManufacturerAndColor = carRepository.findByExample(searchByManufacturerAndColorExampleCar); assertThat(foundCarsByManufacturerAndColor).isNotNull().hasSize(10); }
@Test public void initiate() throws Exception { Person bob = new Person(UUID.randomUUID()); String sessionId = (new Date()).toString(); securityService.setCurrent(bob); UUID selfHelpGuideId = UUID.randomUUID(); SelfHelpGuide selfHelpGuide = new SelfHelpGuide(); SelfHelpGuideResponse selfHelpGuideResponse = new SelfHelpGuideResponse(); expect(selfHelpGuideService.get(selfHelpGuideId)).andReturn(selfHelpGuide); expect(service.initiateSelfHelpGuideResponse(selfHelpGuide, bob, sessionId)) .andReturn(selfHelpGuideResponse); replay(service); replay(selfHelpGuideService); String response = controller.initiate(selfHelpGuideId); verify(service); verify(selfHelpGuideService); assertEquals(selfHelpGuideResponse.toString(), response); }
@Test public void answer() throws ObjectNotFoundException { UUID selfHelpGuideResponseId = UUID.randomUUID(); UUID selfHelpGuideQuestionId = UUID.randomUUID(); Boolean answerResponse = true; SelfHelpGuideResponse selfHelpGuideResponse = new SelfHelpGuideResponse(); SelfHelpGuideQuestion selfHelpGuideQuestion = new SelfHelpGuideQuestion(); expect(service.get(selfHelpGuideResponseId)).andReturn(selfHelpGuideResponse); expect(selfHelpGuideQuestionService.get(selfHelpGuideQuestionId)) .andReturn(selfHelpGuideQuestion); expect( service.answerSelfHelpGuideQuestion( selfHelpGuideResponse, selfHelpGuideQuestion, answerResponse)) .andReturn(false); replay(service); replay(selfHelpGuideQuestionService); try { Boolean response = controller.answer(selfHelpGuideResponseId, selfHelpGuideQuestionId, answerResponse); verify(service); verify(selfHelpGuideQuestionService); assertFalse(response); } catch (Exception e) { fail("controller error"); } }
public static void addCryptoInputParcel( Context context, Intent data, CryptoInputParcel inputParcel) { UUID mTicket = addCryptoInputParcel(context, inputParcel); // And write out the UUID most and least significant bits. data.putExtra(OpenPgpApi.EXTRA_CALL_UUID1, mTicket.getMostSignificantBits()); data.putExtra(OpenPgpApi.EXTRA_CALL_UUID2, mTicket.getLeastSignificantBits()); }
@Test public void testCreateZoneWithNonUniqueSubdomain() { IdentityZone idZone1 = new IdentityZone(); String id1 = UUID.randomUUID().toString(); idZone1.setId(id1); idZone1.setSubdomain(id1 + "non-unique"); idZone1.setName("testCreateZone() " + id1); ResponseEntity<Void> response1 = client.exchange( serverRunning.getUrl("/identity-zones"), HttpMethod.POST, new HttpEntity<>(idZone1), new ParameterizedTypeReference<Void>() {}, id1); assertEquals(HttpStatus.CREATED, response1.getStatusCode()); IdentityZone idZone2 = new IdentityZone(); String id2 = UUID.randomUUID().toString(); idZone2.setId(id2); idZone2.setSubdomain(id1 + "non-unique"); idZone2.setName("testCreateZone() " + id2); ResponseEntity<Map<String, String>> response2 = client.exchange( serverRunning.getUrl("/identity-zones"), HttpMethod.POST, new HttpEntity<>(idZone2), new ParameterizedTypeReference<Map<String, String>>() {}, id2); assertEquals(HttpStatus.CONFLICT, response2.getStatusCode()); Assert.assertTrue( response2.getBody().get("error_description").toLowerCase().contains("subdomain")); }
@Test public void testUpdateState() throws Throwable { assertThat(vm.getState(), is(not(VmState.ERROR))); vmDcpBackend.updateState(vm, VmState.ERROR); assertThat(vm.getState(), is(VmState.ERROR)); vm = vmDcpBackend.findById(vmId); assertThat(vm.getState(), is(VmState.ERROR)); String agent = UUID.randomUUID().toString(); String agentIp = UUID.randomUUID().toString(); String datastoreId = UUID.randomUUID().toString(); String datastoreName = UUID.randomUUID().toString(); vmDcpBackend.updateState(vm, VmState.STARTED, agent, agentIp, datastoreId, datastoreName); assertThat(vm.getState(), is(VmState.STARTED)); assertThat(vm.getAgent(), is(agent)); assertThat(vm.getHost(), is(agentIp)); assertThat(vm.getDatastore(), is(datastoreId)); assertThat(vm.getDatastoreName(), is(datastoreName)); vm = vmDcpBackend.findById(vmId); assertThat(vm.getState(), is(VmState.STARTED)); assertThat(vm.getAgent(), is(agent)); assertThat(vm.getHost(), is(agentIp)); assertThat(vm.getDatastore(), is(datastoreId)); assertThat(vm.getDatastoreName(), is(datastoreName)); }
public void setUpMockitoRules() throws Exception { when(mockPluginDatabaseSystem.openDatabase(pluginId, pluginId.toString())) .thenReturn(mockDatabase); when(mockExtraUserActorDatabaseFactory.createDatabase(pluginId, pluginId.toString())) .thenReturn(mockDatabase); when(mockDatabase.getTable(ExtraUserActorDatabaseConstants.EXTRA_USER_TABLE_NAME)) .thenReturn(mockTable); when(mockTable.getRecords()).thenReturn(mockRecords); when(mockRecords.get(anyInt())).thenReturn(mockTableRecord); when(mockPluginFileSystem.getBinaryFile( any(UUID.class), anyString(), anyString(), any(FilePrivacy.class), any(FileLifeSpan.class))) .thenReturn(mockBinaryFile); when(mockPluginFileSystem.getTextFile( any(UUID.class), anyString(), anyString(), any(FilePrivacy.class), any(FileLifeSpan.class))) .thenReturn(mockFile); when(mockBinaryFile.getContent()).thenReturn(new byte[100]); }
@Test(groups = "slow") public void testGetPaymentInfo() throws Exception { final PaymentPluginApi api = getTestApi(paymentPluginApiOSGIServiceRegistration, BUNDLE_TEST_RESOURCE_PREFIX); final DateTime beforeCall = new DateTime().toDateTime(DateTimeZone.UTC).minusSeconds(1); final PaymentTransactionInfoPlugin res = api.getPaymentInfo( UUID.randomUUID(), UUID.randomUUID(), ImmutableList.<PluginProperty>of(), callContext) .get(0); final DateTime afterCall = new DateTime().toDateTime(DateTimeZone.UTC).plusSeconds(1); Assert.assertTrue(res.getAmount().compareTo(BigDecimal.ZERO) == 0); Assert.assertTrue(res.getCreatedDate().compareTo(beforeCall) >= 0); Assert.assertTrue(res.getCreatedDate().compareTo(afterCall) <= 0); Assert.assertTrue(res.getEffectiveDate().compareTo(beforeCall) >= 0); Assert.assertTrue(res.getEffectiveDate().compareTo(afterCall) <= 0); assertEquals(res.getGatewayError(), "gateway_error"); assertEquals(res.getGatewayErrorCode(), "gateway_error_code"); assertEquals(res.getStatus(), PaymentPluginStatus.PROCESSED); }
private Account createTestAccount(final int billCycleDay, final String phone) { final String thisKey = "test" + UUID.randomUUID().toString(); final String lastName = UUID.randomUUID().toString(); final String thisEmail = "*****@*****.**" + " " + UUID.randomUUID(); final String firstName = "Bob"; final String name = firstName + " " + lastName; final String locale = "EN-US"; final DateTimeZone timeZone = DateTimeZone.forID("America/Los_Angeles"); final int firstNameLength = firstName.length(); return new DefaultAccount( UUID.randomUUID(), thisKey, thisEmail, name, firstNameLength, Currency.USD, new DefaultBillCycleDay(billCycleDay, billCycleDay), UUID.randomUUID(), timeZone, locale, null, null, null, null, null, null, null, // add null address fields phone, false, false); }
/** * Serialize an object into a given byte buffer. * * @param o The object to serialize. * @param b The bytebuf to serialize it into. */ @Override public void serialize(Object o, ByteBuf b) { String className = o == null ? "null" : o.getClass().getName(); if (className.contains("$ByteBuddy$")) { String SMRClass = className.split("\\$")[0]; className = "CorfuObject"; byte[] classNameBytes = className.getBytes(); b.writeShort(classNameBytes.length); b.writeBytes(classNameBytes); byte[] SMRClassNameBytes = SMRClass.getBytes(); b.writeShort(SMRClassNameBytes.length); b.writeBytes(SMRClassNameBytes); UUID id = ((ICorfuObject) o).getStreamID(); log.trace("Serializing a CorfuObject of type {} as a stream pointer to {}", SMRClass, id); b.writeLong(id.getMostSignificantBits()); b.writeLong(id.getLeastSignificantBits()); } else { byte[] classNameBytes = className.getBytes(); b.writeShort(classNameBytes.length); b.writeBytes(classNameBytes); if (o == null) { return; } try (ByteBufOutputStream bbos = new ByteBufOutputStream(b)) { try (OutputStreamWriter osw = new OutputStreamWriter(bbos)) { gson.toJson(o, o.getClass(), osw); } } catch (IOException ie) { log.error("Exception during serialization!", ie); } } }
public static String generateUUIDs(int howMany) { StringBuilder builder = new StringBuilder(); // Append normal UUIDs: for (int count = 0; count < howMany; count++) { builder.append(UUID.randomUUID().toString()).append("\n"); } builder.append("\n"); // Append uppercase UUIDs: for (int count = 0; count < howMany; count++) { builder.append(UUID.randomUUID().toString().toUpperCase()).append("\n"); } builder.append("\n"); // Append uppercase w/ dashes removed: for (int count = 0; count < howMany; count++) { builder.append(UUID.randomUUID().toString().toUpperCase().replace("-", "")).append("\n"); } return builder.toString(); }
@Override public boolean onCommand(CommandSender sender, Command cmd, String tag, String[] args) { if (tag.equalsIgnoreCase("cancelauto")) { if (sender.hasPermission(Permission.AUTO_CANCEL)) { if (args.length == 0) { sender.sendMessage(ChatColor.YELLOW + "/cancelauto <player>"); return true; } else { if (auto.contains(args[0].trim())) { auto.remove(args[0].trim()); sender.sendMessage( ChatColor.YELLOW + "Autoban for " + args[0].trim() + " has been cancelled!"); for (Player online : Bukkit.getOnlinePlayers()) { if (online != sender) { if (online.hasPermission(Permission.AUTO)) { online.sendMessage( ChatColor.GOLD + sender.getName() + " removed " + args[0] + "'s autoban!"); } } } } else if (time.containsKey(UUID.fromString(args[0].trim()))) { time.put(UUID.fromString(args[0].trim()), 0); sender.sendMessage(ChatColor.YELLOW + "Autoban cancelled!"); } else { sender.sendMessage( ChatColor.YELLOW + "This player does not have an autoban scheduled!"); } } } else { sender.sendMessage(ChatColor.WHITE + "Unknown Command! Type \"/help\" for help."); return true; } } return true; }
@Override public OutputStream getOutputStream(Blob blob) throws BlobException { UUID uuid = UUID.randomUUID(); byte[] blobKey = Bytes.toBytes(uuid.getMostSignificantBits()); blobKey = Bytes.add(blobKey, Bytes.toBytes(uuid.getLeastSignificantBits())); return new HBaseBlobOutputStream(table, blobKey, blob); }
public DeviceUuidFactory(Context context) { if (uuid == null) { synchronized (DeviceUuidFactory.class) { if (uuid == null) { final SharedPreferences prefs = context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE); final String id = prefs.getString(PREFS_DEVICE_ID, null); if (id != null) { // Use the ids previously computed and stored in the // prefs file uuid = UUID.fromString(id); } else { UUID newId = UUID.randomUUID(); uuid = newId; // Write the value out to the prefs file prefs.edit().putString(PREFS_DEVICE_ID, newId.toString()).commit(); } } } } }
@Test public void shouldFindCarsWithFindCommandAndNamedQuery() throws Exception { // String uniqueColorForTest = "black-and-pink-with-ruby-named-query"; Car exampleCar = CarBuilder.aCar().withManufacturer(UUID.randomUUID().toString()).withYear(2000).build(); saveNewCopiesOfCarToRepository(exampleCar, 10); Car secondExampleCar = CarBuilder.aCar().withManufacturer(UUID.randomUUID().toString()).withYear(2005).build(); saveNewCopiesOfCarToRepository(secondExampleCar, 5); // Car searchByManufacturerExampleCar = new Car(null, 0, exampleCar.getManufacturer(), null); FindCommand<Car> findCommand = FindCommand.create(Car.class); findCommand.withSearchFilter("year", "2000").withNamedQuery("Car.findGreaterThanYear"); List<Car> foundCars = carRepository.findItemsWith(findCommand); assertThat(foundCars).isNotNull().hasSize(10); FindCommand<Car> findCommand2 = FindCommand.create(Car.class) .withSearchFilter("year", "2005") .withNamedQuery("Car.findGreaterThanYear"); List<Car> foundCarsByColor = carRepository.findItemsWith(findCommand2); assertThat(foundCarsByColor).isNotNull().hasSize(5); /*FindCommand<Car> findCommand3 = FindCommand.create(Car.class) .withNamedQuery("Car.findGreaterThanYear"); findCommand3.withSearchFilter("manufacturer", exampleCar.getManufacturer()); findCommand3.withSearchFilter("color", uniqueColorForTest); List<Car> foundCarsByManufacturerAndColor = carRepository.findItemsWith(findCommand3); assertThat(foundCarsByManufacturerAndColor).isNotNull().hasSize(10);*/ }
public String uuidToBase64(String str) { UUID uuid = UUID.fromString(str); ByteBuffer bb = ByteBuffer.wrap(new byte[16]); bb.putLong(uuid.getMostSignificantBits()); bb.putLong(uuid.getLeastSignificantBits()); return Base64.encodeBase64URLSafeString(bb.array()); }
/** This test tests that complete packet is build correctly */ public static void PacketBuilderTest() throws IOException, JdpException { /* Complete packet test */ { JdpJmxPacket p1 = new JdpJmxPacket(UUID.randomUUID(), "fake://unit-test"); p1.setMainClass("FakeUnitTest"); p1.setInstanceName("Fake"); byte[] b = p1.getPacketData(); JdpJmxPacket p2 = new JdpJmxPacket(b); JdpDoSomething.printJdpPacket(p1); JdpDoSomething.compaireJdpPacketEx(p1, p2); } /*Missed field packet test*/ { JdpJmxPacket p1 = new JdpJmxPacket(UUID.randomUUID(), "fake://unit-test"); p1.setMainClass("FakeUnitTest"); p1.setInstanceName(null); byte[] b = p1.getPacketData(); JdpJmxPacket p2 = new JdpJmxPacket(b); JdpDoSomething.printJdpPacket(p1); JdpDoSomething.compaireJdpPacketEx(p1, p2); } System.out.println("OK: Test passed"); }
/** Get a list of all the people that ignorer is ignoring */ public static ArrayDeque<UUIDName> get_ignoring(UUID ignorer) { ArrayDeque<UUIDName> ret = null; try { String query = "SELECT * FROM ignores WHERE " + "ignorer = ?;"; PreparedStatement st = conn.prepareStatement(query); st.setString(1, ignorer.toString()); ResultSet rs = st.executeQuery(); ret = new ArrayDeque<UUIDName>(); while (rs.next()) { UUID uuid = UUID.fromString(rs.getString("ignored")); String name = rs.getString("ignoredname"); UUIDName tmp = new UUIDName(uuid, name); ret.add(tmp); } rs.close(); st.close(); } catch (Exception e) { Ignore.instance.getLogger().warning(e.getMessage()); } return ret; }
private SAMLProperties setupForKeyManager() { final ResourceLoader resourceLoader = Mockito.mock(ResourceLoader.class); this.config.setResourceLoader(resourceLoader); final Resource storeFile = Mockito.mock(Resource.class); final SAMLProperties properties = Mockito.mock(SAMLProperties.class); this.config.setSamlProperties(properties); final String keyStorePassword = UUID.randomUUID().toString(); final String keyStoreName = UUID.randomUUID().toString() + ".jks"; final String defaultKeyName = UUID.randomUUID().toString(); final String defaultKeyPassword = UUID.randomUUID().toString(); final SAMLProperties.Keystore keyStore = Mockito.mock(SAMLProperties.Keystore.class); final SAMLProperties.Keystore.DefaultKey defaultKey = Mockito.mock(SAMLProperties.Keystore.DefaultKey.class); Mockito.when(properties.getKeystore()).thenReturn(keyStore); Mockito.when(keyStore.getName()).thenReturn(keyStoreName); Mockito.when(keyStore.getPassword()).thenReturn(keyStorePassword); Mockito.when(keyStore.getDefaultKey()).thenReturn(defaultKey); Mockito.when(defaultKey.getName()).thenReturn(defaultKeyName); Mockito.when(defaultKey.getPassword()).thenReturn(defaultKeyPassword); Mockito.when(resourceLoader.getResource(Mockito.eq("classpath:" + keyStoreName))) .thenReturn(storeFile); return properties; }
@Test(groups = "slow") public void testShouldBeAbleToHandleOtherBCDClass() throws Exception { final Account account = createTestAccount(); accountDao.create(account, internalCallContext); final MutableAccountData otherAccount = account.toMutableAccountData(); otherAccount.setAddress1(UUID.randomUUID().toString()); otherAccount.setEmail(UUID.randomUUID().toString()); // Same BCD, but not .equals method otherAccount.setBillCycleDay( new BillCycleDay() { @Override public int getDayOfMonthUTC() { return account.getBillCycleDay().getDayOfMonthUTC(); } @Override public int getDayOfMonthLocal() { return account.getBillCycleDay().getDayOfMonthLocal(); } }); final DefaultAccount newAccount = new DefaultAccount(account.getId(), otherAccount); accountDao.update(newAccount, internalCallContext); final Account newFetchedAccount = accountDao.getById(account.getId(), internalCallContext); Assert.assertEquals(newFetchedAccount.getAddress1(), newAccount.getAddress1()); Assert.assertEquals(newFetchedAccount.getEmail(), newAccount.getEmail()); // Same BCD Assert.assertEquals(newFetchedAccount.getBillCycleDay(), account.getBillCycleDay()); }
@Override public void read(DataInput in) throws IOException { try { long msb = in.readLong(); long lsb = in.readLong(); this.token = new UUID(msb, lsb); } catch (Exception e) { throw new UnknownStoreVersionException(e); } if (!token.equals(JobSchedulerStoreImpl.SCHEDULER_STORE_TOKEN)) { throw new UnknownStoreVersionException(token.toString()); } this.version = in.readInt(); if (in.readBoolean()) { setLastUpdateLocation(LocationMarshaller.INSTANCE.readPayload(in)); } else { setLastUpdateLocation(null); } this.storedSchedulers = new BTreeIndex<String, JobSchedulerImpl>(store.getPageFile(), in.readLong()); this.storedSchedulers.setKeyMarshaller(StringMarshaller.INSTANCE); this.storedSchedulers.setValueMarshaller(new JobSchedulerMarshaller(this.store)); this.journalRC = new BTreeIndex<Integer, Integer>(store.getPageFile(), in.readLong()); this.journalRC.setKeyMarshaller(IntegerMarshaller.INSTANCE); this.journalRC.setValueMarshaller(IntegerMarshaller.INSTANCE); this.removeLocationTracker = new BTreeIndex<Integer, List<Integer>>(store.getPageFile(), in.readLong()); this.removeLocationTracker.setKeyMarshaller(IntegerMarshaller.INSTANCE); this.removeLocationTracker.setValueMarshaller(new IntegerListMarshaller()); LOG.info("Scheduler Store version {} loaded", this.version); }
private void verifyAccountEmailAuditAndHistoryCount( final UUID accountId, final int expectedCount) { final Handle handle = dbi.open(); // verify audit StringBuilder sb = new StringBuilder(); sb.append("select * from audit_log a "); sb.append("inner join account_email_history aeh on a.record_id = aeh.history_record_id "); sb.append("where a.table_name = 'account_email_history' "); sb.append(String.format("and aeh.account_id='%s'", accountId.toString())); List<Map<String, Object>> result = handle.select(sb.toString()); assertEquals(result.size(), expectedCount); // ***** NOT IDEAL // ... but this works after the email record has been deleted; will likely fail when multiple // emails exist for the same account // verify history table sb = new StringBuilder(); sb.append("select * from account_email_history aeh "); sb.append(String.format("where aeh.account_id='%s'", accountId.toString())); result = handle.select(sb.toString()); assertEquals(result.size(), expectedCount); handle.close(); }
@Test public void testCreateRefFromUri() throws BadRequestException { final ParentListRef comptes_expected = ParentListRefImpl.create( // Mediatheque.ref(UUID.fromString("448028fd-fce5-45a5-8ef4-2b591800a7e2")) // , Compte.mCompte // , "comptes") // ; final ParentListRef<Mediatheque.Ref, Compte> comptes_result = Mediatheque.mMediatheque.comptes.parse( "mediatheque/448028fd-fce5-45a5-8ef4-2b591800a7e2/comptes"); assertEquals(comptes_expected, comptes_result); // ListRef result1 = Mediatheque.mMediatheque.comptes_ref(); final UUID idMediatheque = UUID.randomUUID(); final Mediatheque.Ref mediatheque_expected = Mediatheque.ref(idMediatheque); final Mediatheque.Ref mediatheque_result = Mediatheque.mMediatheque.createRefFromUri("mediatheque/" + idMediatheque); assertEquals(mediatheque_expected, mediatheque_result); final UUID idIndividu = UUID.randomUUID(); final Individu.Ref individu_expected = Individu.ref(idIndividu); final Individu.Ref individu_result = Individu.mIndividu.createRefFromUri("individu/" + idIndividu); assertEquals(individu_expected, individu_result); final Compte.Ref compte_expected = Compte.ref(mediatheque_expected, individu_expected); final Compte.Ref compte_result = Compte.mCompte.createRefFromUri( "mediatheque/" + idMediatheque + "/comptes/individu/" + idIndividu); assertEquals(compte_expected, compte_result); }
/** * Tests that a job is properly canceled in the event of a leader change. However, this time only * the TMs are notified about the changing leader. This should be enough to cancel the currently * running job, though. */ @Test public void testStateCleanupAfterListenerNotification() throws Exception { UUID leaderSessionID = UUID.randomUUID(); UUID newLeaderSessionID = UUID.randomUUID(); cluster.grantLeadership(0, leaderSessionID); cluster.notifyRetrievalListeners(0, leaderSessionID); cluster.waitForTaskManagersToBeRegistered(); // submit blocking job cluster.submitJobDetached(job); ActorGateway jm = cluster.getLeaderGateway(timeout); Future<Object> wait = jm.ask(new WaitForAllVerticesToBeRunningOrFinished(job.getJobID()), timeout); Await.ready(wait, timeout); Future<Object> jobRemoval = jm.ask(new NotifyWhenJobRemoved(job.getJobID()), timeout); // notify listeners (TMs) about the leader change cluster.notifyRetrievalListeners(1, newLeaderSessionID); Await.ready(jobRemoval, timeout); }