List of usage examples for java.util Base64 getDecoder
public static Decoder getDecoder()
From source file:com.traffitruck.web.HtmlController.java
@RequestMapping(value = "/load/image/{loadId}", method = RequestMethod.GET, produces = MediaType.IMAGE_PNG_VALUE) public byte[] getLoadImage(@PathVariable String loadId) { String b64dataUrl = new String(dao.getLoadPhoto(loadId)); byte[] bytes = b64dataUrl.substring(b64dataUrl.indexOf(',') + 1).getBytes(); return Base64.getDecoder().decode(bytes); }
From source file:org.elasticsearch.upgrades.FullClusterRestartIT.java
void assertStoredBinaryFields(int count) throws Exception { String requestBody = "{ \"query\": { \"match_all\" : {} }, \"size\": 100, \"stored_fields\": \"binary\"}"; Map<String, Object> rsp = toMap(client().performRequest("GET", "/" + index + "/_search", Collections.emptyMap(), new StringEntity(requestBody, ContentType.APPLICATION_JSON))); int totalCount = (Integer) XContentMapValues.extractValue("hits.total", rsp); assertEquals(count, totalCount);/*from w ww . j ava 2 s . co m*/ List<?> hits = (List<?>) XContentMapValues.extractValue("hits.hits", rsp); assertEquals(100, hits.size()); for (Object hit : hits) { Map<?, ?> hitRsp = (Map<?, ?>) hit; List<?> values = (List<?>) XContentMapValues.extractValue("fields.binary", hitRsp); assertEquals(1, values.size()); String value = (String) values.get(0); byte[] binaryValue = Base64.getDecoder().decode(value); assertEquals("Unexpected string length [" + value + "]", 16, binaryValue.length); } }
From source file:org.codice.ddf.security.idp.server.IdpEndpointTest.java
@Test public void testPassiveLoginPkiUnsupportedPost() throws SecurityServiceException, WSSecurityException, CertificateEncodingException, IOException { String samlRequest = authNRequestPassivePkiPost; HttpServletRequest request = mock(HttpServletRequest.class); X509Certificate x509Certificate = mock(X509Certificate.class); Subject subject = mock(Subject.class); PrincipalCollection principalCollection = mock(PrincipalCollection.class); SecurityAssertion securityAssertion = mock(SecurityAssertion.class); SecurityToken securityToken = mock(SecurityToken.class); SecurityManager securityManager = mock(SecurityManager.class); when(subject.getPrincipals()).thenReturn(principalCollection); when(principalCollection.asList()).thenReturn(Collections.singletonList(securityAssertion)); when(securityAssertion.getSecurityToken()).thenReturn(securityToken); //this mock element is what will cause the signature error when(securityToken.getToken()).thenReturn(mock(Element.class)); when(securityManager.getSubject(anyObject())).thenReturn(subject); idpEndpoint.setSecurityManager(securityManager); idpEndpoint.setStrictSignature(false); when(request.isSecure()).thenReturn(true); when(request.getRequestURL()).thenReturn(requestURL); when(request.getAttribute(ContextPolicy.ACTIVE_REALM)).thenReturn("*"); //dummy cert//from www . jav a 2s. c o m when((X509Certificate[]) request.getAttribute(requestCertificateAttributeName)) .thenReturn(new X509Certificate[] { x509Certificate }); when(x509Certificate.getEncoded()).thenReturn(new byte[48]); Response response = idpEndpoint.showPostLogin(samlRequest, relayState, request); String responseStr = StringUtils.substringBetween(response.getEntity().toString(), "SAMLResponse\" value=\"", "\" />"); responseStr = new String(Base64.getDecoder().decode(responseStr)); //the only cookie that should exist is the "1" cookie so "2" should send us to the login webapp assertThat(responseStr, containsString("status:RequestUnsupported")); }
From source file:com.jivesoftware.os.upena.deployable.UpenaMain.java
public void run(String[] args) throws Exception { HealthFactory.initialize(BindInterfaceToConfiguration::bindDefault, new HealthCheckRegistry() { @Override/*w ww . j a v a 2 s . c om*/ public void register(HealthChecker<?> healthChecker) { } @Override public void unregister(HealthChecker<?> healthChecker) { } }); Properties buildProperties = new Properties(); String upenaVersion = ""; try { buildProperties.load(UpenaMain.class.getClassLoader().getResourceAsStream("build.properties")); upenaVersion = buildProperties.getProperty("my.version", "") + " " + buildProperties.getProperty("my.timestamp", "") + " sha:" + buildProperties.getProperty("git.commit.id", ""); } catch (Exception x) { LOG.warn("Failed to locate build.properties"); } String workingDir = System.getProperty("user.dir"); long start = System.currentTimeMillis(); Exception failed = null; while (start + TimeUnit.SECONDS.toMillis(10) > System.currentTimeMillis()) { try { File lockFile = new File(workingDir, "onlyLetOneRunningAtATime"); lockFile.createNewFile(); FileChannel.open(lockFile.toPath(), StandardOpenOption.WRITE).lock(); failed = null; break; } catch (Exception x) { failed = x; LOG.warn("Failed to acquire lock on onlyLetOneRunningAtATime", x); Thread.sleep(1000); } } if (failed != null) { throw failed; } JDIAPI jvmapi = null; try { jvmapi = new JDIAPI(); } catch (NoClassDefFoundError x) { LOG.warn( "Failed to local tools.jar. Please manually add to classpath. Breakpoint debugger will be disabled."); } String hostname = args[0]; int loopbackPort = Integer.parseInt(System.getProperty("amza.loopback.port", "1174")); int port = Integer.parseInt(System.getProperty("amza.port", "1175")); String multicastGroup = System.getProperty("amza.discovery.group", "225.4.5.6"); int multicastPort = Integer.parseInt(System.getProperty("amza.discovery.port", "1123")); String clusterDiscoveryName = (args.length > 1 ? args[1] : null); String datacenter = System.getProperty("host.datacenter", "unknownDatacenter"); String rack = System.getProperty("host.rack", "unknownRack"); String publicHost = System.getProperty("public.host.name", hostname); UpenaRingHost ringHost = new UpenaRingHost(hostname, port); // TODO include rackId // todo need a better way to create writer id. int writerId = new Random().nextInt(512); TimestampedOrderIdProvider orderIdProvider = new OrderIdProviderImpl( new ConstantWriterIdProvider(writerId)); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); RowsStorageProvider rowsStorageProvider = rowsStorageProvider(orderIdProvider); boolean sslEnable = Boolean.parseBoolean(System.getProperty("ssl.enabled", "true")); String sslKeystorePassword = System.getProperty("ssl.keystore.password", "password"); String sslKeystorePath = System.getProperty("ssl.keystore.path", "./certs/sslKeystore"); String sslKeyStoreAlias = System.getProperty("ssl.keystore.alias", "upenanode").toLowerCase(); boolean sslAutoGenerateSelfSignedCert = Boolean .parseBoolean(System.getProperty("ssl.keystore.autoGenerate", "true")); File sslKeystore = new File(sslKeystorePath); if (sslEnable) { SelfSigningCertGenerator selfSigningCertGenerator = new SelfSigningCertGenerator(); if (sslKeystore.exists()) { if (!selfSigningCertGenerator.validate(sslKeyStoreAlias, sslKeystorePassword, sslKeystore)) { LOG.error("SSL keystore validation failed. keyStoreAlias:{} sslKeystore:{}", sslKeyStoreAlias, sslKeystore); System.exit(1); } } else { sslKeystore.getParentFile().mkdirs(); if (sslAutoGenerateSelfSignedCert) { selfSigningCertGenerator.create(sslKeyStoreAlias, sslKeystorePassword, sslKeystore); } else { LOG.error("Failed to locate mandatory sslKeystore:{}", sslKeystore); System.exit(1); } } } String consumerKey = System.getProperty("upena.consumerKey", clusterDiscoveryName); if (consumerKey == null) { consumerKey = "upena"; LOG.warn("Please provide a stronger consumerKey via -Dupena.consumerKey"); } String finalConsumerKey = consumerKey; String secret = System.getProperty("upena.secret"); if (secret == null) { secret = "secret"; LOG.warn("Please provide a stronger secret via -Dupena.secret"); } String finalSecret = secret; OAuthSigner authSigner = (request) -> { CommonsHttpOAuthConsumer oAuthConsumer = new CommonsHttpOAuthConsumer(finalConsumerKey, finalSecret); oAuthConsumer.setMessageSigner(new HmacSha1MessageSigner()); oAuthConsumer.setTokenWithSecret(finalConsumerKey, finalSecret); return oAuthConsumer.sign(request); }; UpenaSSLConfig upenaSSLConfig = new UpenaSSLConfig(sslEnable, sslAutoGenerateSelfSignedCert, authSigner); UpenaAmzaService upenaAmzaService = null; if (!new File("./state").exists()) { UpdatesSender changeSetSender = new HttpUpdatesSender(sslEnable, sslAutoGenerateSelfSignedCert, authSigner); UpdatesTaker tableTaker = new HttpUpdatesTaker(sslEnable, sslAutoGenerateSelfSignedCert, authSigner); UpenaAmzaServiceConfig upenaAmzaServiceConfig = new UpenaAmzaServiceConfig(); upenaAmzaService = new UpenaAmzaServiceInitializer().initialize(upenaAmzaServiceConfig, orderIdProvider, new com.jivesoftware.os.upena.amza.storage.FstMarshaller( FSTConfiguration.getDefaultConfiguration()), rowsStorageProvider, rowsStorageProvider, rowsStorageProvider, changeSetSender, tableTaker, Optional.<SendFailureListener>absent(), Optional.<UpenaTakeFailureListener>absent(), (changes) -> { }); /*upenaAmzaService.start(ringHost, upenaAmzaServiceConfig.resendReplicasIntervalInMillis, upenaAmzaServiceConfig.applyReplicasIntervalInMillis, upenaAmzaServiceConfig.takeFromNeighborsIntervalInMillis, upenaAmzaServiceConfig.checkIfCompactionIsNeededIntervalInMillis, upenaAmzaServiceConfig.compactTombstoneIfOlderThanNMillis);*/ LOG.info("-----------------------------------------------------------------------"); LOG.info("| OLD Amza Service Online"); LOG.info("-----------------------------------------------------------------------"); } else { LOG.info("-----------------------------------------------------------------------"); LOG.info("| OLD Amza Data is decomissionable"); LOG.info("-----------------------------------------------------------------------"); } BAInterner baInterner = new BAInterner(); AtomicReference<Callable<RingTopology>> topologyProvider = new AtomicReference<>(); // bit of a hack InstanceDescriptor instanceDescriptor = new InstanceDescriptor(datacenter, rack, "", "", "", "", "", "", "", "", 0, "", "", "", 0L, true); ConnectionDescriptorsProvider noAuthConnectionsProvider = (connectionDescriptorsRequest, expectedReleaseGroup) -> { try { RingTopology systemRing = topologyProvider.get().call(); List<ConnectionDescriptor> descriptors = Lists.newArrayList(Iterables.transform(systemRing.entries, input -> new ConnectionDescriptor(instanceDescriptor, sslEnable, false, new HostPort(input.ringHost.getHost(), input.ringHost.getPort()), Collections.emptyMap(), Collections.emptyMap()))); return new ConnectionDescriptorsResponse(200, Collections.emptyList(), "", descriptors, connectionDescriptorsRequest.getRequestUuid()); } catch (Exception e) { throw new RuntimeException(e); } }; TenantsServiceConnectionDescriptorProvider<String> noAuthConnectionPoolProvider = new TenantsServiceConnectionDescriptorProvider<>( Executors.newScheduledThreadPool(1), "", noAuthConnectionsProvider, "", "", 10_000); // TODO config noAuthConnectionPoolProvider.start(); ConnectionDescriptorsProvider connectionsProvider = (connectionDescriptorsRequest, expectedReleaseGroup) -> { try { RingTopology systemRing = topologyProvider.get().call(); List<ConnectionDescriptor> descriptors = Lists.newArrayList(Iterables.transform(systemRing.entries, input -> new ConnectionDescriptor(instanceDescriptor, sslEnable, true, new HostPort(input.ringHost.getHost(), input.ringHost.getPort()), Collections.emptyMap(), Collections.emptyMap()))); return new ConnectionDescriptorsResponse(200, Collections.emptyList(), "", descriptors, connectionDescriptorsRequest.getRequestUuid()); } catch (Exception e) { throw new RuntimeException(e); } }; TenantsServiceConnectionDescriptorProvider<String> connectionPoolProvider = new TenantsServiceConnectionDescriptorProvider<>( Executors.newScheduledThreadPool(1), "", connectionsProvider, "", "", 10_000); // TODO config connectionPoolProvider.start(); HttpDeliveryClientHealthProvider clientHealthProvider = new HttpDeliveryClientHealthProvider("", null, "", 5000, 100); TenantRoutingHttpClientInitializer<String> nonSigningClientInitializer = new TenantRoutingHttpClientInitializer<>( null); TenantAwareHttpClient<String> systemTakeClient = nonSigningClientInitializer .builder(noAuthConnectionPoolProvider, // TODO config clientHealthProvider) .deadAfterNErrors(10).checkDeadEveryNMillis(10_000).maxConnections(1_000) .socketTimeoutInMillis(60_000).build(); // TODO expose to conf TenantAwareHttpClient<String> stripedTakeClient = nonSigningClientInitializer .builder(noAuthConnectionPoolProvider, // TODO config clientHealthProvider) .deadAfterNErrors(10).checkDeadEveryNMillis(10_000).maxConnections(1_000) .socketTimeoutInMillis(60_000).build(); // TODO expose to conf TenantRoutingHttpClientInitializer<String> tenantRoutingHttpClientInitializer = new TenantRoutingHttpClientInitializer<>( new OAuthSignerProvider(() -> authSigner)); TenantAwareHttpClient<String> ringClient = tenantRoutingHttpClientInitializer .builder(connectionPoolProvider, // TODO config clientHealthProvider) .deadAfterNErrors(10).checkDeadEveryNMillis(10_000).maxConnections(1_000) .socketTimeoutInMillis(60_000).build(); // TODO expose to conf AmzaStats amzaStats = new AmzaStats(); AmzaService amzaService = startAmza(workingDir, amzaStats, baInterner, writerId, new RingHost(datacenter, rack, ringHost.getHost(), ringHost.getPort()), new RingMember(ringHost.getHost() + ":" + ringHost.getPort()), authSigner, systemTakeClient, stripedTakeClient, ringClient, topologyProvider, clusterDiscoveryName, multicastGroup, multicastPort); EmbeddedClientProvider embeddedClientProvider = new EmbeddedClientProvider(amzaService); LOG.info("-----------------------------------------------------------------------"); LOG.info("| Amza Service Online"); LOG.info("-----------------------------------------------------------------------"); ObjectMapper storeMapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); UpenaConfigStore upenaConfigStore = new UpenaConfigStore(orderIdProvider, storeMapper, upenaAmzaService, amzaService, embeddedClientProvider); LOG.info("-----------------------------------------------------------------------"); LOG.info("| Upena Config Store Online"); LOG.info("-----------------------------------------------------------------------"); ExecutorService instanceChangedThreads = Executors.newFixedThreadPool(32); AtomicReference<UbaService> ubaServiceReference = new AtomicReference<>(); UpenaStore upenaStore = new UpenaStore(storeMapper, upenaAmzaService, (instanceChanges) -> { instanceChangedThreads.submit(() -> { UbaService got = ubaServiceReference.get(); if (got != null) { try { got.instanceChanged(instanceChanges); } catch (Exception ex) { ex.printStackTrace(); } } }); }, (changes) -> { }, (change) -> { LOG.info("TODO: tie into conductor. " + change); }, amzaService, embeddedClientProvider); //upenaStore.attachWatchers(); ChaosService chaosService = new ChaosService(upenaStore); SecureRandom random = new SecureRandom(); PasswordStore passwordStore = (key) -> { String password = System.getProperty("sauth.keystore.password"); if (password == null) { File passwordFile = new File(workingDir, "keystore/" + key + ".key"); if (passwordFile.exists()) { password = Files.toString(passwordFile, StandardCharsets.UTF_8); } else { passwordFile.getParentFile().mkdirs(); password = new BigInteger(130, random).toString(32); Files.write(password, passwordFile, StandardCharsets.UTF_8); } } return password; }; SessionStore sessionStore = new SessionStore(TimeUnit.MINUTES.toMillis(60), TimeUnit.MINUTES.toMillis(30)); AtomicReference<UpenaHealth> upenaHealthProvider = new AtomicReference<>(); InstanceHealthly instanceHealthly = (key, version) -> { UpenaHealth upenaHealth = upenaHealthProvider.get(); if (upenaHealth == null) { return false; } ConcurrentMap<RingHost, NodeHealth> ringHostNodeHealth = upenaHealth.buildClusterHealth(); for (NodeHealth nodeHealth : ringHostNodeHealth.values()) { for (NannyHealth nannyHealth : nodeHealth.nannyHealths) { if (nannyHealth.instanceDescriptor.instanceKey.equals(key.getKey())) { return nannyHealth.serviceHealth.fullyOnline ? nannyHealth.serviceHealth.version.equals(version) : false; } } } return false; }; UpenaService upenaService = new UpenaService(passwordStore, sessionStore, upenaStore, chaosService, instanceHealthly); LOG.info("-----------------------------------------------------------------------"); LOG.info("| Upena Service Online"); LOG.info("-----------------------------------------------------------------------"); File defaultPathToRepo = new File(new File(System.getProperty("user.dir"), ".m2"), "repository"); PathToRepo localPathToRepo = new PathToRepo( new File(System.getProperty("pathToRepo", defaultPathToRepo.getAbsolutePath()))); RepositoryProvider repositoryProvider = new RepositoryProvider(localPathToRepo); Host host = new Host(publicHost, datacenter, rack, ringHost.getHost(), ringHost.getPort(), workingDir, null, null); HostKey hostKey = new HostKeyProvider().getNodeKey(upenaStore.hosts, host); String hostInstanceId = System.getProperty("host.instance.id", hostKey.getKey()); host = new Host(publicHost, datacenter, rack, ringHost.getHost(), ringHost.getPort(), workingDir, hostInstanceId, null); UbaLog ubaLog = (what, why, how) -> { try { upenaStore.record("Uba", what, System.currentTimeMillis(), why, ringHost.getHost() + ":" + ringHost.getPort(), how); } catch (Exception x) { x.printStackTrace(); // Hmm lame } }; OktaLog oktaLog = (who, what, why, how) -> { try { upenaStore.record("okta:" + who, what, System.currentTimeMillis(), why, ringHost.getHost() + ":" + ringHost.getPort(), how); } catch (Exception x) { x.printStackTrace(); // Hmm lame } }; OktaCredentialsMatcher.oktaLog = oktaLog; OktaRealm.oktaLog = oktaLog; UpenaClient upenaClient = new UpenaClient() { @Override public InstanceDescriptorsResponse instanceDescriptor( InstanceDescriptorsRequest instanceDescriptorsRequest) throws Exception { return upenaService.instanceDescriptors(instanceDescriptorsRequest); } @Override public void updateKeyPair(String instanceKey, String publicKey) throws Exception { Instance i = upenaStore.instances.get(new InstanceKey(instanceKey)); if (i != null) { LOG.info("Updating publicKey for {}", instanceKey); upenaStore.instances.update(new InstanceKey(instanceKey), new Instance(i.clusterKey, i.hostKey, i.serviceKey, i.releaseGroupKey, i.instanceId, i.enabled, i.locked, publicKey, i.restartTimestampGMTMillis, i.ports)); } } }; final UbaService ubaService = new UbaServiceInitializer().initialize(passwordStore, upenaClient, repositoryProvider, hostKey.getKey(), workingDir, new UbaCoordinate(datacenter, rack, publicHost, host.hostName, "localhost", loopbackPort), null, ubaLog); UpenaHealth upenaHealth = new UpenaHealth(amzaService, upenaSSLConfig, upenaConfigStore, ubaService, new RingHost(datacenter, rack, ringHost.getHost(), ringHost.getPort()), hostKey); upenaHealthProvider.set(upenaHealth); DiscoveredRoutes discoveredRoutes = new DiscoveredRoutes(); ShiroRequestHelper shiroRequestHelper = new ShiroRequestHelper(TimeUnit.DAYS.toMillis(1)); // TODO expose Sys prop? String shiroConfigLocation = System.getProperty("shiro.ini.location", "classpath:shiro.ini"); // classpath:oktashiro.ini UpenaJerseyEndpoints jerseyEndpoints = new UpenaJerseyEndpoints(shiroConfigLocation) .addInjectable(ShiroRequestHelper.class, shiroRequestHelper) .addEndpoint(UpenaClusterRestEndpoints.class).addEndpoint(UpenaHostRestEndpoints.class) .addEndpoint(UpenaServiceRestEndpoints.class).addEndpoint(UpenaReleaseRestEndpoints.class) .addEndpoint(UpenaInstanceRestEndpoints.class).addEndpoint(UpenaTenantRestEndpoints.class) .addInjectable(upenaHealth).addInjectable(upenaService).addInjectable(upenaStore) .addInjectable(upenaConfigStore).addInjectable(ubaService) //.addEndpoint(AmzaReplicationRestEndpoints.class) //.addInjectable(UpenaAmzaInstance.class, upenaAmzaService) .addEndpoint(UpenaEndpoints.class).addEndpoint(UpenaConnectivityEndpoints.class) .addEndpoint(UpenaManagedDeployableEndpoints.class).addEndpoint(UpenaHealthEndpoints.class) .addEndpoint(UpenaRepoEndpoints.class).addInjectable(DiscoveredRoutes.class, discoveredRoutes) .addInjectable(UpenaRingHost.class, ringHost).addInjectable(HostKey.class, hostKey) .addInjectable(UpenaAutoRelease.class, new UpenaAutoRelease(repositoryProvider, upenaStore)) .addInjectable(PathToRepo.class, localPathToRepo); PercentileHealthCheckConfig phcc = bindDefault(PercentileHealthCheckConfig.class); PercentileHealthChecker authFilterHealthCheck = new PercentileHealthChecker(phcc); AuthValidationFilter authValidationFilter = new AuthValidationFilter(authFilterHealthCheck); authValidationFilter.addEvaluator(new NoAuthEvaluator(), "/", "/swagger.json", "/ui/*", // Handled by Shiro "/repo/*" // Cough ); OAuth1Signature verifier = new OAuth1Signature(new OAuthServiceLocatorShim()); OAuthSecretManager oAuthSecretManager = new OAuthSecretManager() { @Override public void clearCache() { } @Override public String getSecret(String id) throws AuthValidationException { return id.equals(finalConsumerKey) ? finalSecret : null; } @Override public void verifyLastSecretRemovalTime() throws Exception { } }; AuthValidator<OAuth1Signature, OAuth1Request> oAuthValidator = new DefaultOAuthValidator( Executors.newScheduledThreadPool(1), Long.MAX_VALUE, oAuthSecretManager, 60_000, false, false); oAuthValidator.start(); authValidationFilter.addEvaluator(new NoAuthEvaluator(), "/repo/*", "/amza/rows/stream/*", "/amza/rows/taken/*", "/amza/pong/*", "/amza/invalidate/*"); authValidationFilter.addEvaluator(new OAuthEvaluator(oAuthValidator, verifier), "/upena/*", "/amza/*"); // TODO something better someday String upenaApiUsername = System.getProperty("upena.api.username", null); String upenaApiPassword = System.getProperty("upena.api.password", null); if (upenaApiUsername != null && upenaApiPassword != null) { authValidationFilter.addEvaluator(containerRequestContext -> { String authCredentials = containerRequestContext.getHeaderString("Authorization"); if (authCredentials == null) { return AuthStatus.not_handled; } final String encodedUserPassword = authCredentials.replaceFirst("Basic" + " ", ""); String usernameAndPassword = null; try { byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword); usernameAndPassword = new String(decodedBytes, "UTF-8"); } catch (IOException e) { return AuthStatus.denied; } final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); final String username = tokenizer.nextToken(); final String password = tokenizer.nextToken(); boolean authenticationStatus = upenaApiUsername.equals(username) && upenaApiPassword.equals(password); return authenticationStatus ? AuthStatus.authorized : AuthStatus.denied; }, "/api/*"); } jerseyEndpoints.addContainerRequestFilter(authValidationFilter); String region = System.getProperty("aws.region", null); String roleArn = System.getProperty("aws.roleArn", null); AWSClientFactory awsClientFactory = new AWSClientFactory(region, roleArn); String accountName = System.getProperty("account.name", clusterDiscoveryName == null ? "" : clusterDiscoveryName); String humanReadableUpenaClusterName = datacenter + " - " + accountName; injectUI(upenaVersion, awsClientFactory, storeMapper, mapper, jvmapi, amzaService, localPathToRepo, repositoryProvider, hostKey, ringHost, upenaSSLConfig, port, sessionStore, ubaService, upenaHealth, upenaStore, upenaConfigStore, jerseyEndpoints, humanReadableUpenaClusterName, discoveredRoutes); injectAmza(baInterner, amzaStats, jerseyEndpoints, amzaService, ringClient); InitializeRestfulServer initializeRestfulServer = new InitializeRestfulServer(false, port, "UpenaNode", sslEnable, sslKeyStoreAlias, sslKeystorePassword, sslKeystorePath, 128, 10_000); buildSwagger(); initializeRestfulServer.addClasspathResource("/resources"); initializeRestfulServer.addContextHandler("/", jerseyEndpoints); RestfulServer restfulServer = initializeRestfulServer.build(); restfulServer.start(); LOG.info("-----------------------------------------------------------------------"); LOG.info("| Jetty Service Online"); LOG.info("-----------------------------------------------------------------------"); UpenaJerseyEndpoints loopbackJerseyEndpoints = new UpenaJerseyEndpoints(null) .addEndpoint(UpenaLoopbackEndpoints.class).addEndpoint(UpenaConfigRestEndpoints.class) .addInjectable(SessionStore.class, sessionStore) .addInjectable(DiscoveredRoutes.class, discoveredRoutes).addInjectable(upenaConfigStore) .addInjectable(upenaStore).addInjectable(upenaHealth) .addInjectable(UpenaService.class, upenaService); InitializeRestfulServer initializeLoopbackRestfulServer = new InitializeRestfulServer( Boolean.parseBoolean(System.getProperty("amza.loopback.strict", "true")), loopbackPort, "UpenaNode", false, sslKeyStoreAlias, sslKeystorePassword, sslKeystorePath, 128, 10_000); initializeLoopbackRestfulServer.addClasspathResource("/resources"); initializeLoopbackRestfulServer.addContextHandler("/", loopbackJerseyEndpoints); RestfulServer loopbackRestfulServer = initializeLoopbackRestfulServer.build(); loopbackRestfulServer.start(); LOG.info("-----------------------------------------------------------------------"); LOG.info("| Jetty Service Online"); LOG.info("-----------------------------------------------------------------------"); if (ubaService != null) { Executors.newScheduledThreadPool(1).scheduleWithFixedDelay(() -> { try { ubaService.nanny(); } catch (Exception ex) { LOG.error("Nanny failure", ex); } }, 15, 15, TimeUnit.SECONDS); LOG.info("-----------------------------------------------------------------------"); LOG.info("| Uba Service Online"); LOG.info("-----------------------------------------------------------------------"); } ubaServiceReference.set(ubaService); /*String peers = System.getProperty("manual.peers"); if (peers != null) { String[] hostPortTuples = peers.split(","); for (String hostPortTuple : hostPortTuples) { String hostPort = hostPortTuple.trim(); if (hostPort.length() > 0 && hostPort.contains(":")) { String[] host_port = hostPort.split(":"); try { UpenaRingHost anotherRingHost = new UpenaRingHost(host_port[0].trim(), Integer.parseInt(host_port[1].trim())); List<UpenaRingHost> ring = upenaAmzaService.getRing("master"); if (!ring.contains(anotherRingHost)) { LOG.info("Adding host to the cluster: " + anotherRingHost); upenaAmzaService.addRingHost("master", anotherRingHost); } } catch (Exception x) { LOG.warn("Malformed hostPortTuple {}", hostPort); } } else { LOG.warn("Malformed hostPortTuple {}", hostPort); } } }*/ String vpc = System.getProperty("aws.vpc", null); UpenaAWSLoadBalancerNanny upenaAWSLoadBalancerNanny = new UpenaAWSLoadBalancerNanny(vpc, upenaStore, hostKey, awsClientFactory); Executors.newScheduledThreadPool(1).scheduleWithFixedDelay(() -> { try { upenaAWSLoadBalancerNanny.ensureSelf(); } catch (Exception x) { LOG.warn("Failures while nannying load loadbalancer.", x); } }, 1, 1, TimeUnit.MINUTES); // TODO better LOG.info("-----------------------------------------------------------------------"); LOG.info("| Waiting for amza to be ready...."); LOG.info("-----------------------------------------------------------------------"); while (!amzaService.isReady()) { Thread.sleep(1000); } LOG.info("-----------------------------------------------------------------------"); LOG.info("| Begin Migration"); LOG.info("-----------------------------------------------------------------------"); upenaStore.init(orderIdProvider, Integer.parseInt(System.getProperty("min.service.port", "10000")), Integer.parseInt(System.getProperty("max.service.port", String.valueOf(Short.MAX_VALUE))), false); upenaConfigStore.init(); LOG.info("-----------------------------------------------------------------------"); LOG.info("| End Migration"); LOG.info("-----------------------------------------------------------------------"); addManualPeers(amzaService); Host gotHost = upenaStore.hosts.get(hostKey); if (gotHost == null || !gotHost.equals(host)) { upenaStore.hosts.update(hostKey, host); } }
From source file:com.hackengine_er.muslumyusuf.DBOperations.java
/** * * Upload image to ftp and insert it's URL to database * * @param image//from ww w . j ava 2s . c o m * @return */ public synchronized UploadImageResponse uploadImage(Image image) { try { byte[] imageBytes = Base64.getDecoder().decode(image.getBase64()); if (!uploadToFTP(image.getUsername(), image.getFilename(), new ByteArrayInputStream(imageBytes))) { return new UploadImageResponse(-2); } establishConnection(); callableStatement = connection.prepareCall(DbStoredProcedures.UPDATE_IMAGE); callableStatement.setString(1, Configuration.imageFTPPath() + image.getUsername() + Tags.IMAGE_PREFIX + image.getFilename()); callableStatement.setString(2, image.getUsername()); return new UploadImageResponse(callableStatement.executeUpdate()); } catch (SQLException e) { return new UploadImageResponse(e); } finally { closeEverything(); } }
From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java
/** idemixEnroll returns an Identity Mixer Enrollment, which supports anonymity and unlinkability * * @param enrollment a x509 enrollment credential * @return IdemixEnrollment/*from ww w .j a v a 2s .com*/ * @throws EnrollmentException * @throws InvalidArgumentException */ public Enrollment idemixEnroll(Enrollment enrollment, String mspID) throws EnrollmentException, InvalidArgumentException { if (cryptoSuite == null) { throw new InvalidArgumentException("Crypto primitives not set"); } if (enrollment == null) { throw new InvalidArgumentException("enrollment is missing"); } if (Utils.isNullOrEmpty(mspID)) { throw new InvalidArgumentException("mspID cannot be null or empty"); } if (enrollment instanceof IdemixEnrollment) { throw new InvalidArgumentException("enrollment type must be x509"); } final RAND rng = IdemixUtils.getRand(); try { setUpSSL(); // Get nonce IdemixEnrollmentRequest idemixEnrollReq = new IdemixEnrollmentRequest(); String body = idemixEnrollReq.toJson(); JsonObject result = httpPost(url + HFCA_IDEMIXCRED, body, enrollment); if (result == null) { throw new EnrollmentException("No response received for idemix enrollment request"); } String nonceString = result.getString("Nonce"); if (Utils.isNullOrEmpty(nonceString)) { throw new InvalidArgumentException( "fabric-ca-server did not return a nonce in the response from " + HFCA_IDEMIXCRED); } byte[] nonceBytes = Base64.getDecoder().decode(nonceString.getBytes()); BIG nonce = BIG.fromBytes(nonceBytes); // Get issuer public key and revocation key from the cainfo section of response JsonObject info = result.getJsonObject("CAInfo"); if (info == null) { throw new Exception( "fabric-ca-server did not return 'cainfo' in the response from " + HFCA_IDEMIXCRED); } IdemixIssuerPublicKey ipk = getIssuerPublicKey(info.getString("IssuerPublicKey")); PublicKey rpk = getRevocationPublicKey(info.getString("IssuerRevocationPublicKey")); // Create and send idemix credential request BIG sk = new BIG(IdemixUtils.randModOrder(rng)); IdemixCredRequest idemixCredRequest = new IdemixCredRequest(sk, nonce, ipk); idemixEnrollReq.setIdemixCredReq(idemixCredRequest); body = idemixEnrollReq.toJson(); result = httpPost(url + HFCA_IDEMIXCRED, body, enrollment); if (result == null) { throw new EnrollmentException("No response received for idemix enrollment request"); } // Deserialize idemix credential String credential = result.getString("Credential"); if (Utils.isNullOrEmpty(credential)) { throw new InvalidArgumentException( "fabric-ca-server did not return a 'credential' in the response from " + HFCA_IDEMIXCRED); } byte[] credBytes = Base64.getDecoder().decode(credential.getBytes(UTF_8)); Idemix.Credential credProto = Idemix.Credential.parseFrom(credBytes); IdemixCredential cred = new IdemixCredential(credProto); // Deserialize idemix cri (Credential Revocation Information) String criStr = result.getString("CRI"); if (Utils.isNullOrEmpty(criStr)) { throw new InvalidArgumentException( "fabric-ca-server did not return a 'CRI' in the response from " + HFCA_IDEMIXCRED); } byte[] criBytes = Base64.getDecoder().decode(criStr.getBytes(UTF_8)); Idemix.CredentialRevocationInformation cri = Idemix.CredentialRevocationInformation.parseFrom(criBytes); JsonObject attrs = result.getJsonObject("Attrs"); if (attrs == null) { throw new EnrollmentException( "fabric-ca-server did not return 'attrs' in the response from " + HFCA_IDEMIXCRED); } String ou = attrs.getString("OU"); if (Utils.isNullOrEmpty(ou)) { throw new InvalidArgumentException( "fabric-ca-server did not return a 'ou' attribute in the response from " + HFCA_IDEMIXCRED); } int role = attrs.getInt("Role"); // Encoded IdemixRole from Fabric-Ca // Return the idemix enrollment return new IdemixEnrollment(ipk, rpk, mspID, sk, cred, cri, ou, role); } catch (EnrollmentException ee) { logger.error(ee.getMessage(), ee); throw ee; } catch (Exception e) { EnrollmentException ee = new EnrollmentException("Failed to get Idemix credential", e); logger.error(e.getMessage(), e); throw ee; } }
From source file:org.siphon.jssql.SqlExecutor.java
private byte[] parseBinary(Object value) throws SqlExecutorException { if (JsTypeUtil.isNull(value)) { return null; }/*from w ww . j av a 2 s . c o m*/ if (value instanceof byte[]) { return (byte[]) value; } else if (value instanceof Byte[]) { return ArrayUtils.toPrimitive((Byte[]) value); } if (value instanceof ScriptObjectMirror && ((ScriptObjectMirror) value).isArray()) { value = ((ScriptObjectMirror) value).to(NativeArray.class); } if (value instanceof NativeArray) { NativeArray arr = (NativeArray) value; byte[] r = new byte[JsTypeUtil.getArrayLength(arr)]; for (int i = 0; i < JsTypeUtil.getArrayLength(arr); i++) { if (arr.get(i) instanceof Byte) { r[i] = (Byte) arr.get(i); } else if (arr.get(i) instanceof Double) { r[i] = ((Double) arr.get(i)).byteValue(); } else if (arr.get(i) instanceof Integer) { r[i] = ((Integer) arr.get(i)).byteValue(); } } return r; } else if (value instanceof String) { Decoder decoder = Base64.getDecoder(); try { return decoder.decode((String) value); } catch (Exception e) { throw new SqlExecutorException("cannot parse base64 binary data " + value, e); } } else { throw new SqlExecutorException("unkown binary data " + value + " " + value.getClass()); } }
From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java
private IdemixIssuerPublicKey getIssuerPublicKey(String str) throws EnrollmentException, InvalidProtocolBufferException { if (Utils.isNullOrEmpty(str)) { throw new EnrollmentException( "fabric-ca-server did not return 'issuerPublicKey' in the response from " + HFCA_IDEMIXCRED); }/*w ww . j a va2 s.c o m*/ byte[] ipkBytes = Base64.getDecoder().decode(str.getBytes()); Idemix.IssuerPublicKey ipkProto = Idemix.IssuerPublicKey.parseFrom(ipkBytes); return new IdemixIssuerPublicKey(ipkProto); }
From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java
private PublicKey getRevocationPublicKey(String str) throws EnrollmentException, IOException, NoSuchAlgorithmException, InvalidKeySpecException { if (Utils.isNullOrEmpty(str)) { throw new EnrollmentException( "fabric-ca-server did not return 'issuerPublicKey' in the response from " + HFCA_IDEMIXCRED); }// ww w . j av a 2 s . co m String pem = new String(Base64.getDecoder().decode(str)); byte[] der = convertPemToDer(pem); return KeyFactory.getInstance("EC").generatePublic(new X509EncodedKeySpec(der)); }
From source file:it.greenvulcano.gvesb.datahandling.dbo.DBOCallSP.java
/** * @see org.xml.sax.ContentHandler#endElement(java.lang.String, * java.lang.String, java.lang.String) *//*from w w w. j a v a2s.c o m*/ @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (ROW_NAME.equals(localName)) { if (!currCriticalError) { executeStatement(); } else { rowDisc++; // aggiunta DiscardCause al dhr... String msg = currentXSLMessage; dhr.addDiscardCause(new DiscardCause(rowCounter, msg)); resultMessage.append("Data error on row ").append(rowCounter).append(": ").append(msg); resultMessage.append("SQL Statement Informations:\n").append(sqlStatementInfo); resultMessage.append("Record parameters:\n").append(dumpCurrentRowFields()); resultStatus = STATUS_PARTIAL; } } else if (COL_NAME.equals(localName)) { CallableStatement cs = (CallableStatement) sqlStatementInfo.getStatement(); try { if (!outOnly) { colDataExpecting = false; String text = textBuffer.toString(); if ((currentUUID != null) && (currentUUID.trim().length() > 0) && (text.length() == 0)) { text = uuids.get(currentUUID); if (text == null) { text = currentUUID; } } if (TIMESTAMP_TYPE.equals(currType) || DATE_TYPE.equals(currType) || TIME_TYPE.equals(currType)) { if (text.equals("")) { if (TIMESTAMP_TYPE.equals(currType)) setNull(cs, Types.TIMESTAMP); else if (DATE_TYPE.equals(currType)) setNull(cs, Types.DATE); else setNull(cs, Types.TIME); currentRowFields.add(null); } else { dateFormatter.applyPattern(currDateFormat); Date formattedDate = dateFormatter.parse(text); if (TIMESTAMP_TYPE.equals(currType)) { Timestamp ts = new Timestamp(formattedDate.getTime()); setTimestamp(cs, ts); currentRowFields.add(ts); } else if (DATE_TYPE.equals(currType)) { java.sql.Date d = new java.sql.Date(formattedDate.getTime()); setDate(cs, d); currentRowFields.add(d); } else { java.sql.Time t = new java.sql.Time(formattedDate.getTime()); setTime(cs, t); currentRowFields.add(t); } } } else if (INTEGER_TYPE.equals(currType) || SMALLINT_TYPE.equals(currType) || BIGINT_TYPE.equals(currType)) { if (text.equals("")) { if (INTEGER_TYPE.equals(currType)) setNull(cs, Types.INTEGER); else if (SMALLINT_TYPE.equals(currType)) setNull(cs, Types.SMALLINT); else setNull(cs, Types.BIGINT); currentRowFields.add(null); } else { if (INTEGER_TYPE.equals(currType)) setInt(cs, Integer.parseInt(text, 10)); else if (SMALLINT_TYPE.equals(currType)) setShort(cs, Short.parseShort(text, 10)); else setLong(cs, Long.parseLong(text, 10)); currentRowFields.add(text); } } else if (FLOAT_TYPE.equals(currType) || DOUBLE_TYPE.equals(currType) || DECIMAL_TYPE.equals(currType) || NUMERIC_TYPE.equals(currType)) { if (text.equals("")) { if (DECIMAL_TYPE.equals(currType) || NUMERIC_TYPE.equals(currType)) setNull(cs, Types.NUMERIC); else if (FLOAT_TYPE.equals(currType)) setNull(cs, Types.FLOAT); else setNull(cs, Types.DOUBLE); currentRowFields.add(null); } else { DecimalFormatSymbols dfs = numberFormatter.getDecimalFormatSymbols(); dfs.setDecimalSeparator(currDecSeparator.charAt(0)); dfs.setGroupingSeparator(currGroupSeparator.charAt(0)); numberFormatter.setDecimalFormatSymbols(dfs); numberFormatter.applyPattern(currNumberFormat); boolean isBigDecimal = numberFormatter.isParseBigDecimal(); try { numberFormatter.setParseBigDecimal(true); BigDecimal formattedNumber = (BigDecimal) numberFormatter.parse(text); if (DECIMAL_TYPE.equals(currType) || NUMERIC_TYPE.equals(currType)) { setBigDecimal(cs, formattedNumber); currentRowFields.add(formattedNumber); } else if (FLOAT_TYPE.equals(currType)) { setFloat(cs, formattedNumber.floatValue()); currentRowFields.add(formattedNumber.floatValue()); } else { setDouble(cs, formattedNumber.doubleValue()); currentRowFields.add(formattedNumber.doubleValue()); } } finally { numberFormatter.setParseBigDecimal(isBigDecimal); } } } else if (LONG_STRING_TYPE.equals(currType) || LONG_NSTRING_TYPE.equals(currType)) { if (text.equals("")) { if (LONG_STRING_TYPE.equals(currType)) setNull(cs, Types.CLOB); else setNull(cs, Types.NCLOB); currentRowFields.add(null); } else { if (LONG_STRING_TYPE.equals(currType)) { setCharacterStream(cs, new StringReader(text)); currentRowFields.add(text); } else { setNCharacterStream(cs, new StringReader(text)); currentRowFields.add(text); } } } else if (BASE64_TYPE.equals(currType)) { if (text.equals("")) { setNull(cs, Types.BLOB); currentRowFields.add(null); } else { byte[] data = text.getBytes(); data = Base64.getDecoder().decode(data); ByteArrayInputStream bais = new ByteArrayInputStream(data); setBinaryStream(cs, bais, data.length); currentRowFields.add(text); } } else if (BINARY_TYPE.equals(currType)) { if (text.equals("")) { setNull(cs, Types.BLOB); currentRowFields.add(null); } else { byte[] data = text.getBytes(); ByteArrayInputStream bais = new ByteArrayInputStream(data); setBinaryStream(cs, bais, data.length); currentRowFields.add(text); } } else if (BOOLEAN_TYPE.equals(currType)) { if (text.equals("")) { setNull(cs, Types.BOOLEAN); currentRowFields.add(null); } else { setBoolean(cs, TextUtils.parseBoolean(text)); currentRowFields.add(text); } } else if (XML_TYPE.equals(currType)) { if (text.equals("")) { setNull(cs, Types.SQLXML); currentRowFields.add(null); } else { SQLXML xml = cs.getConnection().createSQLXML(); xml.setString(text); setSQLXML(cs, xml); currentRowFields.add(text); } } else if (NSTRING_TYPE.equals(currType)) { if (text.equals("")) { setNull(cs, Types.NVARCHAR); currentRowFields.add(null); } else { setNString(cs, text); currentRowFields.add(text); } } else { if (text.equals("")) { setNull(cs, Types.VARCHAR); currentRowFields.add(null); } else { setString(cs, text); currentRowFields.add(text); } } } else { currentRowFields.add(currentUUID); } } catch (ParseException exc) { throw new SAXException(exc); } catch (SQLException exc) { OracleExceptionHandler.handleSQLException(exc); throw new SAXException(exc); } } }