List of usage examples for java.util UUID randomUUID
public static UUID randomUUID()
From source file:org.jasig.portlet.announcements.Exporter.java
public static void main(String[] args) throws Exception { String dir = args[0];/*from w ww. jav a 2 s . co m*/ ApplicationContext context = PortletApplicationContextLocator .getApplicationContext(PortletApplicationContextLocator.DATABASE_CONTEXT_LOCATION); SessionFactory sessionFactory = context.getBean(SESSION_FACTORY_BEAN_NAME, SessionFactory.class); IAnnouncementService announcementService = context.getBean(ANNOUNCEMENT_SVC_BEAN_NAME, IAnnouncementService.class); Session session = sessionFactory.getCurrentSession(); Transaction transaction = session.beginTransaction(); JAXBContext jc = JAXBContext.newInstance(Topic.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); List<Topic> topics = announcementService.getAllTopics(); for (Topic topic : topics) { if (topic.getSubscriptionMethod() == 4) { continue; } session.lock(topic, LockMode.NONE); JAXBElement<Topic> je2 = new JAXBElement<Topic>(new QName("topic"), Topic.class, topic); String output = dir + File.separator + UUID.randomUUID().toString() + ".xml"; System.out.println("Exporting Topic " + topic.getId() + " to file " + output); try { marshaller.marshal(je2, new FileOutputStream(output)); } catch (Exception exception) { exception.printStackTrace(); } } transaction.commit(); }
From source file:cf.service.TestBroker.java
public static void main(String[] args) throws Exception { final CfTokens cfTokens = new CfTokens(); final CfTokens.CfToken target = cfTokens.getCurrentTargetToken(); if (target == null) { System.err.println("It appears you haven't logged into a Cloud Foundry instance with cf."); return;/*from w ww .j a v a 2 s. com*/ } if (target.getVersion() == null || target.getVersion() != 2) { System.err.println("You must target a v2 Cloud Controller using cf."); return; } if (target.getSpaceGuid() == null) { System.err.println("You must select a space to use using cf."); return; } LOGGER.info("Using Cloud Controller at: {}", target.getTarget()); final int serverPort = 8000; final String label = "testbroker"; final String provider = "Tester"; final String url = "http://" + localIp(target.getTarget()) + ":" + serverPort; final String description = "A service used for testing the service framework."; final String version = "0.1"; final String servicePlan = "ServicePlan"; final String servicePlanDescription = "Finest service... ever."; final String authToken = "SsshhhThisIsASecret"; final CloudController cloudController = new DefaultCloudController(new DefaultHttpClient(), target.getTarget()); final UUID serviceGuid = UUID.randomUUID(); // We need to keep track of the services GUID. // final String serviceGuid = cloudControllerClient.createService(new CreateServiceRequest( // label, provider, url, description, version // )); // LOGGER.debug("Created service with guid: {}", serviceGuid); // try (final SimpleHttpServer server = new SimpleHttpServer(new InetSocketAddress(serverPort))) { new NettyBrokerServer(server, new Provisioner() { private final AtomicInteger id = new AtomicInteger(); @Override public ServiceInstance create(CreateRequest request) { LOGGER.info("Creating service"); final Integer i = id.getAndIncrement(); final ServiceInstance serviceInstance = new ServiceInstance(i.toString()); serviceInstance.addGatewayDataField("key", "value"); serviceInstance.addCredential("user", "test"); return serviceInstance; } @Override public void delete(String instanceId) { } @Override public ServiceBinding bind(BindRequest request) { LOGGER.info("Binding service"); final Integer i = id.getAndIncrement(); final ServiceBinding serviceBinding = new ServiceBinding(request.getServiceInstanceId(), i.toString()); serviceBinding.addGatewayDataField("bindkey", "bind value"); serviceBinding.addCredential("binduser", "test"); return serviceBinding; } @Override public void unbind(String instanceId, String handleId) { } @Override public Iterable<String> serviceInstanceIds() { return null; } @Override public Iterable<String> bindingIds(String instanceId) { return null; } @Override public void removeOrphanedBinding(String instanceId, String bindingId) { } @Override public void removeOrphanedServiceInstance(String instanceId) { } }, authToken); // final String serviceGuid = cloudControllerClient.createService(new CreateServiceRequest( // label, provider, url, description, version // )); // LOGGER.debug("Created service with guid: {}", serviceGuid); // // final String servicePlanGuid = cloudControllerClient.createServicePlan(new CreateServicePlanRequest(servicePlan, servicePlanDescription, serviceGuid)); // LOGGER.debug("Created service plan with guid: {}", serviceGuid); // // final String authTokenGuid = cloudControllerClient.createAuthToken(new CreateAuthTokenRequest(label, provider, authToken)); // LOGGER.debug("Created service token with guid: {}", authTokenGuid); // // final String instanceName = "testservice"; // final String serviceInstaceGuid = cloudControllerClient.createServiceInstance(instanceName, servicePlanGuid, target.getSpaceGuid()); System.in.read(); } }
From source file:com.termmed.statistics.runner.Runner.java
/** * The main method./*from w w w . j a va 2 s. c o m*/ * * @param args the arguments */ public static void main(String[] args) { logger = new ProcessLogger(); if (args.length == 0) { logger.logInfo("Error happened getting params. Params file doesn't exist"); System.exit(0); // }else{ // args=new String[]{"config/complete_nl-edition11320160930.xml"}; } File infoFolder = new File(I_Constants.PROCESS_INFO_FOLDER); if (!infoFolder.exists()) { infoFolder.mkdirs(); } OutputInfoFactory.get().setExecutionId(UUID.randomUUID().toString()); String msg; int posIni; long start = logger.startTime(); File file = new File(args[0]); Config configFile = getConfig(file); OutputInfoFactory.get().setConfig(configFile); System.setProperty("textdb.allow_full_path", "true"); Connection c; try { boolean clean = false; if (args.length >= 2) { for (int i = 1; i < args.length; i++) { logger.logInfo("Arg " + i + ": " + args[i]); if (args[i].toLowerCase().equals("clean")) { clean = true; } } } dataFolder = new File(I_Constants.REPO_FOLDER); if (!dataFolder.exists()) { dataFolder.mkdirs(); } changedDate = true; changedPreviousDate = true; getParams(file); checkDates(); /*******************************/ // changedDate=false; // changedPreviousDate=false; /********************************/ if (clean || changedDate || changedPreviousDate) { logger.logInfo("Removing old data"); removeDBFolder(); removeRepoFolder(); removeReducedFolder(); changedDate = true; changedPreviousDate = true; } Class.forName("org.hsqldb.jdbcDriver"); logger.logInfo("Connecting to DB. This task can take several minutes... wait please."); c = DriverManager.getConnection("jdbc:hsqldb:file:" + I_Constants.DB_FOLDER, "sa", "sa"); initFileProviders(file); // OutputInfoFactory.get().getStatisticProcess().setOutputFolder(I_Constants.STATS_OUTPUT_FOLDER); /*******************************/ // DbSetup dbs=new DbSetup(c); // dbs.recreatePath("org/ihtsdo/statistics/db/setup/storedprocedure"); // dbs=null; /*******************************/ ImportManager impor = new ImportManager(c, file, changedDate, changedPreviousDate); impor.execute(); impor = null; Processor proc = new Processor(c, file); proc.execute(); proc = null; msg = logger.endTime(start); posIni = msg.indexOf("ProcessingTime:") + 16; OutputInfoFactory.get().getStatisticProcess().setTimeTaken(msg.substring(posIni)); // OutputInfoFactory.get().getPatternProcess().setOutputFolder(I_Constants.PATTERN_OUTPUT_FOLDER); long startPattern = logger.startTime(); PatternExecutor pe = new PatternExecutor(file); pe.execute(); pe = null; msg = logger.endTime(startPattern); posIni = msg.indexOf("ProcessingTime:") + 16; OutputInfoFactory.get().getPatternProcess().setTimeTaken(msg.substring(posIni)); OutputInfoFactory.get().setStatus("Complete"); } catch (Exception e) { OutputInfoFactory.get().setStatus("Error: " + e.getMessage() + " - View log for details."); e.printStackTrace(); } msg = logger.endTime(start); posIni = msg.indexOf("ProcessingTime:") + 16; OutputInfoFactory.get().setTimeTaken(msg.substring(posIni)); try { saveInfo(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.teslagov.joan.example.Main.java
public static void main(String[] args) throws Exception { Properties properties = ArcPropertiesFactory.createArcProperties(); ArcConfiguration arcConfiguration = arcConfig().arcPortalConfiguration(portalConfig() .portalAdminUsername(properties.getString(ArcProperties.PORTAL_ADMIN_USERNAME)) .portalAdminPassword(properties.getString(ArcProperties.PORTAL_ADMIN_PASSWORD)) .portalUrl(properties.getString(ArcProperties.PORTAL_URL)) .portalPort(properties.getInteger(ArcProperties.PORTAL_PORT)) .portalContextPath(properties.getString(ArcProperties.PORTAL_CONTEXT_PATH)) .portalIsUsingWebAdaptor(properties.getBoolean(ArcProperties.PORTAL_IS_USING_WEB_ADAPTOR)).build()) .build();//ww w. j av a 2s . c o m HttpClient httpClient = TrustingHttpClientFactory.createVeryUnsafePortalHttpClient(arcConfiguration, null); ArcPortalConfiguration arcPortalConfiguration = arcConfiguration.getArcPortalConfiguration(); ArcPortalApi arcPortalApi = new ArcPortalApi(httpClient, arcPortalConfiguration, ZoneOffset.UTC, new TokenManager(new TokenRefresher(new PortalTokenFetcher(httpClient, arcPortalConfiguration), ZoneOffset.UTC))); UserListResponse userListResponse = arcPortalApi.userApi.fetchUsers(); if (userListResponse.isSuccess()) { List<UserResponseModel> users = userListResponse.users; users.forEach(u -> logger.debug("User {}", u)); } String username = UUID.randomUUID().toString(); String id = null; String publishedId = null; String groupId = null; try { groupId = createGroupExample(arcPortalApi); createNewUserExample(arcPortalApi, username); id = uploadItemExample(arcPortalApi, username); String analyzeResponse = arcPortalApi.itemApi.analyzeItem(id); publishedId = publishItemExample(arcPortalApi, id, username, analyzeResponse); shareItemExample(arcPortalApi, publishedId, username, groupId); deleteItemExample(arcPortalApi, id, username); deleteItemExample(arcPortalApi, publishedId, username); removeUserExample(arcPortalApi, username); deleteGroupExample(arcPortalApi, groupId); } catch (Exception e) { if (id != null) { arcPortalApi.itemApi.deleteItem(id, username); } if (publishedId != null) { arcPortalApi.itemApi.deleteItem(publishedId, username); } if (groupId != null) { arcPortalApi.groupApi.deleteGroup(groupId); } arcPortalApi.userApi.deleteUser(username); logger.debug("Exception occured {}", e.getMessage()); } }
From source file:com.amazonaws.services.kinesis.application.stocktrades.processor.StockTradesProcessor.java
public static void main(String[] args) throws Exception { checkUsage(args);//from ww w . j ava 2s.c om String applicationName = args[0]; String streamName = args[1]; Region region = RegionUtils.getRegion(args[2]); if (region == null) { System.err.println(args[2] + " is not a valid AWS region."); System.exit(1); } setLogLevels(); AWSCredentialsProvider credentialsProvider = CredentialUtils.getCredentialsProvider(); String workerId = String.valueOf(UUID.randomUUID()); KinesisClientLibConfiguration kclConfig = new KinesisClientLibConfiguration(applicationName, streamName, credentialsProvider, workerId).withRegionName(region.getName()) .withCommonClientConfig(ConfigurationUtils.getClientConfigWithUserAgent()); IRecordProcessorFactory recordProcessorFactory = new StockTradeRecordProcessorFactory(); // Create the KCL worker with the stock trade record processor factory Worker worker = new Worker(recordProcessorFactory, kclConfig); int exitCode = 0; try { worker.run(); } catch (Throwable t) { LOG.error("Caught throwable while processing data.", t); exitCode = 1; } System.exit(exitCode); }
From source file:com.sinotopia.mybatis.plus.test.GlobalConfigurationTest.java
/** * ?//from w ww . j a v a2 s .c om */ @SuppressWarnings("unchecked") public static void main(String[] args) { GlobalConfiguration global = GlobalConfiguration.defaults(); global.setAutoSetDbType(true); // FieldStrategy.Empty global.setFieldStrategy(2); BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/mybatis-plus?characterEncoding=UTF-8"); dataSource.setUsername("root"); dataSource.setPassword("521"); dataSource.setMaxTotal(1000); GlobalConfiguration.setMetaData(dataSource, global); // ? InputStream inputStream = GlobalConfigurationTest.class.getClassLoader() .getResourceAsStream("mysql-config.xml"); MybatisSessionFactoryBuilder factoryBuilder = new MybatisSessionFactoryBuilder(); factoryBuilder.setGlobalConfig(global); SqlSessionFactory sessionFactory = factoryBuilder.build(inputStream); SqlSession session = sessionFactory.openSession(false); TestMapper testMapper = session.getMapper(TestMapper.class); /*Wrapper type = Condition.instance().eq("id",1).or().in("type", new Object[]{1, 2, 3, 4, 5, 6}); List list = testMapper.selectList(type); System.out.println(list.toString());*/ Test test = new Test(); test.setCreateTime(new Date()); // ? test.setType(""); testMapper.insert(test); SqlSession sqlSession = sessionFactory.openSession(false); NotPKMapper pkMapper = sqlSession.getMapper(NotPKMapper.class); NotPK notPK = new NotPK(); notPK.setUuid(UUID.randomUUID().toString()); int num = pkMapper.insert(notPK); Assert.assertTrue(num > 0); NotPK notPK1 = pkMapper.selectOne(notPK); Assert.assertNotNull(notPK1); pkMapper.selectPage(RowBounds.DEFAULT, Condition.create().eq("type", 12121212)); NotPK notPK2 = null; try { notPK2 = pkMapper.selectById("1"); } catch (Exception e) { System.out.println(","); } Assert.assertNull(notPK2); int count = pkMapper.selectCount(Condition.EMPTY); Assert.assertTrue(count > 0); int deleteCount = pkMapper.delete(null); Assert.assertTrue(deleteCount > 0); session.rollback(); sqlSession.commit(); }
From source file:AIR.Common.Web.WebValueCollectionCorrect.java
public static void main(String[] args) { try {//from www. ja va 2 s . com WebValueCollectionCorrect collection = new WebValueCollectionCorrect(); collection.put("a", "A"); collection.put("b", Arrays.asList("1", "2")); collection.put("c", UUID.randomUUID()); System.err.println(collection.toString()); WebValueCollectionCorrect.getInstanceFromString(collection.toString(), true); } catch (Exception exp) { exp.printStackTrace(); } }
From source file:ProductionJS.java
/** * @param args//from w w w . j a va 2 s .c o m */ public static void main(String[] args) { boolean precondition = true; BackupLog backupLog = new BackupLog("log/backupLog.txt"); Property properties = null; Settings settings = null; // Load main cfg file try { properties = new Property("cfg/cfg"); } catch (IOException e) { backupLog.log("ERROR : Config file not found"); precondition = false; } // Load cfg for Log4J if (precondition) { try { DOMConfigurator.configureAndWatch(properties.getProperty("loggerConfiguration")); logger.info("ProductionJS is launched\n_______________________"); } catch (Exception e) { backupLog.log(e.getMessage()); precondition = false; } } // Load settings for current execution if (precondition) { try { settings = new Settings(new File(properties.getProperty("importConfiguration"))); } catch (IOException e) { logger.error("Properties file not found"); precondition = false; } catch (org.json.simple.parser.ParseException e) { logger.error("Properties file reading error : JSON may be invalid, check it!"); precondition = false; } } // All is OK : GO! if (precondition) { logger.info("Configuration OK"); logger.info("\"_______________________\nConcat BEGIN\n_______________________\n"); Concat concat = new Concat(); try { if (settings.getPrior() != null) { logger.info("Add Prior files\n_______________________\n"); concat.addJSONArray(settings.getPrior()); } for (int i = 0; i < settings.getIn().size(); i++) { ProductionJS.logger.info("Importation number " + (i + 1)); ProductionJS.logger.info("Directory imported " + settings.getIn().get(i)); Directory dir = new Directory(new File(settings.getIn().get(i).toString())); dir.scan(); concat.add(dir.getFiles()); } concat.output(settings.getOut()); logger.info("\"_______________________\nConcat END\n_______________________\n"); if (settings.getMinify() != null && settings.getMinify() == true) { logger.info( "\"_______________________\nMinify of concatened file BEGIN\n_______________________\n"); new Minify(new File(settings.getOut()), settings.getOut()); logger.info( "\"_______________________\nMinify of concatened file END\n_______________________\n"); } if (settings.getLicense() != null) { logger.info("Add License\n_______________________\n"); concat = new Concat(); UUID uniqueID = UUID.randomUUID(); PrintWriter tmp = new PrintWriter(uniqueID.toString() + ".txt"); tmp.println(settings.getLicense()); tmp.close(); File license = new File(uniqueID.toString() + ".txt"); concat.add(license); File out = new File(settings.getOut()); File tmpOut = new File(uniqueID + out.getName()); out.renameTo(tmpOut); concat.add(tmpOut); concat.output(settings.getOut()); license.delete(); tmpOut.delete(); } } catch (IOException e) { StackTrace stackTrace = new StackTrace(e.getStackTrace()); logger.error("An error occurred " + e.getMessage() + " " + stackTrace.toString()); } } }
From source file:br.com.thiagomoreira.bancodobrasil.Main.java
/** * @param args/*from w w w. j a va2 s . c o m*/ */ public static void main(String[] args) throws Exception { if (args != null) { NumberFormat formatter = NumberFormat.getNumberInstance(new Locale("pt", "BR")); formatter.setMaximumFractionDigits(2); formatter.setMinimumFractionDigits(2); double total = 0; for (String arg : args) { File input = new File(arg); if (input.exists()) { List<String> lines = IOUtils.readLines(new FileInputStream(input), "ISO-8859-1"); Parser parser = new DefaultParser(); List<Transaction> transactions = parser.parse(lines); TransactionList transactionList = new TransactionList(); transactionList.setStart(parser.getStartDate()); transactionList.setEnd(parser.getEndDate()); transactionList.setTransactions(transactions); CreditCardAccountDetails creditCardAccountDetails = new CreditCardAccountDetails(); creditCardAccountDetails.setAccountNumber("7616-3"); creditCardAccountDetails.setAccountKey(parser.getAccountKey()); CreditCardStatementResponse creditCardStatementResponse = new CreditCardStatementResponse(); creditCardStatementResponse.setAccount(creditCardAccountDetails); creditCardStatementResponse.setCurrencyCode("BRL"); creditCardStatementResponse.setTransactionList(transactionList); Status status = new Status(); status.setCode(Status.KnownCode.SUCCESS); status.setSeverity(Status.Severity.INFO); CreditCardStatementResponseTransaction statementResponse = new CreditCardStatementResponseTransaction(); statementResponse.setClientCookie(UUID.randomUUID().toString()); statementResponse.setStatus(status); statementResponse.setUID(UUID.randomUUID().toString()); statementResponse.setMessage(creditCardStatementResponse); CreditCardResponseMessageSet creditCardResponseMessageSet = new CreditCardResponseMessageSet(); creditCardResponseMessageSet.setStatementResponse(statementResponse); SortedSet<ResponseMessageSet> messageSets = new TreeSet<ResponseMessageSet>(); messageSets.add(creditCardResponseMessageSet); ResponseEnvelope envelope = new ResponseEnvelope(); envelope.setUID(UUID.randomUUID().toString()); envelope.setSecurity(ApplicationSecurity.NONE); envelope.setMessageSets(messageSets); double brazilianRealsamount = parser.getBrazilianRealsAmount(); double dolarsAmount = parser.getDolarsAmount(); double cardTotal = dolarsAmount * parser.getExchangeRate() + brazilianRealsamount; total += cardTotal; System.out.println(creditCardAccountDetails.getAccountKey()); System.out.println("TOTAL EM RS " + formatter.format(brazilianRealsamount)); System.out.println("TOTAL EM US " + formatter.format(dolarsAmount)); System.out.println("TOTAL FATURA EM RS " + formatter.format(cardTotal)); System.out.println(); if (!transactions.isEmpty()) { String parent = System.getProperty("user.home") + "/Downloads"; String fileName = arg.replace(".txt", ".ofx"); File output = new File(parent, fileName); FileOutputStream fos = new FileOutputStream(output); OFXV1Writer writer = new OFXV1Writer(fos); writer.setWriteAttributesOnNewLine(true); AggregateMarshaller marshaller = new AggregateMarshaller(); marshaller.setConversion(new MyFinanceStringConversion()); marshaller.marshal(envelope, writer); writer.flush(); writer.close(); } } } System.out.println("TOTAL FATURAS EM RS " + formatter.format(total)); } }
From source file:fr.inria.atlanmod.kyanos.benchmarks.CdoQueryRenameAllMethods.java
public static void main(String[] args) { Options options = new Options(); Option inputOpt = OptionBuilder.create(IN); inputOpt.setArgName("INPUT"); inputOpt.setDescription("Input CDO resource directory"); inputOpt.setArgs(1);//from w w w .ja va2s .c o m inputOpt.setRequired(true); Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS); inClassOpt.setArgName("CLASS"); inClassOpt.setDescription("FQN of EPackage implementation class"); inClassOpt.setArgs(1); inClassOpt.setRequired(true); Option repoOpt = OptionBuilder.create(REPO_NAME); repoOpt.setArgName("REPO_NAME"); repoOpt.setDescription("CDO Repository name"); repoOpt.setArgs(1); repoOpt.setRequired(true); options.addOption(inputOpt); options.addOption(inClassOpt); options.addOption(repoOpt); CommandLineParser parser = new PosixParser(); try { CommandLine commandLine = parser.parse(options, args); String repositoryDir = commandLine.getOptionValue(IN); String repositoryName = commandLine.getOptionValue(REPO_NAME); Class<?> inClazz = CdoQueryRenameAllMethods.class.getClassLoader() .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS)); inClazz.getMethod("init").invoke(null); EmbeddedCDOServer server = new EmbeddedCDOServer(repositoryDir, repositoryName); try { server.run(); CDOSession session = server.openSession(); ((CDONet4jSession) session).options().setCommitTimeout(50 * 1000); CDOTransaction transaction = session.openTransaction(); Resource resource = transaction.getRootResource(); String name = UUID.randomUUID().toString(); { LOG.log(Level.INFO, "Start query"); long begin = System.currentTimeMillis(); JavaQueries.renameAllMethods(resource, name); long end = System.currentTimeMillis(); transaction.commit(); LOG.log(Level.INFO, "End query"); LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin))); } // { // transaction.close(); // session.close(); // // session = server.openSession(); // transaction = session.openTransaction(); // resource = transaction.getRootResource(); // // EList<? extends EObject> methodList = JavaQueries.getAllInstances(resource, JavaPackage.eINSTANCE.getMethodDeclaration()); // int i = 0; // for (EObject eObject: methodList) { // MethodDeclaration method = (MethodDeclaration) eObject; // if (name.equals(method.getName())) { // i++; // } // } // LOG.log(Level.INFO, MessageFormat.format("Renamed {0} methods", i)); // } transaction.close(); session.close(); } finally { server.stop(); } } catch (ParseException e) { MessageUtil.showError(e.toString()); MessageUtil.showError("Current arguments: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar <this-file.jar>", options, true); } catch (Throwable e) { MessageUtil.showError(e.toString()); } }