input
stringlengths
20
285k
output
stringlengths
20
285k
public void write(Type type, Object obj, String key) { if (obj != null) { type = type.getSchema().type(obj.getClass()); } writeThis(type, obj, key); if (type instanceof ComplexType) { ComplexType complex; String childKey; Collection<?> children; int idx; complex = (ComplexType) type; for (Item item : complex.items()) { children = item.get(obj); idx = 0; for (Object child : children) { childKey = join(key, IO.toExternal(item.getName())); if (item.getCardinality() == Cardinality.SEQUENCE) { childKey = childKey + "[" + Integer.toString(idx++) + "]"; } write(item.getType(), child, childKey); } } } }
public void write(Type type, Object obj, String key) { if (obj != null) { if (type instanceof SimpleType) { } else { type = type.getSchema().type(obj.getClass()); } } writeThis(type, obj, key); if (type instanceof ComplexType) { ComplexType complex; String childKey; Collection<?> children; int idx; complex = (ComplexType) type; for (Item item : complex.items()) { children = item.get(obj); idx = 0; for (Object child : children) { childKey = join(key, IO.toExternal(item.getName())); if (item.getCardinality() == Cardinality.SEQUENCE) { childKey = childKey + "[" + Integer.toString(idx++) + "]"; } write(item.getType(), child, childKey); } } } }
public static void main(String[] args) { try { ConfigManager context = ConfigManager.getInstance(); String server = MetaData.get(context.getPropertyValue("meta") + context.getPropertyValue("hostname")); String ip = MetaData.get(context.getPropertyValue("meta") + context.getPropertyValue("ip")); System.setProperty("java.rmi.server.hostname", ip); System.setProperty("java.net.preferIPv4Stack", "true"); printMessage(server + " " + ip); int port = Integer.parseInt(context.getPropertyValue("port")); printMessage(String.valueOf(port)); Registry registry = LocateRegistry.createRegistry(port); registry.rebind(IAuthentication.class.getSimpleName(), new Authenticator()); printMessage(IAuthentication.class.getSimpleName()); DataAccess.init(context.getPropertyValue("dbConnection"), context.getPropertyValue("dbUserId"), context.getPropertyValue("dbUserToken")); System.out.println("Server started"); } catch (RemoteException ex) { Logger.getLogger(DBoxBroker.class.getName()).log(Level.SEVERE, null, ex); } }
public static void main(String[] args) { try { ConfigManager context = ConfigManager.getInstance(); String server = MetaData.get(context.getPropertyValue("meta") + context.getPropertyValue("host")); String ip = MetaData.get(context.getPropertyValue("meta") + context.getPropertyValue("ip")); System.setProperty("java.rmi.server.hostname", ip); System.setProperty("java.net.preferIPv4Stack", "true"); printMessage(server + " " + ip); int port = Integer.parseInt(context.getPropertyValue("port")); printMessage(String.valueOf(port)); Registry registry = LocateRegistry.createRegistry(port); registry.rebind(IAuthentication.class.getSimpleName(), new Authenticator()); printMessage(IAuthentication.class.getSimpleName()); DataAccess.init(context.getPropertyValue("dbConnection"), context.getPropertyValue("dbUserId"), context.getPropertyValue("dbUserToken")); System.out.println("Server started"); } catch (RemoteException ex) { Logger.getLogger(DBoxBroker.class.getName()).log(Level.SEVERE, null, ex); } }
public Map<String, Object> generateConfig(HtmlTable table) { logger.debug("Generating DataTables configuration .."); Map<String, Object> mainConf = new HashMap<String, Object>(); Map<String, Object> tmp = null; List<Map<String, Object>> aoColumnsContent = new ArrayList<Map<String, Object>>(); for (HtmlColumn column : table.getLastHeaderRow().getColumns()) { if(column.getEnabledDisplayTypes().contains(DisplayType.HTML)){ tmp = new HashMap<String, Object>(); tmp.put(DTConstants.DT_SORTABLE, column.isSortable()); tmp.put(DTConstants.DT_SEARCHABLE, column.getSearchable()); if (StringUtils.isNotBlank(column.getProperty())) { tmp.put(DTConstants.DT_DATA, column.getProperty()); } if (StringUtils.isNotBlank(column.getRenderFunction())) { tmp.put(DTConstants.DT_COLUMN_RENDERER, new JavascriptSnippet(column.getRenderFunction())); } if(column.getDefaultValue() != null){ tmp.put(DTConstants.DT_S_DEFAULT_CONTENT, column.getDefaultValue()); } if (StringUtils.isNotBlank(column.getSortDirection())) { List<Object> sortDirection = new ArrayList<Object>(); Collections.addAll(sortDirection, column.getSortDirection().trim().toLowerCase().split(",")); tmp.put(DTConstants.DT_SORT_DIR, sortDirection); } aoColumnsContent.add(tmp); } } mainConf.put(DTConstants.DT_AOCOLUMNS, aoColumnsContent); List<Object> aaSortingtmp = null; List<Object> aaSortingContent = new ArrayList<Object>(); Integer columnIndex = 0; for (HtmlColumn column : table.getLastHeaderRow().getColumns()) { if (StringUtils.isNotBlank(column.getSortInit())) { aaSortingtmp = new ArrayList<Object>(); aaSortingtmp.add(columnIndex); aaSortingtmp.add(column.getSortInit()); aaSortingContent.add(aaSortingtmp); } columnIndex++; } if (!aaSortingContent.isEmpty()) { mainConf.put(DTConstants.DT_SORT_INIT, aaSortingContent); } if (table.getLabels() != null) { tmp = new HashMap<String, Object>(); tmp.put(DTConstants.DT_URL, table.getLabels()); mainConf.put(DTConstants.DT_LANGUAGE, tmp); } if (table.getAutoWidth() != null) { mainConf.put(DTConstants.DT_AUTO_WIDTH, table.getAutoWidth()); } if (table.getDeferRender() != null) { mainConf.put(DTConstants.DT_DEFER_RENDER, table.getDeferRender()); } if (table.getFilterable() != null) { mainConf.put(DTConstants.DT_FILTER, table.getFilterable()); } if (table.getInfo() != null) { mainConf.put(DTConstants.DT_INFO, table.getInfo()); } if (table.getPaginate() != null) { mainConf.put(DTConstants.DT_PAGINATE, table.getPaginate()); } if (table.getLengthChange() != null) { mainConf.put(DTConstants.DT_LENGTH_CHANGE, table.getLengthChange()); } if (table.getPaginationType() != null) { mainConf.put(DTConstants.DT_PAGINATION_TYPE, table.getPaginationType().toString()); } if (table.getSort() != null) { mainConf.put(DTConstants.DT_SORT, table.getSort()); } if (table.getStateSave() != null) { mainConf.put(DTConstants.DT_STATE_SAVE, table.getStateSave()); } if (table.getJqueryUI() != null) { mainConf.put(DTConstants.DT_JQUERYUI, table.getJqueryUI()); } if(StringUtils.isNotBlank(table.getLengthMenu())){ mainConf.put(DTConstants.DT_A_LENGTH_MENU, new JavascriptSnippet(table.getLengthMenu())); } if(StringUtils.isNotBlank(table.getStripeClasses())){ mainConf.put(DTConstants.DT_AS_STRIPE_CLASSES, new JavascriptSnippet(table.getStripeClasses())); } if (table.getProcessing() != null) { mainConf.put(DTConstants.DT_B_PROCESSING, table.getProcessing()); } if(table.getServerSide() != null){ mainConf.put(DTConstants.DT_B_SERVER_SIDE, table.getServerSide()); if(StringUtils.isNotBlank(table.getDatasourceUrl())){ mainConf.put(DTConstants.DT_S_AJAX_SOURCE, table.getDatasourceUrl()); } if(StringUtils.isNotBlank(table.getServerData())){ mainConf.put(DTConstants.DT_FN_SERVERDATA, new JavascriptSnippet(table.getServerData())); } if(StringUtils.isNotBlank(table.getServerParam())){ mainConf.put(DTConstants.DT_FN_SERVERPARAMS, new JavascriptSnippet(table.getServerParam())); } if(StringUtils.isNotBlank(table.getServerMethod())){ mainConf.put(DTConstants.DT_S_SERVERMETHOD, new JavascriptSnippet(table.getServerMethod())); } } if(table.getCallbacks() != null){ for(Callback callback : table.getCallbacks()){ mainConf.put(callback.getType().getFunction(), new JavascriptSnippet(callback.getFunction())); } } mainConf.put(DTConstants.DT_DOM, "lfrtip"); logger.debug("DataTables configuration generated"); return mainConf; }
public Map<String, Object> generateConfig(HtmlTable table) { logger.debug("Generating DataTables configuration .."); Map<String, Object> mainConf = new HashMap<String, Object>(); Map<String, Object> tmp = null; List<Map<String, Object>> aoColumnsContent = new ArrayList<Map<String, Object>>(); for (HtmlColumn column : table.getLastHeaderRow().getColumns()) { if(column.getEnabledDisplayTypes().contains(DisplayType.HTML)){ tmp = new HashMap<String, Object>(); tmp.put(DTConstants.DT_SORTABLE, column.isSortable()); tmp.put(DTConstants.DT_SEARCHABLE, column.getSearchable()); if (StringUtils.isNotBlank(column.getProperty())) { tmp.put(DTConstants.DT_DATA, column.getProperty()); } if (StringUtils.isNotBlank(column.getRenderFunction())) { tmp.put(DTConstants.DT_COLUMN_RENDERER, new JavascriptSnippet(column.getRenderFunction())); } if(column.getDefaultValue() != null){ tmp.put(DTConstants.DT_S_DEFAULT_CONTENT, column.getDefaultValue()); } if (StringUtils.isNotBlank(column.getSortDirection())) { List<Object> sortDirection = new ArrayList<Object>(); Collections.addAll(sortDirection, column.getSortDirection().trim().toLowerCase().split(",")); tmp.put(DTConstants.DT_SORT_DIR, sortDirection); } aoColumnsContent.add(tmp); } } mainConf.put(DTConstants.DT_AOCOLUMNS, aoColumnsContent); List<Object> aaSortingtmp = null; List<Object> aaSortingContent = new ArrayList<Object>(); Integer columnIndex = 0; for (HtmlColumn column : table.getLastHeaderRow().getColumns()) { if (StringUtils.isNotBlank(column.getSortInit())) { aaSortingtmp = new ArrayList<Object>(); aaSortingtmp.add(columnIndex); aaSortingtmp.add(column.getSortInit()); aaSortingContent.add(aaSortingtmp); } columnIndex++; } if (!aaSortingContent.isEmpty()) { mainConf.put(DTConstants.DT_SORT_INIT, aaSortingContent); } if (table.getLabels() != null) { tmp = new HashMap<String, Object>(); tmp.put(DTConstants.DT_URL, table.getLabels()); mainConf.put(DTConstants.DT_LANGUAGE, tmp); } if (table.getAutoWidth() != null) { mainConf.put(DTConstants.DT_AUTO_WIDTH, table.getAutoWidth()); } if (table.getDeferRender() != null) { mainConf.put(DTConstants.DT_DEFER_RENDER, table.getDeferRender()); } if (table.getFilterable() != null) { mainConf.put(DTConstants.DT_FILTER, table.getFilterable()); } if (table.getInfo() != null) { mainConf.put(DTConstants.DT_INFO, table.getInfo()); } if (table.getPaginate() != null) { mainConf.put(DTConstants.DT_PAGINATE, table.getPaginate()); } if (table.getLengthChange() != null) { mainConf.put(DTConstants.DT_LENGTH_CHANGE, table.getLengthChange()); } if (table.getPaginationType() != null) { mainConf.put(DTConstants.DT_PAGINATION_TYPE, table.getPaginationType().toString()); } if (table.getSort() != null) { mainConf.put(DTConstants.DT_SORT, table.getSort()); } if (table.getStateSave() != null) { mainConf.put(DTConstants.DT_STATE_SAVE, table.getStateSave()); } if (table.getJqueryUI() != null) { mainConf.put(DTConstants.DT_JQUERYUI, table.getJqueryUI()); } if(StringUtils.isNotBlank(table.getLengthMenu())){ mainConf.put(DTConstants.DT_A_LENGTH_MENU, new JavascriptSnippet(table.getLengthMenu())); } if(StringUtils.isNotBlank(table.getStripeClasses())){ mainConf.put(DTConstants.DT_AS_STRIPE_CLASSES, new JavascriptSnippet(table.getStripeClasses())); } if (table.getProcessing() != null) { mainConf.put(DTConstants.DT_B_PROCESSING, table.getProcessing()); } if(table.getServerSide() != null){ mainConf.put(DTConstants.DT_B_SERVER_SIDE, table.getServerSide()); if(StringUtils.isNotBlank(table.getDatasourceUrl())){ mainConf.put(DTConstants.DT_S_AJAX_SOURCE, table.getDatasourceUrl()); } if(StringUtils.isNotBlank(table.getServerData())){ mainConf.put(DTConstants.DT_FN_SERVERDATA, new JavascriptSnippet(table.getServerData())); } if(StringUtils.isNotBlank(table.getServerParam())){ mainConf.put(DTConstants.DT_FN_SERVERPARAMS, new JavascriptSnippet(table.getServerParam())); } if(StringUtils.isNotBlank(table.getServerMethod())){ mainConf.put(DTConstants.DT_S_SERVERMETHOD, table.getServerMethod()); } } if(table.getCallbacks() != null){ for(Callback callback : table.getCallbacks()){ mainConf.put(callback.getType().getFunction(), new JavascriptSnippet(callback.getFunction())); } } mainConf.put(DTConstants.DT_DOM, "lfrtip"); logger.debug("DataTables configuration generated"); return mainConf; }
public void run() { int originalCount = count; int delay = 0; int total = 0; while(count > 0) { delay = (int) (Math.random() * 3) + 1; total += delay; int millisecondsPerSecond = 1000; try { Thread.sleep(delay * millisecondsPerSecond); } catch (InterruptedException e) { System.err.println("Producer was interrupted."); } count--; producer.produce(); System.out.println("Time to produce was " + delay + " seconds. Parts remaining: " + count); } System.out.println("All done. Average time to produce: " + total / (double) originalCount); }
public void run() { int originalCount = count; int delay = 0; int total = 0; while(count > 0) { delay = (int) (Math.random() * 3) + 1; total += delay; int millisecondsPerSecond = 1000; try { Thread.sleep(delay * millisecondsPerSecond); } catch (InterruptedException e) { System.err.println("Producer was interrupted."); } count--; producer.produce(); System.out.println("Time to produce was " + delay + " seconds. Parts remaining: " + count); } System.out.println("All done. Average time to produce: " + total / (double) originalCount + " seconds."); }
public void getLanguagesToInject(@NotNull MultiHostRegistrar registrar, @NotNull PsiElement context) { if (context.getContainingFile().getViewProvider() instanceof MultiplePsiFilesPerDocumentFileViewProvider) return; final Project project = context.getProject(); if (AngularIndexUtil.resolve(project, AngularDirectivesIndex.INDEX_ID, "ng-model") == null) return; if (context instanceof XmlAttributeValueImpl) { final XmlAttribute attribute = (XmlAttribute)context.getParent(); if (isAngularAttribute(attribute, "ng-init") || isAngularAttribute(attribute, "ng-repeat")) { registrar.startInjecting(AngularJSLanguage.INSTANCE). addPlace(null, null, (PsiLanguageInjectionHost)context, new TextRange(1, context.getTextLength() - 1)). doneInjecting(); return; } } if (context instanceof XmlTextImpl || context instanceof XmlAttributeValueImpl) { final String text = context.getText(); int startIndex; int endIndex = -1; do { startIndex = text.indexOf("{{", endIndex); endIndex = startIndex >= 0 ? text.indexOf("}}", startIndex) : -1; endIndex = endIndex > 0 ? endIndex : text.length(); if (startIndex >= 0) { registrar.startInjecting(AngularJSLanguage.INSTANCE). addPlace(null, null, (PsiLanguageInjectionHost)context, new TextRange(startIndex + 2, endIndex)). doneInjecting(); } } while (startIndex >= 0); } }
public void getLanguagesToInject(@NotNull MultiHostRegistrar registrar, @NotNull PsiElement context) { if (context.getContainingFile().getViewProvider() instanceof MultiplePsiFilesPerDocumentFileViewProvider) return; final Project project = context.getProject(); if (AngularIndexUtil.resolve(project, AngularDirectivesIndex.INDEX_ID, "ng-model") == null) return; final PsiElement parent = context.getParent(); if (context instanceof XmlAttributeValueImpl && parent instanceof XmlAttribute) { final XmlAttribute attribute = (XmlAttribute)parent; if (isAngularAttribute(attribute, "ng-init") || isAngularAttribute(attribute, "ng-repeat")) { registrar.startInjecting(AngularJSLanguage.INSTANCE). addPlace(null, null, (PsiLanguageInjectionHost)context, new TextRange(1, context.getTextLength() - 1)). doneInjecting(); return; } } if (context instanceof XmlTextImpl || context instanceof XmlAttributeValueImpl) { final String text = context.getText(); int startIndex; int endIndex = -1; do { startIndex = text.indexOf("{{", endIndex); endIndex = startIndex >= 0 ? text.indexOf("}}", startIndex) : -1; endIndex = endIndex > 0 ? endIndex : text.length(); if (startIndex >= 0) { registrar.startInjecting(AngularJSLanguage.INSTANCE). addPlace(null, null, (PsiLanguageInjectionHost)context, new TextRange(startIndex + 2, endIndex)). doneInjecting(); } } while (startIndex >= 0); } }
public void save(View view) { SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit(); try { long tbu = Long.parseLong(((EditText) findViewById(R.id.settings_time_between_updates)).getText().toString()); System.out.println("tbu is " + tbu); if(tbu == 0) { System.out.println("Disabling updates."); ((AndroidSession) Session.session).stopUpdater(); editor.putLong(getString(R.string.settings_time_between_updates_key), tbu); } else if(tbu < 60 * 1000) { new AlertDialog.Builder(this).setMessage(R.string.settings_time_between_updates_error_message).show(); return; } else { System.out.println("Updating time between updates."); editor.putLong(getString(R.string.settings_time_between_updates_key), tbu); ((AndroidSession) Session.session).setTimeBetweenUpdates(tbu); } } catch (NumberFormatException e) { System.out.println("FAILZ!"); } boolean disableUpdatesWhenNotOnWifi = ((CheckBox) findViewById(R.id.settings_disable_when_not_on_wifi_cb)).isChecked(); editor.putBoolean(getString(R.string.settings_disable_updates_when_not_on_wifi_key), disableUpdatesWhenNotOnWifi); UpdaterService.shouldUpdateWithoutWifi = !disableUpdatesWhenNotOnWifi; editor.commit(); startActivity(new Intent(this, DebtViewActivity.class)); }
public void save(View view) { SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit(); try { long tbu = Long.parseLong(((EditText) findViewById(R.id.settings_time_between_updates)).getText().toString()); System.out.println("tbu is " + tbu); if(tbu == 0) { System.out.println("Disabling updates."); ((AndroidSession) Session.session).stopUpdater(); editor.putLong(getString(R.string.settings_time_between_updates_key), tbu); } else if(tbu < 60 * 1000) { new AlertDialog.Builder(this).setMessage(R.string.settings_time_between_updates_error_message).show(); return; } else { System.out.println("Updating time between updates."); editor.putLong(getString(R.string.settings_time_between_updates_key), tbu); ((AndroidSession) Session.session).setTimeBetweenUpdates(tbu); ((AndroidSession) Session.session).startUpdater( this, tbu, UpdaterService.shouldUpdateWithoutWifi); } } catch (NumberFormatException e) { System.out.println("FAILZ!"); } boolean disableUpdatesWhenNotOnWifi = ((CheckBox) findViewById(R.id.settings_disable_when_not_on_wifi_cb)).isChecked(); editor.putBoolean(getString(R.string.settings_disable_updates_when_not_on_wifi_key), disableUpdatesWhenNotOnWifi); UpdaterService.shouldUpdateWithoutWifi = !disableUpdatesWhenNotOnWifi; editor.commit(); startActivity(new Intent(this, DebtViewActivity.class)); }
public void bootstrapEc2CloudTest() throws Exception { for (int i = 0; i < NUM_OF_MANAGEMENT_MACHINES; i++) { assertWebServiceAvailable(new URL( restAdminUrl[i].toString() + "/service/testrest")); assertWebServiceAvailable(webUIUrl[i]); } String connectCommand = "connect " + restAdminUrl[0].toString() + ";"; URL machinesURL = getMachinesUrl(restAdminUrl[0].toString()); assertEquals("Expecting " + NUM_OF_MANAGEMENT_MACHINES + " machines", NUM_OF_MANAGEMENT_MACHINES, getNumberOfMachines(machinesURL)); String installCommand = new StringBuilder() .append("install-application ") .append("--verbose ") .append("-timeout ") .append(TimeUnit.MILLISECONDS.toMinutes(DEFAULT_TEST_TIMEOUT * 2)).append(" ") .append((new File(ScriptUtils.getBuildPath(), "examples/travel").toString()).replace('\\', '/')) .toString(); String output = CommandTestUtils.runCommandAndWait(connectCommand + installCommand); Assert.assertTrue(output.contains(INSTALL_TRAVEL_EXPECTED_OUTPUT)); assertEquals("Expecting " + (NUM_OF_MANAGEMENT_MACHINES+2) + " machines", NUM_OF_MANAGEMENT_MACHINES+2, getNumberOfMachines(machinesURL)); String uninstallCommand = "uninstall-application --verbose travel"; output = CommandTestUtils.runCommandAndWait(connectCommand + uninstallCommand); Assert.assertTrue(output.contains(UNINSTALL_TRAVEL_EXPECTED_OUTPUT)); }
public void bootstrapEc2CloudTest() throws Exception { for (int i = 0; i < NUM_OF_MANAGEMENT_MACHINES; i++) { assertWebServiceAvailable(new URL( restAdminUrl[i].toString() + "/service/testrest")); assertWebServiceAvailable(webUIUrl[i]); } String connectCommand = "connect " + restAdminUrl[0].toString() + ";"; URL machinesURL = getMachinesUrl(restAdminUrl[0].toString()); assertEquals("Expecting " + NUM_OF_MANAGEMENT_MACHINES + " machines", NUM_OF_MANAGEMENT_MACHINES, getNumberOfMachines(machinesURL)); String installCommand = new StringBuilder() .append("install-application ") .append("--verbose ") .append("-timeout ") .append(TimeUnit.MILLISECONDS.toMinutes(DEFAULT_TEST_TIMEOUT * 2)).append(" ") .append((new File(ScriptUtils.getBuildPath(), "recipes/apps/travel").toString()).replace('\\', '/')) .toString(); String output = CommandTestUtils.runCommandAndWait(connectCommand + installCommand); Assert.assertTrue(output.contains(INSTALL_TRAVEL_EXPECTED_OUTPUT)); assertEquals("Expecting " + (NUM_OF_MANAGEMENT_MACHINES+2) + " machines", NUM_OF_MANAGEMENT_MACHINES+2, getNumberOfMachines(machinesURL)); String uninstallCommand = "uninstall-application --verbose travel"; output = CommandTestUtils.runCommandAndWait(connectCommand + uninstallCommand); Assert.assertTrue(output.contains(UNINSTALL_TRAVEL_EXPECTED_OUTPUT)); }
private boolean setCacheThroughAll(int place, long availableMemory) { int availableIntMemory = (int) Math.min(availableMemory, Integer.MAX_VALUE); long currentMajorChild = majorHasher.nextChild(' ', 'P', place); int availableMajor = (int) (db.recordsForBytes(availableIntMemory) / minorHasher .numHashesForTier()); if (availableMajor == 0) return false; else { int addMajor = availableMajor * 2; long lastMajorChild; long majorHash = majorHasher.getHash(); do { majorHasher.unhash(majorHash + addMajor - 1); lastMajorChild = majorHasher.previousChild(' ', 'P', place); addMajor /= 2; } while (lastMajorChild - currentMajorChild + 1 > availableMajor); majorHasher.unhash(majorHash); setCacheMajorRange(lowerCache[place], place, currentMajorChild, (int) (lastMajorChild - currentMajorChild + 1), availableIntMemory); return true; } }
private boolean setCacheThroughAll(int place, long availableMemory) { int availableIntMemory = (int) Math.min(availableMemory, Integer.MAX_VALUE); long currentMajorChild = majorHasher.nextChild(' ', 'P', place); int availableMajor = (int) (db.recordsForBytes(availableIntMemory) / minorHasher .numHashesForTier()); if (availableMajor == 0) return false; else { int addMajor = availableMajor * 2; long lastMajorChild; long majorHash = majorHasher.getHash(); long remainingMajor = majorHasher.numHashes() - majorHash; addMajor = (int) Math.min(addMajor, remainingMajor); do { majorHasher.unhash(majorHash + addMajor - 1); lastMajorChild = majorHasher.previousChild(' ', 'P', place); addMajor /= 2; } while (lastMajorChild - currentMajorChild + 1 > availableMajor); majorHasher.unhash(majorHash); setCacheMajorRange(lowerCache[place], place, currentMajorChild, (int) (lastMajorChild - currentMajorChild + 1), availableIntMemory); return true; } }
private static Map loadAdviceMap(IPath basePath, IPath adviceFilePath) { File location = basePath.toFile(); if (location == null || !location.exists()) return Collections.EMPTY_MAP; ZipFile jar = null; InputStream stream = null; try { if (location.isDirectory()) { File adviceFile = new File(location, adviceFilePath.toString()); stream = new BufferedInputStream(new FileInputStream(adviceFile)); } else if (location.isFile()) { jar = new ZipFile(location); ZipEntry entry = jar.getEntry(adviceFilePath.toString()); if (entry == null) return Collections.EMPTY_MAP; stream = new BufferedInputStream(jar.getInputStream(entry)); } Properties advice = new Properties(); advice.load(stream); return (advice != null ? advice : Collections.EMPTY_MAP); } catch (IOException e) { String message = "An error occured while reading advice file: basePath=" + basePath + ", adviceFilePath=" + adviceFilePath + "."; IStatus status = new Status(IStatus.ERROR, Activator.ID, message, e); LogHelper.log(status); return Collections.EMPTY_MAP; } finally { if (stream != null) try { stream.close(); } catch (IOException e) { } if (jar != null) try { jar.close(); } catch (IOException e) { } } }
private static Map loadAdviceMap(IPath basePath, IPath adviceFilePath) { File location = basePath.toFile(); if (location == null || !location.exists()) return Collections.EMPTY_MAP; ZipFile jar = null; InputStream stream = null; try { if (location.isDirectory()) { File adviceFile = new File(location, adviceFilePath.toString()); if (!adviceFile.isFile()) return Collections.EMPTY_MAP; stream = new BufferedInputStream(new FileInputStream(adviceFile)); } else if (location.isFile()) { jar = new ZipFile(location); ZipEntry entry = jar.getEntry(adviceFilePath.toString()); if (entry == null) return Collections.EMPTY_MAP; stream = new BufferedInputStream(jar.getInputStream(entry)); } Properties advice = new Properties(); advice.load(stream); return (advice != null ? advice : Collections.EMPTY_MAP); } catch (IOException e) { String message = "An error occured while reading advice file: basePath=" + basePath + ", adviceFilePath=" + adviceFilePath + "."; IStatus status = new Status(IStatus.ERROR, Activator.ID, message, e); LogHelper.log(status); return Collections.EMPTY_MAP; } finally { if (stream != null) try { stream.close(); } catch (IOException e) { } if (jar != null) try { jar.close(); } catch (IOException e) { } } }
public static ActionDefinition reverse(String action, Map<String, Object> args) { if (action.startsWith("controllers.")) { action = action.substring(12); } Map<String, Object> argsbackup = args; if (Scope.RouteArgs.current() != null) { argsbackup.putAll(Scope.RouteArgs.current().data); } for (Route route : routes) { args = new HashMap<String, Object>(argsbackup); if (route.actionPattern != null) { Matcher matcher = route.actionPattern.matcher(action); if (matcher.matches()) { for (String group : route.actionArgs) { String v = matcher.group(group); if (v == null) { continue; } args.put(group, v.toLowerCase()); } List<String> inPathArgs = new ArrayList<String>(16); boolean allRequiredArgsAreHere = true; for (Route.Arg arg : route.args) { inPathArgs.add(arg.name); Object value = args.get(arg.name); if (value == null) { String host = route.host.replaceAll("\\{", "").replaceAll("\\}", ""); if (host.equals(arg.name) || host.matches(arg.name)) { args.remove(arg.name); route.host = Http.Request.current().domain; break; } else { allRequiredArgsAreHere = false; break; } } else { if (value instanceof List<?>) { @SuppressWarnings("unchecked") List<Object> l = (List<Object>) value; value = l.get(0); } if (!value.toString().startsWith(":") && !arg.constraint.matches(value.toString())) { allRequiredArgsAreHere = false; break; } } } for (String staticKey : route.staticArgs.keySet()) { if (staticKey.equals("format")) { if (!Http.Request.current().format.equals(route.staticArgs.get("format"))) { allRequiredArgsAreHere = false; break; } continue; } if (!args.containsKey(staticKey) || (args.get(staticKey) == null) || !args.get(staticKey).toString().equals(route.staticArgs.get(staticKey))) { allRequiredArgsAreHere = false; break; } } if (allRequiredArgsAreHere) { StringBuilder queryString = new StringBuilder(); String path = route.path; String host = route.host; if (path.endsWith("/?")) { path = path.substring(0, path.length() - 2); } for (Map.Entry<String, Object> entry : args.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (inPathArgs.contains(key) && value != null) { if (List.class.isAssignableFrom(value.getClass())) { @SuppressWarnings("unchecked") List<Object> vals = (List<Object>) value; try { path = path.replaceAll("\\{(<[^>]+>)?" + key + "\\}", URLEncoder.encode(vals.get(0).toString().replace("$", "\\$"), "utf-8")); } catch(UnsupportedEncodingException e) { throw new UnexpectedException(e); } } else { try { path = path.replaceAll("\\{(<[^>]+>)?" + key + "\\}", URLEncoder.encode(value.toString().replace("$", "\\$"), "utf-8")); host = host.replaceAll("\\{(<[^>]+>)?" + key + "\\}", URLEncoder.encode(value.toString().replace("$", "\\$"), "utf-8")); } catch(UnsupportedEncodingException e) { throw new UnexpectedException(e); } } } else if (route.staticArgs.containsKey(key)) { } else if (value != null) { if (List.class.isAssignableFrom(value.getClass())) { @SuppressWarnings("unchecked") List<Object> vals = (List<Object>) value; for (Object object : vals) { try { queryString.append(URLEncoder.encode(key, "utf-8")); queryString.append("="); if (object.toString().startsWith(":")) { queryString.append(object.toString()); } else { queryString.append(URLEncoder.encode(object.toString() + "", "utf-8")); } queryString.append("&"); } catch (UnsupportedEncodingException ex) { } } } else if (value.getClass().equals(Default.class)) { } else { try { queryString.append(URLEncoder.encode(key, "utf-8")); queryString.append("="); if (value.toString().startsWith(":")) { queryString.append(value.toString()); } else { queryString.append(URLEncoder.encode(value.toString() + "", "utf-8")); } queryString.append("&"); } catch (UnsupportedEncodingException ex) { } } } } String qs = queryString.toString(); if (qs.endsWith("&")) { qs = qs.substring(0, qs.length() - 1); } ActionDefinition actionDefinition = new ActionDefinition(); actionDefinition.url = qs.length() == 0 ? path : path + "?" + qs; actionDefinition.method = route.method == null || route.method.equals("*") ? "GET" : route.method.toUpperCase(); actionDefinition.star = "*".equals(route.method); actionDefinition.action = action; actionDefinition.args = args; actionDefinition.host = host; return actionDefinition; } } } } throw new NoRouteFoundException(action, args); }
public static ActionDefinition reverse(String action, Map<String, Object> args) { if (action.startsWith("controllers.")) { action = action.substring(12); } Map<String, Object> argsbackup = args; if (Scope.RouteArgs.current() != null) { argsbackup.putAll(Scope.RouteArgs.current().data); } for (Route route : routes) { args = new HashMap<String, Object>(argsbackup); if (route.actionPattern != null) { Matcher matcher = route.actionPattern.matcher(action); if (matcher.matches()) { for (String group : route.actionArgs) { String v = matcher.group(group); if (v == null) { continue; } args.put(group, v.toLowerCase()); } List<String> inPathArgs = new ArrayList<String>(16); boolean allRequiredArgsAreHere = true; for (Route.Arg arg : route.args) { inPathArgs.add(arg.name); Object value = args.get(arg.name); if (value == null) { String host = route.host.replaceAll("\\{", "").replaceAll("\\}", ""); if (host.equals(arg.name) || host.matches(arg.name)) { args.remove(arg.name); route.host = Http.Request.current().domain; break; } else { allRequiredArgsAreHere = false; break; } } else { if (value instanceof List<?>) { @SuppressWarnings("unchecked") List<Object> l = (List<Object>) value; value = l.get(0); } if (!value.toString().startsWith(":") && !arg.constraint.matches(value.toString())) { allRequiredArgsAreHere = false; break; } } } for (String staticKey : route.staticArgs.keySet()) { if (staticKey.equals("format")) { if (!Http.Request.current().format.equals(route.staticArgs.get("format"))) { allRequiredArgsAreHere = false; break; } continue; } if (!args.containsKey(staticKey) || (args.get(staticKey) == null) || !args.get(staticKey).toString().equals(route.staticArgs.get(staticKey))) { allRequiredArgsAreHere = false; break; } } if (allRequiredArgsAreHere) { StringBuilder queryString = new StringBuilder(); String path = route.path; String host = route.host; if (path.endsWith("/?")) { path = path.substring(0, path.length() - 2); } for (Map.Entry<String, Object> entry : args.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (inPathArgs.contains(key) && value != null) { if (List.class.isAssignableFrom(value.getClass())) { @SuppressWarnings("unchecked") List<Object> vals = (List<Object>) value; try { path = path.replaceAll("\\{(<[^>]+>)?" + key + "\\}", URLEncoder.encode(vals.get(0).toString().replace("$", "\\$"), "utf-8")); } catch(UnsupportedEncodingException e) { throw new UnexpectedException(e); } } else { try { path = path.replaceAll("\\{(<[^>]+>)?" + key + "\\}", URLEncoder.encode(value.toString().replace("$", "\\$"), "utf-8").replace("%3A", ":").replace("%40", "@")); host = host.replaceAll("\\{(<[^>]+>)?" + key + "\\}", URLEncoder.encode(value.toString().replace("$", "\\$"), "utf-8").replace("%3A", ":").replace("%40", "@")); } catch(UnsupportedEncodingException e) { throw new UnexpectedException(e); } } } else if (route.staticArgs.containsKey(key)) { } else if (value != null) { if (List.class.isAssignableFrom(value.getClass())) { @SuppressWarnings("unchecked") List<Object> vals = (List<Object>) value; for (Object object : vals) { try { queryString.append(URLEncoder.encode(key, "utf-8")); queryString.append("="); if (object.toString().startsWith(":")) { queryString.append(object.toString()); } else { queryString.append(URLEncoder.encode(object.toString() + "", "utf-8")); } queryString.append("&"); } catch (UnsupportedEncodingException ex) { } } } else if (value.getClass().equals(Default.class)) { } else { try { queryString.append(URLEncoder.encode(key, "utf-8")); queryString.append("="); if (value.toString().startsWith(":")) { queryString.append(value.toString()); } else { queryString.append(URLEncoder.encode(value.toString() + "", "utf-8")); } queryString.append("&"); } catch (UnsupportedEncodingException ex) { } } } } String qs = queryString.toString(); if (qs.endsWith("&")) { qs = qs.substring(0, qs.length() - 1); } ActionDefinition actionDefinition = new ActionDefinition(); actionDefinition.url = qs.length() == 0 ? path : path + "?" + qs; actionDefinition.method = route.method == null || route.method.equals("*") ? "GET" : route.method.toUpperCase(); actionDefinition.star = "*".equals(route.method); actionDefinition.action = action; actionDefinition.args = args; actionDefinition.host = host; return actionDefinition; } } } } throw new NoRouteFoundException(action, args); }
public boolean run(String[] args) { Mine curMine; if(args.length == 1) curMine = PrisonMine.getCurMine(); else if(args[1].equalsIgnoreCase("all")) { boolean success = true; for(Mine mine : PrisonMine.getMines()) { if(!MineCommand.RESET.run(mine.getName())) success = false; } return success; } else curMine = Mine.get(args[1]); if(curMine == null) { if(args.length == 1) getHelp(); return false; } Message.debug("Resetting mine: " + curMine.getId()); boolean automatic; if(CommandManager.getSender() == null) { automatic = true; Message.debug("Automatic reset!"); } else { automatic = false; Message.debug("Manual reset!"); } if(!automatic) { if(!Util.hasPermission("mcprison.mine.reset.manual." + curMine.getId()) && !Util.hasPermission("mcprison.mine.reset.manual")) { Message.sendError(PrisonMine.getLanguage().ERROR_ACCESS); return false; } if(curMine.getCooldown() && curMine.getCooldownEndsIn() > 0 && !Util.hasPermission("mcprison.mine.bypass.cooldown")) { Message.sendError(Util.parseVars(PrisonMine.getLanguage().RESET_COOLDOWN, curMine)); return false; } } String forcedGenerator = ""; if(args.length == 3) forcedGenerator = args[2]; String generator = curMine.getGenerator(); if(forcedGenerator.equals("")) generator = curMine.getGenerator(); if(curMine.getCooldown()) curMine.resetCooldown(); if(!(curMine.reset(generator))) return false; String broadcastMessage; if(automatic) { for(Mine childMine : curMine.getChildren()) { MineCommand.RESET.run(childMine.getId()); } if(curMine.getResetsIn() <= 0) broadcastMessage = PrisonMine.getLanguage().RESET_TIMED; else if(curMine.getPercent() <= curMine.getCompositionPercent()) broadcastMessage = PrisonMine.getLanguage().RESET_COMPOSITION; else broadcastMessage = PrisonMine.getLanguage().RESET_AUTOMATIC; } else broadcastMessage = PrisonMine.getLanguage().RESET_MANUAL; if(curMine.getParent() == null) { broadcastMessage = Util.parseVars(broadcastMessage, curMine); if(!curMine.getSilent()) Message.broadcast(broadcastMessage); else if(!automatic) Message.sendSuccess(broadcastMessage); } curMine.recountBlocks(); return true; }
public boolean run(String[] args) { Mine curMine; if(args.length == 1) curMine = PrisonMine.getCurMine(); else if(args[1].equalsIgnoreCase("all")) { boolean success = true; for(Mine mine : PrisonMine.getMines()) { if(!MineCommand.RESET.run(mine.getName())) success = false; } return success; } else curMine = Mine.get(args[1]); if(curMine == null) { if(args.length == 1) getHelp(); return false; } Message.debug("Resetting mine: " + curMine.getId()); boolean automatic; if(CommandManager.getSender() == null) { automatic = true; Message.debug("Automatic reset!"); } else { automatic = false; Message.debug("Manual reset!"); } if(!automatic) { if(!Util.hasPermission("mcprison.mine.reset.manual." + curMine.getId()) && !Util.hasPermission("mcprison.mine.reset.manual")) { Message.sendError(PrisonMine.getLanguage().ERROR_ACCESS); return false; } if(curMine.getCooldown() && curMine.getCooldownEndsIn() > 0 && !Util.hasPermission("mcprison.mine.bypass.cooldown")) { Message.sendError(Util.parseVars(PrisonMine.getLanguage().RESET_COOLDOWN, curMine)); return false; } } String forcedGenerator = ""; if(args.length == 3) forcedGenerator = args[2]; String generator = curMine.getGenerator(); if(forcedGenerator.equals("")) generator = curMine.getGenerator(); if(curMine.getCooldown()) curMine.resetCooldown(); if(!(curMine.reset(generator))) return false; String broadcastMessage; if(automatic) { for(Mine childMine : curMine.getChildren()) { MineCommand.RESET.run(childMine.getId()); } if(curMine.getAutomaticReset() && curMine.getResetsIn() <= 0) broadcastMessage = PrisonMine.getLanguage().RESET_TIMED; else if(curMine.getCompositionReset() && curMine.getPercent() <= curMine.getCompositionPercent()) broadcastMessage = PrisonMine.getLanguage().RESET_COMPOSITION; else broadcastMessage = PrisonMine.getLanguage().RESET_AUTOMATIC; } else broadcastMessage = PrisonMine.getLanguage().RESET_MANUAL; if(curMine.getParent() == null) { broadcastMessage = Util.parseVars(broadcastMessage, curMine); if(!curMine.getSilent()) Message.broadcast(broadcastMessage); else if(!automatic) Message.sendSuccess(broadcastMessage); } curMine.recountBlocks(); return true; }
public void start(BundleContext context) throws Exception { super.start(context); try { WorkspaceAwareContextStore contextStore = new WorkspaceAwareContextStore(); contextStore.init(); ContextCorePlugin.setContextStore(contextStore); WebClientUtil.initCommonsLoggingSettings(); initializeDefaultPreferences(getPreferenceStore()); taskListWriter = new TaskListWriter(); File dataDir = new File(getDataDirectory()); dataDir.mkdirs(); String path = getDataDirectory() + File.separator + ITasksUiConstants.DEFAULT_TASK_LIST_FILE; File taskListFile = new File(path); taskListManager = new TaskListManager(taskListWriter, taskListFile); taskRepositoryManager = new TaskRepositoryManager(taskListManager.getTaskList()); synchronizationManager = new RepositorySynchronizationManager(); TasksUiExtensionReader.initStartupExtensions(taskListWriter); taskRepositoryManager.readRepositories(getRepositoriesFilePath()); for(AbstractRepositoryConnector connector: taskRepositoryManager.getRepositoryConnectors()){ for(RepositoryTemplate template: connector.getTemplates()){ if(template.addAutomatically){ TaskRepository taskRepository = taskRepositoryManager.getRepository(connector.getRepositoryType(), template.repositoryUrl); if(taskRepository == null){ taskRepository = new TaskRepository(connector.getRepositoryType(), template.repositoryUrl, template.version); taskRepositoryManager.addRepository(taskRepository, getRepositoriesFilePath()); } } } } readOfflineReports(); for (ITaskListExternalizer externalizer : taskListWriter.getExternalizers()) { if (externalizer instanceof DelegatingTaskExternalizer) { ((DelegatingTaskExternalizer) externalizer).init(offlineTaskManager); } } taskListWriter.setTaskDataManager(offlineTaskManager); taskListManager.init(); taskListManager.addActivityListener(CONTEXT_TASK_ACTIVITY_LISTENER); taskListManager.readExistingOrCreateNewList(); initialized = true; PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { try { TasksUiExtensionReader.initWorkbenchUiExtensions(); PlatformUI.getWorkbench().addWindowListener(WINDOW_LISTENER); if (taskListManager.getTaskList().getActiveTask() != null) { taskListManager.activateTask(taskListManager.getTaskList().getActiveTask()); } taskListManager.initActivityHistory(); taskListNotificationManager = new TaskListNotificationManager(); taskListNotificationManager.addNotificationProvider(REMINDER_NOTIFICATION_PROVIDER); taskListNotificationManager.addNotificationProvider(INCOMING_NOTIFICATION_PROVIDER); taskListNotificationManager.startNotification(NOTIFICATION_DELAY); getPreferenceStore().addPropertyChangeListener(taskListNotificationManager); taskListBackupManager = new TaskListBackupManager(); getPreferenceStore().addPropertyChangeListener(taskListBackupManager); synchronizationScheduler = new TaskListSynchronizationScheduler(true); synchronizationScheduler.startSynchJob(); taskListSaveManager = new TaskListSaveManager(); taskListManager.setTaskListSaveManager(taskListSaveManager); ContextCorePlugin.getDefault().getPluginPreferences().addPropertyChangeListener( PREFERENCE_LISTENER); getPreferenceStore().addPropertyChangeListener(PROPERTY_LISTENER); getPreferenceStore().addPropertyChangeListener(synchronizationScheduler); getPreferenceStore().addPropertyChangeListener(taskListManager); TaskRepositoriesView repositoriesView = TaskRepositoriesView.getFromActivePerspective(); if (repositoriesView != null) { repositoriesView.getViewer().refresh(); } } catch (Exception e) { MylarStatusHandler.fail(e, "Mylar Tasks UI start failed", false); } } }); Bundle bundle = Platform.getBundle("org.eclipse.ui.workbench"); if (bundle.getLocation().contains("_3.3.")) { eclipse_3_3_workbench = true; } } catch (Exception e) { e.printStackTrace(); MylarStatusHandler.fail(e, "Mylar Task List initialization failed", false); } }
public void start(BundleContext context) throws Exception { super.start(context); try { WorkspaceAwareContextStore contextStore = new WorkspaceAwareContextStore(); contextStore.init(); ContextCorePlugin.setContextStore(contextStore); WebClientUtil.initCommonsLoggingSettings(); initializeDefaultPreferences(getPreferenceStore()); taskListWriter = new TaskListWriter(); File dataDir = new File(getDataDirectory()); dataDir.mkdirs(); String path = getDataDirectory() + File.separator + ITasksUiConstants.DEFAULT_TASK_LIST_FILE; File taskListFile = new File(path); taskListManager = new TaskListManager(taskListWriter, taskListFile); taskRepositoryManager = new TaskRepositoryManager(taskListManager.getTaskList()); synchronizationManager = new RepositorySynchronizationManager(); TasksUiExtensionReader.initStartupExtensions(taskListWriter); taskRepositoryManager.readRepositories(getRepositoriesFilePath()); for(AbstractRepositoryConnector connector: taskRepositoryManager.getRepositoryConnectors()){ for(RepositoryTemplate template: connector.getTemplates()){ if(template.addAutomatically){ TaskRepository taskRepository = taskRepositoryManager.getRepository(connector.getRepositoryType(), template.repositoryUrl); if(taskRepository == null){ taskRepository = new TaskRepository(connector.getRepositoryType(), template.repositoryUrl, template.version); taskRepository.setRepositoryLabel(template.label); taskRepositoryManager.addRepository(taskRepository, getRepositoriesFilePath()); } } } } readOfflineReports(); for (ITaskListExternalizer externalizer : taskListWriter.getExternalizers()) { if (externalizer instanceof DelegatingTaskExternalizer) { ((DelegatingTaskExternalizer) externalizer).init(offlineTaskManager); } } taskListWriter.setTaskDataManager(offlineTaskManager); taskListManager.init(); taskListManager.addActivityListener(CONTEXT_TASK_ACTIVITY_LISTENER); taskListManager.readExistingOrCreateNewList(); initialized = true; PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { try { TasksUiExtensionReader.initWorkbenchUiExtensions(); PlatformUI.getWorkbench().addWindowListener(WINDOW_LISTENER); if (taskListManager.getTaskList().getActiveTask() != null) { taskListManager.activateTask(taskListManager.getTaskList().getActiveTask()); } taskListManager.initActivityHistory(); taskListNotificationManager = new TaskListNotificationManager(); taskListNotificationManager.addNotificationProvider(REMINDER_NOTIFICATION_PROVIDER); taskListNotificationManager.addNotificationProvider(INCOMING_NOTIFICATION_PROVIDER); taskListNotificationManager.startNotification(NOTIFICATION_DELAY); getPreferenceStore().addPropertyChangeListener(taskListNotificationManager); taskListBackupManager = new TaskListBackupManager(); getPreferenceStore().addPropertyChangeListener(taskListBackupManager); synchronizationScheduler = new TaskListSynchronizationScheduler(true); synchronizationScheduler.startSynchJob(); taskListSaveManager = new TaskListSaveManager(); taskListManager.setTaskListSaveManager(taskListSaveManager); ContextCorePlugin.getDefault().getPluginPreferences().addPropertyChangeListener( PREFERENCE_LISTENER); getPreferenceStore().addPropertyChangeListener(PROPERTY_LISTENER); getPreferenceStore().addPropertyChangeListener(synchronizationScheduler); getPreferenceStore().addPropertyChangeListener(taskListManager); TaskRepositoriesView repositoriesView = TaskRepositoriesView.getFromActivePerspective(); if (repositoriesView != null) { repositoriesView.getViewer().refresh(); } } catch (Exception e) { MylarStatusHandler.fail(e, "Mylar Tasks UI start failed", false); } } }); Bundle bundle = Platform.getBundle("org.eclipse.ui.workbench"); if (bundle.getLocation().contains("_3.3.")) { eclipse_3_3_workbench = true; } } catch (Exception e) { e.printStackTrace(); MylarStatusHandler.fail(e, "Mylar Task List initialization failed", false); } }
private static HttpRequest construct(AsyncHttpClientConfig config, Request request, HttpMethod m, URI uri, ChannelBuffer buffer) throws IOException { String host = AsyncHttpProviderUtils.getHost(uri); boolean webSocket = isWebSocket(uri); if (request.getVirtualHost() != null) { host = request.getVirtualHost(); } HttpRequest nettyRequest; if (m.equals(HttpMethod.CONNECT)) { nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_0, m, AsyncHttpProviderUtils.getAuthority(uri)); } else { StringBuilder path = null; if (isProxyServer(config, request)) path = new StringBuilder(uri.toString()); else { path = new StringBuilder(uri.getRawPath()); if (uri.getQuery() != null) { path.append("?").append(uri.getRawQuery()); } } nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, path.toString()); } if (webSocket) { nettyRequest.addHeader(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET); nettyRequest.addHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE); nettyRequest.addHeader("Origin", "http://" + uri.getHost() + ":" + (uri.getPort() == -1 ? isSecure(uri.getScheme()) ? 443 : 80 : uri.getPort())); nettyRequest.addHeader(WEBSOCKET_KEY, WebSocketUtil.getKey()); nettyRequest.addHeader("Sec-WebSocket-Version", "13"); } if (host != null) { if (uri.getPort() == -1) { nettyRequest.setHeader(HttpHeaders.Names.HOST, host); } else if (request.getVirtualHost() != null) { nettyRequest.setHeader(HttpHeaders.Names.HOST, host); } else { nettyRequest.setHeader(HttpHeaders.Names.HOST, host + ":" + uri.getPort()); } } else { host = "127.0.0.1"; } if (!m.equals(HttpMethod.CONNECT)) { FluentCaseInsensitiveStringsMap h = request.getHeaders(); if (h != null) { for (String name : h.keySet()) { if (!"host".equalsIgnoreCase(name)) { for (String value : h.get(name)) { nettyRequest.addHeader(name, value); } } } } if (config.isCompressionEnabled()) { nettyRequest.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); } } else { List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION); if (auth != null && auth.size() > 0 && auth.get(0).startsWith("NTLM")) { nettyRequest.addHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, auth.get(0)); } } ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer(); Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm(); if (realm != null && realm.getUsePreemptiveAuth()) { String domain = realm.getNtlmDomain(); if (proxyServer != null && proxyServer.getNtlmDomain() != null) { domain = proxyServer.getNtlmDomain(); } String authHost = realm.getNtlmHost(); if (proxyServer != null && proxyServer.getHost() != null) { host = proxyServer.getHost(); } switch (realm.getAuthScheme()) { case BASIC: nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, AuthenticatorUtils.computeBasicAuthentication(realm)); break; case DIGEST: if (realm.getNonce() != null && !realm.getNonce().equals("")) { try { nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, AuthenticatorUtils.computeDigestAuthentication(realm)); } catch (NoSuchAlgorithmException e) { throw new SecurityException(e); } } break; case NTLM: try { String msg = ntlmEngine.generateType1Msg("NTLM " + domain, authHost); nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, "NTLM " + msg); } catch (NTLMEngineException e) { IOException ie = new IOException(); ie.initCause(e); throw ie; } break; case KERBEROS: case SPNEGO: String challengeHeader = null; String server = proxyServer == null ? host : proxyServer.getHost(); try { challengeHeader = spnegoEngine.generateToken(server); } catch (Throwable e) { IOException ie = new IOException(); ie.initCause(e); throw ie; } nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, "Negotiate " + challengeHeader); break; case NONE: break; default: throw new IllegalStateException(String.format("Invalid Authentication %s", realm.toString())); } } if (!webSocket && !request.getHeaders().containsKey(HttpHeaders.Names.CONNECTION)) { nettyRequest.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive"); } boolean avoidProxy = ProxyUtils.avoidProxy(proxyServer, request); if (!avoidProxy) { if (!request.getHeaders().containsKey("Proxy-Connection")) { nettyRequest.setHeader("Proxy-Connection", "keep-alive"); } if (proxyServer.getPrincipal() != null) { if (proxyServer.getNtlmDomain() != null && proxyServer.getNtlmDomain().length() > 0) { List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION); if (!(auth != null && auth.size() > 0 && auth.get(0).startsWith("NTLM"))) { try { String msg = ntlmEngine.generateType1Msg(proxyServer.getNtlmDomain(), proxyServer.getHost()); nettyRequest.setHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + msg); } catch (NTLMEngineException e) { IOException ie = new IOException(); ie.initCause(e); throw ie; } } } else { nettyRequest.setHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, AuthenticatorUtils.computeBasicAuthentication(proxyServer)); } } } if (request.getHeaders().getFirstValue("Accept") == null) { nettyRequest.setHeader(HttpHeaders.Names.ACCEPT, "*/*"); } if (request.getHeaders().getFirstValue("User-Agent") != null) { nettyRequest.setHeader("User-Agent", request.getHeaders().getFirstValue("User-Agent")); } else if (config.getUserAgent() != null) { nettyRequest.setHeader("User-Agent", config.getUserAgent()); } else { nettyRequest.setHeader("User-Agent", AsyncHttpProviderUtils.constructUserAgent(NettyAsyncHttpProvider.class, config)); } if (!m.equals(HttpMethod.CONNECT)) { if (request.getCookies() != null && !request.getCookies().isEmpty()) { CookieEncoder httpCookieEncoder = new CookieEncoder(false); Iterator<Cookie> ic = request.getCookies().iterator(); Cookie c; org.jboss.netty.handler.codec.http.Cookie cookie; while (ic.hasNext()) { c = ic.next(); cookie = new DefaultCookie(c.getName(), c.getValue()); cookie.setPath(c.getPath()); cookie.setMaxAge(c.getMaxAge()); cookie.setDomain(c.getDomain()); httpCookieEncoder.addCookie(cookie); } nettyRequest.setHeader(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode()); } String reqType = request.getMethod(); if (!"GET".equals(reqType) && !"HEAD".equals(reqType) && !"OPTION".equals(reqType) && !"TRACE".equals(reqType)) { String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding(); if (buffer != null && buffer.writerIndex() != 0) { nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, buffer.writerIndex()); nettyRequest.setContent(buffer); } else if (request.getByteData() != null) { nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getByteData().length)); nettyRequest.setContent(ChannelBuffers.wrappedBuffer(request.getByteData())); } else if (request.getStringData() != null) { nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getStringData().getBytes(bodyCharset).length)); nettyRequest.setContent(ChannelBuffers.wrappedBuffer(request.getStringData().getBytes(bodyCharset))); } else if (request.getStreamData() != null) { int[] lengthWrapper = new int[1]; byte[] bytes = AsyncHttpProviderUtils.readFully(request.getStreamData(), lengthWrapper); int length = lengthWrapper[0]; nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length)); nettyRequest.setContent(ChannelBuffers.wrappedBuffer(bytes, 0, length)); } else if (request.getParams() != null && !request.getParams().isEmpty()) { StringBuilder sb = new StringBuilder(); for (final Entry<String, List<String>> paramEntry : request.getParams()) { final String key = paramEntry.getKey(); for (final String value : paramEntry.getValue()) { if (sb.length() > 0) { sb.append("&"); } UTF8UrlEncoder.appendEncoded(sb, key); sb.append("="); UTF8UrlEncoder.appendEncoded(sb, value); } } nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sb.length())); nettyRequest.setContent(ChannelBuffers.wrappedBuffer(sb.toString().getBytes(bodyCharset))); if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE)) { nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded"); } } else if (request.getParts() != null) { int lenght = computeAndSetContentLength(request, nettyRequest); if (lenght == -1) { lenght = MAX_BUFFERED_BYTES; } MultipartRequestEntity mre = AsyncHttpProviderUtils.createMultipartRequestEntity(request.getParts(), request.getParams()); nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType()); nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(mre.getContentLength())); if (isSecure(uri)) { ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght); mre.writeRequest(new ChannelBufferOutputStream(b)); nettyRequest.setContent(b); } } else if (request.getEntityWriter() != null) { int lenght = computeAndSetContentLength(request, nettyRequest); if (lenght == -1) { lenght = MAX_BUFFERED_BYTES; } ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght); request.getEntityWriter().writeEntity(new ChannelBufferOutputStream(b)); nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, b.writerIndex()); nettyRequest.setContent(b); } else if (request.getFile() != null) { File file = request.getFile(); if (!file.isFile()) { throw new IOException(String.format("File %s is not a file or doesn't exist", file.getAbsolutePath())); } nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, file.length()); } } } return nettyRequest; }
private static HttpRequest construct(AsyncHttpClientConfig config, Request request, HttpMethod m, URI uri, ChannelBuffer buffer) throws IOException { String host = AsyncHttpProviderUtils.getHost(uri); boolean webSocket = isWebSocket(uri); if (request.getVirtualHost() != null) { host = request.getVirtualHost(); } HttpRequest nettyRequest; if (m.equals(HttpMethod.CONNECT)) { nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_0, m, AsyncHttpProviderUtils.getAuthority(uri)); } else { StringBuilder path = null; if (isProxyServer(config, request)) path = new StringBuilder(uri.toString()); else { path = new StringBuilder(uri.getRawPath()); if (uri.getQuery() != null) { path.append("?").append(uri.getRawQuery()); } } nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, path.toString()); } if (webSocket) { nettyRequest.addHeader(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET); nettyRequest.addHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE); nettyRequest.addHeader("Origin", "http://" + uri.getHost() + ":" + (uri.getPort() == -1 ? isSecure(uri.getScheme()) ? 443 : 80 : uri.getPort())); nettyRequest.addHeader(WEBSOCKET_KEY, WebSocketUtil.getKey()); nettyRequest.addHeader("Sec-WebSocket-Version", "13"); } if (host != null) { if (uri.getPort() == -1) { nettyRequest.setHeader(HttpHeaders.Names.HOST, host); } else if (request.getVirtualHost() != null) { nettyRequest.setHeader(HttpHeaders.Names.HOST, host); } else { nettyRequest.setHeader(HttpHeaders.Names.HOST, host + ":" + uri.getPort()); } } else { host = "127.0.0.1"; } if (!m.equals(HttpMethod.CONNECT)) { FluentCaseInsensitiveStringsMap h = request.getHeaders(); if (h != null) { for (String name : h.keySet()) { if (!"host".equalsIgnoreCase(name)) { for (String value : h.get(name)) { nettyRequest.addHeader(name, value); } } } } if (config.isCompressionEnabled()) { nettyRequest.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); } } else { List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION); if (auth != null && auth.size() > 0 && auth.get(0).startsWith("NTLM")) { nettyRequest.addHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, auth.get(0)); } } ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer(); Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm(); if (realm != null && realm.getUsePreemptiveAuth()) { String domain = realm.getNtlmDomain(); if (proxyServer != null && proxyServer.getNtlmDomain() != null) { domain = proxyServer.getNtlmDomain(); } String authHost = realm.getNtlmHost(); if (proxyServer != null && proxyServer.getHost() != null) { host = proxyServer.getHost(); } switch (realm.getAuthScheme()) { case BASIC: nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, AuthenticatorUtils.computeBasicAuthentication(realm)); break; case DIGEST: if (realm.getNonce() != null && !realm.getNonce().equals("")) { try { nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, AuthenticatorUtils.computeDigestAuthentication(realm)); } catch (NoSuchAlgorithmException e) { throw new SecurityException(e); } } break; case NTLM: try { String msg = ntlmEngine.generateType1Msg("NTLM " + domain, authHost); nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, "NTLM " + msg); } catch (NTLMEngineException e) { IOException ie = new IOException(); ie.initCause(e); throw ie; } break; case KERBEROS: case SPNEGO: String challengeHeader = null; String server = proxyServer == null ? host : proxyServer.getHost(); try { challengeHeader = spnegoEngine.generateToken(server); } catch (Throwable e) { IOException ie = new IOException(); ie.initCause(e); throw ie; } nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, "Negotiate " + challengeHeader); break; case NONE: break; default: throw new IllegalStateException(String.format("Invalid Authentication %s", realm.toString())); } } if (!webSocket && !request.getHeaders().containsKey(HttpHeaders.Names.CONNECTION)) { nettyRequest.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive"); } boolean avoidProxy = ProxyUtils.avoidProxy(proxyServer, request); if (!avoidProxy) { if (!request.getHeaders().containsKey("Proxy-Connection")) { nettyRequest.setHeader("Proxy-Connection", "keep-alive"); } if (proxyServer.getPrincipal() != null) { if (proxyServer.getNtlmDomain() != null && proxyServer.getNtlmDomain().length() > 0) { List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION); if (!(auth != null && auth.size() > 0 && auth.get(0).startsWith("NTLM"))) { try { String msg = ntlmEngine.generateType1Msg(proxyServer.getNtlmDomain(), proxyServer.getHost()); nettyRequest.setHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + msg); } catch (NTLMEngineException e) { IOException ie = new IOException(); ie.initCause(e); throw ie; } } } else { nettyRequest.setHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, AuthenticatorUtils.computeBasicAuthentication(proxyServer)); } } } if (request.getHeaders().getFirstValue("Accept") == null) { nettyRequest.setHeader(HttpHeaders.Names.ACCEPT, "*/*"); } if (request.getHeaders().getFirstValue("User-Agent") != null) { nettyRequest.setHeader("User-Agent", request.getHeaders().getFirstValue("User-Agent")); } else if (config.getUserAgent() != null) { nettyRequest.setHeader("User-Agent", config.getUserAgent()); } else { nettyRequest.setHeader("User-Agent", AsyncHttpProviderUtils.constructUserAgent(NettyAsyncHttpProvider.class, config)); } if (!m.equals(HttpMethod.CONNECT)) { if (request.getCookies() != null && !request.getCookies().isEmpty()) { CookieEncoder httpCookieEncoder = new CookieEncoder(false); Iterator<Cookie> ic = request.getCookies().iterator(); Cookie c; org.jboss.netty.handler.codec.http.Cookie cookie; while (ic.hasNext()) { c = ic.next(); cookie = new DefaultCookie(c.getName(), c.getValue()); cookie.setPath(c.getPath()); cookie.setMaxAge(c.getMaxAge()); cookie.setDomain(c.getDomain()); httpCookieEncoder.addCookie(cookie); } nettyRequest.setHeader(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode()); } String reqType = request.getMethod(); if (!"HEAD".equals(reqType) && !"OPTION".equals(reqType) && !"TRACE".equals(reqType)) { String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding(); if (buffer != null && buffer.writerIndex() != 0) { nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, buffer.writerIndex()); nettyRequest.setContent(buffer); } else if (request.getByteData() != null) { nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getByteData().length)); nettyRequest.setContent(ChannelBuffers.wrappedBuffer(request.getByteData())); } else if (request.getStringData() != null) { nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getStringData().getBytes(bodyCharset).length)); nettyRequest.setContent(ChannelBuffers.wrappedBuffer(request.getStringData().getBytes(bodyCharset))); } else if (request.getStreamData() != null) { int[] lengthWrapper = new int[1]; byte[] bytes = AsyncHttpProviderUtils.readFully(request.getStreamData(), lengthWrapper); int length = lengthWrapper[0]; nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length)); nettyRequest.setContent(ChannelBuffers.wrappedBuffer(bytes, 0, length)); } else if (request.getParams() != null && !request.getParams().isEmpty()) { StringBuilder sb = new StringBuilder(); for (final Entry<String, List<String>> paramEntry : request.getParams()) { final String key = paramEntry.getKey(); for (final String value : paramEntry.getValue()) { if (sb.length() > 0) { sb.append("&"); } UTF8UrlEncoder.appendEncoded(sb, key); sb.append("="); UTF8UrlEncoder.appendEncoded(sb, value); } } nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sb.length())); nettyRequest.setContent(ChannelBuffers.wrappedBuffer(sb.toString().getBytes(bodyCharset))); if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE)) { nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded"); } } else if (request.getParts() != null) { int lenght = computeAndSetContentLength(request, nettyRequest); if (lenght == -1) { lenght = MAX_BUFFERED_BYTES; } MultipartRequestEntity mre = AsyncHttpProviderUtils.createMultipartRequestEntity(request.getParts(), request.getParams()); nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType()); nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(mre.getContentLength())); if (isSecure(uri)) { ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght); mre.writeRequest(new ChannelBufferOutputStream(b)); nettyRequest.setContent(b); } } else if (request.getEntityWriter() != null) { int lenght = computeAndSetContentLength(request, nettyRequest); if (lenght == -1) { lenght = MAX_BUFFERED_BYTES; } ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght); request.getEntityWriter().writeEntity(new ChannelBufferOutputStream(b)); nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, b.writerIndex()); nettyRequest.setContent(b); } else if (request.getFile() != null) { File file = request.getFile(); if (!file.isFile()) { throw new IOException(String.format("File %s is not a file or doesn't exist", file.getAbsolutePath())); } nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, file.length()); } } } return nettyRequest; }
public void transform(String originalFile, String thumbnailFile, int thumbWidth, int thumbHeight, int quality) throws Exception { Image image = javax.imageio.ImageIO.read(new File(originalFile)); double thumbRatio = (double)thumbWidth / (double)thumbHeight; int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); double imageRatio = (double)imageWidth / (double)imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int)(thumbWidth / imageRatio); } else { thumbWidth = (int)(thumbHeight * imageRatio); } if(imageWidth < thumbWidth && imageHeight < thumbHeight) { thumbWidth = imageWidth; thumbHeight = imageHeight; } else if(imageWidth < thumbWidth) thumbWidth = imageWidth; else if(imageHeight < thumbHeight) thumbHeight = imageHeight; if(thumbWidth < 1) thumbWidth = 1; if(thumbHeight < 1) thumbHeight = 1; if(CmsPropertyHandler.getProperty("externalThumbnailGeneration") != null) { String[] args = new String[5]; args[0] = CmsPropertyHandler.getProperty("externalThumbnailGeneration"); args[1] = "-resize"; args[2] = String.valueOf(thumbWidth) + "x" + String.valueOf(thumbHeight); args[3] = originalFile; args[4] = thumbnailFile; try { Process p = Runtime.getRuntime().exec(args); p.waitFor(); } catch(InterruptedException e) { new Exception("Error resizing image for thumbnail", e); } } else { BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setBackground(Color.WHITE); graphics2D.setPaint(Color.WHITE); graphics2D.fillRect(0, 0, thumbWidth, thumbHeight); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); javax.imageio.ImageIO.write(thumbImage, "JPG", new File(thumbnailFile)); } }
public void transform(String originalFile, String thumbnailFile, int thumbWidth, int thumbHeight, int quality) throws Exception { Image image = javax.imageio.ImageIO.read(new File(originalFile)); double thumbRatio = (double)thumbWidth / (double)thumbHeight; int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); double imageRatio = (double)imageWidth / (double)imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int)(thumbWidth / imageRatio); } else { thumbWidth = (int)(thumbHeight * imageRatio); } if(imageWidth < thumbWidth && imageHeight < thumbHeight) { thumbWidth = imageWidth; thumbHeight = imageHeight; } else if(imageWidth < thumbWidth) thumbWidth = imageWidth; else if(imageHeight < thumbHeight) thumbHeight = imageHeight; if(thumbWidth < 1) thumbWidth = 1; if(thumbHeight < 1) thumbHeight = 1; if(CmsPropertyHandler.getProperty("externalThumbnailGeneration") != null && CmsPropertyHandler.getProperty("externalThumbnailGeneration").equalsIgnoreCase("")) { String[] args = new String[5]; args[0] = CmsPropertyHandler.getProperty("externalThumbnailGeneration"); args[1] = "-resize"; args[2] = String.valueOf(thumbWidth) + "x" + String.valueOf(thumbHeight); args[3] = originalFile; args[4] = thumbnailFile; try { Process p = Runtime.getRuntime().exec(args); p.waitFor(); } catch(InterruptedException e) { new Exception("Error resizing image for thumbnail", e); } } else { BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setBackground(Color.WHITE); graphics2D.setPaint(Color.WHITE); graphics2D.fillRect(0, 0, thumbWidth, thumbHeight); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); javax.imageio.ImageIO.write(thumbImage, "JPG", new File(thumbnailFile)); } }
public boolean equals(Object obj) { if (!(obj instanceof TupleType)) { return false; } TupleType other= (TupleType) obj; if (fFieldTypes.length != other.fFieldTypes.length) { return false; } for(int i=0; i < fFieldTypes.length; i++) { if (fFieldTypes[i] != other.fFieldTypes[i]) { return false; } } if (fFieldNames != null) { for (int i = 0; i < fFieldNames.length; i++) { if (!fFieldNames[i].equals(other.fFieldNames[i])) { return false; } } } return true; }
public boolean equals(Object obj) { if (!(obj instanceof TupleType)) { return false; } TupleType other= (TupleType) obj; if (fFieldTypes.length != other.fFieldTypes.length) { return false; } for(int i=0; i < fFieldTypes.length; i++) { if (fFieldTypes[i] != other.fFieldTypes[i]) { return false; } } if (fFieldNames != null) { if (other.fFieldNames == null) { return false; } for (int i = 0; i < fFieldNames.length; i++) { if (!fFieldNames[i].equals(other.fFieldNames[i])) { return false; } } } return true; }
public static void execute(String schemaName, String userName) throws SQLException { Statement s1 = null, s2 = null; PreparedStatement ps; ResultSet rs; Connection conn = null; StringWriter sw; StackWriter stackw; PrintWriter pw; conn = DriverManager.getConnection("jdbc:default:connection"); ps = conn.prepareStatement("select SCHEMA_NAME, TABLE_NAME " + "from SYS_ROOT.DBA_TABLES where SCHEMA_NAME = ?"); ps.setString(1, schemaName); rs = ps.executeQuery(); while (rs.next()) { sw = new StringWriter(); stackw = new StackWriter(sw, StackWriter.INDENT_SPACE4); pw = new PrintWriter(stackw); pw.print("grant select on "); StackWriter.printSqlIdentifier(pw, rs.getString(1)); pw.print("."); StackWriter.printSqlIdentifier(pw, rs.getString(2)); pw.print(" to "); StackWriter.printSqlIdentifier(pw, userName); pw.close(); ps = conn.prepareStatement(sw.toString()); rs = ps.executeQuery(); } }
public static void execute(String schemaName, String userName) throws SQLException { Statement s1 = null, s2 = null; PreparedStatement ps; ResultSet rs; Connection conn = null; StringWriter sw; StackWriter stackw; PrintWriter pw; conn = DriverManager.getConnection("jdbc:default:connection"); ps = conn.prepareStatement("select SCHEMA_NAME, TABLE_NAME " + "from SYS_ROOT.DBA_TABLES where SCHEMA_NAME = ?"); ps.setString(1, schemaName); rs = ps.executeQuery(); while (rs.next()) { sw = new StringWriter(); stackw = new StackWriter(sw, StackWriter.INDENT_SPACE4); pw = new PrintWriter(stackw); pw.print("grant select on "); StackWriter.printSqlIdentifier(pw, rs.getString(1)); pw.print("."); StackWriter.printSqlIdentifier(pw, rs.getString(2)); pw.print(" to "); StackWriter.printSqlIdentifier(pw, userName); pw.close(); ps = conn.prepareStatement(sw.toString()); ps.executeUpdate(); } }
protected void addToolBarActions(JToolBar tb) { tb.setLayout(new WrapLayout(1, 1)); addToToolbar(StandaloneActions.newAction); addToToolbar(actions.saveAction); tb.addSeparator(); addToToolbar(actions.copyAction); addToToolbar(actions.pasteAction); tb.addSeparator(); addToToolbar(actions.undoAction); tb.addSeparator(); addToToolbar(new JLabel("Zoom:", JLabel.LEFT)); JComboBox combo = new JComboBox(actions.zoomActions); combo.setMaximumSize(combo.getPreferredSize()); combo.setEditable(true); combo.setSelectedIndex(5); combo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JComboBox combo = (JComboBox) e.getSource(); Object s = combo.getSelectedItem(); if (s instanceof Action) { ((Action) s).actionPerformed(e); } else if (s instanceof String) { String zs = (String) s; try { double zf = Double.parseDouble(zs); ZoomAction za = new ZoomAction(zf); za.setEnabled(true); za.actionPerformed(e); } catch (Exception ex) { } } } }); addToToolbar(combo, TB_GROUP_SHOW_IF_VPATHWAY); tb.addSeparator(); String submenu = "line"; for(Action[] aa : actions.newElementActions) { if(aa.length == 1) { addToToolbar(aa[0]); } else { String icon = "newlinemenu.gif"; String tooltip = "Select a line to draw"; if(submenu.equals("receptors")) { icon = "newlineshapemenu.gif"; tooltip = "Select a receptor/ligand to draw"; } else { submenu = "receptors"; } DropDownButton lineButton = new DropDownButton(new ImageIcon(Engine.getCurrent() .getResourceURL(icon))); lineButton.setToolTipText(tooltip); for(Action a : aa) { lineButton.addComponent(new JMenuItem(a)); } addToToolbar(lineButton, TB_GROUP_SHOW_IF_EDITMODE); } } tb.addSeparator(); addToToolbar(actions.alignActions); addToToolbar(actions.stackActions); }
protected void addToolBarActions(JToolBar tb) { tb.setLayout(new WrapLayout(1, 1)); addToToolbar(StandaloneActions.newAction); addToToolbar(StandaloneActions.openAction); addToToolbar(actions.saveAction); tb.addSeparator(); addToToolbar(actions.copyAction); addToToolbar(actions.pasteAction); tb.addSeparator(); addToToolbar(actions.undoAction); tb.addSeparator(); addToToolbar(new JLabel("Zoom:", JLabel.LEFT)); JComboBox combo = new JComboBox(actions.zoomActions); combo.setMaximumSize(combo.getPreferredSize()); combo.setEditable(true); combo.setSelectedIndex(5); combo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JComboBox combo = (JComboBox) e.getSource(); Object s = combo.getSelectedItem(); if (s instanceof Action) { ((Action) s).actionPerformed(e); } else if (s instanceof String) { String zs = (String) s; try { double zf = Double.parseDouble(zs); ZoomAction za = new ZoomAction(zf); za.setEnabled(true); za.actionPerformed(e); } catch (Exception ex) { } } } }); addToToolbar(combo, TB_GROUP_SHOW_IF_VPATHWAY); tb.addSeparator(); String submenu = "line"; for(Action[] aa : actions.newElementActions) { if(aa.length == 1) { addToToolbar(aa[0]); } else { String icon = "newlinemenu.gif"; String tooltip = "Select a line to draw"; if(submenu.equals("receptors")) { icon = "newlineshapemenu.gif"; tooltip = "Select a receptor/ligand to draw"; } else { submenu = "receptors"; } DropDownButton lineButton = new DropDownButton(new ImageIcon(Engine.getCurrent() .getResourceURL(icon))); lineButton.setToolTipText(tooltip); for(Action a : aa) { lineButton.addComponent(new JMenuItem(a)); } addToToolbar(lineButton, TB_GROUP_SHOW_IF_EDITMODE); } } tb.addSeparator(); addToToolbar(actions.alignActions); addToToolbar(actions.stackActions); }
private void configureSelection( CursorLoader loader, long directoryId, ContactListFilter filter) { if (filter == null) { return; } if (directoryId != Directory.DEFAULT) { return; } StringBuilder selection = new StringBuilder(); List<String> selectionArgs = new ArrayList<String>(); switch (filter.filterType) { case ContactListFilter.FILTER_TYPE_ALL_ACCOUNTS: { break; } case ContactListFilter.FILTER_TYPE_SINGLE_CONTACT: { break; } case ContactListFilter.FILTER_TYPE_STARRED: { selection.append(Contacts.STARRED + "!=0"); break; } case ContactListFilter.FILTER_TYPE_WITH_PHONE_NUMBERS_ONLY: { selection.append(Contacts.HAS_PHONE_NUMBER + "=1"); break; } case ContactListFilter.FILTER_TYPE_CUSTOM: { selection.append(Contacts.IN_VISIBLE_GROUP + "=1"); if (isCustomFilterForPhoneNumbersOnly()) { selection.append(" AND " + Contacts.HAS_PHONE_NUMBER + "=1"); } break; } case ContactListFilter.FILTER_TYPE_ACCOUNT: { selection.append( Contacts._ID + " IN (" + "SELECT DISTINCT " + RawContacts.CONTACT_ID + " FROM raw_contacts" + " WHERE " + RawContacts.ACCOUNT_TYPE + "=?" + " AND " + RawContacts.ACCOUNT_NAME + "=?"); selectionArgs.add(filter.accountType); selectionArgs.add(filter.accountName); if (filter.dataSet != null) { selection.append(" AND " + RawContacts.DATA_SET + "=?"); selectionArgs.add(filter.dataSet); } else { selection.append(" AND " + RawContacts.DATA_SET + " IS NULL"); } selection.append(") OR " + Contacts._ID + "=(" + "SELECT contact_id " + "FROM raw_contacts rc inner join accounts a" + " ON a.profile_raw_contact_id = rc._id)"); break; } case ContactListFilter.FILTER_TYPE_GROUP: { selection.append(Data.MIMETYPE + "=?" + " AND " + GroupMembership.GROUP_ROW_ID + "=?"); selectionArgs.add(GroupMembership.CONTENT_ITEM_TYPE); selectionArgs.add(String.valueOf(filter.groupId)); break; } } loader.setSelection(selection.toString()); loader.setSelectionArgs(selectionArgs.toArray(new String[0])); }
private void configureSelection( CursorLoader loader, long directoryId, ContactListFilter filter) { if (filter == null) { return; } if (directoryId != Directory.DEFAULT) { return; } StringBuilder selection = new StringBuilder(); List<String> selectionArgs = new ArrayList<String>(); switch (filter.filterType) { case ContactListFilter.FILTER_TYPE_ALL_ACCOUNTS: { break; } case ContactListFilter.FILTER_TYPE_SINGLE_CONTACT: { break; } case ContactListFilter.FILTER_TYPE_STARRED: { selection.append(Contacts.STARRED + "!=0"); break; } case ContactListFilter.FILTER_TYPE_WITH_PHONE_NUMBERS_ONLY: { selection.append(Contacts.HAS_PHONE_NUMBER + "=1"); break; } case ContactListFilter.FILTER_TYPE_CUSTOM: { selection.append(Contacts.IN_VISIBLE_GROUP + "=1"); if (isCustomFilterForPhoneNumbersOnly()) { selection.append(" AND " + Contacts.HAS_PHONE_NUMBER + "=1"); } break; } case ContactListFilter.FILTER_TYPE_ACCOUNT: { selection.append( Contacts._ID + " IN (" + "SELECT DISTINCT " + RawContacts.CONTACT_ID + " FROM raw_contacts" + " WHERE " + RawContacts.ACCOUNT_TYPE + "=?" + " AND " + RawContacts.ACCOUNT_NAME + "=?"); selectionArgs.add(filter.accountType); selectionArgs.add(filter.accountName); if (filter.dataSet != null) { selection.append(" AND " + RawContacts.DATA_SET + "=?"); selectionArgs.add(filter.dataSet); } else { selection.append(" AND " + RawContacts.DATA_SET + " IS NULL"); } selection.append(")"); break; } case ContactListFilter.FILTER_TYPE_GROUP: { selection.append(Data.MIMETYPE + "=?" + " AND " + GroupMembership.GROUP_ROW_ID + "=?"); selectionArgs.add(GroupMembership.CONTENT_ITEM_TYPE); selectionArgs.add(String.valueOf(filter.groupId)); break; } } loader.setSelection(selection.toString()); loader.setSelectionArgs(selectionArgs.toArray(new String[0])); }
public static void checkLibrary(int library, HashSet missing) { switch (library) { case BIO_FORMATS: checkLibrary("loci.formats.FormatHandler", "bio-formats.jar", missing); checkLibrary("org.apache.poi.poifs.filesystem.POIFSFileSystem", "poi-loci.jar", missing); break; case OME_JAVA_XML: checkLibrary("org.openmicroscopy.xml.OMENode", "ome-java.jar", missing); break; case OME_JAVA_DS: checkLibrary("org.openmicroscopy.ds.DataServer", "ome-java.jar", missing); checkLibrary("org.apache.xmlrpc.XmlRpcClient", "xmlrpc-1.2-b1.jar", missing); checkLibrary("org.apache.commons.httpclient.HttpClient", "commons-httpclient-2.0-rc2.jar", missing); checkLibrary("org.apache.commons.logging.Log", "commons-logging.jar", missing); break; case FORMS: checkLibrary("com.jgoodies.forms.layout.FormLayout", "forms-1.0.4.jar", missing); break; } }
public static void checkLibrary(int library, HashSet missing) { switch (library) { case BIO_FORMATS: checkLibrary("loci.formats.FormatHandler", "bio-formats.jar", missing); checkLibrary("org.apache.poi.poifs.filesystem.POIFSFileSystem", "poi-loci.jar", missing); break; case OME_JAVA_XML: checkLibrary("ome.xml.OMEXMLNode", "ome-xml.jar", missing); break; case OME_JAVA_DS: checkLibrary("org.openmicroscopy.ds.DataServer", "ome-java.jar", missing); checkLibrary("org.apache.xmlrpc.XmlRpcClient", "xmlrpc-1.2-b1.jar", missing); checkLibrary("org.apache.commons.httpclient.HttpClient", "commons-httpclient-2.0-rc2.jar", missing); checkLibrary("org.apache.commons.logging.Log", "commons-logging.jar", missing); break; case FORMS: checkLibrary("com.jgoodies.forms.layout.FormLayout", "forms-1.0.4.jar", missing); break; } }
public static void postUserDb(String schemaName, String type, String name, String xrefId, String permission) { EntityUser user = Utility.getCurrentUser(session); SecureSchema schema = schemaCheck(schemaName, user, PermissionType.ADMIN); PermissionType p = PermissionType.lookup(permission); SecureResourceGroupXref xref; if(xrefId == null || "".equals(xrefId)) { Entity entity; if("group".equals(type)) { entity = EntityGroup.findByName(NoSql.em(), name); if (entity == null) { flash.error("The group="+name+" does not exist"); flash.keep(); MyDatabases.dbUserAdd(schemaName, type); } } else { entity = EntityUser.findByName(NoSql.em(), name); if (entity == null) { flash.error("The user="+name+" does not exist. Please ask them to login to the system once first!!!"); flash.keep(); MyDatabases.dbUserAdd(schema.getSchemaName(), type); } } xref = new SecureResourceGroupXref(entity, schema, p); xref.setPermission(p); NoSql.em().put(xref); NoSql.em().put(schema); NoSql.em().put(user); } else { for(SecureResourceGroupXref ref : schema.getEntitiesWithAccess()) { Entity ent = ref.getUserOrGroup(); if(ent.getName().equals(name)) { if(ent instanceof EntityGroup && "group".equals(type)) { flash.error("The group="+name+" already has access to this database"); flash.keep(); MyDatabases.dbUserAdd(schemaName, type); } else if(ent instanceof EntityUser && "user".equals(type)) { flash.error("The user="+name+" already has access to this database"); flash.keep(); MyDatabases.dbUserAdd(schemaName, type); } } } xref = NoSql.em().find(SecureResourceGroupXref.class, xrefId); xref.setPermission(p); NoSql.em().put(xref); } NoSql.em().flush(); dbUsers(schemaName); }
public static void postUserDb(String schemaName, String type, String name, String xrefId, String permission) { EntityUser user = Utility.getCurrentUser(session); SecureSchema schema = schemaCheck(schemaName, user, PermissionType.ADMIN); PermissionType p = PermissionType.lookup(permission); SecureResourceGroupXref xref; if(xrefId == null || "".equals(xrefId)) { Entity entity; if("group".equals(type)) { entity = EntityGroup.findByName(NoSql.em(), name); if (entity == null) { flash.error("The group="+name+" does not exist"); flash.keep(); MyDatabases.dbUserAdd(schemaName, type); } } else { entity = EntityUser.findByName(NoSql.em(), name); if (entity == null) { flash.error("The user="+name+" does not exist. Please ask them to login to the system once first!!!"); flash.keep(); MyDatabases.dbUserAdd(schema.getSchemaName(), type); } } xref = new SecureResourceGroupXref(entity, schema, p); xref.setPermission(p); NoSql.em().put(xref); NoSql.em().put(schema); NoSql.em().put(entity); } else { for(SecureResourceGroupXref ref : schema.getEntitiesWithAccess()) { Entity ent = ref.getUserOrGroup(); if(ent.getName().equals(name)) { if(ent instanceof EntityGroup && "group".equals(type)) { flash.error("The group="+name+" already has access to this database"); flash.keep(); MyDatabases.dbUserAdd(schemaName, type); } else if(ent instanceof EntityUser && "user".equals(type)) { flash.error("The user="+name+" already has access to this database"); flash.keep(); MyDatabases.dbUserAdd(schemaName, type); } } } xref = NoSql.em().find(SecureResourceGroupXref.class, xrefId); xref.setPermission(p); NoSql.em().put(xref); } NoSql.em().flush(); dbUsers(schemaName); }
public Object getObject(Library library) throws PDFException { int deepnessCount = 0; boolean inObject = false; boolean complete = false; Object nextToken; Reference objectReference = null; try { reader.mark(1); if (library.isLinearTraversal() && reader instanceof BufferedMarkedInputStream) { linearTraversalOffset = ((BufferedMarkedInputStream) reader).getMarkedPosition(); } do { try { nextToken = getToken(); } catch (IOException e) { return null; } if (nextToken instanceof StringObject || nextToken instanceof Name || nextToken instanceof Number) { if (nextToken instanceof StringObject) { StringObject tmp = (StringObject) nextToken; tmp.setReference(objectReference); } stack.push(nextToken); } else if (nextToken.equals("obj")) { if (inObject) { stack.pop(); stack.pop(); return addPObject(library, objectReference); } deepnessCount = 0; inObject = true; Number generationNumber = (Number) (stack.pop()); Number objectNumber = (Number) (stack.pop()); objectReference = new Reference(objectNumber, generationNumber); } else if (nextToken.equals("endobj") || nextToken.equals("endobject")) { if (inObject) { inObject = false; return addPObject(library, objectReference); } else { } } else if (nextToken.equals("endstream")) { deepnessCount--; if (inObject) { inObject = false; return addPObject(library, objectReference); } } else if (nextToken.equals("stream")) { deepnessCount++; HashMap streamHash = (HashMap) stack.pop(); int streamLength = library.getInt(streamHash, Dictionary.LENGTH_KEY); SeekableInputConstrainedWrapper streamInputWrapper; try { reader.mark(2); int curChar = reader.read(); if (curChar == 13) { reader.mark(1); if (reader.read() != 10) { reader.reset(); } } else if (curChar == 10) { } else { reader.reset(); } if (reader instanceof SeekableInput) { SeekableInput streamDataInput = (SeekableInput) reader; long filePositionOfStreamData = streamDataInput.getAbsolutePosition(); long lengthOfStreamData; if (streamLength > 0) { lengthOfStreamData = streamLength; streamDataInput.seekRelative(streamLength); lengthOfStreamData += skipUntilEndstream(null); } else { lengthOfStreamData = captureStreamData(null); } streamInputWrapper = new SeekableInputConstrainedWrapper( streamDataInput, filePositionOfStreamData, lengthOfStreamData); } else { ConservativeSizingByteArrayOutputStream out; if (!library.isLinearTraversal() && streamLength > 0) { byte[] buffer = new byte[streamLength]; int totalRead = 0; while (totalRead < buffer.length) { int currRead = reader.read(buffer, totalRead, buffer.length - totalRead); if (currRead <= 0) break; totalRead += currRead; } out = new ConservativeSizingByteArrayOutputStream( buffer); skipUntilEndstream(out); } else { out = new ConservativeSizingByteArrayOutputStream( 16 * 1024); captureStreamData(out); } int size = out.size(); out.trim(); byte[] buffer = out.relinquishByteArray(); SeekableInput streamDataInput = new SeekableByteArrayInputStream(buffer); long filePositionOfStreamData = 0L; streamInputWrapper = new SeekableInputConstrainedWrapper( streamDataInput, filePositionOfStreamData, size); } } catch (IOException e) { e.printStackTrace(); return null; } PTrailer trailer = null; Stream stream = null; Name type = (Name) library.getObject(streamHash, Dictionary.TYPE_KEY); Name subtype = (Name) library.getObject(streamHash, Dictionary.SUBTYPE_KEY); if (type != null) { if (type.equals("XRef")) { stream = new Stream(library, streamHash, streamInputWrapper); stream.init(); InputStream in = stream.getDecodedByteArrayInputStream(); CrossReference xrefStream = new CrossReference(); if (in != null) { try { xrefStream.addXRefStreamEntries(library, streamHash, in); } finally { try { in.close(); } catch (Throwable e) { logger.log(Level.WARNING, "Error appending stream entries.", e); } } } HashMap trailerHash = (HashMap) streamHash.clone(); trailer = new PTrailer(library, trailerHash, null, xrefStream); } else if (type.equals("ObjStm")) { stream = new ObjectStream(library, streamHash, streamInputWrapper); } else if (type.equals("XObject") && subtype.equals("Image")) { stream = new ImageStream(library, streamHash, streamInputWrapper); } else if (type.equals("Pattern")) { stream = new TilingPattern(library, streamHash, streamInputWrapper); } } if (stream == null && subtype != null) { if (subtype.equals("Image")) { stream = new ImageStream(library, streamHash, streamInputWrapper); } else if (subtype.equals("Form") && !"Pattern".equals(type)) { stream = new Form(library, streamHash, streamInputWrapper); } else if (subtype.equals("Form") && "Pattern".equals(type)) { stream = new TilingPattern(library, streamHash, streamInputWrapper); } } if (trailer != null) { stack.push(trailer); } else { if (stream == null) { stream = new Stream(library, streamHash, streamInputWrapper); } stack.push(stream); return addPObject(library, objectReference); } } else if (nextToken.equals("true")) { stack.push(true); } else if (nextToken.equals("false")) { stack.push(false); } else if (nextToken.equals("R")) { Number generationNumber = (Number) (stack.pop()); Number objectNumber = (Number) (stack.pop()); stack.push(new Reference(objectNumber, generationNumber)); } else if (nextToken.equals("[")) { deepnessCount++; stack.push(nextToken); } else if (nextToken.equals("]")) { deepnessCount--; final int searchPosition = stack.search("["); final int size = searchPosition - 1; List v = new ArrayList(size); Object[] tmp = new Object[size]; if (searchPosition > 0) { for (int i = size - 1; i >= 0; i--) { tmp[i] = stack.pop(); } for (int i = 0; i < size; i++) { v.add(tmp[i]); } stack.pop(); } else { stack.clear(); } stack.push(v); } else if (nextToken.equals("<<")) { deepnessCount++; stack.push(nextToken); } else if (nextToken.equals(">>")) { deepnessCount--; if (!isTrailer && deepnessCount >= 0) { if (!stack.isEmpty()) { HashMap hashMap = new HashMap(); Object obj = stack.pop(); while (!((obj instanceof String) && (obj.equals("<<"))) && !stack.isEmpty()) { Object key = stack.pop(); hashMap.put(key, obj); if (!stack.isEmpty()) { obj = stack.pop(); } else { break; } } obj = hashMap.get(Dictionary.TYPE_KEY); if (obj != null && obj instanceof Name) { Name n = (Name) obj; if (n.equals(Catalog.TYPE)) { stack.push(new Catalog(library, hashMap)); } else if (n.equals(PageTree.TYPE)) { stack.push(new PageTree(library, hashMap)); } else if (n.equals(Page.TYPE)) { stack.push(new Page(library, hashMap)); } else if (n.equals(Font.TYPE)) { boolean fontDescriptor = hashMap.get(FontDescriptor.FONT_FILE) != null || hashMap.get(FontDescriptor.FONT_FILE_2) != null || hashMap.get(FontDescriptor.FONT_FILE_3) != null; if (!fontDescriptor) { stack.push(FontFactory.getInstance() .getFont(library, hashMap)); } else { stack.push(new FontDescriptor(library, hashMap)); } } else if (n.equals(FontDescriptor.TYPE)) { stack.push(new FontDescriptor(library, hashMap)); } else if (n.equals(CMap.TYPE)) { stack.push(hashMap); } else if (n.equals(Annotation.TYPE)) { stack.push(Annotation.buildAnnotation(library, hashMap)); } else if (n.equals(OptionalContentGroup.TYPE)) { stack.push(new OptionalContentGroup(library, hashMap)); } else if (n.equals(OptionalContentMembership.TYPE)) { stack.push(new OptionalContentMembership(library, hashMap)); } else stack.push(hashMap); } else { stack.push(hashMap); } } } else if (isTrailer && deepnessCount == 0) { HashMap hashMap = new HashMap(); Object obj = stack.pop(); while (!((obj instanceof String) && (obj.equals("<<"))) && !stack.isEmpty()) { Object key = stack.pop(); hashMap.put(key, obj); if (!stack.isEmpty()) { obj = stack.pop(); } else { break; } } return hashMap; } } else if (nextToken.equals("xref")) { CrossReference xrefTable = new CrossReference(); xrefTable.addXRefTableEntries(this); stack.push(xrefTable); } else if (nextToken.equals("trailer")) { CrossReference xrefTable = null; if (stack.peek() instanceof CrossReference) xrefTable = (CrossReference) stack.pop(); stack.clear(); isTrailer = true; HashMap trailerDictionary = (HashMap) getObject(library); isTrailer = false; return new PTrailer(library, trailerDictionary, xrefTable, null); } else if (nextToken instanceof String && ((String) nextToken).startsWith("%")) { } else { stack.push(nextToken); } if (parseMode == PARSE_MODE_OBJECT_STREAM && deepnessCount == 0 && stack.size() > 0) { return stack.pop(); } } while (!complete); } catch (Exception e) { logger.log(Level.WARNING, "Fatal error parsing PDF file stream.", e); e.printStackTrace(); return null; } return stack.pop(); }
public Object getObject(Library library) throws PDFException { int deepnessCount = 0; boolean inObject = false; boolean complete = false; Object nextToken; Reference objectReference = null; try { reader.mark(1); if (library.isLinearTraversal() && reader instanceof BufferedMarkedInputStream) { linearTraversalOffset = ((BufferedMarkedInputStream) reader).getMarkedPosition(); } do { try { nextToken = getToken(); } catch (IOException e) { return null; } if (nextToken instanceof StringObject || nextToken instanceof Name || nextToken instanceof Number) { if (nextToken instanceof StringObject) { StringObject tmp = (StringObject) nextToken; tmp.setReference(objectReference); } stack.push(nextToken); } else if (nextToken.equals("obj")) { if (inObject) { stack.pop(); stack.pop(); return addPObject(library, objectReference); } deepnessCount = 0; inObject = true; Number generationNumber = (Number) (stack.pop()); Number objectNumber = (Number) (stack.pop()); objectReference = new Reference(objectNumber, generationNumber); } else if (nextToken.equals("endobj") || nextToken.equals("endobject") || nextToken.equals("enbobj")) { if (inObject) { inObject = false; return addPObject(library, objectReference); } else { } } else if (nextToken.equals("endstream")) { deepnessCount--; if (inObject) { inObject = false; return addPObject(library, objectReference); } } else if (nextToken.equals("stream")) { deepnessCount++; HashMap streamHash = (HashMap) stack.pop(); int streamLength = library.getInt(streamHash, Dictionary.LENGTH_KEY); SeekableInputConstrainedWrapper streamInputWrapper; try { reader.mark(2); int curChar = reader.read(); if (curChar == 13) { reader.mark(1); if (reader.read() != 10) { reader.reset(); } } else if (curChar == 10) { } else { reader.reset(); } if (reader instanceof SeekableInput) { SeekableInput streamDataInput = (SeekableInput) reader; long filePositionOfStreamData = streamDataInput.getAbsolutePosition(); long lengthOfStreamData; if (streamLength > 0) { lengthOfStreamData = streamLength; streamDataInput.seekRelative(streamLength); lengthOfStreamData += skipUntilEndstream(null); } else { lengthOfStreamData = captureStreamData(null); } streamInputWrapper = new SeekableInputConstrainedWrapper( streamDataInput, filePositionOfStreamData, lengthOfStreamData); } else { ConservativeSizingByteArrayOutputStream out; if (!library.isLinearTraversal() && streamLength > 0) { byte[] buffer = new byte[streamLength]; int totalRead = 0; while (totalRead < buffer.length) { int currRead = reader.read(buffer, totalRead, buffer.length - totalRead); if (currRead <= 0) break; totalRead += currRead; } out = new ConservativeSizingByteArrayOutputStream( buffer); skipUntilEndstream(out); } else { out = new ConservativeSizingByteArrayOutputStream( 16 * 1024); captureStreamData(out); } int size = out.size(); out.trim(); byte[] buffer = out.relinquishByteArray(); SeekableInput streamDataInput = new SeekableByteArrayInputStream(buffer); long filePositionOfStreamData = 0L; streamInputWrapper = new SeekableInputConstrainedWrapper( streamDataInput, filePositionOfStreamData, size); } } catch (IOException e) { e.printStackTrace(); return null; } PTrailer trailer = null; Stream stream = null; Name type = (Name) library.getObject(streamHash, Dictionary.TYPE_KEY); Name subtype = (Name) library.getObject(streamHash, Dictionary.SUBTYPE_KEY); if (type != null) { if (type.equals("XRef")) { stream = new Stream(library, streamHash, streamInputWrapper); stream.init(); InputStream in = stream.getDecodedByteArrayInputStream(); CrossReference xrefStream = new CrossReference(); if (in != null) { try { xrefStream.addXRefStreamEntries(library, streamHash, in); } finally { try { in.close(); } catch (Throwable e) { logger.log(Level.WARNING, "Error appending stream entries.", e); } } } HashMap trailerHash = (HashMap) streamHash.clone(); trailer = new PTrailer(library, trailerHash, null, xrefStream); } else if (type.equals("ObjStm")) { stream = new ObjectStream(library, streamHash, streamInputWrapper); } else if (type.equals("XObject") && subtype.equals("Image")) { stream = new ImageStream(library, streamHash, streamInputWrapper); } else if (type.equals("Pattern")) { stream = new TilingPattern(library, streamHash, streamInputWrapper); } } if (stream == null && subtype != null) { if (subtype.equals("Image")) { stream = new ImageStream(library, streamHash, streamInputWrapper); } else if (subtype.equals("Form") && !"Pattern".equals(type)) { stream = new Form(library, streamHash, streamInputWrapper); } else if (subtype.equals("Form") && "Pattern".equals(type)) { stream = new TilingPattern(library, streamHash, streamInputWrapper); } } if (trailer != null) { stack.push(trailer); } else { if (stream == null) { stream = new Stream(library, streamHash, streamInputWrapper); } stack.push(stream); return addPObject(library, objectReference); } } else if (nextToken.equals("true")) { stack.push(true); } else if (nextToken.equals("false")) { stack.push(false); } else if (nextToken.equals("R")) { Number generationNumber = (Number) (stack.pop()); Number objectNumber = (Number) (stack.pop()); stack.push(new Reference(objectNumber, generationNumber)); } else if (nextToken.equals("[")) { deepnessCount++; stack.push(nextToken); } else if (nextToken.equals("]")) { deepnessCount--; final int searchPosition = stack.search("["); final int size = searchPosition - 1; List v = new ArrayList(size); Object[] tmp = new Object[size]; if (searchPosition > 0) { for (int i = size - 1; i >= 0; i--) { tmp[i] = stack.pop(); } for (int i = 0; i < size; i++) { v.add(tmp[i]); } stack.pop(); } else { stack.clear(); } stack.push(v); } else if (nextToken.equals("<<")) { deepnessCount++; stack.push(nextToken); } else if (nextToken.equals(">>")) { deepnessCount--; if (!isTrailer && deepnessCount >= 0) { if (!stack.isEmpty()) { HashMap hashMap = new HashMap(); Object obj = stack.pop(); while (!((obj instanceof String) && (obj.equals("<<"))) && !stack.isEmpty()) { Object key = stack.pop(); hashMap.put(key, obj); if (!stack.isEmpty()) { obj = stack.pop(); } else { break; } } obj = hashMap.get(Dictionary.TYPE_KEY); if (obj != null && obj instanceof Name) { Name n = (Name) obj; if (n.equals(Catalog.TYPE)) { stack.push(new Catalog(library, hashMap)); } else if (n.equals(PageTree.TYPE)) { stack.push(new PageTree(library, hashMap)); } else if (n.equals(Page.TYPE)) { stack.push(new Page(library, hashMap)); } else if (n.equals(Font.TYPE)) { boolean fontDescriptor = hashMap.get(FontDescriptor.FONT_FILE) != null || hashMap.get(FontDescriptor.FONT_FILE_2) != null || hashMap.get(FontDescriptor.FONT_FILE_3) != null; if (!fontDescriptor) { stack.push(FontFactory.getInstance() .getFont(library, hashMap)); } else { stack.push(new FontDescriptor(library, hashMap)); } } else if (n.equals(FontDescriptor.TYPE)) { stack.push(new FontDescriptor(library, hashMap)); } else if (n.equals(CMap.TYPE)) { stack.push(hashMap); } else if (n.equals(Annotation.TYPE)) { stack.push(Annotation.buildAnnotation(library, hashMap)); } else if (n.equals(OptionalContentGroup.TYPE)) { stack.push(new OptionalContentGroup(library, hashMap)); } else if (n.equals(OptionalContentMembership.TYPE)) { stack.push(new OptionalContentMembership(library, hashMap)); } else stack.push(hashMap); } else { stack.push(hashMap); } } } else if (isTrailer && deepnessCount == 0) { HashMap hashMap = new HashMap(); Object obj = stack.pop(); while (!((obj instanceof String) && (obj.equals("<<"))) && !stack.isEmpty()) { Object key = stack.pop(); hashMap.put(key, obj); if (!stack.isEmpty()) { obj = stack.pop(); } else { break; } } return hashMap; } } else if (nextToken.equals("xref")) { CrossReference xrefTable = new CrossReference(); xrefTable.addXRefTableEntries(this); stack.push(xrefTable); } else if (nextToken.equals("trailer")) { CrossReference xrefTable = null; if (stack.peek() instanceof CrossReference) xrefTable = (CrossReference) stack.pop(); stack.clear(); isTrailer = true; HashMap trailerDictionary = (HashMap) getObject(library); isTrailer = false; return new PTrailer(library, trailerDictionary, xrefTable, null); } else if (nextToken instanceof String && ((String) nextToken).startsWith("%")) { } else { stack.push(nextToken); } if (parseMode == PARSE_MODE_OBJECT_STREAM && deepnessCount == 0 && stack.size() > 0) { return stack.pop(); } } while (!complete); } catch (Exception e) { logger.log(Level.WARNING, "Fatal error parsing PDF file stream.", e); e.printStackTrace(); return null; } return stack.pop(); }
private static void readProperties() { File file = new File(Variables.applicationHome + System.getProperty("file.separator") + "WEB-INF" + System.getProperty("file.separator") + "classes" + System.getProperty("file.separator") + "query.properties"); if (file.exists()) { Properties queryProperties = new Properties(); try { queryProperties.load(new FileInputStream(file)); Variables.queryGeneratorClassName = queryProperties.getProperty("query.queryGeneratorClassName"); Variables.abstractQueryClassName = queryProperties.getProperty("query.abstractQueryClassName"); Variables.abstractQueryManagerClassName = queryProperties.getProperty("query.abstractQueryManagerClassName"); Variables.abstractQueryUIManagerClassName = queryProperties.getProperty("query.abstractQueryUIManagerClassName"); Variables.abstractQueryITableManagerClassName = queryProperties.getProperty("query.abstractQueryITableManagerClassName"); Variables.viewIQueryGeneratorClassName = queryProperties.getProperty("query.viewIQueryGeneratorClassName"); Variables.recordsPerPageForSpreadSheet = Integer.parseInt(queryProperties.getProperty("spreadSheet.recordsPerPage")); Variables.recordsPerPageForTree = Integer.parseInt(queryProperties.getProperty("tree.recordsPerPage")); Variables.resultLimit = Integer.parseInt(queryProperties.getProperty("datasecurity.resultLimit")); Variables.exportDataThreadClassName = queryProperties.getProperty("query.exportDataThreadClassName"); Variables.dataQueryExecutionClassName = queryProperties.getProperty("query.dataQueryExecutionClassName"); Variables.properties = queryProperties; Variables.csmUtility = queryProperties.getProperty("query.csmUtility"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
private static void readProperties() { File file = new File(Variables.applicationHome + System.getProperty("file.separator") + "WEB-INF" + System.getProperty("file.separator") + "classes" + System.getProperty("file.separator") + "query.properties"); if (file.exists()) { Properties queryProperties = new Properties(); try { queryProperties.load(new FileInputStream(file)); Variables.queryGeneratorClassName = queryProperties.getProperty("query.queryGeneratorClassName"); Variables.abstractQueryClassName = queryProperties.getProperty("query.abstractQueryClassName"); Variables.abstractQueryManagerClassName = queryProperties.getProperty("query.abstractQueryManagerClassName"); Variables.abstractQueryUIManagerClassName = queryProperties.getProperty("query.abstractQueryUIManagerClassName"); Variables.abstractQueryITableManagerClassName = queryProperties.getProperty("query.abstractQueryITableManagerClassName"); Variables.viewIQueryGeneratorClassName = queryProperties.getProperty("query.viewIQueryGeneratorClassName"); Variables.recordsPerPageForSpreadSheet = Integer.parseInt(queryProperties.getProperty("spreadSheet.recordsPerPage")); Variables.recordsPerPageForTree = Integer.parseInt(queryProperties.getProperty("tree.recordsPerPage")); Variables.resultLimit = Integer.parseInt(queryProperties.getProperty("datasecurity.resultLimit")); Variables.exportDataThreadClassName = queryProperties.getProperty("query.exportDataThreadClassName"); Variables.dataQueryExecutionClassName = queryProperties.getProperty("query.dataQueryExecutionClassName"); Variables.properties = queryProperties; Variables.csmUtility = queryProperties.getProperty("query.csmUtility"); Variables.spreadSheetGeneratorClassName = queryProperties.getProperty("query.spreadSheetGeneratorClassName"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
private MediaSessionConfig getMediaSessionconfigFromParams(Parameters params) throws MsControlException { if (params == null) throw new MsControlException("Parameters are NULL"); Object obj; obj = params.get(STUN_HOST); if (obj == null) throw new MsControlException( "Params must have MediaSessionAndroid.STUN_HOST param"); if (!(obj instanceof String)) throw new MsControlException( "Parameter MediaSessionAndroid.STUN_HOST must be instance of String"); String stunHost= (String) obj; obj = params.get(STUN_PORT); if (obj == null) throw new MsControlException( "Params must have MediaSessionAndroid.STUN_PORT param"); if (!(obj instanceof Integer)) throw new MsControlException( "Parameter MediaSessionAndroid.STUN_PORT must be instance of Integer"); Integer stunPort = (Integer) obj; obj = params.get(NET_IF); if (obj == null) throw new MsControlException( "Params must have MediaSessionAndroid.NET_IF param"); if (!(obj instanceof NetIF)) throw new MsControlException( "Parameter MediaSessionAndroid.NET_IF must be instance of NetIF"); NetIF netIF = (NetIF) obj; obj = params.get(LOCAL_ADDRESS); if (obj == null) { throw new MsControlException( "Params must have MediaSessionAndroid.LOCAL_ADDRESS param"); } else if (!(obj instanceof InetAddress)) throw new MsControlException( "Parameter MediaSessionAndroid.LOCAL_ADDRESS must be instance of InetAddress"); InetAddress localAddress = (InetAddress) obj; obj = params.get(PUBLIC_ADDRESS); if (obj == null) { throw new MsControlException( "Params must have MediaSessionAndroid.PUBLIC_ADDRESS param"); } else if (!(obj instanceof InetAddress)) throw new MsControlException( "Parameter MediaSessionAndroid.PUBLIC_ADDRESS must be instance of InetAddress"); InetAddress publicAddress = (InetAddress) obj; Integer maxBW = null; obj = params.get(MAX_BANDWIDTH); if (obj == null) { } else if (!(obj instanceof Integer)) throw new MsControlException( "Parameter MediaSessionAndroid.MAX_BANDWIDTH must be instance of Integer"); else maxBW = (Integer) obj; Map<MediaType, Mode> mediaTypeModes = null; obj = params.get(STREAMS_MODES); if (obj == null) { } else try { mediaTypeModes = (Map<MediaType, Mode>) obj; } catch (ClassCastException e) { throw new MsControlException( "Parameter MediaSessionAndroid.STREAMS_MODES must be instance of Map<MediaType, Mode>", e); } ArrayList<AudioCodecType> audioCodecs = null; obj = params.get(AUDIO_CODECS); if (obj == null) { } else try { audioCodecs = (ArrayList<AudioCodecType>) obj; } catch (ClassCastException e) { throw new MsControlException( "Parameter MediaSessionAndroid.AUDIO_CODECS must be instance of ArrayList<AudioCodecType>", e); } ArrayList<VideoCodecType> videoCodecs = null; obj = params.get(VIDEO_CODECS); if (obj == null) { } else try { videoCodecs = (ArrayList<VideoCodecType>) obj; } catch (ClassCastException e) { throw new MsControlException( "Parameter MediaSessionAndroid.VIDEO_CODECS must be instance of ArrayList<VideoCodecType>", e); } Integer frameWidth = null; obj = params.get(FRAME_WIDTH); if (obj == null) { } else if (!(obj instanceof Size)) throw new MsControlException( "Parameter MediaSessionAndroid.FRAME_WIDTH must be instance of Integer"); else frameWidth = (Integer) obj; Integer frameHeight = null; obj = params.get(FRAME_HEIGTH); if (obj == null) { } else if (!(obj instanceof Size)) throw new MsControlException( "Parameter MediaSessionAndroid.FRAME_HEIGTH must be instance of Integer"); else frameHeight = (Integer) obj; Integer maxFrameRate = null; obj = params.get(MAX_FRAME_RATE); if (obj == null) { } else if (!(obj instanceof Integer)) throw new MsControlException( "Parameter MediaSessionAndroid.MAX_FRAME_RATE must be instance of Integer"); else maxFrameRate = (Integer) obj; Integer gopSize = null; obj = params.get(GOP_SIZE); if (obj == null) { } else if (!(obj instanceof Integer)) throw new MsControlException( "Parameter MediaSessionAndroid.GOP_SIZE must be instance of Integer"); else gopSize = (Integer) obj; Integer framesQueueSize = null; obj = params.get(FRAMES_QUEUE_SIZE); if (obj == null) { } else if (!(obj instanceof Integer)) throw new MsControlException( "Parameter MediaSessionAndroid.FRAMES_QUEUE_SIZE must be instance of Integer"); else framesQueueSize = (Integer) obj; return new MediaSessionConfig(netIF, localAddress, publicAddress, maxBW, mediaTypeModes, audioCodecs, videoCodecs, frameWidth, frameHeight, maxFrameRate, gopSize, framesQueueSize, stunHost, stunPort); }
private MediaSessionConfig getMediaSessionconfigFromParams(Parameters params) throws MsControlException { if (params == null) throw new MsControlException("Parameters are NULL"); Object obj; obj = params.get(STUN_HOST); if (obj == null) throw new MsControlException( "Params must have MediaSessionAndroid.STUN_HOST param"); if (!(obj instanceof String)) throw new MsControlException( "Parameter MediaSessionAndroid.STUN_HOST must be instance of String"); String stunHost= (String) obj; obj = params.get(STUN_PORT); if (obj == null) throw new MsControlException( "Params must have MediaSessionAndroid.STUN_PORT param"); if (!(obj instanceof Integer)) throw new MsControlException( "Parameter MediaSessionAndroid.STUN_PORT must be instance of Integer"); Integer stunPort = (Integer) obj; obj = params.get(NET_IF); if (obj == null) throw new MsControlException( "Params must have MediaSessionAndroid.NET_IF param"); if (!(obj instanceof NetIF)) throw new MsControlException( "Parameter MediaSessionAndroid.NET_IF must be instance of NetIF"); NetIF netIF = (NetIF) obj; obj = params.get(LOCAL_ADDRESS); if (obj == null) { throw new MsControlException( "Params must have MediaSessionAndroid.LOCAL_ADDRESS param"); } else if (!(obj instanceof InetAddress)) throw new MsControlException( "Parameter MediaSessionAndroid.LOCAL_ADDRESS must be instance of InetAddress"); InetAddress localAddress = (InetAddress) obj; obj = params.get(PUBLIC_ADDRESS); if (obj == null) { throw new MsControlException( "Params must have MediaSessionAndroid.PUBLIC_ADDRESS param"); } else if (!(obj instanceof InetAddress)) throw new MsControlException( "Parameter MediaSessionAndroid.PUBLIC_ADDRESS must be instance of InetAddress"); InetAddress publicAddress = (InetAddress) obj; Integer maxBW = null; obj = params.get(MAX_BANDWIDTH); if (obj == null) { } else if (!(obj instanceof Integer)) throw new MsControlException( "Parameter MediaSessionAndroid.MAX_BANDWIDTH must be instance of Integer"); else maxBW = (Integer) obj; Map<MediaType, Mode> mediaTypeModes = null; obj = params.get(STREAMS_MODES); if (obj == null) { } else try { mediaTypeModes = (Map<MediaType, Mode>) obj; } catch (ClassCastException e) { throw new MsControlException( "Parameter MediaSessionAndroid.STREAMS_MODES must be instance of Map<MediaType, Mode>", e); } ArrayList<AudioCodecType> audioCodecs = null; obj = params.get(AUDIO_CODECS); if (obj == null) { } else try { audioCodecs = (ArrayList<AudioCodecType>) obj; } catch (ClassCastException e) { throw new MsControlException( "Parameter MediaSessionAndroid.AUDIO_CODECS must be instance of ArrayList<AudioCodecType>", e); } ArrayList<VideoCodecType> videoCodecs = null; obj = params.get(VIDEO_CODECS); if (obj == null) { } else try { videoCodecs = (ArrayList<VideoCodecType>) obj; } catch (ClassCastException e) { throw new MsControlException( "Parameter MediaSessionAndroid.VIDEO_CODECS must be instance of ArrayList<VideoCodecType>", e); } Integer frameWidth = null; obj = params.get(FRAME_WIDTH); if (obj == null) { } else if (!(obj instanceof Integer)) throw new MsControlException( "Parameter MediaSessionAndroid.FRAME_WIDTH must be instance of Integer"); else frameWidth = (Integer) obj; Integer frameHeight = null; obj = params.get(FRAME_HEIGTH); if (obj == null) { } else if (!(obj instanceof Integer)) throw new MsControlException( "Parameter MediaSessionAndroid.FRAME_HEIGTH must be instance of Integer"); else frameHeight = (Integer) obj; Integer maxFrameRate = null; obj = params.get(MAX_FRAME_RATE); if (obj == null) { } else if (!(obj instanceof Integer)) throw new MsControlException( "Parameter MediaSessionAndroid.MAX_FRAME_RATE must be instance of Integer"); else maxFrameRate = (Integer) obj; Integer gopSize = null; obj = params.get(GOP_SIZE); if (obj == null) { } else if (!(obj instanceof Integer)) throw new MsControlException( "Parameter MediaSessionAndroid.GOP_SIZE must be instance of Integer"); else gopSize = (Integer) obj; Integer framesQueueSize = null; obj = params.get(FRAMES_QUEUE_SIZE); if (obj == null) { } else if (!(obj instanceof Integer)) throw new MsControlException( "Parameter MediaSessionAndroid.FRAMES_QUEUE_SIZE must be instance of Integer"); else framesQueueSize = (Integer) obj; return new MediaSessionConfig(netIF, localAddress, publicAddress, maxBW, mediaTypeModes, audioCodecs, videoCodecs, frameWidth, frameHeight, maxFrameRate, gopSize, framesQueueSize, stunHost, stunPort); }
public void sendJMS() throws Exception { Session session = null; try { session = hornetQMixIn.createJMSSession(); MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(QUEUE_NAME)); Message message = hornetQMixIn.createJMSMessage(TEST_MESSAGE); producer.send(message); MessageConsumer consumer = session.createConsumer(HornetQMixIn.getJMSQueue(QUEUE_NAME_RESPONSE)); Message receivedMessage = consumer.receive(3000); assertThat(receivedMessage, is(instanceOf(TextMessage.class))); assertThat(((TextMessage) receivedMessage).getText(), is(equalTo("\nBEFORE**\n" + TEST_MESSAGE + "\nAFTER**\n"))); } finally { HornetQMixIn.closeJMSSession(session); } }
public void sendJMS() throws Exception { Session session = null; try { session = hornetQMixIn.createJMSSession(); MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(QUEUE_NAME)); Message message = hornetQMixIn.createJMSMessage(TEST_MESSAGE); producer.send(message); MessageConsumer consumer = session.createConsumer(HornetQMixIn.getJMSQueue(QUEUE_NAME_RESPONSE)); Message receivedMessage = consumer.receive(3000); assertThat(receivedMessage, is(instanceOf(TextMessage.class))); assertThat(((TextMessage) receivedMessage).getText(), is(equalTo("\nBEFORE**\n" + TEST_MESSAGE + "\nAFTER**\n"))); assertThat(receivedMessage.getStringProperty("quickstart"), is(equalTo("hello_world_action"))); } finally { HornetQMixIn.closeJMSSession(session); } }
public boolean addPlayer(Player player) { if (!api.getLoungeWaypoint().isSet() || arena == null || !arena.isSetup(1)) { Messenger.tell(player, Message.WAYPOINTS_UNSET); return false; } PlayerData.store(player); PlayerData.reset(player); players.add(player.getName()); SafeTeleporter.tp(player, api.getExitWaypoint().getLocation()); return true; }
public boolean addPlayer(Player player) { if (!api.getLoungeWaypoint().isSet() || arena == null || !arena.isSetup(1)) { Messenger.tell(player, Message.WAYPOINTS_UNSET); return false; } PlayerData.store(player); PlayerData.reset(player); players.add(player.getName()); SafeTeleporter.tp(player, api.getLoungeWaypoint().getLocation()); return true; }
private void joinFragments(Pattern pattern, boolean skipStraySlash) { boolean inMultiSQLStatement = false; StringBuffer collector = null; ArrayList<String> tmp = new ArrayList<String>(); String sep = _prefs.getProcedureSeparator(); for (Iterator<String> iter = _queries.iterator(); iter.hasNext();) { String next = iter.next(); if (pattern.matcher(next.toUpperCase()).matches()) { inMultiSQLStatement = true; collector = new StringBuffer(next); collector.append(";"); continue; } if (next.startsWith(sep)) { inMultiSQLStatement = false; if (collector != null) { tmp.add(collector.toString()); collector = null; } else { if (skipStraySlash) { if (s_log.isDebugEnabled()) { s_log.debug("Detected stray proc separator(" + sep + "). Skipping"); } } else { tmp.add(next); } } continue; } if (inMultiSQLStatement) { collector.append(next); collector.append(";"); continue; } tmp.add(next); } _queries = tmp; }
private void joinFragments(Pattern pattern, boolean skipStraySlash) { boolean inMultiSQLStatement = false; StringBuffer collector = null; ArrayList<String> tmp = new ArrayList<String>(); String sep = _prefs.getProcedureSeparator(); for (Iterator<String> iter = _queries.iterator(); iter.hasNext();) { String next = iter.next(); if (pattern.matcher(next.toUpperCase()).matches()) { inMultiSQLStatement = true; collector = new StringBuffer(next); collector.append(";"); continue; } if (next.startsWith(sep) && ! next.startsWith("/*")) { inMultiSQLStatement = false; if (collector != null) { tmp.add(collector.toString()); collector = null; } else { if (skipStraySlash) { if (s_log.isDebugEnabled()) { s_log.debug("Detected stray proc separator(" + sep + "). Skipping"); } } else { tmp.add(next); } } continue; } if (inMultiSQLStatement) { collector.append(next); collector.append(";"); continue; } tmp.add(next); } _queries = tmp; }
protected final void namespaceFixUp (ElementImpl element, AttributeMap attributes){ if (DEBUG) { System.out.println("[ns-fixup] element:" +element.getNodeName()+ " uri: "+element.getNamespaceURI()); } String localUri, value, name, uri, prefix; if (attributes != null) { for (int k=0; k < attributes.getLength(); k++) { Attr attr = (Attr)attributes.getItem(k); uri = attr.getNamespaceURI(); if (uri != null && uri.equals(NamespaceSupport.XMLNS_URI)) { value = attr.getNodeValue(); if (value == null) { value=XMLSymbols.EMPTY_STRING; } if (value.equals(NamespaceSupport.XMLNS_URI)) { if (fErrorHandler != null) { modifyDOMError("No prefix other than 'xmlns' can be bound to 'http://www.w3.org/2000/xmlns/' namespace name", DOMError.SEVERITY_ERROR, attr); boolean continueProcess = fErrorHandler.handleError(fDOMError); if (!continueProcess) { throw new RuntimeException("Stopped at user request"); } } } else { prefix = attr.getPrefix(); prefix = (prefix == null || prefix.length() == 0) ? XMLSymbols.EMPTY_STRING :fSymbolTable.addSymbol(prefix); String localpart = fSymbolTable.addSymbol( attr.getLocalName()); if (prefix == XMLSymbols.EMPTY_STRING) { value = fSymbolTable.addSymbol(value); if (value.length() != 0) { fNamespaceBinder.declarePrefix(localpart, value); fLocalNSBinder.declarePrefix(localpart, value); if (fValidationHandler != null) { fValidationHandler.startPrefixMapping(localpart, value, null); } } else { } removeDefault (attr, attributes); continue; } else { value = fSymbolTable.addSymbol(value); fLocalNSBinder.declarePrefix(XMLSymbols.EMPTY_STRING, value); fNamespaceBinder.declarePrefix(XMLSymbols.EMPTY_STRING, value); if (fValidationHandler != null) { fValidationHandler.startPrefixMapping(XMLSymbols.EMPTY_STRING, value, null); } removeDefault (attr, attributes); continue; } } } } } uri = element.getNamespaceURI(); prefix = element.getPrefix(); if (uri != null) { uri = fSymbolTable.addSymbol(uri); prefix = (prefix == null || prefix.length() == 0) ? XMLSymbols.EMPTY_STRING :fSymbolTable.addSymbol(prefix); if (fNamespaceBinder.getURI(prefix) == uri) { } else { addNamespaceDecl(prefix, uri, element); fLocalNSBinder.declarePrefix(prefix, uri); fNamespaceBinder.declarePrefix(prefix, uri); if (fValidationHandler != null) { fValidationHandler.startPrefixMapping(prefix, uri, null); } } } else { String tagName = element.getNodeName(); int colon = tagName.indexOf(':'); if (colon > -1) { boolean continueProcess = true; if (fErrorHandler != null) { if (fNamespaceValidation) { modifyDOMError("DOM Level 1 node: "+tagName, DOMError.SEVERITY_FATAL_ERROR, element); fErrorHandler.handleError(fDOMError); } else { modifyDOMError("DOM Level 1 node: "+tagName, DOMError.SEVERITY_ERROR, element); continueProcess = fErrorHandler.handleError(fDOMError); } } if (fNamespaceValidation || !continueProcess) { throw new RuntimeException("DOM Level 1 node: "+tagName); } } else { uri = fNamespaceBinder.getURI(XMLSymbols.EMPTY_STRING); if (uri !=null && uri.length() > 0) { addNamespaceDecl (XMLSymbols.EMPTY_STRING, XMLSymbols.EMPTY_STRING, element); fLocalNSBinder.declarePrefix(XMLSymbols.EMPTY_STRING, XMLSymbols.EMPTY_STRING); fNamespaceBinder.declarePrefix(XMLSymbols.EMPTY_STRING, XMLSymbols.EMPTY_STRING); if (fValidationHandler != null) { fValidationHandler.startPrefixMapping(XMLSymbols.EMPTY_STRING, XMLSymbols.EMPTY_STRING, null); } } } } if (attributes != null) { attributes.cloneMap(fAttributeList); for (int i = 0; i < fAttributeList.size(); i++) { Attr attr = (Attr) fAttributeList.elementAt(i); attr.normalize(); if (DEBUG) { System.out.println("==>[ns-fixup] process attribute: "+attr.getNodeName()); } value = attr.getValue(); name = attr.getNodeName(); uri = attr.getNamespaceURI(); if (value == null) { value=XMLSymbols.EMPTY_STRING; } if (uri != null) { prefix = attr.getPrefix(); prefix = (prefix == null || prefix.length() == 0) ? XMLSymbols.EMPTY_STRING :fSymbolTable.addSymbol(prefix); String localpart = fSymbolTable.addSymbol( attr.getLocalName()); if (uri != null && uri.equals(NamespaceSupport.XMLNS_URI)) { continue; } if (removeDefault(attr, attributes)) { continue; } uri = fSymbolTable.addSymbol(uri); String declaredURI = fNamespaceBinder.getURI(prefix); if (prefix == XMLSymbols.EMPTY_STRING || declaredURI != uri) { name = attr.getNodeName(); String declaredPrefix = fNamespaceBinder.getPrefix(uri); if (declaredPrefix !=null && declaredPrefix !=XMLSymbols.EMPTY_STRING) { prefix = declaredPrefix; } else { if (prefix != XMLSymbols.EMPTY_STRING && fLocalNSBinder.getURI(prefix) == null) { } else { prefix = fSymbolTable.addSymbol(PREFIX +fNamespaceCounter++); while (fLocalNSBinder.getURI(prefix)!=null) { prefix = fSymbolTable.addSymbol(PREFIX +fNamespaceCounter++); } } addNamespaceDecl(prefix, uri, element); value = fSymbolTable.addSymbol(value); fLocalNSBinder.declarePrefix(prefix, value); fNamespaceBinder.declarePrefix(prefix, uri); if (fValidationHandler != null) { fValidationHandler.startPrefixMapping(prefix, uri, null); } } attr.setPrefix(prefix); } } else { int colon = name.indexOf(':'); if (colon > -1) { boolean continueProcess = true; if (fErrorHandler != null) { if (fNamespaceValidation) { modifyDOMError("DOM Level 1 node: "+name, DOMError.SEVERITY_FATAL_ERROR, attr); fErrorHandler.handleError(fDOMError); } else { modifyDOMError("DOM Level 1 node: "+name, DOMError.SEVERITY_ERROR, attr); continueProcess = fErrorHandler.handleError(fDOMError); } } if (fNamespaceValidation || !continueProcess) { throw new RuntimeException("DOM Level 1 node"); } } else { removeDefault(attr, attributes); } } } } }
protected final void namespaceFixUp (ElementImpl element, AttributeMap attributes){ if (DEBUG) { System.out.println("[ns-fixup] element:" +element.getNodeName()+ " uri: "+element.getNamespaceURI()); } String localUri, value, name, uri, prefix; if (attributes != null) { for (int k=0; k < attributes.getLength(); k++) { Attr attr = (Attr)attributes.getItem(k); uri = attr.getNamespaceURI(); if (uri != null && uri.equals(NamespaceSupport.XMLNS_URI)) { value = attr.getNodeValue(); if (value == null) { value=XMLSymbols.EMPTY_STRING; } if (value.equals(NamespaceSupport.XMLNS_URI)) { if (fErrorHandler != null) { modifyDOMError("No prefix other than 'xmlns' can be bound to 'http://www.w3.org/2000/xmlns/' namespace name", DOMError.SEVERITY_ERROR, attr); boolean continueProcess = fErrorHandler.handleError(fDOMError); if (!continueProcess) { throw new RuntimeException("Stopped at user request"); } } } else { prefix = attr.getPrefix(); prefix = (prefix == null || prefix.length() == 0) ? XMLSymbols.EMPTY_STRING :fSymbolTable.addSymbol(prefix); String localpart = fSymbolTable.addSymbol( attr.getLocalName()); if (prefix == XMLSymbols.PREFIX_XMLNS) { value = fSymbolTable.addSymbol(value); if (value.length() != 0) { fNamespaceBinder.declarePrefix(localpart, value); fLocalNSBinder.declarePrefix(localpart, value); if (fValidationHandler != null) { fValidationHandler.startPrefixMapping(localpart, value, null); } } else { } removeDefault (attr, attributes); continue; } else { value = fSymbolTable.addSymbol(value); fLocalNSBinder.declarePrefix(XMLSymbols.EMPTY_STRING, value); fNamespaceBinder.declarePrefix(XMLSymbols.EMPTY_STRING, value); if (fValidationHandler != null) { fValidationHandler.startPrefixMapping(XMLSymbols.EMPTY_STRING, value, null); } removeDefault (attr, attributes); continue; } } } } } uri = element.getNamespaceURI(); prefix = element.getPrefix(); if (uri != null) { uri = fSymbolTable.addSymbol(uri); prefix = (prefix == null || prefix.length() == 0) ? XMLSymbols.EMPTY_STRING :fSymbolTable.addSymbol(prefix); if (fNamespaceBinder.getURI(prefix) == uri) { } else { addNamespaceDecl(prefix, uri, element); fLocalNSBinder.declarePrefix(prefix, uri); fNamespaceBinder.declarePrefix(prefix, uri); if (fValidationHandler != null) { fValidationHandler.startPrefixMapping(prefix, uri, null); } } } else { String tagName = element.getNodeName(); int colon = tagName.indexOf(':'); if (colon > -1) { boolean continueProcess = true; if (fErrorHandler != null) { if (fNamespaceValidation) { modifyDOMError("DOM Level 1 node: "+tagName, DOMError.SEVERITY_FATAL_ERROR, element); fErrorHandler.handleError(fDOMError); } else { modifyDOMError("DOM Level 1 node: "+tagName, DOMError.SEVERITY_ERROR, element); continueProcess = fErrorHandler.handleError(fDOMError); } } if (fNamespaceValidation || !continueProcess) { throw new RuntimeException("DOM Level 1 node: "+tagName); } } else { uri = fNamespaceBinder.getURI(XMLSymbols.EMPTY_STRING); if (uri !=null && uri.length() > 0) { addNamespaceDecl (XMLSymbols.EMPTY_STRING, XMLSymbols.EMPTY_STRING, element); fLocalNSBinder.declarePrefix(XMLSymbols.EMPTY_STRING, XMLSymbols.EMPTY_STRING); fNamespaceBinder.declarePrefix(XMLSymbols.EMPTY_STRING, XMLSymbols.EMPTY_STRING); if (fValidationHandler != null) { fValidationHandler.startPrefixMapping(XMLSymbols.EMPTY_STRING, XMLSymbols.EMPTY_STRING, null); } } } } if (attributes != null) { attributes.cloneMap(fAttributeList); for (int i = 0; i < fAttributeList.size(); i++) { Attr attr = (Attr) fAttributeList.elementAt(i); attr.normalize(); if (DEBUG) { System.out.println("==>[ns-fixup] process attribute: "+attr.getNodeName()); } value = attr.getValue(); name = attr.getNodeName(); uri = attr.getNamespaceURI(); if (value == null) { value=XMLSymbols.EMPTY_STRING; } if (uri != null) { prefix = attr.getPrefix(); prefix = (prefix == null || prefix.length() == 0) ? XMLSymbols.EMPTY_STRING :fSymbolTable.addSymbol(prefix); String localpart = fSymbolTable.addSymbol( attr.getLocalName()); if (uri != null && uri.equals(NamespaceSupport.XMLNS_URI)) { continue; } if (removeDefault(attr, attributes)) { continue; } uri = fSymbolTable.addSymbol(uri); String declaredURI = fNamespaceBinder.getURI(prefix); if (prefix == XMLSymbols.EMPTY_STRING || declaredURI != uri) { name = attr.getNodeName(); String declaredPrefix = fNamespaceBinder.getPrefix(uri); if (declaredPrefix !=null && declaredPrefix !=XMLSymbols.EMPTY_STRING) { prefix = declaredPrefix; } else { if (prefix != XMLSymbols.EMPTY_STRING && fLocalNSBinder.getURI(prefix) == null) { } else { prefix = fSymbolTable.addSymbol(PREFIX +fNamespaceCounter++); while (fLocalNSBinder.getURI(prefix)!=null) { prefix = fSymbolTable.addSymbol(PREFIX +fNamespaceCounter++); } } addNamespaceDecl(prefix, uri, element); value = fSymbolTable.addSymbol(value); fLocalNSBinder.declarePrefix(prefix, value); fNamespaceBinder.declarePrefix(prefix, uri); if (fValidationHandler != null) { fValidationHandler.startPrefixMapping(prefix, uri, null); } } attr.setPrefix(prefix); } } else { int colon = name.indexOf(':'); if (colon > -1) { boolean continueProcess = true; if (fErrorHandler != null) { if (fNamespaceValidation) { modifyDOMError("DOM Level 1 node: "+name, DOMError.SEVERITY_FATAL_ERROR, attr); fErrorHandler.handleError(fDOMError); } else { modifyDOMError("DOM Level 1 node: "+name, DOMError.SEVERITY_ERROR, attr); continueProcess = fErrorHandler.handleError(fDOMError); } } if (fNamespaceValidation || !continueProcess) { throw new RuntimeException("DOM Level 1 node"); } } else { removeDefault(attr, attributes); } } } } }
public boolean respond(Request request) throws IOException { if (!request.url.contains("://")) { request.url = "http://" + request.headers.get("host") + request.url; } return false; }
public boolean respond(Request request) throws IOException { if (!request.url.startsWith("http://")) { request.url = "http://" + request.headers.get("host") + request.url; } return false; }
public void startAFKChecker() { final Integer afklimit = plugin.getConfig().getInt("afk-timer"); afkchecker = plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { @Override public void run() { try { for (Map map : MapUtilities.getUtilities().getMaps()) { for (String p : GameUtilities.getUtilities().getGame(map).getPlayersIngame()) { Player player = plugin.getServer().getPlayerExact(p); if (player == null) { continue; } Integer afktime = LocationStore.getAFKTime(player); Location lastloc = LocationStore.getLastLocation(player); Location currentloc = new Location(player.getWorld(), player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()); if (lastloc != null) { if (lastloc.getWorld().getName().equals(currentloc.getWorld().getName()) && lastloc.getBlockX() == currentloc.getBlockX() && lastloc.getBlockY() == currentloc.getBlockY() && lastloc.getBlockZ() == currentloc.getBlockZ()) { if (afktime == null) { LocationStore.setAFKTime(player, 1); } else { LocationStore.setAFKTime(player, afktime + 1); } if (afklimit.equals(afktime)) { GameUtilities.getUtilities().getGamePlayer(player).getGame().leaveGame(player); player.sendMessage(Localizer.getLocalizer().loadPrefixedMessage("PLAYER-KICKED-FOR-AFK")); LocationStore.setAFKTime(player, null); LocationStore.unsetLastLocation(player); } } else { LocationStore.setAFKTime(player, null); LocationStore.unsetLastLocation(player); } LocationStore.setLastLocation(player); } else { LocationStore.setLastLocation(player); } } } } catch (Exception e) { e.printStackTrace(); } } }, 0L, 20L); int remindEvery = plugin.getConfig().getInt("capture-reminder"); if (remindEvery != 0) { reminderTimer = plugin.getServer().getScheduler().runTaskTimer(plugin, new Runnable() { @Override public void run() { try { for (Map map : MapUtilities.getUtilities().getMaps()) { for (String p : GameUtilities.getUtilities().getGame(map).getPlayersIngame()) { Player player = Bukkit.getPlayerExact(p); if (player == null) { continue; } player.getLocation().getWorld().strikeLightningEffect(CapturePointUtilities.getUtilities().getFirstUncaptured(map).getLocation()); } return; } } catch (Exception e) { e.printStackTrace(); } } }, 0L, remindEvery * 20L); } }
public void startAFKChecker() { final Integer afklimit = plugin.getConfig().getInt("afk-timer"); afkchecker = plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { @Override public void run() { try { for (Map map : MapUtilities.getUtilities().getMaps()) { for (String p : GameUtilities.getUtilities().getGame(map).getPlayersIngame()) { Player player = plugin.getServer().getPlayerExact(p); if (player == null) { continue; } Integer afktime = LocationStore.getAFKTime(player); Location lastloc = LocationStore.getLastLocation(player); Location currentloc = new Location(player.getWorld(), player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()); if (lastloc != null) { if (lastloc.getWorld().getName().equals(currentloc.getWorld().getName()) && lastloc.getBlockX() == currentloc.getBlockX() && lastloc.getBlockY() == currentloc.getBlockY() && lastloc.getBlockZ() == currentloc.getBlockZ()) { if (afktime == null) { LocationStore.setAFKTime(player, 1); } else { LocationStore.setAFKTime(player, afktime + 1); } if (afklimit.equals(afktime)) { GameUtilities.getUtilities().getGamePlayer(player).getGame().leaveGame(player); player.sendMessage(Localizer.getLocalizer().loadPrefixedMessage("PLAYER-KICKED-FOR-AFK")); LocationStore.setAFKTime(player, null); LocationStore.unsetLastLocation(player); } } else { LocationStore.setAFKTime(player, null); LocationStore.unsetLastLocation(player); } LocationStore.setLastLocation(player); } else { LocationStore.setLastLocation(player); } } } } catch (Exception e) { e.printStackTrace(); } } }, 0L, 20L); int remindEvery = plugin.getConfig().getInt("capture-reminder"); if (remindEvery != 0) { reminderTimer = plugin.getServer().getScheduler().runTaskTimer(plugin, new Runnable() { @Override public void run() { try { for (Map map : MapUtilities.getUtilities().getMaps()) { for (String p : GameUtilities.getUtilities().getGame(map).getPlayersIngame()) { Player player = Bukkit.getPlayerExact(p); if (player == null) { continue; } if (CapturePointUtilities.getUtilities().getFirstUncaptured(map) != null && CapturePointUtilities.getUtilities().getFirstUncaptured(map).getLocation() != null) { player.getLocation().getWorld().strikeLightningEffect(CapturePointUtilities.getUtilities().getFirstUncaptured(map).getLocation()); } } return; } } catch (Exception e) { e.printStackTrace(); } } }, 0L, remindEvery * 20L); } }
private void refreshBusLineInfo() { ((TextView) findViewById(R.id.line_number)).setText(this.busLine.getNumber()); ((TextView) findViewById(R.id.line_name)).setText(this.busLine.getName()); ((ImageView) findViewById(R.id.bus_type)).setImageResource(Utils.getBusLineTypeImgFromType(this.busLine.getType())); BusLineSelectDirection selectBusLineDirection = new BusLineSelectDirection(this, this.busLine.getNumber(), this); ((TextView) findViewById(R.id.direction_string)).setOnClickListener(selectBusLineDirection); List<Integer> busLineDirection = Utils.getBusLineDirectionStringIdFromId(this.busLineDirection.getId()); ((TextView) findViewById(R.id.direction_main)).setText(getResources().getString(busLineDirection.get(0))); ((TextView) findViewById(R.id.direction_main)).setOnClickListener(selectBusLineDirection); if (busLineDirection.size() >= 2) { ((TextView) findViewById(R.id.direction_detail)).setVisibility(View.VISIBLE); ((TextView) findViewById(R.id.direction_detail)).setText(getResources().getString(busLineDirection.get(1))); ((TextView) findViewById(R.id.direction_detail)).setOnClickListener(selectBusLineDirection); } }
private void refreshBusLineInfo() { ((TextView) findViewById(R.id.line_number)).setText(this.busLine.getNumber()); ((TextView) findViewById(R.id.line_name)).setText(this.busLine.getName()); ((ImageView) findViewById(R.id.bus_type)).setImageResource(Utils.getBusLineTypeImgFromType(this.busLine.getType())); BusLineSelectDirection selectBusLineDirection = new BusLineSelectDirection(this, this.busLine.getNumber(), this); ((TextView) findViewById(R.id.direction_string)).setOnClickListener(selectBusLineDirection); List<Integer> busLineDirection = Utils.getBusLineDirectionStringIdFromId(this.busLineDirection.getId()); ((TextView) findViewById(R.id.direction_main)).setText(getResources().getString(busLineDirection.get(0))); ((TextView) findViewById(R.id.direction_main)).setOnClickListener(selectBusLineDirection); if (busLineDirection.size() >= 2) { ((TextView) findViewById(R.id.direction_detail)).setVisibility(View.VISIBLE); ((TextView) findViewById(R.id.direction_detail)).setText(getResources().getString(busLineDirection.get(1))); ((TextView) findViewById(R.id.direction_detail)).setOnClickListener(selectBusLineDirection); } else { ((TextView) findViewById(R.id.direction_detail)).setVisibility(View.INVISIBLE); } }
private void recoverItem(Context ctx, File archive, String objId, Properties props) throws IOException { try { String collId = props.getProperty(OWNER_ID); Collection coll = (Collection)HandleManager.resolveToObject(ctx, collId); WorkspaceItem wi = WorkspaceItem.create(ctx, coll, false); Packer packer = PackerFactory.instance(wi.getItem()); packer.unpack(archive); Item item = InstallItem.restoreItem(ctx, wi, objId); String colls = props.getProperty(OTHER_IDS); if (colls != null) { for (String link : colls.split(",")) { Collection linkC = (Collection)HandleManager.resolveToObject(ctx, link); linkC.addItem(item); } } if (props.getProperty(WITHDRAWN) != null) { item.withdraw(); } EmbargoManager.setEmbargo(ctx, item, null); } catch (AuthorizeException authE) { throw new IOException(authE); } catch (SQLException sqlE) { throw new IOException(sqlE); } }
private void recoverItem(Context ctx, File archive, String objId, Properties props) throws IOException { try { String collId = props.getProperty(OWNER_ID); Collection coll = (Collection)HandleManager.resolveToObject(ctx, collId); WorkspaceItem wi = WorkspaceItem.create(ctx, coll, false); Packer packer = PackerFactory.instance(wi.getItem()); packer.unpack(archive); Item item = InstallItem.restoreItem(ctx, wi, objId); String colls = props.getProperty(OTHER_IDS); if (colls != null) { for (String link : colls.split(",")) { Collection linkC = (Collection)HandleManager.resolveToObject(ctx, link); linkC.addItem(item); } } if (props.getProperty(WITHDRAWN) != null) { item.withdraw(); } EmbargoManager.setEmbargo(ctx, item); } catch (AuthorizeException authE) { throw new IOException(authE); } catch (SQLException sqlE) { throw new IOException(sqlE); } }
public AnimatedEntity(ILevel level, float startX, float startY, EntityType entityType, Animation animation) { super(level, startX, startY, entityType); this.animation = animation; }
public AnimatedEntity(ILevel level, float startX, float startY, EntityType entityType, Animation animation) { super(level, startX, startY, entityType); this.animation = animation; width = animation.getAnimation().getSprite(0, 0).getWidth(); height = animation.getAnimation().getSprite(0, 0).getHeight(); }
protected List<User> findUsersByGroupId(LdapUserQueryImpl query) { String baseDn = getDnForGroup(query.getGroupId()); String groupSearchFilter = "(& "+ldapConfiguration.getGroupSearchFilter()+")"; NamingEnumeration<SearchResult> enumeration = null; try { enumeration = initialContext.search(baseDn, groupSearchFilter, ldapConfiguration.getSearchControls()); List<User> userList = new ArrayList<User>(); List<String> userDnList = new ArrayList<String>(); while (enumeration.hasMoreElements()) { SearchResult result = (SearchResult) enumeration.nextElement(); Attribute memberAttribute = result.getAttributes().get("member"); NamingEnumeration<?> allMembers = memberAttribute.getAll(); while (allMembers.hasMoreElements() && userList.size() < query.getMaxResults()) { userDnList.add((String) allMembers.nextElement()); } } String queriedUserId = query.getId(); String userBaseDn = composeDn(ldapConfiguration.getUserSearchBase(), ldapConfiguration.getBaseDn()); for (String userDn : userDnList) { String userId = userDn.substring(userDn.indexOf("=")+1, userDn.indexOf(",")); if(queriedUserId == null) { query.userId(userId); } if(queriedUserId == null || queriedUserId.equals(userId)) { userList.addAll(findUsersWithoutGroupId(query, userBaseDn)); } } return userList; } catch (NamingException e) { throw new IdentityProviderException("Could not query for users", e); } finally { try { if (enumeration != null) { enumeration.close(); } } catch (Exception e) { } } }
protected List<User> findUsersByGroupId(LdapUserQueryImpl query) { String baseDn = getDnForGroup(query.getGroupId()); String groupSearchFilter = "(& "+ldapConfiguration.getGroupSearchFilter()+")"; NamingEnumeration<SearchResult> enumeration = null; try { enumeration = initialContext.search(baseDn, groupSearchFilter, ldapConfiguration.getSearchControls()); List<User> userList = new ArrayList<User>(); List<String> userDnList = new ArrayList<String>(); while (enumeration.hasMoreElements()) { SearchResult result = (SearchResult) enumeration.nextElement(); Attribute memberAttribute = result.getAttributes().get(ldapConfiguration.getGroupMemberAttribute()); NamingEnumeration<?> allMembers = memberAttribute.getAll(); while (allMembers.hasMoreElements() && userList.size() < query.getMaxResults()) { userDnList.add((String) allMembers.nextElement()); } } String queriedUserId = query.getId(); String userBaseDn = composeDn(ldapConfiguration.getUserSearchBase(), ldapConfiguration.getBaseDn()); for (String userDn : userDnList) { String userId = userDn.substring(userDn.indexOf("=")+1, userDn.indexOf(",")); if(queriedUserId == null) { query.userId(userId); } if(queriedUserId == null || queriedUserId.equals(userId)) { userList.addAll(findUsersWithoutGroupId(query, userBaseDn)); } } return userList; } catch (NamingException e) { throw new IdentityProviderException("Could not query for users", e); } finally { try { if (enumeration != null) { enumeration.close(); } } catch (Exception e) { } } }
final void defaultdict___init__(PyObject[] args, String[] kwds) { int nargs = args.length - kwds.length; if (nargs != 0) { defaultFactory = args[0]; if (defaultFactory.__findattr__("__call__") == null) { throw Py.TypeError("first argument must be callable"); } PyObject newargs[] = new PyObject[args.length - 1]; System.arraycopy(args, 1, newargs, 0, newargs.length); dict___init__(newargs , kwds); } }
final void defaultdict___init__(PyObject[] args, String[] kwds) { int nargs = args.length - kwds.length; if (nargs != 0) { defaultFactory = args[0]; if (!defaultFactory.isCallable()) { throw Py.TypeError("first argument must be callable"); } PyObject newargs[] = new PyObject[args.length - 1]; System.arraycopy(args, 1, newargs, 0, newargs.length); dict___init__(newargs , kwds); } }
public String renderNode(Object obj) throws Exception { String nodeIcon = expandIcon; String iconGroup = icon; String note = "" ; if(isSelected(obj)) { nodeIcon = colapseIcon; iconGroup = selectedIcon; note = " NodeSelected" ; } if(beanIconField_ != null && beanIconField_.length() > 0) { if(getFieldValue(obj, beanIconField_) != null) iconGroup = (String)getFieldValue(obj, beanIconField_); } String objId = String.valueOf(getId(obj)) ; String actionLink = event("ChangeNode", objId); StringBuilder builder = new StringBuilder(); if(nodeIcon.equals(expandIcon)) { builder.append(" <a class=\"").append(nodeIcon).append("\" href=\"").append(actionLink).append("\">") ; } else { builder.append(" <a class=\"").append(nodeIcon).append("\" onclick=\"eXo.portal.UIPortalControl.collapseTree(this)").append("\">") ; } if(uiPopupMenu_ == null) { builder.append(" <div class=\"NodeIcon ").append(iconGroup).append(note).append("\">").append(getFieldValue(obj, beanLabelField_)).append("</div>") ; } else { builder.append("<div class=\"NodeIcon ").append(iconGroup).append(note).append("\" ").append(uiPopupMenu_.getJSOnclickShowPopup(objId, null)).append(">") .append(getFieldValue(obj, beanLabelField_)).append("</div>") ; } builder.append(" </a>") ; return builder.toString(); }
public String renderNode(Object obj) throws Exception { String nodeIcon = expandIcon; String iconGroup = icon; String note = "" ; if(isSelected(obj)) { nodeIcon = colapseIcon; iconGroup = selectedIcon; note = " NodeSelected" ; } if(beanIconField_ != null && beanIconField_.length() > 0) { if(getFieldValue(obj, beanIconField_) != null) iconGroup = (String)getFieldValue(obj, beanIconField_); } String objId = String.valueOf(getId(obj)) ; String actionLink = event("ChangeNode", objId); StringBuilder builder = new StringBuilder(); if(nodeIcon.equals(expandIcon)) { builder.append(" <a class=\"").append(nodeIcon).append("\" href=\"").append(actionLink).append("\">") ; } else { builder.append(" <a class=\"").append(nodeIcon).append("\" onclick=\"eXo.portal.UIPortalControl.collapseTree(this)").append("\">") ; } if(uiPopupMenu_ == null) { builder.append(" <div class=\"NodeIcon ").append(iconGroup).append(note).append("\"").append(" title=\"").append(getFieldValue(obj, beanLabelField_)).append("\"").append(">").append(getFieldValue(obj, beanLabelField_)).append("</div>") ; } else { builder.append("<div class=\"NodeIcon ").append(iconGroup).append(note).append("\" ").append(uiPopupMenu_.getJSOnclickShowPopup(objId, null)).append(" title=\"").append(getFieldValue(obj, beanLabelField_)).append("\"").append(">") .append(getFieldValue(obj, beanLabelField_)).append("</div>") ; } builder.append(" </a>") ; return builder.toString(); }
public void lineAppended(IRegion line) { if (!isPatternSetup()) return; try { IDocument document = mConsole.getDocument(); String text = document.get(line.getOffset(), line.getLength()); Matcher matcher = mErrorPattern.matcher(text); if (matcher.matches()) { int linkOffset = line.getOffset() + matcher.start(mLinkGroup); int linkEnd = line.getOffset() + matcher.end(mLinkGroup); int linkLength = linkEnd - linkOffset; String filename = text.substring(matcher.start(mFilenameGroup), matcher.end(mFilenameGroup)); String lineStr = text.substring(matcher.start(mLineNoGroup), matcher.end(mLineNoGroup)); int lineno = Integer.parseInt(lineStr); IFile file = findFile(filename); if (file != null) { mConsole.addLink(new FileLink(file, null, -1, -1, lineno), linkOffset, linkLength); } } } catch (BadLocationException exception) { } }
public void lineAppended(IRegion line) { if (!isPatternSetup()) return; try { IDocument document = mConsole.getDocument(); String text = document.get(line.getOffset(), line.getLength()); Matcher matcher = mErrorPattern.matcher(text); if (matcher.matches()) { int linkOffset = line.getOffset() + matcher.start(mLinkGroup); int linkEnd = line.getOffset() + matcher.end(mLinkGroup); int linkLength = linkEnd - linkOffset; String filename = text.substring(matcher.start(mFilenameGroup), matcher.end(mFilenameGroup)); String lineStr = text.substring(matcher.start(mLineNoGroup), matcher.end(mLineNoGroup)); int lineno = Integer.parseInt(lineStr); IFile file = findFile(filename); if (file != null) { mConsole.addLink(new FileLink(file, null, -1, -1, lineno), linkOffset, linkLength); } } } catch (BadLocationException exception) { } catch (IndexOutOfBoundsException exception) { SchemeScriptPlugin.logException("Invalid regex group for interpreter error messages", exception); } }
public ClientFactory startApp() { client.getCurrentUser(new Callback<UserInfoTO>(){ @Override protected void ok(UserInfoTO user) { String token; if(!"".equals(Window.Location.getHash()) && "details".equals(Window.Location.getHash().split(":")[0].split("#")[1])){ token = Window.Location.getHash().split("#")[1]; } else { token = user.getLastPlaceVisited(); } if(token != null){ defaultPlace = historyMapper.getPlace(token); }else { defaultPlace = DEFAULT_PLACE; } startApp(defaultPlace); } @Override protected void unauthorized() { VitrinePlace vitrinePlace; if(Window.Location.getHash().split(":").length > 1){ vitrinePlace = new VitrinePlace(Window.Location.getHash().split(":")[1]); } else { vitrinePlace = new VitrinePlace(); } startApp(vitrinePlace); } protected void startApp(final Place defaultPlace){ client.institution("00a4966d-5442-4a44-9490-ef36f133a259").getInstitution(new Callback<Institution>(){ @Override protected void ok(Institution institution){ ClientProperties.setEncoded(ClientProperties.INSTITUTION_ASSETS_URL, institution.getAssetsURL()); ClientProperties.setEncoded(ClientProperties.INSTITUTION_NAME, institution.getName()); initGUI(); initActivityManagers(); initHistoryHandler(defaultPlace); initException(); initSCORM(); initPersonnel(); } }); } private void initPersonnel() { new Captain(bus, placeCtrl); new Dean(bus, client); } }); return this; }
public ClientFactory startApp() { client.getCurrentUser(new Callback<UserInfoTO>(){ @Override protected void ok(UserInfoTO user) { String token; if(!"".equals(Window.Location.getHash()) && "details".equals(Window.Location.getHash().split(":")[0].split("#")[1])){ token = Window.Location.getHash().split("#")[1]; } else { token = user.getLastPlaceVisited(); } if(token != null){ defaultPlace = historyMapper.getPlace(token); }else { defaultPlace = DEFAULT_PLACE; } startApp(defaultPlace); } @Override protected void unauthorized() { VitrinePlace vitrinePlace; if(Window.Location.getHash().split(":").length > 1 && "#vitrine".equalsIgnoreCase(Window.Location.getHash().split(":")[0])){ vitrinePlace = new VitrinePlace(Window.Location.getHash().split(":")[1]); } else { vitrinePlace = new VitrinePlace(); } startApp(vitrinePlace); } protected void startApp(final Place defaultPlace){ client.institution("00a4966d-5442-4a44-9490-ef36f133a259").getInstitution(new Callback<Institution>(){ @Override protected void ok(Institution institution){ ClientProperties.setEncoded(ClientProperties.INSTITUTION_ASSETS_URL, institution.getAssetsURL()); ClientProperties.setEncoded(ClientProperties.INSTITUTION_NAME, institution.getName()); initGUI(); initActivityManagers(); initHistoryHandler(defaultPlace); initException(); initSCORM(); initPersonnel(); } }); } private void initPersonnel() { new Captain(bus, placeCtrl); new Dean(bus, client); } }); return this; }
public void addRcaCaseTest() { User rcaCaseUser = new User("rcaCaseUser@arcatool.fi", "password").save(); assertNotNull(rcaCaseUser); rcaCaseUser.addRCACase("new unique rca case", "type", true, "test company", "14", true).save(); rcaCaseUser.save(); rcaCaseUser.refresh(); assertTrue(rcaCaseUser.cases.size() == 1); assertTrue(rcaCaseUser.myCases.size() == 1); RCACase rcaCase = RCACase.find("byName", "new unique rca case").first(); assertNotNull(rcaCase); assertTrue(rcaCaseUser.cases.contains(rcaCase)); assertTrue(rcaCaseUser.myCases.contains(rcaCase)); assertTrue(rcaCase.problem.name.equals("new unique rca case")); }
public void addRcaCaseTest() { User rcaCaseUser = new User("rcaCaseUser@arcatool.fi", "password").save(); assertNotNull(rcaCaseUser); rcaCaseUser.addRCACase("new unique rca case", "type", true, "test company", "14", true).save(); rcaCaseUser.save(); rcaCaseUser.refresh(); assertTrue(rcaCaseUser.cases.size() == 1); RCACase rcaCase = RCACase.find("byName", "new unique rca case").first(); assertNotNull(rcaCase); assertTrue(rcaCaseUser.cases.contains(rcaCase)); assertTrue(rcaCase.problem.name.equals("new unique rca case")); }
public static void main(String[] args) { Game g = new Game(); Scanner in = new Scanner(System.in); while (true) { System.out.println(g.board); System.out.println("Player " + g.currentPlayerIndex); Player p = g.getPlayer(g.currentPlayerIndex); System.out.println("Your hand: " + p.getHand()); System.out.println("Which tile do you want to play (index 0 to " + (p.getHand().size() - 1) + ")?"); int tileIndex = in.nextInt(); Tile tile = p.getHand().get(tileIndex); System.out.println("Give the rotation of the tile:"); int rotation = in.nextInt(); System.out.println("Give row to place tile:"); int row = in.nextInt(); System.out.println("Give column to place tile:"); int column = in.nextInt(); if (g.placeTile(tile, row, column, rotation)) { p.getHand().remove(tileIndex); System.out.println("Player who scored"); System.out.println(g.players); if (g.getPlayer(g.getCurrentPlayerIndex()).getPlaysLeft() == 0) { if (p.canSwapTiles()) { System.out.println("Do you want to swap your hand (0 = no, 1 = yes)?"); int answer = in.nextInt(); if (answer == 1) { p.swapTiles(); continue; } } p.refreshHand(); } } else { System.out.println("Invalid move: try again"); } } }
public static void main(String[] args) { Game g = new Game(); Scanner in = new Scanner(System.in); while (true) { System.out.println(g.board); System.out.println("Player " + g.getCurrentPlayerIndex()); Player p = g.getPlayer(g.getCurrentPlayerIndex()); System.out.println("Your hand: " + p.getHand()); System.out.println("Which tile do you want to play (index 0 to " + (p.getHand().size() - 1) + ")?"); int tileIndex = in.nextInt(); Tile tile = p.getHand().get(tileIndex); System.out.println("Give the rotation of the tile:"); int rotation = in.nextInt(); System.out.println("Give row to place tile:"); int row = in.nextInt(); System.out.println("Give column to place tile:"); int column = in.nextInt(); if (g.play(g.getCurrentPlayerIndex(), tile, row, column, rotation)) { p.getHand().remove(tileIndex); System.out.println("Player who scored"); System.out.println(g.players); if (g.getPlayer(g.getCurrentPlayerIndex()).getPlaysLeft() == 0) { if (p.canSwapTiles()) { System.out.println("Do you want to swap your hand (0 = no, 1 = yes)?"); int answer = in.nextInt(); if (answer == 1) { p.swapTiles(); continue; } } p.refreshHand(); } } else { System.out.println("Invalid move: try again"); } } }
public void run() { while (true) { Excerpt excerpt = chr.createExcerpt(); long size = excerpt.size(); long index = getLastIndex(); while (index < size && listeners.size() > 0) { log.debug("index:" + index + ",size:" + size); excerpt.index(index); Object o = excerpt.readObject(); for (MessageListener l : listeners) { log.info("notifying listener:" + l); l.onMessage(o); } index++; size = excerpt.size(); saveIndex(index); } excerpt.finish(); try { Thread.sleep(1); } catch (InterruptedException ie) { ie.printStackTrace(); } } }
public void run() { while (true) { Excerpt excerpt = chr.createExcerpt(); long size = excerpt.size(); long index = getLastIndex(); while (index < size && listeners.size() > 0) { log.debug("index:" + index + ",size:" + size); excerpt.index(index); Object o = excerpt.readObject(); for (MessageListener l : listeners) { log.info("notifying listener:" + l); l.onMessage(o); } index++; size = excerpt.size(); saveIndex(index); } excerpt.close(); try { Thread.sleep(1); } catch (InterruptedException ie) { ie.printStackTrace(); } } }
private HtmlElement generateMemberPageMain(boolean myPage) { final HtmlDiv master = new HtmlDiv("member_page"); if (member.canAccessUserInformations(Action.WRITE)) { final HtmlDiv modify = new HtmlDiv("float_right"); master.add(modify); modify.add(new ModifyMemberPageUrl().getHtmlLink(Context.tr("Change account settings"))); } final String title = (myPage) ? Context.tr("My page") : Context.tr("{0}''s page", member.getDisplayName()); final HtmlTitleBlock tBlock = new HtmlTitleBlock(title, 1); master.add(tBlock); final HtmlDiv main = new HtmlDiv("member"); master.add(main); final HtmlDiv memberId = new HtmlDiv("member_id"); final HtmlDiv avatarDiv = new HtmlDiv("float_left"); avatarDiv.add(MembersTools.getMemberAvatar(member)); memberId.add(avatarDiv); main.add(memberId); try { final HtmlList memberIdList = new HtmlList(); memberId.add(memberIdList); if (member.canAccessUserInformations(Action.READ)) { final HtmlSpan login = new HtmlSpan("id_category"); login.addText(Context.trc("login (noun)", "Login: ")); memberIdList.add(new PlaceHolderElement().add(login).addText(member.getLogin())); final HtmlSpan fullname = new HtmlSpan("id_category"); fullname.addText(Context.tr("Fullname: ")); if (member.getFullname() != null) { memberIdList.add(new PlaceHolderElement().add(fullname).addText(member.getFullname())); } else { memberIdList.add(new PlaceHolderElement().add(fullname)); } final HtmlSpan email = new HtmlSpan("id_category"); email.addText(Context.tr("Email: ")); memberIdList.add(new PlaceHolderElement().add(email).addText(member.getEmail())); } else { final HtmlSpan name = new HtmlSpan("id_category"); name.addText(Context.tr("Name: ")); memberIdList.add(new PlaceHolderElement().add(name).addText(member.getDisplayName())); } final Locale userLocale = Context.getLocalizator().getLocale(); final HtmlSpan country = new HtmlSpan("id_category"); country.addText(Context.tr("Country: ")); memberIdList.add(new PlaceHolderElement().add(country).addText(member.getLocale().getDisplayCountry(userLocale))); final HtmlSpan language = new HtmlSpan("id_category"); language.addText(Context.tr("Language: ")); memberIdList.add(new PlaceHolderElement().add(language).addText(member.getLocale().getDisplayLanguage(userLocale))); final HtmlSpan karma = new HtmlSpan("id_category"); karma.addText(Context.tr("Karma: ")); memberIdList.add(new PlaceHolderElement().add(karma).addText("" + member.getKarma())); } catch (final UnauthorizedOperationException e) { getSession().notifyError("An error prevented us from displaying user information. Please notify us."); throw new ShallNotPassException("Error while gathering user information", e); } if (!member.canGetInternalAccount()) { final HtmlTitleBlock recent = new HtmlTitleBlock(Context.tr("Recent activity"), 2); main.add(recent); recent.add(ActivityTab.generateActivities(member, url)); } return master; }
private HtmlElement generateMemberPageMain(boolean myPage) { final HtmlDiv master = new HtmlDiv("member_page"); if (member.canAccessUserInformations(Action.WRITE)) { final HtmlDiv modify = new HtmlDiv("float_right"); master.add(modify); modify.add(new ModifyMemberPageUrl().getHtmlLink(Context.tr("Change member settings"))); } final String title = (myPage) ? Context.tr("My page") : Context.tr("{0}''s page", member.getDisplayName()); final HtmlTitleBlock tBlock = new HtmlTitleBlock(title, 1); master.add(tBlock); final HtmlDiv main = new HtmlDiv("member"); master.add(main); final HtmlDiv memberId = new HtmlDiv("member_id"); final HtmlDiv avatarDiv = new HtmlDiv("float_left"); avatarDiv.add(MembersTools.getMemberAvatar(member)); memberId.add(avatarDiv); main.add(memberId); try { final HtmlList memberIdList = new HtmlList(); memberId.add(memberIdList); if (member.canAccessUserInformations(Action.READ)) { final HtmlSpan login = new HtmlSpan("id_category"); login.addText(Context.trc("login (noun)", "Login: ")); memberIdList.add(new PlaceHolderElement().add(login).addText(member.getLogin())); final HtmlSpan fullname = new HtmlSpan("id_category"); fullname.addText(Context.tr("Fullname: ")); if (member.getFullname() != null) { memberIdList.add(new PlaceHolderElement().add(fullname).addText(member.getFullname())); } else { memberIdList.add(new PlaceHolderElement().add(fullname)); } final HtmlSpan email = new HtmlSpan("id_category"); email.addText(Context.tr("Email: ")); memberIdList.add(new PlaceHolderElement().add(email).addText(member.getEmail())); } else { final HtmlSpan name = new HtmlSpan("id_category"); name.addText(Context.tr("Name: ")); memberIdList.add(new PlaceHolderElement().add(name).addText(member.getDisplayName())); } final Locale userLocale = Context.getLocalizator().getLocale(); final HtmlSpan country = new HtmlSpan("id_category"); country.addText(Context.tr("Country: ")); memberIdList.add(new PlaceHolderElement().add(country).addText(member.getLocale().getDisplayCountry(userLocale))); final HtmlSpan language = new HtmlSpan("id_category"); language.addText(Context.tr("Language: ")); memberIdList.add(new PlaceHolderElement().add(language).addText(member.getLocale().getDisplayLanguage(userLocale))); final HtmlSpan karma = new HtmlSpan("id_category"); karma.addText(Context.tr("Karma: ")); memberIdList.add(new PlaceHolderElement().add(karma).addText("" + member.getKarma())); } catch (final UnauthorizedOperationException e) { getSession().notifyError("An error prevented us from displaying user information. Please notify us."); throw new ShallNotPassException("Error while gathering user information", e); } if (!member.canGetInternalAccount()) { final HtmlTitleBlock recent = new HtmlTitleBlock(Context.tr("Recent activity"), 2); main.add(recent); recent.add(ActivityTab.generateActivities(member, url)); } return master; }
public void parseCommand(String cmd, String[] args) { PacketHandler ph = new PacketHandler(); DataManager dm = new DataManager(); if(cmd.equalsIgnoreCase("help")) { ph.sendPacket(new Packet5Message("/quit [message] - Disconnects you from the server."), client, this.socket); ph.sendPacket(new Packet5Message("/stop - Stops the server. (Op-only)"), client, this.socket); ph.sendPacket(new Packet5Message("/say <message> - Broadcasts a server message."), client, this.socket); ph.sendPacket(new Packet5Message("/ping - Ping! Pong!"), client, this.socket); ph.sendPacket(new Packet5Message("/kill <name> - Kills a user."), client, this.socket); ph.sendPacket(new Packet5Message("/nuke - NUKE THE CHAT!!!!! (Op-only)"), client, this.socket); ph.sendPacket(new Packet5Message("/whois <name> - Gets information on a user."), client, this.socket); ph.sendPacket(new Packet5Message("/list - Lists users in the chat."), client, this.socket); ph.sendPacket(new Packet5Message("/me <message> - Makes you do an action."), client, this.socket); ph.sendPacket(new Packet5Message("/nick <name> - Changes your name!"), client, this.socket); ph.sendPacket(new Packet5Message("/op <name> - Ops a user."), client, this.socket); ph.sendPacket(new Packet5Message("/deop <name> - De-ops a user."), client, this.socket); ph.sendPacket(new Packet5Message("/kick <name> - Kicks a user."), client, this.socket); ph.sendPacket(new Packet5Message("/ban <name> - Bans a user."), client, this.socket); ph.sendPacket(new Packet5Message("/unban <name> - Unbans a user."), client, this.socket); ph.sendPacket(new Packet5Message("/banip <ip> - Bans an IP."), client, this.socket); ph.sendPacket(new Packet5Message("/unbanip <ip> - Unbans an IP."), client, this.socket); } else if(cmd.equalsIgnoreCase("quit")) { String msg = ""; for(int i = 0; i < args.length; i++) msg += args[i] + " "; msg = msg.trim(); System.out.println(client.getUsername() + " quit. Reason: " + msg) ; Packet4Kick packet = new Packet4Kick("Quitting. Reason: " + msg); Packet5Message packet2 = new Packet5Message(client.getUsername() + " quit. (" + msg + ")"); ph.sendPacket(packet, client, this.socket); client.stopKeepAliveThread(); client.stopKeepAliveSendThread(); clients.remove(client); ph.sendAllPacket(packet2, clients, this.socket); } else if(cmd.equalsIgnoreCase("stop")) { if(dm.isOp(client.getUsername())) { System.out.println(client.getUsername() + " stopped the server."); System.exit(0); } else { Packet5Message packet = new Packet5Message("You are not an op."); ph.sendPacket(packet, client, this.socket); } } else if(cmd.equalsIgnoreCase("say")) { if(dm.isOp(client.getUsername())) { String msg = ""; for(int i = 0; i < args.length; i++) msg += args[i] + " "; msg = msg.trim(); Packet5Message packet = new Packet5Message("[Server] " + msg); ph.sendAllPacket(packet, clients, this.socket); } else { Packet5Message packet = new Packet5Message("You are not an op."); ph.sendPacket(packet, client, this.socket); } } else if(cmd.equalsIgnoreCase("ping")) { Packet5Message packet = new Packet5Message("Pong!"); ph.sendPacket(packet, client, this.socket); } else if(cmd.equalsIgnoreCase("kill")) { if(args.length < 1) { Packet5Message packet = new Packet5Message("Not enough paramters."); ph.sendPacket(packet, client, this.socket); } else { Packet5Message packet = new Packet5Message(client.getUsername() + " was kicked for killing " + args[0] + ". " + args[0] + " will be missed. :("); Packet4Kick packet2 = new Packet4Kick("YOU MURDERER, YOU KILLED " + args[0].toUpperCase() + "! GET OUT!!!!!"); ph.sendAllExcludePacket(packet, clients, client, this.socket); ph.sendPacket(packet2, client, this.socket); client.stopKeepAliveThread(); client.stopKeepAliveSendThread(); clients.remove(client); } } else if(cmd.equalsIgnoreCase("nuke")) { if(!dm.isOp(client.getUsername())) { Packet5Message packet = new Packet5Message("You are not an op."); ph.sendPacket(packet, client, this.socket); } else { try { System.out.println("Nuke started!"); Packet5Message packet = new Packet5Message("IT'S NUKE TIME OH BOY!!!!!"); ph.sendAllPacket(packet, clients, this.socket); packet = new Packet5Message("NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE"); for(int i = 0; i < 1000; i++) { if((i % 100) == 0) System.out.println("Packets left: " + (1000 - i)); ph.sendAllPacket(packet, clients, this.socket); Thread.sleep(10); } System.out.println("Nuke ended!"); packet = new Packet5Message("Phew, now that the nuke is over, continue chatting!"); ph.sendAllPacket(packet, clients, this.socket); } catch(InterruptedException e) { System.out.println("Nuke command thread was interrupted."); } } } else if(cmd.equalsIgnoreCase("whois")) { if(args.length < 1) { Packet5Message packet = new Packet5Message("Not enough paramters."); ph.sendPacket(packet, client, this.socket); } else { ClientData client2 = findClient(args[0]); if(client2 != null) { String msg = "IP: " + client2.getIP().getHostAddress() + "\n"; msg += "Port: " + client2.getPort() + "\n"; msg += "Hostname: " + client2.getIP().getCanonicalHostName(); Packet5Message packet = new Packet5Message(msg); ph.sendPacket(packet, client, this.socket); } else { Packet5Message packet = new Packet5Message("User not found."); ph.sendPacket(packet, client, this.socket); } } } else if(cmd.equalsIgnoreCase("list")) { String msg = "Online Users: "; for(int i = 0; i < clients.size(); i++) { ClientData client2 = (ClientData)clients.get(i); msg += client2.getUsername() + ", "; } Packet5Message packet = new Packet5Message(msg.substring(0, Math.min(msg.length() - 2, 500))); ph.sendPacket(packet, client, this.socket); } else if(cmd.equalsIgnoreCase("me")) { String msg = ""; for(int i = 0; i < args.length; i++) msg += args[i] + " "; msg = msg.trim(); System.out.println(client.getUsername() + " did action: " + msg); Packet5Message packet = new Packet5Message("*" + client.getUsername() + " " + msg); ph.sendAllPacket(packet, clients, this.socket); } else if(cmd.equalsIgnoreCase("nick")) { if(args.length < 1) { Packet5Message packet = new Packet5Message("Not enough paramters."); ph.sendPacket(packet, client, this.socket); } else if(args[0].equalsIgnoreCase(client.getUsername())) { Packet5Message packet = new Packet5Message("Your name is already " + args[0] + "."); ph.sendPacket(packet, client, this.socket); } else if(nameTaken(args[0])) { Packet5Message packet = new Packet5Message("That name is taken."); ph.sendPacket(packet, client, this.socket); } else if(dm.isOp(args[0]) && !dm.isOp(client.getUsername())) { Packet5Message packet = new Packet5Message("You can't /nick to an op's name if you aren't an op."); ph.sendPacket(packet, client, this.socket); } else { System.out.println(client.getUsername() + " has changed name to " + args[0]); Packet5Message packet = new Packet5Message(client.getUsername() + " is now known as " + args[0]); clients.remove(client); client.setUsername(args[0]); clients.add(client); Packet6NameChange packet2 = new Packet6NameChange(args[0]); ph.sendAllPacket(packet, clients, this.socket); ph.sendPacket(packet2, client, this.socket); } } else if(cmd.equalsIgnoreCase("op")) { if(dm.isOp(client.getUsername())) { if(args.length < 1) { Packet5Message packet = new Packet5Message("Not enough paramters."); ph.sendPacket(packet, client, this.socket); } else if(args[0].equalsIgnoreCase(client.getUsername())) { Packet5Message packet = new Packet5Message("You can not op yourself."); ph.sendPacket(packet, client, this.socket); } else if(dm.isOp(args[0])) { Packet5Message packet = new Packet5Message("That user is already an op."); ph.sendPacket(packet, client, this.socket); } else { dm.addOp(args[0]); System.out.println(client.getUsername() + " opped " + args[0] + "."); Packet5Message packet = new Packet5Message(args[0] + " has been opped."); Packet5Message packet2 = new Packet5Message("You are now an op!"); ph.sendPacket(packet, client, this.socket); ClientData client2 = findClient(args[0]); if(client2 != null) ph.sendPacket(packet2, client2, this.socket); } } else { Packet5Message packet = new Packet5Message("You are not an op."); ph.sendPacket(packet, client, this.socket); } } else if(cmd.equalsIgnoreCase("deop")) { if(dm.isOp(client.getUsername())) { if(args.length < 1) { Packet5Message packet = new Packet5Message("Not enough paramters."); ph.sendPacket(packet, client, this.socket); } else if(args[0].equalsIgnoreCase(client.getUsername())) { Packet5Message packet = new Packet5Message("You can not deop yourself."); ph.sendPacket(packet, client, this.socket); } else if(!dm.isOp(args[0])) { Packet5Message packet = new Packet5Message("That user is not an op."); ph.sendPacket(packet, client, this.socket); } else { dm.removeOp(args[0]); System.out.println(client.getUsername() + " deopped " + args[0] + "."); Packet5Message packet = new Packet5Message(args[0] + " has been deopped."); Packet5Message packet2 = new Packet5Message("You are no longer an op!"); ph.sendPacket(packet, client, this.socket); ClientData client2 = findClient(args[0]); if(client2 != null) ph.sendPacket(packet2, client2, this.socket); } } else { Packet5Message packet = new Packet5Message("You are not an op."); ph.sendPacket(packet, client, this.socket); } } else if(cmd.equalsIgnoreCase("kick")) { if(dm.isOp(client.getUsername())) { if(args.length < 1) { Packet5Message packet = new Packet5Message("Not enough paramters."); ph.sendPacket(packet, client, this.socket); } else if(args[0].equalsIgnoreCase(client.getUsername())) { Packet5Message packet = new Packet5Message("You can not kick yourself."); ph.sendPacket(packet, client, this.socket); } else if(findClient(args[0]) == null) { Packet5Message packet = new Packet5Message("That user isn't in the chat."); ph.sendPacket(packet, client, this.socket); } else { String msg = ""; for(int i = 1; i < args.length; i++) msg += args[i] + " "; msg = msg.trim(); System.out.println(client.getUsername() + " kicked " + args[0] + " with reason: " + msg); Packet5Message packet = new Packet5Message(args[0] + " has been kicked. (" + (msg.equals("") ? "No reason." : msg) + ")"); Packet4Kick packet2 = new Packet4Kick("You were kicked: " + (msg.equals("") ? "No reason." : msg)); ClientData client2 = findClient(args[0]); ph.sendPacket(packet2, client2, this.socket); client2.stopKeepAliveThread(); client2.stopKeepAliveSendThread(); clients.remove(client2); ph.sendAllPacket(packet, clients, this.socket); } } else { Packet5Message packet = new Packet5Message("You are not an op."); ph.sendPacket(packet, client, this.socket); } } else if(cmd.equalsIgnoreCase("ban")) { if(dm.isOp(client.getUsername())) { if(args.length < 1) { Packet5Message packet = new Packet5Message("Not enough paramters."); ph.sendPacket(packet, client, this.socket); } else if(args[0].equalsIgnoreCase(client.getUsername())) { Packet5Message packet = new Packet5Message("You can not ban yourself."); ph.sendPacket(packet, client, this.socket); } else if(dm.isBanned(args[0])) { Packet5Message packet = new Packet5Message("That user is already banned."); ph.sendPacket(packet, client, this.socket); } else { String msg = ""; for(int i = 1; i < args.length; i++) msg += args[i] + " "; msg = msg.trim(); dm.addBan(args[0]); System.out.println(client.getUsername() + " banned " + args[0] + " with reason: " + msg); Packet5Message packet = new Packet5Message(args[0] + " has been banned. (" + (msg.equals("") ? "No reason." : msg) + ")"); Packet4Kick packet2 = new Packet4Kick("You have been banned: " + (msg.equals("") ? "No reason." : msg)); ClientData client2 = findClient(args[0]); if(client2 != null) { ph.sendPacket(packet2, client2, this.socket); client2.stopKeepAliveThread(); client2.stopKeepAliveSendThread(); clients.remove(client2); } ph.sendAllPacket(packet, clients, this.socket); } } else { Packet5Message packet = new Packet5Message("You are not an op."); ph.sendPacket(packet, client, this.socket); } } else if(cmd.equalsIgnoreCase("unban")) { if(dm.isOp(client.getUsername())) { if(args.length < 1) { Packet5Message packet = new Packet5Message("Not enough paramters."); ph.sendPacket(packet, client, this.socket); } else if(args[0].equalsIgnoreCase(client.getUsername())) { Packet5Message packet = new Packet5Message("You can not unban yourself."); ph.sendPacket(packet, client, this.socket); } else if(!dm.isBanned(args[0])) { Packet5Message packet = new Packet5Message("That user is not banned."); ph.sendPacket(packet, client, this.socket); } else { dm.removeBan(args[0]); System.out.println(client.getUsername() + " unbanned " + args[0] + "."); Packet5Message packet = new Packet5Message(args[0] + " has been unbanned."); ph.sendPacket(packet, client, this.socket); } } else { Packet5Message packet = new Packet5Message("You are not an op."); ph.sendPacket(packet, client, this.socket); } } else if(cmd.equalsIgnoreCase("banip")) { if(dm.isOp(client.getUsername())) { if(args.length < 1) { Packet5Message packet = new Packet5Message("Not enough paramters."); ph.sendPacket(packet, client, this.socket); } else { InetAddress ip = null; try { ip = InetAddress.getByName(args[0]); } catch(UnknownHostException e) { } if(ip == null) { Packet5Message packet = new Packet5Message("The IP is invalid."); ph.sendPacket(packet, client, this.socket); } else if(ip == client.getIP()) { Packet5Message packet = new Packet5Message("You can not ban your own IP."); ph.sendPacket(packet, client, this.socket); } else if(dm.isIPBanned(ip.getHostAddress())) { Packet5Message packet = new Packet5Message("That IP is already banned."); ph.sendPacket(packet, client, this.socket); } else { String msg = ""; for(int i = 1; i < args.length; i++) msg += args[i] + " "; msg = msg.trim(); dm.addIPBan(ip.getHostAddress()); System.out.println(client.getUsername() + " banned the IP " + ip.getHostAddress() + " with reason: " + msg); Packet5Message packet = new Packet5Message("The IP " + ip.getHostAddress() + " has been banned. (" + (msg.equals("") ? "No reason." : msg) + ")"); Packet4Kick packet2 = new Packet4Kick("Your IP has been banned: " + (msg.equals("") ? "No reason." : msg)); ClientData client2 = findClient(ip); if(client2 != null) { ph.sendPacket(packet2, client2, this.socket); client2.stopKeepAliveThread(); client2.stopKeepAliveSendThread(); clients.remove(client2); } ph.sendAllPacket(packet, clients, this.socket); } } } else { Packet5Message packet = new Packet5Message("You are not an op."); ph.sendPacket(packet, client, this.socket); } } else if(cmd.equalsIgnoreCase("unbanip")) { if(dm.isOp(client.getUsername())) { if(args.length < 1) { Packet5Message packet = new Packet5Message("Not enough paramters."); ph.sendPacket(packet, client, this.socket); } else { InetAddress ip = null; try { ip = InetAddress.getByName(args[0]); } catch(UnknownHostException e) { } if(ip == null) { Packet5Message packet = new Packet5Message("The IP is invalid."); ph.sendPacket(packet, client, this.socket); } else if(ip == client.getIP()) { Packet5Message packet = new Packet5Message("You can not unban your own IP."); ph.sendPacket(packet, client, this.socket); } else if(!dm.isIPBanned(ip.getHostAddress())) { Packet5Message packet = new Packet5Message("That IP is not banned."); ph.sendPacket(packet, client, this.socket); } else { dm.removeIPBan(ip.getHostAddress()); System.out.println(client.getUsername() + " unbanned the IP " + ip.getHostAddress() + "."); Packet5Message packet = new Packet5Message("The IP " + ip.getHostAddress() + " has been unbanned."); ph.sendPacket(packet, client, this.socket); } } } else { Packet5Message packet = new Packet5Message("You are not an op."); ph.sendPacket(packet, client, this.socket); } } else { System.out.println("Command \"" + cmd + "\" not found."); Packet5Message packet = new Packet5Message("Unknown command."); ph.sendPacket(packet, client, this.socket); } }
public void parseCommand(String cmd, String[] args) { PacketHandler ph = new PacketHandler(); DataManager dm = new DataManager(); if(cmd.equalsIgnoreCase("help")) { ph.sendPacket(new Packet5Message("/quit [message] - Disconnects you from the server."), client, this.socket); ph.sendPacket(new Packet5Message("/stop - Stops the server. (Op-only)"), client, this.socket); ph.sendPacket(new Packet5Message("/say <message> - Broadcasts a server message."), client, this.socket); ph.sendPacket(new Packet5Message("/ping - Ping! Pong!"), client, this.socket); ph.sendPacket(new Packet5Message("/kill <name> - Kills a user."), client, this.socket); ph.sendPacket(new Packet5Message("/nuke - NUKE THE CHAT!!!!! (Op-only)"), client, this.socket); ph.sendPacket(new Packet5Message("/whois <name> - Gets information on a user."), client, this.socket); ph.sendPacket(new Packet5Message("/list - Lists users in the chat."), client, this.socket); ph.sendPacket(new Packet5Message("/me <message> - Makes you do an action."), client, this.socket); ph.sendPacket(new Packet5Message("/nick <name> - Changes your name!"), client, this.socket); ph.sendPacket(new Packet5Message("/op <name> - Ops a user. (Op-only)"), client, this.socket); ph.sendPacket(new Packet5Message("/deop <name> - De-ops a user. (Op-only)"), client, this.socket); ph.sendPacket(new Packet5Message("/kick <name> - Kicks a user. (Op-only)"), client, this.socket); ph.sendPacket(new Packet5Message("/ban <name> - Bans a user. (Op-only)"), client, this.socket); ph.sendPacket(new Packet5Message("/unban <name> - Unbans a user. (Op-only)"), client, this.socket); ph.sendPacket(new Packet5Message("/banip <ip> - Bans an IP. (Op-only)"), client, this.socket); ph.sendPacket(new Packet5Message("/unbanip <ip> - Unbans an IP. (Op-only)"), client, this.socket); } else if(cmd.equalsIgnoreCase("quit")) { String msg = ""; for(int i = 0; i < args.length; i++) msg += args[i] + " "; msg = msg.trim(); System.out.println(client.getUsername() + " quit. Reason: " + msg) ; Packet4Kick packet = new Packet4Kick("Quitting. Reason: " + msg); Packet5Message packet2 = new Packet5Message(client.getUsername() + " quit. (" + msg + ")"); ph.sendPacket(packet, client, this.socket); client.stopKeepAliveThread(); client.stopKeepAliveSendThread(); clients.remove(client); ph.sendAllPacket(packet2, clients, this.socket); } else if(cmd.equalsIgnoreCase("stop")) { if(dm.isOp(client.getUsername())) { System.out.println(client.getUsername() + " stopped the server."); System.exit(0); } else { Packet5Message packet = new Packet5Message("You are not an op."); ph.sendPacket(packet, client, this.socket); } } else if(cmd.equalsIgnoreCase("say")) { if(dm.isOp(client.getUsername())) { String msg = ""; for(int i = 0; i < args.length; i++) msg += args[i] + " "; msg = msg.trim(); Packet5Message packet = new Packet5Message("[Server] " + msg); ph.sendAllPacket(packet, clients, this.socket); } else { Packet5Message packet = new Packet5Message("You are not an op."); ph.sendPacket(packet, client, this.socket); } } else if(cmd.equalsIgnoreCase("ping")) { Packet5Message packet = new Packet5Message("Pong!"); ph.sendPacket(packet, client, this.socket); } else if(cmd.equalsIgnoreCase("kill")) { if(args.length < 1) { Packet5Message packet = new Packet5Message("Not enough paramters."); ph.sendPacket(packet, client, this.socket); } else { Packet5Message packet = new Packet5Message(client.getUsername() + " was kicked for killing " + args[0] + ". " + args[0] + " will be missed. :("); Packet4Kick packet2 = new Packet4Kick("YOU MURDERER, YOU KILLED " + args[0].toUpperCase() + "! GET OUT!!!!!"); ph.sendAllExcludePacket(packet, clients, client, this.socket); ph.sendPacket(packet2, client, this.socket); client.stopKeepAliveThread(); client.stopKeepAliveSendThread(); clients.remove(client); } } else if(cmd.equalsIgnoreCase("nuke")) { if(!dm.isOp(client.getUsername())) { Packet5Message packet = new Packet5Message("You are not an op."); ph.sendPacket(packet, client, this.socket); } else { try { System.out.println("Nuke started!"); Packet5Message packet = new Packet5Message("IT'S NUKE TIME OH BOY!!!!!"); ph.sendAllPacket(packet, clients, this.socket); packet = new Packet5Message("NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE"); for(int i = 0; i < 1000; i++) { if((i % 100) == 0) System.out.println("Packets left: " + (1000 - i)); ph.sendAllPacket(packet, clients, this.socket); Thread.sleep(10); } System.out.println("Nuke ended!"); packet = new Packet5Message("Phew, now that the nuke is over, continue chatting!"); ph.sendAllPacket(packet, clients, this.socket); } catch(InterruptedException e) { System.out.println("Nuke command thread was interrupted."); } } } else if(cmd.equalsIgnoreCase("whois")) { if(args.length < 1) { Packet5Message packet = new Packet5Message("Not enough paramters."); ph.sendPacket(packet, client, this.socket); } else { ClientData client2 = findClient(args[0]); if(client2 != null) { String msg = "IP: " + client2.getIP().getHostAddress() + "\n"; msg += "Port: " + client2.getPort() + "\n"; msg += "Hostname: " + client2.getIP().getCanonicalHostName(); Packet5Message packet = new Packet5Message(msg); ph.sendPacket(packet, client, this.socket); } else { Packet5Message packet = new Packet5Message("User not found."); ph.sendPacket(packet, client, this.socket); } } } else if(cmd.equalsIgnoreCase("list")) { String msg = "Online Users: "; for(int i = 0; i < clients.size(); i++) { ClientData client2 = (ClientData)clients.get(i); msg += client2.getUsername() + ", "; } Packet5Message packet = new Packet5Message(msg.substring(0, Math.min(msg.length() - 2, 500))); ph.sendPacket(packet, client, this.socket); } else if(cmd.equalsIgnoreCase("me")) { String msg = ""; for(int i = 0; i < args.length; i++) msg += args[i] + " "; msg = msg.trim(); System.out.println(client.getUsername() + " did action: " + msg); Packet5Message packet = new Packet5Message("*" + client.getUsername() + " " + msg); ph.sendAllPacket(packet, clients, this.socket); } else if(cmd.equalsIgnoreCase("nick")) { if(args.length < 1) { Packet5Message packet = new Packet5Message("Not enough paramters."); ph.sendPacket(packet, client, this.socket); } else if(args[0].equalsIgnoreCase(client.getUsername())) { Packet5Message packet = new Packet5Message("Your name is already " + args[0] + "."); ph.sendPacket(packet, client, this.socket); } else if(nameTaken(args[0])) { Packet5Message packet = new Packet5Message("That name is taken."); ph.sendPacket(packet, client, this.socket); } else if(dm.isOp(args[0]) && !dm.isOp(client.getUsername())) { Packet5Message packet = new Packet5Message("You can't /nick to an op's name if you aren't an op."); ph.sendPacket(packet, client, this.socket); } else { System.out.println(client.getUsername() + " has changed name to " + args[0]); Packet5Message packet = new Packet5Message(client.getUsername() + " is now known as " + args[0]); clients.remove(client); client.setUsername(args[0]); clients.add(client); Packet6NameChange packet2 = new Packet6NameChange(args[0]); ph.sendAllPacket(packet, clients, this.socket); ph.sendPacket(packet2, client, this.socket); } } else if(cmd.equalsIgnoreCase("op")) { if(dm.isOp(client.getUsername())) { if(args.length < 1) { Packet5Message packet = new Packet5Message("Not enough paramters."); ph.sendPacket(packet, client, this.socket); } else if(args[0].equalsIgnoreCase(client.getUsername())) { Packet5Message packet = new Packet5Message("You can not op yourself."); ph.sendPacket(packet, client, this.socket); } else if(dm.isOp(args[0])) { Packet5Message packet = new Packet5Message("That user is already an op."); ph.sendPacket(packet, client, this.socket); } else { dm.addOp(args[0]); System.out.println(client.getUsername() + " opped " + args[0] + "."); Packet5Message packet = new Packet5Message(args[0] + " has been opped."); Packet5Message packet2 = new Packet5Message("You are now an op!"); ph.sendPacket(packet, client, this.socket); ClientData client2 = findClient(args[0]); if(client2 != null) ph.sendPacket(packet2, client2, this.socket); } } else { Packet5Message packet = new Packet5Message("You are not an op."); ph.sendPacket(packet, client, this.socket); } } else if(cmd.equalsIgnoreCase("deop")) { if(dm.isOp(client.getUsername())) { if(args.length < 1) { Packet5Message packet = new Packet5Message("Not enough paramters."); ph.sendPacket(packet, client, this.socket); } else if(args[0].equalsIgnoreCase(client.getUsername())) { Packet5Message packet = new Packet5Message("You can not deop yourself."); ph.sendPacket(packet, client, this.socket); } else if(!dm.isOp(args[0])) { Packet5Message packet = new Packet5Message("That user is not an op."); ph.sendPacket(packet, client, this.socket); } else { dm.removeOp(args[0]); System.out.println(client.getUsername() + " deopped " + args[0] + "."); Packet5Message packet = new Packet5Message(args[0] + " has been deopped."); Packet5Message packet2 = new Packet5Message("You are no longer an op!"); ph.sendPacket(packet, client, this.socket); ClientData client2 = findClient(args[0]); if(client2 != null) ph.sendPacket(packet2, client2, this.socket); } } else { Packet5Message packet = new Packet5Message("You are not an op."); ph.sendPacket(packet, client, this.socket); } } else if(cmd.equalsIgnoreCase("kick")) { if(dm.isOp(client.getUsername())) { if(args.length < 1) { Packet5Message packet = new Packet5Message("Not enough paramters."); ph.sendPacket(packet, client, this.socket); } else if(args[0].equalsIgnoreCase(client.getUsername())) { Packet5Message packet = new Packet5Message("You can not kick yourself."); ph.sendPacket(packet, client, this.socket); } else if(findClient(args[0]) == null) { Packet5Message packet = new Packet5Message("That user isn't in the chat."); ph.sendPacket(packet, client, this.socket); } else { String msg = ""; for(int i = 1; i < args.length; i++) msg += args[i] + " "; msg = msg.trim(); System.out.println(client.getUsername() + " kicked " + args[0] + " with reason: " + msg); Packet5Message packet = new Packet5Message(args[0] + " has been kicked. (" + (msg.equals("") ? "No reason." : msg) + ")"); Packet4Kick packet2 = new Packet4Kick("You were kicked: " + (msg.equals("") ? "No reason." : msg)); ClientData client2 = findClient(args[0]); ph.sendPacket(packet2, client2, this.socket); client2.stopKeepAliveThread(); client2.stopKeepAliveSendThread(); clients.remove(client2); ph.sendAllPacket(packet, clients, this.socket); } } else { Packet5Message packet = new Packet5Message("You are not an op."); ph.sendPacket(packet, client, this.socket); } } else if(cmd.equalsIgnoreCase("ban")) { if(dm.isOp(client.getUsername())) { if(args.length < 1) { Packet5Message packet = new Packet5Message("Not enough paramters."); ph.sendPacket(packet, client, this.socket); } else if(args[0].equalsIgnoreCase(client.getUsername())) { Packet5Message packet = new Packet5Message("You can not ban yourself."); ph.sendPacket(packet, client, this.socket); } else if(dm.isBanned(args[0])) { Packet5Message packet = new Packet5Message("That user is already banned."); ph.sendPacket(packet, client, this.socket); } else { String msg = ""; for(int i = 1; i < args.length; i++) msg += args[i] + " "; msg = msg.trim(); dm.addBan(args[0]); System.out.println(client.getUsername() + " banned " + args[0] + " with reason: " + msg); Packet5Message packet = new Packet5Message(args[0] + " has been banned. (" + (msg.equals("") ? "No reason." : msg) + ")"); Packet4Kick packet2 = new Packet4Kick("You have been banned: " + (msg.equals("") ? "No reason." : msg)); ClientData client2 = findClient(args[0]); if(client2 != null) { ph.sendPacket(packet2, client2, this.socket); client2.stopKeepAliveThread(); client2.stopKeepAliveSendThread(); clients.remove(client2); } ph.sendAllPacket(packet, clients, this.socket); } } else { Packet5Message packet = new Packet5Message("You are not an op."); ph.sendPacket(packet, client, this.socket); } } else if(cmd.equalsIgnoreCase("unban")) { if(dm.isOp(client.getUsername())) { if(args.length < 1) { Packet5Message packet = new Packet5Message("Not enough paramters."); ph.sendPacket(packet, client, this.socket); } else if(args[0].equalsIgnoreCase(client.getUsername())) { Packet5Message packet = new Packet5Message("You can not unban yourself."); ph.sendPacket(packet, client, this.socket); } else if(!dm.isBanned(args[0])) { Packet5Message packet = new Packet5Message("That user is not banned."); ph.sendPacket(packet, client, this.socket); } else { dm.removeBan(args[0]); System.out.println(client.getUsername() + " unbanned " + args[0] + "."); Packet5Message packet = new Packet5Message(args[0] + " has been unbanned."); ph.sendPacket(packet, client, this.socket); } } else { Packet5Message packet = new Packet5Message("You are not an op."); ph.sendPacket(packet, client, this.socket); } } else if(cmd.equalsIgnoreCase("banip")) { if(dm.isOp(client.getUsername())) { if(args.length < 1) { Packet5Message packet = new Packet5Message("Not enough paramters."); ph.sendPacket(packet, client, this.socket); } else { InetAddress ip = null; try { ip = InetAddress.getByName(args[0]); } catch(UnknownHostException e) { } if(ip == null) { Packet5Message packet = new Packet5Message("The IP is invalid."); ph.sendPacket(packet, client, this.socket); } else if(ip == client.getIP()) { Packet5Message packet = new Packet5Message("You can not ban your own IP."); ph.sendPacket(packet, client, this.socket); } else if(dm.isIPBanned(ip.getHostAddress())) { Packet5Message packet = new Packet5Message("That IP is already banned."); ph.sendPacket(packet, client, this.socket); } else { String msg = ""; for(int i = 1; i < args.length; i++) msg += args[i] + " "; msg = msg.trim(); dm.addIPBan(ip.getHostAddress()); System.out.println(client.getUsername() + " banned the IP " + ip.getHostAddress() + " with reason: " + msg); Packet5Message packet = new Packet5Message("The IP " + ip.getHostAddress() + " has been banned. (" + (msg.equals("") ? "No reason." : msg) + ")"); Packet4Kick packet2 = new Packet4Kick("Your IP has been banned: " + (msg.equals("") ? "No reason." : msg)); ClientData client2 = findClient(ip); if(client2 != null) { ph.sendPacket(packet2, client2, this.socket); client2.stopKeepAliveThread(); client2.stopKeepAliveSendThread(); clients.remove(client2); } ph.sendAllPacket(packet, clients, this.socket); } } } else { Packet5Message packet = new Packet5Message("You are not an op."); ph.sendPacket(packet, client, this.socket); } } else if(cmd.equalsIgnoreCase("unbanip")) { if(dm.isOp(client.getUsername())) { if(args.length < 1) { Packet5Message packet = new Packet5Message("Not enough paramters."); ph.sendPacket(packet, client, this.socket); } else { InetAddress ip = null; try { ip = InetAddress.getByName(args[0]); } catch(UnknownHostException e) { } if(ip == null) { Packet5Message packet = new Packet5Message("The IP is invalid."); ph.sendPacket(packet, client, this.socket); } else if(ip == client.getIP()) { Packet5Message packet = new Packet5Message("You can not unban your own IP."); ph.sendPacket(packet, client, this.socket); } else if(!dm.isIPBanned(ip.getHostAddress())) { Packet5Message packet = new Packet5Message("That IP is not banned."); ph.sendPacket(packet, client, this.socket); } else { dm.removeIPBan(ip.getHostAddress()); System.out.println(client.getUsername() + " unbanned the IP " + ip.getHostAddress() + "."); Packet5Message packet = new Packet5Message("The IP " + ip.getHostAddress() + " has been unbanned."); ph.sendPacket(packet, client, this.socket); } } } else { Packet5Message packet = new Packet5Message("You are not an op."); ph.sendPacket(packet, client, this.socket); } } else { System.out.println("Command \"" + cmd + "\" not found."); Packet5Message packet = new Packet5Message("Unknown command."); ph.sendPacket(packet, client, this.socket); } }
public static void main(final String[] args) { final OutputCloneInCCFinderFormat outputter = new OutputCloneInCCFinderFormat(); System.out.print("identifying source files in revision "); System.out.print(Long.toString(Config.getCloneDetectionRevision())); System.out.print(" ... "); final SortedSet<String> paths = outputter.identifyFiles(); System.out.print(Integer.toString(paths.size())); System.out.println(" files: done."); System.out.print("measuring file size ... "); final ConcurrentMap<String, List<Statement>> contents = outputter .getFileContent(paths); System.out.println(": done."); System.out.print("outputting ... "); final Map<String, Integer> ids = new HashMap<String, Integer>(); for (final String path : contents.keySet()) { ids.put(path, ids.size()); } try { final BufferedWriter writer = new BufferedWriter(new FileWriter( Config.getCloneOutputFile())); writer.write("#begin{file description}"); writer.newLine(); for (final Entry<String, List<Statement>> entry : contents .entrySet()) { final String path = entry.getKey(); final List<Statement> statements = entry.getValue(); final int numberOfStatements = outputter .getNumberOfStatements(statements); final int numberOfTokens = outputter .getNumberOfTokens(statements); writer.write("0."); writer.write(ids.get(path).toString()); writer.write("\t"); writer.write(Integer.toString(numberOfStatements)); writer.write("\t"); writer.write(Integer.toString(numberOfTokens)); writer.write("\t"); writer.write(path); writer.newLine(); } writer.write("#end{file description}"); writer.newLine(); writer.write("#begin{clone}"); writer.newLine(); Map<Integer, List<Clone>> clones; try { final ReadOnlyDAO readOnlyDAO = ReadOnlyDAO.getInstance(); clones = readOnlyDAO.getClones(); readOnlyDAO.close(); } catch (final Exception e) { clones = new HashMap<Integer, List<Clone>>(); e.printStackTrace(); System.exit(0); } for (final List<Clone> set : clones.values()) { writer.write("#begin{set}"); writer.newLine(); for (final Clone clone : set) { final String start = Integer.toString(clone.startLine); final String end = Integer.toString(clone.endLine); writer.write("0."); writer.write(ids.get(clone.path).toString()); writer.write("\t"); writer.write(start); writer.write(",1,"); writer.write(start); writer.write("\t"); writer.write(end); writer.write(",1,"); writer.write(end); writer.write("\t"); if (0 < clone.changed) { writer.write(Integer.toString(clone.endLine - clone.startLine)); } else { writer.write("0"); } writer.newLine(); } writer.write("#end{set}"); writer.newLine(); } writer.write("#end{clone}"); writer.newLine(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(0); } System.out.println(": done."); }
public static void main(final String[] args) { final OutputCloneInCCFinderFormat outputter = new OutputCloneInCCFinderFormat(); System.out.print("identifying source files in revision "); System.out.print(Long.toString(Config.getCloneDetectionRevision())); System.out.print(" ... "); final SortedSet<String> paths = outputter.identifyFiles(); System.out.print(Integer.toString(paths.size())); System.out.println(" files: done."); System.out.print("measuring file size ... "); final ConcurrentMap<String, List<Statement>> contents = outputter .getFileContent(paths); System.out.println(": done."); System.out.print("outputting ... "); final Map<String, Integer> ids = new HashMap<String, Integer>(); for (final String path : contents.keySet()) { ids.put(path, ids.size()); } try { final BufferedWriter writer = new BufferedWriter(new FileWriter( Config.getCloneOutputFile())); writer.write("#begin{file description}"); writer.newLine(); for (final Entry<String, List<Statement>> entry : contents .entrySet()) { final String path = entry.getKey(); final List<Statement> statements = entry.getValue(); writer.write("0."); writer.write(ids.get(path).toString()); writer.write("\t"); writer.write(Integer.toString(statements.size())); writer.write("\t"); writer.write(Integer.toString(statements.size())); writer.write("\t"); writer.write(path); writer.newLine(); } writer.write("#end{file description}"); writer.newLine(); writer.write("#begin{clone}"); writer.newLine(); Map<Integer, List<Clone>> clones; try { final ReadOnlyDAO readOnlyDAO = ReadOnlyDAO.getInstance(); clones = readOnlyDAO.getClones(); readOnlyDAO.close(); } catch (final Exception e) { clones = new HashMap<Integer, List<Clone>>(); e.printStackTrace(); System.exit(0); } for (final List<Clone> set : clones.values()) { writer.write("#begin{set}"); writer.newLine(); for (final Clone clone : set) { final String start = Integer.toString(clone.startLine); final String end = Integer.toString(clone.endLine); writer.write("0."); writer.write(ids.get(clone.path).toString()); writer.write("\t"); writer.write(start); writer.write(",1,"); writer.write(start); writer.write("\t"); writer.write(end); writer.write(",1,"); writer.write(end); writer.write("\t"); if (0 < clone.changed) { writer.write(Integer.toString(clone.endLine - clone.startLine)); } else { writer.write("0"); } writer.newLine(); } writer.write("#end{set}"); writer.newLine(); } writer.write("#end{clone}"); writer.newLine(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(0); } System.out.println(": done."); }
static List<Expression> topLevelExps(RSyntaxDocument doc) { List<Expression> r = new LinkedList<Expression>(); int parenLevel = 0; int height = 0; boolean first = false; StringBuilder contents = new StringBuilder(); boolean contentsAdmittable = true; ExpType firstType = ExpType.FINAL; int charIndex = -1; Expression prev = null; int gapHeight = 0; for (int i = 0; i < doc.getDefaultRootElement().getElementCount(); i++) { height++; Token token = doc.getTokenListForLine(i); while (token != null && token.offset != -1) { if (charIndex == -1) { charIndex = token.offset; } if (!token.isComment() && !token.isWhitespace() && !token.isSingleChar('\r')) { contents.append(token.text, token.textOffset, token.textCount); if (firstType == ExpType.FINAL && !token.isSingleChar('(')) { firstType = token.type == Token.RESERVED_WORD_2 ? ExpType.UNDOABLE : ExpType.NORMAL; if (token.getLexeme().equalsIgnoreCase("defproperty")) { firstType = ExpType.UNDOABLE; } gapHeight = height - 1; height = 1; } contentsAdmittable = true; } else if (token.isWhitespace()) { contents.append(token.text, token.textOffset, token.textCount); } if (token.isSingleChar('(')) { parenLevel++; } else if (token.isSingleChar(')') && parenLevel > 0) { parenLevel--; } boolean nextTokenIsNull = token.getNextToken() == null || token.getNextToken().type == Token.NULL; if (parenLevel == 0 && nextTokenIsNull && contents.length() != 0 && contentsAdmittable) { if (prev != null) { prev.nextGapHeight = gapHeight; } prev = new Expression(height, contents.toString(), firstType, charIndex, token.offset + token.textCount, prev); prev.prevGapHeight = gapHeight; r.add(prev); firstType = ExpType.FINAL; charIndex = -1; contents = new StringBuilder(); contentsAdmittable = false; height = 0; } if (first) first = false; token = token.getNextToken(); } contents.append('\n'); } r.add(new Expression(height, "", ExpType.FINAL, charIndex, -1, prev)); return r; }
static List<Expression> topLevelExps(RSyntaxDocument doc) { List<Expression> r = new LinkedList<Expression>(); int parenLevel = 0; int height = 0; boolean first = false; StringBuilder contents = new StringBuilder(); boolean contentsAdmittable = false; ExpType firstType = ExpType.FINAL; int charIndex = -1; Expression prev = null; int gapHeight = 0; for (int i = 0; i < doc.getDefaultRootElement().getElementCount(); i++) { height++; Token token = doc.getTokenListForLine(i); while (token != null && token.offset != -1) { if (charIndex == -1) { charIndex = token.offset; } if (!token.isComment() && !token.isWhitespace() && !token.isSingleChar('\r')) { contents.append(token.text, token.textOffset, token.textCount); if (firstType == ExpType.FINAL && !token.isSingleChar('(')) { firstType = token.type == Token.RESERVED_WORD_2 ? ExpType.UNDOABLE : ExpType.NORMAL; if (token.getLexeme().equalsIgnoreCase("defproperty")) { firstType = ExpType.UNDOABLE; } gapHeight = height - 1; height = 1; } contentsAdmittable = true; } else if (token.isWhitespace()) { contents.append(token.text, token.textOffset, token.textCount); } if (token.isSingleChar('(')) { parenLevel++; } else if (token.isSingleChar(')') && parenLevel > 0) { parenLevel--; } boolean nextTokenIsNull = token.getNextToken() == null || token.getNextToken().type == Token.NULL; if (parenLevel == 0 && nextTokenIsNull && contents.length() != 0 && contentsAdmittable) { if (prev != null) { prev.nextGapHeight = gapHeight; } prev = new Expression(height, contents.toString(), firstType, charIndex, token.offset + token.textCount, prev); prev.prevGapHeight = gapHeight; r.add(prev); firstType = ExpType.FINAL; charIndex = -1; contents = new StringBuilder(); contentsAdmittable = false; height = 0; } if (first) first = false; token = token.getNextToken(); } contents.append('\n'); } r.add(new Expression(height, "", ExpType.FINAL, charIndex, -1, prev)); return r; }
public void privateDeploy() throws Exception { verifier.getCliOptions().clear(); verifier.getCliOptions().add("-X"); try { verifier.executeGoal( "deploy" ); verifier.verifyErrorFreeLog(); failTest( verifier ); } catch ( VerificationException e ) { } }
public void privateDeploy() throws Exception { verifier.getCliOptions().clear(); verifier.getCliOptions().add("-X"); verifier.getCliOptions().add("-DaltDeploymentRepository=\"\""); try { verifier.executeGoal( "deploy" ); verifier.verifyErrorFreeLog(); failTest( verifier ); } catch ( VerificationException e ) { } }
public void testSave() throws Exception { Date date = new Date(); MedicalResult medicalResult = new MedicalResult(); medicalResult.setRadarNo(1L); medicalResult.setSerumCreatanine(10.25); medicalResult.setAntihypertensiveDrugs(MedicalResult.YesNo.YES); medicalResult.setBloodUrea(12.25); medicalResult.setBloodUreaDate(date); medicalResult.setSerumCreatanine(15.5); medicalResult.setCreatanineDate(date); medicalResult.setBpDiastolic(18); medicalResult.setBpSystolic(19); medicalResult.setHeight(100.5); medicalResult.setHeightDate(date); medicalResult.setWeight(122.0); medicalResult.setWeightDate(date); medicalResult.setBpDate(date); DiseaseGroup diseaseGroup = diseaseGroupDao.getById("1"); medicalResult.setDiseaseGroup(diseaseGroup); medicalResultDao.save(medicalResult); medicalResult = medicalResultDao.getMedicalResult(1L, diseaseGroup.getId()); Assert.assertNotNull("Medical result should not be null", medicalResult); medicalResult.setBloodUrea(15.5); medicalResultDao.save(medicalResult); medicalResult = medicalResultDao.getMedicalResult(1L, diseaseGroup.getId()); Assert.assertEquals("Blood urea has wrong value", new Double(15.5), medicalResult.getBloodUrea()); }
public void testSave() throws Exception { Date date = new Date(); MedicalResult medicalResult = new MedicalResult(); medicalResult.setNhsNo("123456789"); medicalResult.setRadarNo(1L); medicalResult.setSerumCreatanine(10.25); medicalResult.setAntihypertensiveDrugs(MedicalResult.YesNo.YES); medicalResult.setAntihypertensiveDrugsDate(date); medicalResult.setBloodUrea(12.25); medicalResult.setBloodUreaDate(date); medicalResult.setSerumCreatanine(15.5); medicalResult.setCreatanineDate(date); medicalResult.setBpDiastolic(18); medicalResult.setBpSystolic(19); medicalResult.setHeight(100.5); medicalResult.setHeightDate(date); medicalResult.setWeight(122.0); medicalResult.setWeightDate(date); medicalResult.setBpDate(date); medicalResult.setPcr(1); medicalResult.setPcrDate(date); medicalResult.setAcr(1); medicalResult.setAcrDate(date); DiseaseGroup diseaseGroup = diseaseGroupDao.getById("1"); medicalResult.setDiseaseGroup(diseaseGroup); medicalResultDao.save(medicalResult); medicalResult = medicalResultDao.getMedicalResult(1L, diseaseGroup.getId()); Assert.assertNotNull("Medical result should not be null", medicalResult); medicalResult.setBloodUrea(15.5); medicalResult.setNhsNo("123456789"); medicalResultDao.save(medicalResult); medicalResult = medicalResultDao.getMedicalResult(1L, diseaseGroup.getId()); Assert.assertEquals("Blood urea has wrong value", new Double(15.5), medicalResult.getBloodUrea()); }
public void testGlobalData() { String[] ids = { "a", "b", "c" }; for (String s : ids) { User user = new User(); user.setId(s); userDataResource.user = user; userDataResource.createDataset(); } GlobalDataServerResource globalDataResource = new GlobalDataServerResource(application); assertTrue(globalDataResource.getAllUsersWithData().contains(ids[0])); assertEquals(ids.length, globalDataResource.getAllUsersWithData() .size()); Workflow workflow = EmbeddedEngine.getQRSWorkflow(); GlobalAnalysisServerResource globalAnalysisResource = new GlobalAnalysisServerResource(application, workflow); Form form = new Form(); form.add(ServerParameter.USER_ID.getName(), USER_ID); assertEquals(ids.length, globalAnalysisResource.execute(form).size()); }
public void testGlobalData() { Workflow workflow = EmbeddedEngine.getQRSWorkflow(); Instances instances = new Instances("test", workflow.getInputSpec(), 0); String[] ids = { "a", "b", "c" }; for (String s : ids) { User user = new User(); user.setId(s); userDataResource.user = user; userDataResource.createDataset(instances); } GlobalDataServerResource globalDataResource = new GlobalDataServerResource(application); assertTrue(globalDataResource.getAllUsersWithData().contains(ids[0])); assertEquals(ids.length, globalDataResource.getAllUsersWithData() .size()); GlobalAnalysisServerResource globalAnalysisResource = new GlobalAnalysisServerResource(application, workflow); Form form = new Form(); assertEquals(ids.length, globalAnalysisResource.execute(form).size()); }
public SrmPutDoneResponse srmPutDone() throws SRMException, org.apache.axis.types.URI.MalformedURIException, java.sql.SQLException, IllegalStateTransition { say("Entering srmPutDone."); String requestToken = srmPutDoneRequest.getRequestToken(); if( requestToken == null ) { return getFailedResponse("request contains no request token"); } Long requestId; try { requestId = new Long( requestToken); } catch (NumberFormatException nfe){ return getFailedResponse(" requestToken \""+ requestToken+"\"is not valid", TStatusCode.SRM_FAILURE); } ContainerRequest request =(ContainerRequest) ContainerRequest.getRequest(requestId); if(request == null) { return getFailedResponse("request for requestToken \""+ requestToken+"\"is not found", TStatusCode.SRM_FAILURE); } if ( !(request instanceof PutRequest) ){ return getFailedResponse("request for requestToken \""+ requestToken+"\"is not srmPrepareToGet request", TStatusCode.SRM_FAILURE); } PutRequest putRequest = (PutRequest) request; org.apache.axis.types.URI [] surls; if(srmPutDoneRequest.getArrayOfSURLs() ==null) { surls = null; } else { surls = srmPutDoneRequest.getArrayOfSURLs().getUrlArray(); } String[] surl_strings = null; TReturnStatus status = new TReturnStatus(); SrmPutDoneResponse srmPutDoneResponse = new SrmPutDoneResponse(); synchronized(putRequest) { FileRequest requests[] = putRequest.getFileRequests(); State state = putRequest.getState(); if(!State.isFinalState(state)) { if( surls == null ){ int fail_counter=0; int success_counter=0; if ( requests != null ) { for (int i=0;i<requests.length;i++) { PutFileRequest fileRequest = (PutFileRequest) requests[i]; synchronized(fileRequest) { if ( !State.isFinalState(fileRequest.getState())) { if ( fileRequest.getTurlString()==null) { fileRequest.setStatusCode(TStatusCode.SRM_INVALID_PATH); fileRequest.setState(State.FAILED,"SrmPutDone called, TURL is not ready"); fail_counter++; } else { try { FileMetaData fmd= storage.getFileMetaData(user,fileRequest.getPath()); fileRequest.setState(State.DONE,"SrmPutDone called"); success_counter++; } catch (Exception srme) { fail_counter++; fileRequest.setStatusCode(TStatusCode.SRM_INVALID_PATH); fileRequest.setState(State.FAILED,"SrmPutDone called "+srme.getMessage()); } } } else { if (fileRequest.getState()==State.DONE) { success_counter++; } if (fileRequest.getState()==State.FAILED) { fail_counter++; } if (fileRequest.getState()==State.CANCELED) { fail_counter++; } } } } if (success_counter==requests.length) { putRequest.setState(State.DONE,"SrmPutDone called"); status.setStatusCode(TStatusCode.SRM_SUCCESS); status.setExplanation("success"); } else if (success_counter<requests.length) { putRequest.setStatusCode(TStatusCode.SRM_REQUEST_INPROGRESS); status.setStatusCode(TStatusCode.SRM_REQUEST_INPROGRESS); status.setExplanation("request in progress"); } if (fail_counter>0&&fail_counter<requests.length) { putRequest.setStatusCode(TStatusCode.SRM_PARTIAL_SUCCESS); status.setStatusCode(TStatusCode.SRM_PARTIAL_SUCCESS); status.setExplanation("some file transfer(s) were not performed on all SURLs"); } else if (fail_counter==requests.length) { putRequest.setStatusCode(TStatusCode.SRM_FAILURE); putRequest.setState(State.FAILED,"no file transfer(s) were performed on SURL(s)"); status.setStatusCode(TStatusCode.SRM_FAILURE); status.setExplanation("no file transfer(s) were performed on SURL(s)"); } } else { return getFailedResponse("0 length file request array", TStatusCode.SRM_INVALID_REQUEST); } } else { if(surls.length == 0) { return getFailedResponse("0 lenght SiteURLs array", TStatusCode.SRM_INVALID_REQUEST); } surl_strings = new String[surls.length]; int fail_counter=0; int success_counter=0; for(int i = 0; i< surls.length; ++i) { if(surls[i] != null ) { surl_strings[i] =surls[i].toString(); PutFileRequest fileRequest = (PutFileRequest) putRequest.getFileRequestBySurl(surl_strings[i]); synchronized(fileRequest) { if ( !State.isFinalState(fileRequest.getState())) { if ( fileRequest.getTurlString()==null) { fileRequest.setStatusCode(TStatusCode.SRM_INVALID_PATH); fileRequest.setState(State.FAILED,"SrmPutDone called, TURL is not ready"); fail_counter++; } else { try { FileMetaData fmd= storage.getFileMetaData(user,fileRequest.getPath()); fileRequest.setState(State.DONE,"SrmPutDone called"); success_counter++; } catch (Exception srme) { fail_counter++; fileRequest.setStatusCode(TStatusCode.SRM_INVALID_PATH); fileRequest.setState(State.FAILED,"SrmPutDone called "+srme.getMessage()); } } } else { if (fileRequest.getState()==State.DONE) { success_counter++; } if (fileRequest.getState()==State.FAILED) { fail_counter++; } if (fileRequest.getState()==State.CANCELED) { fail_counter++; } } } } else { return getFailedResponse("SiteURLs["+i+"] is null", TStatusCode.SRM_INVALID_REQUEST); } } if (success_counter==requests.length) { putRequest.setState(State.DONE,"SrmPutDone called"); status.setStatusCode(TStatusCode.SRM_SUCCESS); status.setExplanation("success"); } else if (success_counter<requests.length) { putRequest.setStatusCode(TStatusCode.SRM_REQUEST_INPROGRESS); status.setStatusCode(TStatusCode.SRM_REQUEST_INPROGRESS); status.setExplanation("request in progress"); } if (fail_counter>0&&fail_counter<requests.length) { putRequest.setStatusCode(TStatusCode.SRM_PARTIAL_SUCCESS); status.setStatusCode(TStatusCode.SRM_PARTIAL_SUCCESS); status.setExplanation("some file transfer(s) were not performed on all SURLs"); } else if (fail_counter==requests.length) { putRequest.setStatusCode(TStatusCode.SRM_FAILURE); putRequest.setState(State.FAILED,"no file transfer(s) were performed on SURL(s)"); status.setStatusCode(TStatusCode.SRM_FAILURE); status.setExplanation("no file transfer(s) were performed on SURL(s)"); } } } else { int fail_counter=0; int success_counter=0; if( surls == null ){ if ( requests != null ) { for (int i=0;i<requests.length;i++) { PutFileRequest fileRequest = (PutFileRequest) requests[i]; synchronized(fileRequest) { if (fileRequest.getState()==State.DONE) { success_counter++; } else { fail_counter++; } } } } } else { surl_strings = new String[surls.length]; for(int i = 0; i< surls.length; ++i) { if(surls[i] != null ) { surl_strings[i] =surls[i].toString(); PutFileRequest fileRequest = (PutFileRequest) putRequest.getFileRequestBySurl(surl_strings[i]); synchronized(fileRequest) { if (fileRequest.getState()==State.DONE) { success_counter++; } else { fail_counter++; } } } else { return getFailedResponse("SiteURLs["+i+"] is null", TStatusCode.SRM_INVALID_REQUEST); } } } if (success_counter==requests.length) { putRequest.setState(State.DONE,"SrmPutDone called"); status.setStatusCode(TStatusCode.SRM_SUCCESS); status.setExplanation("success"); } else if (success_counter<requests.length) { putRequest.setStatusCode(TStatusCode.SRM_REQUEST_INPROGRESS); status.setStatusCode(TStatusCode.SRM_REQUEST_INPROGRESS); status.setExplanation("request in progress"); } if (fail_counter>0&&fail_counter<requests.length) { putRequest.setStatusCode(TStatusCode.SRM_PARTIAL_SUCCESS); status.setStatusCode(TStatusCode.SRM_PARTIAL_SUCCESS); status.setExplanation("some file transfer(s) were not performed on all SURLs"); } else if (fail_counter==requests.length) { putRequest.setStatusCode(TStatusCode.SRM_FAILURE); putRequest.setState(State.FAILED,"no file transfer(s) were performed on SURL(s)"); status.setStatusCode(TStatusCode.SRM_FAILURE); status.setExplanation("no file transfer(s) were performed on SURL(s)"); } if(surls != null) { srmPutDoneResponse.setArrayOfFileStatuses( new ArrayOfTSURLReturnStatus( putRequest.getArrayOfTSURLReturnStatus(surl_strings))); } } srmPutDoneResponse.setReturnStatus(status); } say("returning srmPutDoneResponse statuscode="+srmPutDoneResponse.getReturnStatus().getStatusCode()+ " explanation = "+srmPutDoneResponse.getReturnStatus().getExplanation()); return srmPutDoneResponse; }
public SrmPutDoneResponse srmPutDone() throws SRMException, org.apache.axis.types.URI.MalformedURIException, java.sql.SQLException, IllegalStateTransition { say("Entering srmPutDone."); String requestToken = srmPutDoneRequest.getRequestToken(); if( requestToken == null ) { return getFailedResponse("request contains no request token"); } Long requestId; try { requestId = new Long( requestToken); } catch (NumberFormatException nfe){ return getFailedResponse(" requestToken \""+ requestToken+"\"is not valid", TStatusCode.SRM_FAILURE); } ContainerRequest request =(ContainerRequest) ContainerRequest.getRequest(requestId); if(request == null) { return getFailedResponse("request for requestToken \""+ requestToken+"\"is not found", TStatusCode.SRM_FAILURE); } if ( !(request instanceof PutRequest) ){ return getFailedResponse("request for requestToken \""+ requestToken+"\"is not srmPrepareToGet request", TStatusCode.SRM_FAILURE); } PutRequest putRequest = (PutRequest) request; org.apache.axis.types.URI [] surls; if(srmPutDoneRequest.getArrayOfSURLs() ==null) { surls = null; } else { surls = srmPutDoneRequest.getArrayOfSURLs().getUrlArray(); } String[] surl_strings = null; TReturnStatus status = new TReturnStatus(); SrmPutDoneResponse srmPutDoneResponse = new SrmPutDoneResponse(); synchronized(putRequest) { FileRequest requests[] = putRequest.getFileRequests(); State state = putRequest.getState(); if(!State.isFinalState(state)) { if( surls == null ){ int fail_counter=0; int success_counter=0; if ( requests != null ) { for (int i=0;i<requests.length;i++) { PutFileRequest fileRequest = (PutFileRequest) requests[i]; synchronized(fileRequest) { if ( !State.isFinalState(fileRequest.getState())) { if ( fileRequest.getTurlString()==null) { fileRequest.setStatusCode(TStatusCode.SRM_INVALID_PATH); fileRequest.setState(State.FAILED,"SrmPutDone called, TURL is not ready"); fail_counter++; } else { try { FileMetaData fmd= storage.getFileMetaData(user,fileRequest.getPath()); fileRequest.setState(State.DONE,"SrmPutDone called"); success_counter++; } catch (Exception srme) { fail_counter++; fileRequest.setStatusCode(TStatusCode.SRM_INVALID_PATH); fileRequest.setState(State.FAILED,"SrmPutDone called "+srme.getMessage()); } } } else { if (fileRequest.getState()==State.DONE) { success_counter++; } if (fileRequest.getState()==State.FAILED) { fail_counter++; } if (fileRequest.getState()==State.CANCELED) { fail_counter++; } } } } if (success_counter==requests.length) { putRequest.setState(State.DONE,"SrmPutDone called"); status.setStatusCode(TStatusCode.SRM_SUCCESS); status.setExplanation("success"); } else if (success_counter<requests.length) { putRequest.setStatusCode(TStatusCode.SRM_REQUEST_INPROGRESS); status.setStatusCode(TStatusCode.SRM_REQUEST_INPROGRESS); status.setExplanation("request in progress"); } if (fail_counter>0&&fail_counter<requests.length) { putRequest.setStatusCode(TStatusCode.SRM_PARTIAL_SUCCESS); status.setStatusCode(TStatusCode.SRM_PARTIAL_SUCCESS); status.setExplanation("some file transfer(s) were not performed on all SURLs"); } else if (fail_counter==requests.length) { putRequest.setStatusCode(TStatusCode.SRM_FAILURE); putRequest.setState(State.FAILED,"no file transfer(s) were performed on SURL(s)"); status.setStatusCode(TStatusCode.SRM_FAILURE); status.setExplanation("no file transfer(s) were performed on SURL(s)"); } } else { return getFailedResponse("0 length file request array", TStatusCode.SRM_INVALID_REQUEST); } } else { if(surls.length == 0) { return getFailedResponse("0 lenght SiteURLs array", TStatusCode.SRM_INVALID_REQUEST); } surl_strings = new String[surls.length]; int fail_counter=0; int success_counter=0; for(int i = 0; i< surls.length; ++i) { if(surls[i] != null ) { surl_strings[i] =surls[i].toString(); PutFileRequest fileRequest = (PutFileRequest) putRequest.getFileRequestBySurl(surl_strings[i]); synchronized(fileRequest) { if ( !State.isFinalState(fileRequest.getState())) { if ( fileRequest.getTurlString()==null) { fileRequest.setStatusCode(TStatusCode.SRM_INVALID_PATH); fileRequest.setState(State.FAILED,"SrmPutDone called, TURL is not ready"); fail_counter++; } else { try { FileMetaData fmd= storage.getFileMetaData(user,fileRequest.getPath()); fileRequest.setState(State.DONE,"SrmPutDone called"); success_counter++; } catch (Exception srme) { fail_counter++; fileRequest.setStatusCode(TStatusCode.SRM_INVALID_PATH); fileRequest.setState(State.FAILED,"SrmPutDone called "+srme.getMessage()); } } } else { if (fileRequest.getState()==State.DONE) { success_counter++; } if (fileRequest.getState()==State.FAILED) { fail_counter++; } if (fileRequest.getState()==State.CANCELED) { fail_counter++; } } } } else { return getFailedResponse("SiteURLs["+i+"] is null", TStatusCode.SRM_INVALID_REQUEST); } } if (success_counter==requests.length) { putRequest.setState(State.DONE,"SrmPutDone called"); status.setStatusCode(TStatusCode.SRM_SUCCESS); status.setExplanation("success"); } else if (success_counter<requests.length) { putRequest.setStatusCode(TStatusCode.SRM_REQUEST_INPROGRESS); status.setStatusCode(TStatusCode.SRM_REQUEST_INPROGRESS); status.setExplanation("request in progress"); } if (fail_counter>0&&fail_counter<requests.length) { putRequest.setStatusCode(TStatusCode.SRM_PARTIAL_SUCCESS); status.setStatusCode(TStatusCode.SRM_PARTIAL_SUCCESS); status.setExplanation("some file transfer(s) were not performed on all SURLs"); } else if (fail_counter==requests.length) { putRequest.setStatusCode(TStatusCode.SRM_FAILURE); putRequest.setState(State.FAILED,"no file transfer(s) were performed on SURL(s)"); status.setStatusCode(TStatusCode.SRM_FAILURE); status.setExplanation("no file transfer(s) were performed on SURL(s)"); } } } else { int fail_counter=0; int success_counter=0; if( surls == null ){ if ( requests != null ) { for (int i=0;i<requests.length;i++) { PutFileRequest fileRequest = (PutFileRequest) requests[i]; synchronized(fileRequest) { if (fileRequest.getState()==State.DONE) { success_counter++; } else { fail_counter++; } } } } } else { surl_strings = new String[surls.length]; for(int i = 0; i< surls.length; ++i) { if(surls[i] != null ) { surl_strings[i] =surls[i].toString(); PutFileRequest fileRequest = (PutFileRequest) putRequest.getFileRequestBySurl(surl_strings[i]); synchronized(fileRequest) { if (fileRequest.getState()==State.DONE) { success_counter++; } else { fail_counter++; } } } else { return getFailedResponse("SiteURLs["+i+"] is null", TStatusCode.SRM_INVALID_REQUEST); } } } if (success_counter==requests.length) { putRequest.setState(State.DONE,"SrmPutDone called"); status.setStatusCode(TStatusCode.SRM_SUCCESS); status.setExplanation("success"); } else if (success_counter<requests.length) { putRequest.setStatusCode(TStatusCode.SRM_REQUEST_INPROGRESS); status.setStatusCode(TStatusCode.SRM_REQUEST_INPROGRESS); status.setExplanation("request in progress"); } if (fail_counter>0&&fail_counter<requests.length) { putRequest.setStatusCode(TStatusCode.SRM_PARTIAL_SUCCESS); status.setStatusCode(TStatusCode.SRM_PARTIAL_SUCCESS); status.setExplanation("some file transfer(s) were not performed on all SURLs"); } else if (fail_counter==requests.length) { putRequest.setStatusCode(TStatusCode.SRM_FAILURE); putRequest.setState(State.FAILED,"no file transfer(s) were performed on SURL(s)"); status.setStatusCode(TStatusCode.SRM_FAILURE); status.setExplanation("no file transfer(s) were performed on SURL(s)"); } } if(surls != null) { srmPutDoneResponse.setArrayOfFileStatuses( new ArrayOfTSURLReturnStatus( putRequest.getArrayOfTSURLReturnStatus(surl_strings))); } srmPutDoneResponse.setReturnStatus(status); } say("returning srmPutDoneResponse statuscode="+srmPutDoneResponse.getReturnStatus().getStatusCode()+ " explanation = "+srmPutDoneResponse.getReturnStatus().getExplanation()); return srmPutDoneResponse; }
public void generate(final Workbook workbook, final Solution... solutions) { for (Solution solution : solutions) { Sheet sheet = workbook.createSheet(solution.getName()); List<Map<String, String>> sections = solution.getSections(); Collections.sort(sections, new Comparator<Map<String, String>>() { public int compare(final Map<String, String> o1, final Map<String, String> o2) { return new Integer(o1.get("id")).compareTo(new Integer(o2.get("id"))); } }); List<Map<String, String>> events = solution.getEvents(); Collections.sort(events, new Comparator<Map<String, String>>() { public int compare(final Map<String, String> o1, final Map<String, String> o2) { return new Integer(o2.get("solution")).compareTo(new Integer(o1.get("solution"))); } }); double min = 0.0; for (int i = 0; i < events.size(); i++) { Map<String, String> event = events.get(i); if (event.containsKey("agemin")) { double age = Double.parseDouble(event.get("agemin")); if (age < min) { event.put("agemin", "" + min); } else { min = age; } } } double max = -1; for (int i = events.size() - 1; i >= 0; i--) { Map<String, String> event = events.get(i); if (event.containsKey("agemax")) { double age = Double.parseDouble(event.get("agemax")); if (max == -1) { max = age; } else if (age > max) { event.put("agemax", "" + max); } else { max = age; } } } CellStyle style = sheet.getWorkbook().createCellStyle(); Font font = sheet.getWorkbook().createFont(); font.setBoldweight(Font.BOLDWEIGHT_BOLD); style.setFont(font); style.setAlignment(CellStyle.ALIGN_CENTER); style.setBorderBottom(CellStyle.BORDER_THIN); Row header = sheet.createRow(0); header.createCell(0).setCellValue("Event"); header.createCell(1).setCellValue("Type"); header.createCell(2).setCellValue("Rank"); header.createCell(3).setCellValue("Min Rank"); header.createCell(4).setCellValue("Max Rank"); header.createCell(5).setCellValue("Min Age"); header.createCell(6).setCellValue("Max Age"); for (int i = 0; i < sections.size(); i++) { header.createCell(2 * i + 7).setCellValue(sections.get(i).get("name") + " (O)"); header.createCell(2 * i + 8).setCellValue(sections.get(i).get("name") + " (P)"); } for (Cell cell : header) { cell.setCellStyle(style); } for (int i = 0; i < events.size(); i++) { Map<String, String> event = events.get(i); Row row = sheet.createRow(i + 1); row.createCell(0).setCellValue(event.get("name")); row.createCell(1).setCellValue(event.get("type")); row.createCell(2).setCellValue(Integer.parseInt(event.get("solution"))); if (event.containsKey("rankmin")) { row.createCell(3).setCellValue(Double.parseDouble(event.get("rankmin"))); } if (event.containsKey("rankmax")) { row.createCell(4).setCellValue(Double.parseDouble(event.get("rankmax"))); } if (event.containsKey("agemin")) { row.createCell(5).setCellValue(Double.parseDouble(event.get("agemin"))); } else { int before = before(events, i); int after = after(events, i); double a1 = (before == -1 ? 0.0 : Double.parseDouble(events.get(before).get("agemin"))); double a2 = (after == -1 ? a1 : Double.parseDouble(events.get(after).get("agemin"))); if (after == -1) { after = events.size(); } row.createCell(5).setCellValue(a1 + ((a2 - a1) / (after - before)) * (i - before)); } if (event.containsKey("agemax")) { row.createCell(6).setCellValue(Double.parseDouble(event.get("agemax"))); } else { int before = before(events, i); int after = after(events, i); double a1 = (before == -1 ? 0.0 : Double.parseDouble(events.get(before).get("agemax"))); double a2 = (after == -1 ? a1 : Double.parseDouble(events.get(after).get("agemax"))); if (after == -1) { after = events.size(); } row.createCell(6).setCellValue(a1 + ((a2 - a1) / (after - before)) * (i - before)); } for (int j = 0; j < sections.size(); j++) { row.createCell(2 * j + 7).setCellValue(Double.parseDouble(event.get("observed." + (j + 1)))); row.createCell(2 * j + 8).setCellValue(Double.parseDouble(event.get("placed." + (j + 1)))); } } } }
public void generate(final Workbook workbook, final Solution... solutions) { for (Solution solution : solutions) { Sheet sheet = workbook.createSheet(solution.getName()); List<Map<String, String>> sections = solution.getSections(); Collections.sort(sections, new Comparator<Map<String, String>>() { public int compare(final Map<String, String> o1, final Map<String, String> o2) { return new Integer(o1.get("id")).compareTo(new Integer(o2.get("id"))); } }); List<Map<String, String>> events = solution.getEvents(); Collections.sort(events, new Comparator<Map<String, String>>() { public int compare(final Map<String, String> o1, final Map<String, String> o2) { return new Integer(o2.get("solution")).compareTo(new Integer(o1.get("solution"))); } }); double min = 0.0; for (int i = 0; i < events.size(); i++) { Map<String, String> event = events.get(i); if (event.containsKey("agemin")) { double age = Double.parseDouble(event.get("agemin")); if (age < min) { event.put("agemin", "" + min); } else { min = age; } } } double max = -1; for (int i = events.size() - 1; i >= 0; i--) { Map<String, String> event = events.get(i); if (event.containsKey("agemax")) { double age = Double.parseDouble(event.get("agemax")); if (max == -1) { max = age; } else if (age > max) { event.put("agemax", "" + max); } else { max = age; } } } CellStyle style = sheet.getWorkbook().createCellStyle(); Font font = sheet.getWorkbook().createFont(); font.setBoldweight(Font.BOLDWEIGHT_BOLD); style.setFont(font); style.setAlignment(CellStyle.ALIGN_CENTER); style.setBorderBottom(CellStyle.BORDER_THIN); Row header = sheet.createRow(0); header.createCell(0).setCellValue("Event"); header.createCell(1).setCellValue("Type"); header.createCell(2).setCellValue("Rank"); header.createCell(3).setCellValue("Min Rank"); header.createCell(4).setCellValue("Max Rank"); header.createCell(5).setCellValue("Min Age"); header.createCell(6).setCellValue("Max Age"); for (int i = 0; i < sections.size(); i++) { header.createCell(2 * i + 7).setCellValue(sections.get(i).get("name") + " (O)"); header.createCell(2 * i + 8).setCellValue(sections.get(i).get("name") + " (P)"); } for (Cell cell : header) { cell.setCellStyle(style); } for (int i = 0; i < events.size(); i++) { Map<String, String> event = events.get(i); Row row = sheet.createRow(i + 1); row.createCell(0).setCellValue(event.get("name")); row.createCell(1).setCellValue(event.get("type")); row.createCell(2).setCellValue(Integer.parseInt(event.get("solution"))); if (event.containsKey("rankmin")) { row.createCell(3).setCellValue(Double.parseDouble(event.get("rankmin"))); } if (event.containsKey("rankmax")) { row.createCell(4).setCellValue(Double.parseDouble(event.get("rankmax"))); } if (event.containsKey("agemin")) { row.createCell(5).setCellValue(Double.parseDouble(event.get("agemin"))); } else { int before = before(events, i); int after = after(events, i); double a1 = (before == -1 ? 0.0 : Double.parseDouble(events.get(before).get("agemin"))); double a2 = (after == -1 ? a1 : Double.parseDouble(events.get(after).get("agemin"))); if (after == -1) { after = events.size(); } row.createCell(5).setCellValue(a1 + ((a2 - a1) / (after - before)) * (i - before)); } if (event.containsKey("agemax")) { row.createCell(6).setCellValue(Double.parseDouble(event.get("agemax"))); } else { int before = before(events, i); int after = after(events, i); double a1 = (before == -1 ? 0.0 : Double.parseDouble(events.get(before).get("agemax"))); double a2 = (after == -1 ? a1 : Double.parseDouble(events.get(after).get("agemax"))); if (after == -1) { after = events.size(); } row.createCell(6).setCellValue(a1 + ((a2 - a1) / (after - before)) * (i - before)); } for (int j = 0; j < sections.size(); j++) { String observed = event.get("observed." + (j + 1)); if ((observed != null) && !"".equals(observed.trim())) { row.createCell(2 * j + 7).setCellValue(Double.parseDouble(observed)); } row.createCell(2 * j + 8).setCellValue(Double.parseDouble(event.get("placed." + (j + 1)))); } } } }
protected void setUp() throws Exception { prefetcher = new RssNewsitemPrefetcher(resourceDAO, rssHttpFetcher, rssCache, feedReaderRunner, null, configDAO); firstFeed = new FeedImpl(); firstFeed.setUrl("http://testdata/rss/1"); secondFeed = new FeedImpl(); secondFeed.setUrl("http://testdata/rss/2"); feeds = new ArrayList<Feed>(); feeds.add(firstFeed); feeds.add(secondFeed); when(configDAO.isFeedReadingEnabled()).thenReturn(true); when(resourceDAO.getAllFeeds()).thenReturn(feeds); }
protected void setUp() throws Exception { prefetcher = new RssNewsitemPrefetcher(resourceDAO, rssHttpFetcher, rssCache, feedReaderRunner, configDAO); firstFeed = new FeedImpl(); firstFeed.setUrl("http://testdata/rss/1"); secondFeed = new FeedImpl(); secondFeed.setUrl("http://testdata/rss/2"); feeds = new ArrayList<Feed>(); feeds.add(firstFeed); feeds.add(secondFeed); when(configDAO.isFeedReadingEnabled()).thenReturn(true); when(resourceDAO.getAllFeeds()).thenReturn(feeds); }
public Gun(SceletonActivity activity) { ITextureRegion gunTexture = activity.getResourceManager().getLoadedTextureRegion(R.drawable.gun); ZoomCamera camera = activity.getCamera(); PointF gunPosition = new PointF( camera.getCenterX() - gunTexture.getWidth() , camera.getYMax() - gunTexture.getHeight() * 0.6f); gunSprite = new Sprite( gunPosition.x , gunPosition.y , gunTexture , activity.getEngine().getVertexBufferObjectManager()); gunSprite.setRotationCenter(gunSprite.getWidth() / 2, gunSprite.getHeight()); }
public Gun(SceletonActivity activity) { ITextureRegion gunTexture = activity.getResourceManager().getLoadedTextureRegion(R.drawable.gun); ZoomCamera camera = activity.getCamera(); PointF gunPosition = new PointF( camera.getCenterX() - gunTexture.getWidth() / 2 , camera.getYMax() - gunTexture.getHeight() * 0.6f); gunSprite = new Sprite( gunPosition.x , gunPosition.y , gunTexture , activity.getEngine().getVertexBufferObjectManager()); gunSprite.setRotationCenter(gunSprite.getWidth() / 2, gunSprite.getHeight()); }
public void careForInventorySlot(int i, float startTemp) { NBTTagCompound inputCompound; float mod = 1; if(i == 0) { if(fireItemStacks[5] != null) { mod = 0.8F; } else { mod = 0.6F; if(fireItemStacks[6] == null) { mod = 0.3F; } } } else if(i == 1) { if(fireItemStacks[6] != null) { mod = 0.9F; } else { mod = 0.7F; if(fireItemStacks[7] == null) { mod = 0.4F; } } } else if(i == 2) { if(fireItemStacks[7] != null) { mod = 1.0F; } else { mod = 0.5F; } } else if(i == 3) { if(fireItemStacks[8] != null) { mod = 0.9F; } else { mod = 0.7F; if(fireItemStacks[7] == null) { mod = 0.4F; } } } else if(i == 4) { if(fireItemStacks[9] != null) { mod = 0.8F; } else { mod = 0.6F; if(fireItemStacks[8] == null) { mod = 0.3F; } } } HeatManager manager = HeatManager.getInstance(); if(fireItemStacks[i]!= null && fireItemStacks[i].hasTagCompound()) { HeatIndex index = manager.findMatchingIndex(fireItemStacks[i]); inputCompound = fireItemStacks[i].getTagCompound(); if(inputCompound.hasKey("temperature")) { inputItemTemps[i] = inputCompound.getFloat("temperature"); } else { inputItemTemps[i] = ambientTemp; } if(fireTemperature*mod > inputItemTemps[i]) { float increase = TFC_ItemHeat.getTempIncrease(fireItemStacks[i], fireTemperature*mod, MaxFireTemp); inputItemTemps[i] += increase; } else if(fireTemperature*mod < inputItemTemps[i]) { float increase = TFC_ItemHeat.getTempDecrease(fireItemStacks[i]); inputItemTemps[i] -= increase; } inputCompound.setFloat("temperature", inputItemTemps[i]); fireItemStacks[i].setTagCompound(inputCompound); if(inputItemTemps[i] <= ambientTemp) { Collection C = fireItemStacks[i].getTagCompound().getTags(); Iterator itr = C.iterator(); while(itr.hasNext()) { Object tag = itr.next(); if(TFC_ItemHeat.canRemoveTag(tag, "temperature", NBTTagFloat.class)) { itr.remove(); break; } } } if(index != null && index.boilTemp <= inputItemTemps[i]) { fireItemStacks[i] = null; } } else if(fireItemStacks[i] != null && !fireItemStacks[i].hasTagCompound()) { if(TFC_ItemHeat.getMeltingPoint(fireItemStacks[i]) != -1) { inputCompound = new NBTTagCompound(); inputCompound.setFloat("temperature", startTemp); fireItemStacks[i].setTagCompound(inputCompound); } } else if(fireItemStacks[i] == null) { inputItemTemps[i] = 0; } }
public void careForInventorySlot(int i, float startTemp) { NBTTagCompound inputCompound; float mod = 1; if(i == 0) { if(fireItemStacks[5] != null) { mod = 0.8F; } else { mod = 0.6F; if(fireItemStacks[6] == null) { mod = 0.3F; } } } else if(i == 1) { if(fireItemStacks[6] != null) { mod = 0.9F; } else { mod = 0.7F; if(fireItemStacks[7] == null) { mod = 0.4F; } } } else if(i == 2) { if(fireItemStacks[7] != null) { mod = 1.0F; } else { mod = 0.5F; } } else if(i == 3) { if(fireItemStacks[8] != null) { mod = 0.9F; } else { mod = 0.7F; if(fireItemStacks[7] == null) { mod = 0.4F; } } } else if(i == 4) { if(fireItemStacks[9] != null) { mod = 0.8F; } else { mod = 0.6F; if(fireItemStacks[8] == null) { mod = 0.3F; } } } HeatManager manager = HeatManager.getInstance(); if(fireItemStacks[i]!= null && fireItemStacks[i].hasTagCompound()) { HeatIndex index = manager.findMatchingIndex(fireItemStacks[i]); inputCompound = fireItemStacks[i].getTagCompound(); if(inputCompound.hasKey("temperature")) { inputItemTemps[i] = inputCompound.getFloat("temperature"); } else { inputItemTemps[i] = ambientTemp; } if(fireTemperature*mod > inputItemTemps[i]) { float increase = TFC_ItemHeat.getTempIncrease(fireItemStacks[i], fireTemperature*mod, MaxFireTemp); inputItemTemps[i] += increase; } else if(fireTemperature*mod < inputItemTemps[i]) { float increase = TFC_ItemHeat.getTempDecrease(fireItemStacks[i]); inputItemTemps[i] -= increase; } inputCompound.setFloat("temperature", inputItemTemps[i]); fireItemStacks[i].setTagCompound(inputCompound); if(inputItemTemps[i] <= ambientTemp) { Collection C = fireItemStacks[i].getTagCompound().getTags(); Iterator itr = C.iterator(); while(itr.hasNext()) { Object tag = itr.next(); if(TFC_ItemHeat.canRemoveTag(tag, "temperature", NBTTagFloat.class)) { itr.remove(); break; } } } if(index != null && index.boilTemp <= inputItemTemps[i]) { fireItemStacks[i] = null; } } else if(fireItemStacks[i] != null && !fireItemStacks[i].hasTagCompound()) { if(TFC_ItemHeat.getMeltingPoint(fireItemStacks[i]) != -1) { inputCompound = new NBTTagCompound(); inputCompound.setFloat("temperature", startTemp); fireItemStacks[i].setTagCompound(inputCompound); inputItemTemps[i] = startTemp; } } else if(fireItemStacks[i] == null) { inputItemTemps[i] = 0; } }
public static void main(String argv[]) { modshogun.init_shogun_with_defaults(); double width = 0.8; int C = 1; double epsilon = 1e-5; double tube_epsilon = 1e-2; DoubleMatrix traindata_real = Load.load_numbers("../data/fm_train_real.dat"); DoubleMatrix testdata_real = Load.load_numbers("../data/fm_test_real.dat"); DoubleMatrix trainlab = Load.load_labels("../data/label_train_twoclass.dat"); RealFeatures feats_train = new RealFeatures(traindata_real); RealFeatures feats_test = new RealFeatures(testdata_real); GaussianKernel kernel= new GaussianKernel(feats_train, feats_train, width); Labels labels = new Labels(trainlab); LibSVR svr = new LibSVR(C, epsilon, kernel, labels); svr.set_tube_epsilon(tube_epsilon); svr.train(); kernel.init(feats_train, feats_test); DoubleMatrix out_labels = svr.apply().get_labels(); System.out.println(out_labels.toString()); modshogun.exit_shogun(); }
public static void main(String argv[]) { modshogun.init_shogun_with_defaults(); double width = 0.8; int C = 1; double epsilon = 1e-5; double tube_epsilon = 1e-2; DoubleMatrix traindata_real = Load.load_numbers("../data/fm_train_real.dat"); DoubleMatrix testdata_real = Load.load_numbers("../data/fm_test_real.dat"); DoubleMatrix trainlab = Load.load_labels("../data/label_train_twoclass.dat"); RealFeatures feats_train = new RealFeatures(traindata_real); RealFeatures feats_test = new RealFeatures(testdata_real); GaussianKernel kernel= new GaussianKernel(feats_train, feats_train, width); Labels labels = new Labels(trainlab); LibSVR svr = new LibSVR(C, tube_epsilon, kernel, labels); svr.set_epsilon(epsilon); svr.train(); kernel.init(feats_train, feats_test); DoubleMatrix out_labels = svr.apply().get_labels(); System.out.println(out_labels.toString()); modshogun.exit_shogun(); }
public void onPlayerInteract(PlayerInteractEvent event){ Player p = event.getPlayer(); Action a = event.getAction(); if(a.equals(Action.LEFT_CLICK_BLOCK)){ if(leftClick(p, event.getClickedBlock())){ event.setCancelled(true); } return; } if(!a.equals(Action.RIGHT_CLICK_BLOCK)){ return; } Block b = event.getClickedBlock(); if(b.getType() == Material.SIGN_POST || b.getType() == Material.WALL_SIGN || b.getType() == Material.SIGN){ Sign s = (Sign)b.getState(); String[] lines = s.getLines(); if(lines[0].equalsIgnoreCase(plugin.signContains) || lines[0].equalsIgnoreCase("[Sortal]")){ if(event.getPlayer().hasPermission("sortal.warp")){ String line2 = lines[1]; if(line2.startsWith("w:")){ String[] split = line2.split(":"); String warp = split[1]; if(!plugin.warp.containsKey(warp)){ p.sendMessage("This warp does not exist!"); return; } Warp d = plugin.warp.get(warp); if(!pay(p, d)){ return; } d.getWorld().loadChunk((int)d.getX(), (int)d.getY()); if(d.getWorld().equals(p.getLocation().getWorld())){ p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getZ(), p.getLocation().getYaw(), p.getLocation().getPitch())); }else{ p.teleport(new Location(d.getWorld(), 0, 100, 0)); p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getZ(), p.getLocation().getYaw(), p.getLocation().getPitch())); } p.sendMessage("You teleported to " + ChatColor.RED + d.warp() +"!"); }else{ if(line2.contains(",")){ Warp d = new Warp(plugin); if(!pay(p,d)){ return; } String[] split = line2.split(","); if(split.length == 3){ if(isInt(split[0]) && isInt(split[1]) && isInt(split[2])){ int x = Integer.parseInt(split[0]); int y = Integer.parseInt(split[1]); int z = Integer.parseInt(split[2]); Location loc = new Location(p.getWorld(), x, y, z, p.getLocation().getYaw(), p.getLocation().getPitch()); loc.getChunk().load(); p.teleport(loc); p.sendMessage("You teleported to " + ChatColor.RED + line2 + "!"); } } if(split.length == 4){ if(isInt(split[3]) && isInt(split[1]) && isInt(split[2])){ int x = Integer.parseInt(split[1]); int y = Integer.parseInt(split[2]); int z = Integer.parseInt(split[3]); World world = plugin.getServer().getWorld(split[0]); Location loc = new Location(world, x, y, z, p.getLocation().getYaw(), p.getLocation().getPitch()); loc.getChunk().load(); p.teleport(loc); p.sendMessage("You teleported to " + ChatColor.RED + line2 + "!"); } } }else{ p.sendMessage("[Sortal] There's something wrong with this sign.."); } } }else{ p.sendMessage(plugin.noPerm); } }else if(lines[1].equalsIgnoreCase(plugin.signContains) || lines[1].equalsIgnoreCase("[sortal]")){ if(event.getPlayer().hasPermission("sortal.warp")){ String line2 = lines[2]; if(line2.startsWith("w:")){ String[] split = line2.split(":"); String warp = split[1]; if(!plugin.warp.containsKey(warp)){ p.sendMessage("This warp does not exist!"); return; } Warp d = plugin.warp.get(warp); if(!pay(p,d)){ return; } d.getWorld().loadChunk((int)d.getX(), (int)d.getY()); if(d.getWorld().equals(p.getLocation().getWorld())){ p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getZ(), p.getLocation().getYaw(), p.getLocation().getPitch())); }else{ p.teleport(new Location(d.getWorld(), 0, 100, 0)); p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getZ(), p.getLocation().getYaw(), p.getLocation().getPitch())); } p.sendMessage("You teleported to " + ChatColor.RED + d.warp()); }else{ if(line2.contains(",")){ String[] split = line2.split(","); if(split.length == 3){ if(isInt(split[0]) && isInt(split[1]) && isInt(split[2])){ int x = Integer.parseInt(split[0]); int y = Integer.parseInt(split[1]); int z = Integer.parseInt(split[2]); Location loc = new Location(p.getWorld(), x, y, z, p.getLocation().getYaw(), p.getLocation().getPitch()); loc.getChunk().load(); p.teleport(loc); p.sendMessage("You teleported to " + ChatColor.RED + line2 + "!"); } } if(split.length == 4){ if(isInt(split[3]) && isInt(split[1]) && isInt(split[2])){ int x = Integer.parseInt(split[1]); int y = Integer.parseInt(split[2]); int z = Integer.parseInt(split[3]); World world = plugin.getServer().getWorld(split[0]); Location loc = new Location(world, x, y, z, p.getLocation().getYaw(), p.getLocation().getPitch()); loc.getChunk().load(); p.teleport(loc); p.sendMessage("You teleported to " + ChatColor.RED + line2 + "!"); } } } } } }else{ if(event.getPlayer().hasPermission("sortal.warp")){ Location c = new Location(b.getWorld(), b.getX(), b.getY(), b.getZ()); if(plugin.loc.containsKey(c)){ String warp = plugin.loc.get(c); if(!plugin.warp.containsKey(warp)){ p.sendMessage("[Sortal] This sign pointer is broken! Ask an Admin to fix it!"); return; } Warp d = plugin.warp.get(warp); Location goo = new Location(d.getWorld(), d.getX(), d.getY(), d.getZ(), p.getLocation().getYaw(), p.getLocation().getPitch()); goo.getChunk().load(); if(d.getWorld().equals(p.getWorld())){ p.teleport(goo); }else{ p.teleport(goo); p.teleport(goo); } p.sendMessage("You teleported to " + ChatColor.RED + warp + "!"); } } } } }
public void onPlayerInteract(PlayerInteractEvent event){ Player p = event.getPlayer(); Action a = event.getAction(); if(a.equals(Action.LEFT_CLICK_BLOCK)){ if(leftClick(p, event.getClickedBlock())){ event.setCancelled(true); } return; } if(!a.equals(Action.RIGHT_CLICK_BLOCK)){ return; } Block b = event.getClickedBlock(); if(b.getType() == Material.SIGN_POST || b.getType() == Material.WALL_SIGN || b.getType() == Material.SIGN){ Sign s = (Sign)b.getState(); String[] lines = s.getLines(); if(lines[0].equalsIgnoreCase(plugin.signContains) || lines[0].equalsIgnoreCase("[Sortal]")){ if(event.getPlayer().hasPermission("sortal.warp")){ String line2 = lines[1]; if(line2.startsWith("w:")){ String[] split = line2.split(":"); String warp = split[1]; if(!plugin.warp.containsKey(warp)){ p.sendMessage("This warp does not exist!"); return; } Warp d = plugin.warp.get(warp); if(!pay(p, d)){ return; } d.getWorld().getChunkAt((int)d.getX(), (int)d.getZ()).load(); if(d.getWorld().equals(p.getLocation().getWorld())){ p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getZ(), p.getLocation().getYaw(), p.getLocation().getPitch())); }else{ p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getX())); p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getZ(), p.getLocation().getYaw(), p.getLocation().getPitch())); } p.sendMessage("You teleported to " + ChatColor.RED + d.warp() +"!"); }else{ if(line2.contains(",")){ Warp d = new Warp(plugin); if(!pay(p,d)){ return; } String[] split = line2.split(","); if(split.length == 3){ if(isInt(split[0]) && isInt(split[1]) && isInt(split[2])){ int x = Integer.parseInt(split[0]); int y = Integer.parseInt(split[1]); int z = Integer.parseInt(split[2]); Location loc = new Location(p.getWorld(), x, y, z, p.getLocation().getYaw(), p.getLocation().getPitch()); loc.getChunk().load(); p.teleport(loc); p.sendMessage("You teleported to " + ChatColor.RED + line2 + "!"); } } if(split.length == 4){ if(isInt(split[3]) && isInt(split[1]) && isInt(split[2])){ int x = Integer.parseInt(split[1]); int y = Integer.parseInt(split[2]); int z = Integer.parseInt(split[3]); World world = plugin.getServer().getWorld(split[0]); Location loc = new Location(world, x, y, z, p.getLocation().getYaw(), p.getLocation().getPitch()); loc.getChunk().load(); p.teleport(loc); p.sendMessage("You teleported to " + ChatColor.RED + line2 + "!"); } } }else{ p.sendMessage("[Sortal] There's something wrong with this sign.."); } } }else{ p.sendMessage(plugin.noPerm); } }else if(lines[1].equalsIgnoreCase(plugin.signContains) || lines[1].equalsIgnoreCase("[sortal]")){ if(event.getPlayer().hasPermission("sortal.warp")){ String line2 = lines[2]; if(line2.startsWith("w:")){ String[] split = line2.split(":"); String warp = split[1]; if(!plugin.warp.containsKey(warp)){ p.sendMessage("This warp does not exist!"); return; } Warp d = plugin.warp.get(warp); if(!pay(p,d)){ return; } d.getWorld().getChunkAt((int)d.getX(), (int)d.getZ()).load(); if(d.getWorld().equals(p.getLocation().getWorld())){ p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getZ(), p.getLocation().getYaw(), p.getLocation().getPitch())); }else{ p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getZ())); p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getZ(), p.getLocation().getYaw(), p.getLocation().getPitch())); } p.sendMessage("You teleported to " + ChatColor.RED + d.warp()); }else{ if(line2.contains(",")){ String[] split = line2.split(","); if(split.length == 3){ if(isInt(split[0]) && isInt(split[1]) && isInt(split[2])){ int x = Integer.parseInt(split[0]); int y = Integer.parseInt(split[1]); int z = Integer.parseInt(split[2]); Location loc = new Location(p.getWorld(), x, y, z, p.getLocation().getYaw(), p.getLocation().getPitch()); loc.getChunk().load(); p.teleport(loc); p.sendMessage("You teleported to " + ChatColor.RED + line2 + "!"); } } if(split.length == 4){ if(isInt(split[3]) && isInt(split[1]) && isInt(split[2])){ int x = Integer.parseInt(split[1]); int y = Integer.parseInt(split[2]); int z = Integer.parseInt(split[3]); World world = plugin.getServer().getWorld(split[0]); Location loc = new Location(world, x, y, z, p.getLocation().getYaw(), p.getLocation().getPitch()); loc.getChunk().load(); p.teleport(loc); p.sendMessage("You teleported to " + ChatColor.RED + line2 + "!"); } } } } } }else{ if(event.getPlayer().hasPermission("sortal.warp")){ Location c = new Location(b.getWorld(), b.getX(), b.getY(), b.getZ()); if(plugin.loc.containsKey(c)){ String warp = plugin.loc.get(c); if(!plugin.warp.containsKey(warp)){ p.sendMessage("[Sortal] This sign pointer is broken! Ask an Admin to fix it!"); return; } Warp d = plugin.warp.get(warp); Location goo = new Location(d.getWorld(), d.getX(), d.getY(), d.getZ(), p.getLocation().getYaw(), p.getLocation().getPitch()); goo.getChunk().load(); if(d.getWorld().equals(p.getWorld())){ p.teleport(goo); }else{ p.teleport(goo); p.teleport(goo); } p.sendMessage("You teleported to " + ChatColor.RED + warp + "!"); } } } } }
private void renderRadialData(GL10 gl, RadialDataPacket packet, Color[] palette) { float kmPerRangeBin = 1.0f; for (int i = 1; i < 16; i++) { if (mRadialBuffers[i] == null) { TriangleBuffer buffer = new TriangleBuffer(); for (int az = 0; az < packet.radials.length; az++) { RadialPacket radial = packet.radials[az]; float start = 90.0f - (radial.start + radial.delta); float end = start + radial.delta; float cosx1 = (float)Math.cos(Math.toRadians(start)); float siny1 = (float)Math.sin(Math.toRadians(start)); float cosx2 = (float)Math.cos(Math.toRadians(end)); float siny2 = (float)Math.sin(Math.toRadians(end)); int startRange = 0; for (int range = 0; range < radial.codes.length; range++) { int color = radial.codes[range]; if (startRange == 0 && color == i) startRange = range+1; if ((startRange != 0 && color < i) || (startRange != 0 && (range == packet.rangeBinCount-1))) { if (range == packet.rangeBinCount-1) range++; Vertex v1 = new Vertex( (startRange-1) * kmPerRangeBin * cosx1, (startRange-1) * kmPerRangeBin * siny1); Vertex v2 = new Vertex( (range-1) * kmPerRangeBin * cosx1, (range-1) * kmPerRangeBin * siny1); Vertex v3 = new Vertex( (range-1) * kmPerRangeBin * cosx2, (range-1) * kmPerRangeBin * siny2); Vertex v4 = new Vertex( (startRange-1) * kmPerRangeBin * cosx2, (startRange-1) * kmPerRangeBin * siny2); buffer.addTriangle(v1, v2, v3); buffer.addTriangle(v3, v4, v1); startRange = 0; } } } mRadialBuffers[i] = buffer.getBuffer(); mRadialSize[i] = buffer.size(); } Color c = palette[i]; gl.glColor4f(c.r, c.g, c.b, 1.0f); FloatBuffer buf = mRadialBuffers[i]; gl.glVertexPointer(2, GL10.GL_FLOAT, 0, buf); gl.glDrawArrays(GL10.GL_TRIANGLES, 0, mRadialSize[i]); } }
private void renderRadialData(GL10 gl, RadialDataPacket packet, Color[] palette) { float kmPerRangeBin = 1.0f; for (int i = 1; i < 16; i++) { if (mRadialBuffers[i] == null) { TriangleBuffer buffer = new TriangleBuffer(); for (int az = 0; az < packet.radials.length; az++) { RadialPacket radial = packet.radials[az]; float start = 90.0f - (radial.start + radial.delta); float end = start + radial.delta; float cosx1 = (float)Math.cos(Math.toRadians(start)); float siny1 = (float)Math.sin(Math.toRadians(start)); float cosx2 = (float)Math.cos(Math.toRadians(end)); float siny2 = (float)Math.sin(Math.toRadians(end)); int startRange = 0; for (int range = 0; range < radial.codes.length; range++) { int color = radial.codes[range]; if (startRange == 0 && color == i) startRange = range; if ((startRange != 0 && color < i) || (startRange != 0 && (range == packet.rangeBinCount-1))) { if (color >= i && range == packet.rangeBinCount-1) range++; Vertex v1 = new Vertex( (startRange-1) * kmPerRangeBin * cosx1, (startRange-1) * kmPerRangeBin * siny1); Vertex v2 = new Vertex( (range-1) * kmPerRangeBin * cosx1, (range-1) * kmPerRangeBin * siny1); Vertex v3 = new Vertex( (range-1) * kmPerRangeBin * cosx2, (range-1) * kmPerRangeBin * siny2); Vertex v4 = new Vertex( (startRange-1) * kmPerRangeBin * cosx2, (startRange-1) * kmPerRangeBin * siny2); buffer.addTriangle(v1, v2, v3); buffer.addTriangle(v3, v4, v1); startRange = 0; } } } mRadialBuffers[i] = buffer.getBuffer(); mRadialSize[i] = buffer.size(); } Color c = palette[i]; gl.glColor4f(c.r, c.g, c.b, 1.0f); FloatBuffer buf = mRadialBuffers[i]; gl.glVertexPointer(2, GL10.GL_FLOAT, 0, buf); gl.glDrawArrays(GL10.GL_TRIANGLES, 0, mRadialSize[i]); } }
public static void main(String[] args) throws Exception { XDIDiscoveryClient discovery = new XDIDiscoveryClient(); discovery.setRegistryXdiClient(new XDIHttpClient("http://localhost:12220/")); XDIDiscoveryResult result = discovery.discoverFromRegistry(XDI3Segment.create("=markus")); System.out.println("Cloud Number: " + result.getCloudNumber()); System.out.println("URI: " + result.getXdiEndpointUri()); }
public static void main(String[] args) throws Exception { XDIDiscoveryClient discovery = new XDIDiscoveryClient(); discovery.setRegistryXdiClient(new XDIHttpClient("http://mycloud.neustar.biz:12220/")); XDIDiscoveryResult result = discovery.discoverFromRegistry(XDI3Segment.create("=markus")); result = discovery.discoverFromAuthority(result.getXdiEndpointUri(), result.getCloudNumber()); System.out.println("Cloud Number: " + result.getCloudNumber()); System.out.println("URI: " + result.getXdiEndpointUri()); }
public void testMultiset() { Multiset<String> worldCupChampionships = HashMultiset.<String>create(); worldCupChampionships.add("Brazil"); worldCupChampionships.add("Brazil"); worldCupChampionships.add("Brazil"); worldCupChampionships.add("Brazil"); worldCupChampionships.add("Brazil"); worldCupChampionships.add("Italy"); worldCupChampionships.add("Italy"); worldCupChampionships.add("Italy"); worldCupChampionships.add("Italy"); worldCupChampionships.add("Germany", 4); assertEquals(worldCupChampionships.count("Brazil"), 4); assertEquals(worldCupChampionships.count("Italy"), 4); assertEquals(worldCupChampionships.count("Germany"), 3); assertEquals(worldCupChampionships.count("United States"), 0); assertFalse(worldCupChampionships.contains("United States")); worldCupChampionships.add("United States", 0); assertEquals(worldCupChampionships.count("United States"), 0); assertFalse(worldCupChampionships.contains("United States")); Collection<String> g = Collections2.transform(worldCupChampionships, new Function<String, String>() { public String apply(String input) { return "Team " + input; } }); assertTrue(g.contains("Team Brazil")); }
public void testMultiset() { Multiset<String> worldCupChampionships = HashMultiset.<String>create(); worldCupChampionships.add("Brazil"); worldCupChampionships.add("Brazil"); worldCupChampionships.add("Brazil"); worldCupChampionships.add("Brazil"); worldCupChampionships.add("Brazil"); worldCupChampionships.add("Italy"); worldCupChampionships.add("Italy"); worldCupChampionships.add("Italy"); worldCupChampionships.add("Italy"); worldCupChampionships.add("Germany", 4); assertEquals(worldCupChampionships.count("Brazil"), 5); assertEquals(worldCupChampionships.count("Italy"), 4); assertEquals(worldCupChampionships.count("Germany"), 4); assertEquals(worldCupChampionships.count("United States"), 0); assertFalse(worldCupChampionships.contains("United States")); worldCupChampionships.add("United States", 0); assertEquals(worldCupChampionships.count("United States"), 0); assertFalse(worldCupChampionships.contains("United States")); Collection<String> g = Collections2.transform(worldCupChampionships, new Function<String, String>() { public String apply(String input) { return "Team " + input; } }); assertTrue(g.contains("Team Brazil")); }
public void testLoadShiporder() throws Exception { GmlInstanceCollection instances = loadInstances( getClass().getResource("/data/shiporder/shiporder.xsd").toURI(), getClass().getResource("/data/shiporder/shiporder.xml").toURI()); String ns = "http://www.example.com"; ResourceIterator<Instance> it = instances.iterator(); assertTrue(it.hasNext()); Instance instance = it.next(); assertNotNull(instance); Object[] orderid = instance.getProperty(new QName(ns, "orderid")); assertNotNull(orderid); assertEquals(1, orderid.length); assertEquals("889923", orderid[0]); Object[] orderperson = instance.getProperty(new QName(ns, "orderperson")); assertNotNull(orderperson); assertEquals(1, orderperson.length); assertEquals("John Smith", orderperson[0]); Object[] shipto = instance.getProperty(new QName(ns, "shipto")); assertNotNull(shipto); assertEquals(1, shipto.length); assertTrue(shipto[0] instanceof Instance); Instance shipto1 = (Instance) shipto[0]; Object[] shiptoName = shipto1.getProperty(new QName(ns, "name")); assertNotNull(shiptoName); assertEquals(1, shiptoName.length); assertEquals("Ola Nordmann", shiptoName[0]); Object[] shiptoAddress = shipto1.getProperty(new QName(ns, "address")); assertNotNull(shiptoAddress); assertEquals(1, shiptoAddress.length); assertEquals("Langgt 23", shiptoAddress[0]); Object[] shiptoCity = shipto1.getProperty(new QName(ns, "city")); assertNotNull(shiptoCity); assertEquals(1, shiptoCity.length); assertEquals("4000 Stavanger", shiptoCity[0]); Object[] shiptoCountry = shipto1.getProperty(new QName(ns, "country")); assertNotNull(shiptoCountry); assertEquals(1, shiptoCountry.length); assertEquals("Norway", shiptoCountry[0]); assertFalse(it.hasNext()); it.dispose(); }
public void testLoadShiporder() throws Exception { GmlInstanceCollection instances = loadInstances( getClass().getResource("/data/shiporder/shiporder.xsd").toURI(), getClass().getResource("/data/shiporder/shiporder.xml").toURI()); String ns = "http://www.example.com"; ResourceIterator<Instance> it = instances.iterator(); assertTrue(it.hasNext()); Instance instance = it.next(); assertNotNull(instance); Object[] orderid = instance.getProperty(new QName("orderid")); assertNotNull(orderid); assertEquals(1, orderid.length); assertEquals("889923", orderid[0]); Object[] orderperson = instance.getProperty(new QName(ns, "orderperson")); assertNotNull(orderperson); assertEquals(1, orderperson.length); assertEquals("John Smith", orderperson[0]); Object[] shipto = instance.getProperty(new QName(ns, "shipto")); assertNotNull(shipto); assertEquals(1, shipto.length); assertTrue(shipto[0] instanceof Instance); Instance shipto1 = (Instance) shipto[0]; Object[] shiptoName = shipto1.getProperty(new QName(ns, "name")); assertNotNull(shiptoName); assertEquals(1, shiptoName.length); assertEquals("Ola Nordmann", shiptoName[0]); Object[] shiptoAddress = shipto1.getProperty(new QName(ns, "address")); assertNotNull(shiptoAddress); assertEquals(1, shiptoAddress.length); assertEquals("Langgt 23", shiptoAddress[0]); Object[] shiptoCity = shipto1.getProperty(new QName(ns, "city")); assertNotNull(shiptoCity); assertEquals(1, shiptoCity.length); assertEquals("4000 Stavanger", shiptoCity[0]); Object[] shiptoCountry = shipto1.getProperty(new QName(ns, "country")); assertNotNull(shiptoCountry); assertEquals(1, shiptoCountry.length); assertEquals("Norway", shiptoCountry[0]); assertFalse(it.hasNext()); it.dispose(); }
public Collection<String> getImplementedInterfaces(String resourcePath){ Set<String> implInterfaces = new HashSet<String>(); Class<?> c = null; try { c = findClass(ClusterClassLoaderUtils.getClassNameFromResourcePath(resourcePath)); } catch (ClassNotFoundException e) { } if(c != null){ for(Class<?> inter : c.getInterfaces()){ implInterfaces.add(inter.getName()); } if(c.getSuperclass() != null && !c.getSuperclass().getName().equals(Object.class.getName())){ String superClassResourceName = ClusterClassLoaderUtils.getResourcePathFromClassName(c.getSuperclass().getName()); implInterfaces.addAll(getImplementedInterfaces(superClassResourceName)); } } return implInterfaces; }
public Collection<String> getImplementedInterfaces(String resourcePath){ Set<String> implInterfaces = new HashSet<String>(); Class<?> c = null; try { String classNameFromResourcePath = ClusterClassLoaderUtils.getClassNameFromResourcePath(resourcePath); if(classNameFromResourcePath != null){ c = findClass(classNameFromResourcePath); } } catch (ClassNotFoundException e) { } if(c != null){ for(Class<?> inter : c.getInterfaces()){ implInterfaces.add(inter.getName()); } if(c.getSuperclass() != null && !c.getSuperclass().getName().equals(Object.class.getName())){ String superClassResourceName = ClusterClassLoaderUtils.getResourcePathFromClassName(c.getSuperclass().getName()); implInterfaces.addAll(getImplementedInterfaces(superClassResourceName)); } } return implInterfaces; }
public Index addIndex(Session session, String indexName, int indexId, IndexColumn[] cols, IndexType indexType, boolean create, String indexComment) { if (indexType.isPrimaryKey()) { for (IndexColumn c : cols) { Column column = c.column; if (column.isNullable()) { throw DbException.get(ErrorCode.COLUMN_MUST_NOT_BE_NULLABLE_1, column.getName()); } column.setPrimaryKey(true); } } boolean isSessionTemporary = isTemporary() && !isGlobalTemporary(); if (!isSessionTemporary) { database.lockMeta(session); } Index index; if (isPersistIndexes() && indexType.isPersistent()) { int mainIndexColumn; if (database.isStarting() && database.getPageStore().getRootPageId(indexId) != 0) { mainIndexColumn = -1; } else if (!database.isStarting() && mainIndex.getRowCount(session) != 0) { mainIndexColumn = -1; } else { mainIndexColumn = getMainIndexColumn(indexType, cols); } if (mainIndexColumn != -1) { mainIndex.setMainIndexColumn(mainIndexColumn); index = new PageDelegateIndex(this, indexId, indexName, indexType, mainIndex, create, session); } else if (indexType.isSpatial()) { index = new SpatialTreeIndex(this, indexId, indexName, cols, indexType, true, create, session); } else { index = new PageBtreeIndex(this, indexId, indexName, cols, indexType, create, session); } } else { if (indexType.isHash() && cols.length <= 1) { if (indexType.isUnique()) { index = new HashIndex(this, indexId, indexName, cols, indexType); } else { index = new NonUniqueHashIndex(this, indexId, indexName, cols, indexType); } } else if (!indexType.isSpatial()) { index = new TreeIndex(this, indexId, indexName, cols, indexType); } else { index = new SpatialTreeIndex(this, indexId, indexName, cols, indexType, false, true, session); } } if (database.isMultiVersion()) { index = new MultiVersionIndex(index, this); } if (index.needRebuild() && rowCount > 0) { try { Index scan = getScanIndex(session); long remaining = scan.getRowCount(session); long total = remaining; Cursor cursor = scan.find(session, null, null); long i = 0; int bufferSize = (int) Math.min(rowCount, Constants.DEFAULT_MAX_MEMORY_ROWS); ArrayList<Row> buffer = New.arrayList(bufferSize); String n = getName() + ":" + index.getName(); int t = MathUtils.convertLongToInt(total); while (cursor.next()) { database.setProgress(DatabaseEventListener.STATE_CREATE_INDEX, n, MathUtils.convertLongToInt(i++), t); Row row = cursor.get(); buffer.add(row); if (buffer.size() >= bufferSize) { addRowsToIndex(session, buffer, index); } remaining--; } addRowsToIndex(session, buffer, index); if (SysProperties.CHECK && remaining != 0) { DbException.throwInternalError("rowcount remaining=" + remaining + " " + getName()); } } catch (DbException e) { getSchema().freeUniqueName(indexName); try { index.remove(session); } catch (DbException e2) { trace.error(e2, "could not remove index"); throw e2; } throw e; } } index.setTemporary(isTemporary()); if (index.getCreateSQL() != null) { index.setComment(indexComment); if (isSessionTemporary) { session.addLocalTempTableIndex(index); } else { database.addSchemaObject(session, index); } } indexes.add(index); setModified(); return index; }
public Index addIndex(Session session, String indexName, int indexId, IndexColumn[] cols, IndexType indexType, boolean create, String indexComment) { if (indexType.isPrimaryKey()) { for (IndexColumn c : cols) { Column column = c.column; if (column.isNullable()) { throw DbException.get(ErrorCode.COLUMN_MUST_NOT_BE_NULLABLE_1, column.getName()); } column.setPrimaryKey(true); } } boolean isSessionTemporary = isTemporary() && !isGlobalTemporary(); if (!isSessionTemporary) { database.lockMeta(session); } Index index; if (isPersistIndexes() && indexType.isPersistent()) { int mainIndexColumn; if (database.isStarting() && database.getPageStore().getRootPageId(indexId) != 0) { mainIndexColumn = -1; } else if (!database.isStarting() && mainIndex.getRowCount(session) != 0) { mainIndexColumn = -1; } else { mainIndexColumn = getMainIndexColumn(indexType, cols); } if (mainIndexColumn != -1) { mainIndex.setMainIndexColumn(mainIndexColumn); index = new PageDelegateIndex(this, indexId, indexName, indexType, mainIndex, create, session); } else if (indexType.isSpatial()) { index = new SpatialTreeIndex(this, indexId, indexName, cols, indexType, true, create, session); } else { index = new PageBtreeIndex(this, indexId, indexName, cols, indexType, create, session); } } else { if (indexType.isHash()) { if (cols.length != 1) { throw DbException.getUnsupportedException("hash indexes may index only one column"); } if (indexType.isUnique()) { index = new HashIndex(this, indexId, indexName, cols, indexType); } else { index = new NonUniqueHashIndex(this, indexId, indexName, cols, indexType); } } else if (!indexType.isSpatial()) { index = new TreeIndex(this, indexId, indexName, cols, indexType); } else { index = new SpatialTreeIndex(this, indexId, indexName, cols, indexType, false, true, session); } } if (database.isMultiVersion()) { index = new MultiVersionIndex(index, this); } if (index.needRebuild() && rowCount > 0) { try { Index scan = getScanIndex(session); long remaining = scan.getRowCount(session); long total = remaining; Cursor cursor = scan.find(session, null, null); long i = 0; int bufferSize = (int) Math.min(rowCount, Constants.DEFAULT_MAX_MEMORY_ROWS); ArrayList<Row> buffer = New.arrayList(bufferSize); String n = getName() + ":" + index.getName(); int t = MathUtils.convertLongToInt(total); while (cursor.next()) { database.setProgress(DatabaseEventListener.STATE_CREATE_INDEX, n, MathUtils.convertLongToInt(i++), t); Row row = cursor.get(); buffer.add(row); if (buffer.size() >= bufferSize) { addRowsToIndex(session, buffer, index); } remaining--; } addRowsToIndex(session, buffer, index); if (SysProperties.CHECK && remaining != 0) { DbException.throwInternalError("rowcount remaining=" + remaining + " " + getName()); } } catch (DbException e) { getSchema().freeUniqueName(indexName); try { index.remove(session); } catch (DbException e2) { trace.error(e2, "could not remove index"); throw e2; } throw e; } } index.setTemporary(isTemporary()); if (index.getCreateSQL() != null) { index.setComment(indexComment); if (isSessionTemporary) { session.addLocalTempTableIndex(index); } else { database.addSchemaObject(session, index); } } indexes.add(index); setModified(); return index; }
public static Iterable<ITmfNewAnalysisModuleListener> getOutputListeners() { List<ITmfNewAnalysisModuleListener> newModuleListeners = new ArrayList<>(); IConfigurationElement[] config = Platform.getExtensionRegistry().getConfigurationElementsFor(TMF_ANALYSIS_TYPE_ID); for (IConfigurationElement ce : config) { String elementName = ce.getName(); if (elementName.equals(OUTPUT_ELEM)) { try { IAnalysisOutput output = (IAnalysisOutput) ce.createExecutableExtension(CLASS_ATTR); ITmfNewAnalysisModuleListener listener = null; for (IConfigurationElement childCe : ce.getChildren()) { if (childCe.getName().equals(ANALYSIS_ID_ELEM)) { listener = new TmfNewAnalysisOutputListener(output, childCe.getAttribute(ID_ATTR), null); } else if (childCe.getName().equals(MODULE_CLASS_ELEM)) { listener = new TmfNewAnalysisOutputListener(output, null, (Class<? extends IAnalysisModule>) childCe.createExecutableExtension(CLASS_ATTR).getClass()); } } if (listener != null) { newModuleListeners.add(listener); } } catch (InvalidRegistryObjectException | CoreException e) { Activator.logError("Error creating module output listener", e); } } } return newModuleListeners; }
public static Iterable<ITmfNewAnalysisModuleListener> getOutputListeners() { List<ITmfNewAnalysisModuleListener> newModuleListeners = new ArrayList<>(); IConfigurationElement[] config = Platform.getExtensionRegistry().getConfigurationElementsFor(TMF_ANALYSIS_TYPE_ID); for (IConfigurationElement ce : config) { String elementName = ce.getName(); if (elementName.equals(OUTPUT_ELEM)) { try { IAnalysisOutput output = (IAnalysisOutput) ce.createExecutableExtension(CLASS_ATTR); ITmfNewAnalysisModuleListener listener = null; for (IConfigurationElement childCe : ce.getChildren()) { if (childCe.getName().equals(ANALYSIS_ID_ELEM)) { listener = new TmfNewAnalysisOutputListener(output, childCe.getAttribute(ID_ATTR), null); } else if (childCe.getName().equals(MODULE_CLASS_ELEM)) { listener = new TmfNewAnalysisOutputListener(output, null, childCe.createExecutableExtension(CLASS_ATTR).getClass().asSubclass(IAnalysisModule.class)); } } if (listener != null) { newModuleListeners.add(listener); } } catch (InvalidRegistryObjectException | CoreException e) { Activator.logError("Error creating module output listener", e); } } } return newModuleListeners; }
public void testAppendRestart() throws Exception { final Configuration conf = new HdfsConfiguration(); conf.setInt( CommonConfigurationKeysPublic.IPC_CLIENT_CONNECTION_MAXIDLETIME_KEY, 0); MiniDFSCluster cluster = null; FSDataOutputStream stream = null; try { cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build(); FileSystem fs = cluster.getFileSystem(); File editLog = new File(FSImageTestUtil.getNameNodeCurrentDirs(cluster, 0).get(0), NNStorage.getInProgressEditsFileName(1)); EnumMap<FSEditLogOpCodes, Holder<Integer>> counts; Path p1 = new Path("/block-boundaries"); writeAndAppend(fs, p1, BLOCK_SIZE, BLOCK_SIZE); counts = FSImageTestUtil.countEditLogOpTypes(editLog); assertEquals(4, (int)counts.get(FSEditLogOpCodes.OP_ADD).held); assertEquals(2, (int)counts.get(FSEditLogOpCodes.OP_CLOSE).held); Path p2 = new Path("/not-block-boundaries"); writeAndAppend(fs, p2, BLOCK_SIZE/2, BLOCK_SIZE); counts = FSImageTestUtil.countEditLogOpTypes(editLog); assertEquals(9, (int)counts.get(FSEditLogOpCodes.OP_ADD).held); assertEquals(4, (int)counts.get(FSEditLogOpCodes.OP_CLOSE).held); cluster.restartNameNode(); AppendTestUtil.check(fs, p1, 2*BLOCK_SIZE); AppendTestUtil.check(fs, p2, 3*BLOCK_SIZE/2); } finally { IOUtils.closeStream(stream); if (cluster != null) { cluster.shutdown(); } } }
public void testAppendRestart() throws Exception { final Configuration conf = new HdfsConfiguration(); conf.setInt( CommonConfigurationKeysPublic.IPC_CLIENT_CONNECTION_MAXIDLETIME_KEY, 0); MiniDFSCluster cluster = null; FSDataOutputStream stream = null; try { cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build(); FileSystem fs = cluster.getFileSystem(); File editLog = new File(FSImageTestUtil.getNameNodeCurrentDirs(cluster, 0).get(0), NNStorage.getInProgressEditsFileName(1)); EnumMap<FSEditLogOpCodes, Holder<Integer>> counts; Path p1 = new Path("/block-boundaries"); writeAndAppend(fs, p1, BLOCK_SIZE, BLOCK_SIZE); counts = FSImageTestUtil.countEditLogOpTypes(editLog); assertEquals(2, (int)counts.get(FSEditLogOpCodes.OP_ADD).held); assertEquals(2, (int)counts.get(FSEditLogOpCodes.OP_UPDATE_BLOCKS).held); assertEquals(2, (int)counts.get(FSEditLogOpCodes.OP_CLOSE).held); Path p2 = new Path("/not-block-boundaries"); writeAndAppend(fs, p2, BLOCK_SIZE/2, BLOCK_SIZE); counts = FSImageTestUtil.countEditLogOpTypes(editLog); assertEquals(2+2, (int)counts.get(FSEditLogOpCodes.OP_ADD).held); assertEquals(2+3, (int)counts.get(FSEditLogOpCodes.OP_UPDATE_BLOCKS).held); assertEquals(2+2, (int)counts.get(FSEditLogOpCodes.OP_CLOSE).held); cluster.restartNameNode(); AppendTestUtil.check(fs, p1, 2*BLOCK_SIZE); AppendTestUtil.check(fs, p2, 3*BLOCK_SIZE/2); } finally { IOUtils.closeStream(stream); if (cluster != null) { cluster.shutdown(); } } }
public void showInternalHighlight(EditWindow wnd, Graphics g, int highOffX, int highOffY, boolean onlyHighlight, boolean setConnected) { Graphics2D g2 = (Graphics2D)g; highlightConnected = setConnected; Color oldColor = null; if (color != null) { oldColor = g.getColor(); g.setColor(color); } if (eobj instanceof ArcInst) { ArcInst ai = (ArcInst)eobj; try { Poly poly = ai.makeLambdaPoly(ai.getGridBaseWidth(), Poly.Type.CLOSED); if (poly == null) return; drawOutlineFromPoints(wnd, g, poly.getPoints(), highOffX, highOffY, false, false); if (onlyHighlight) { String constraints = "X"; if (ai.isRigid()) constraints = "R"; else { if (ai.isFixedAngle()) { if (ai.isSlidable()) constraints = "FS"; else constraints = "F"; } else if (ai.isSlidable()) constraints = "S"; } Point p = wnd.databaseToScreen(ai.getTrueCenterX(), ai.getTrueCenterY()); Font font = wnd.getFont(null); if (font != null) { GlyphVector gv = wnd.getGlyphs(constraints, font); Rectangle2D glyphBounds = gv.getVisualBounds(); g.drawString(constraints, (int)(p.x - glyphBounds.getWidth()/2 + highOffX), p.y + font.getSize()/2 + highOffY); } } } catch (Error e) { throw e; } return; } PortProto pp = null; ElectricObject realEObj = eobj; PortInst originalPi = null; if (realEObj instanceof PortInst) { originalPi = ((PortInst)realEObj); pp = originalPi.getPortProto(); realEObj = ((PortInst)realEObj).getNodeInst(); } if (realEObj instanceof NodeInst) { NodeInst ni = (NodeInst)realEObj; AffineTransform trans = ni.rotateOutAboutTrueCenter(); int offX = highOffX; int offY = highOffY; if (point >= 0) { Point2D [] points = ni.getTrace(); if (points != null) { if (ni.getProto() == Artwork.tech().splineNode) { Point2D [] changedPoints = new Point2D[points.length]; for(int i=0; i<points.length; i++) { changedPoints[i] = points[i]; if (i == point) { double x = ni.getAnchorCenterX() + points[point].getX(); double y = ni.getAnchorCenterY() + points[point].getY(); Point2D thisPt = new Point2D.Double(x, y); trans.transform(thisPt, thisPt); Point cThis = wnd.databaseToScreen(thisPt); Point2D db = wnd.screenToDatabase(cThis.x+offX, cThis.y+offY); changedPoints[i] = new Point2D.Double(db.getX() - ni.getAnchorCenterX(), db.getY() - ni.getAnchorCenterY()); } } Point2D [] spPoints = Artwork.tech().fillSpline(ni.getAnchorCenterX(), ni.getAnchorCenterY(), changedPoints); Point cLast = wnd.databaseToScreen(spPoints[0]); for(int i=1; i<spPoints.length; i++) { Point cThis = wnd.databaseToScreen(spPoints[i]); drawLine(g, wnd, cLast.x, cLast.y, cThis.x, cThis.y); cLast = cThis; } } if (points[point] != null) { double x = ni.getAnchorCenterX() + points[point].getX(); double y = ni.getAnchorCenterY() + points[point].getY(); Point2D thisPt = new Point2D.Double(x, y); trans.transform(thisPt, thisPt); Point cThis = wnd.databaseToScreen(thisPt); int size = 3; drawLine(g, wnd, cThis.x + size + offX, cThis.y + size + offY, cThis.x - size + offX, cThis.y - size + offY); drawLine(g, wnd, cThis.x + size + offX, cThis.y - size + offY, cThis.x - size + offX, cThis.y + size + offY); boolean showWrap = ni.traceWraps(); Point2D prevPt = null, nextPt = null; int prevPoint = point - 1; if (prevPoint < 0 && showWrap) prevPoint = points.length - 1; if (prevPoint >= 0 && points[prevPoint] != null) { prevPt = new Point2D.Double(ni.getAnchorCenterX() + points[prevPoint].getX(), ni.getAnchorCenterY() + points[prevPoint].getY()); trans.transform(prevPt, prevPt); if (prevPt.getX() == thisPt.getX() && prevPt.getY() == thisPt.getY()) prevPoint = -1; else { Point cPrev = wnd.databaseToScreen(prevPt); drawLine(g, wnd, cThis.x + offX, cThis.y + offY, cPrev.x, cPrev.y); } } int nextPoint = point + 1; if (nextPoint >= points.length) { if (showWrap) nextPoint = 0; else nextPoint = -1; } if (nextPoint >= 0 && points[nextPoint] != null) { nextPt = new Point2D.Double(ni.getAnchorCenterX() + points[nextPoint].getX(), ni.getAnchorCenterY() + points[nextPoint].getY()); trans.transform(nextPt, nextPt); if (nextPt.getX() == thisPt.getX() && nextPt.getY() == thisPt.getY()) nextPoint = -1; else { Point cNext = wnd.databaseToScreen(nextPt); drawLine(g, wnd, cThis.x + offX, cThis.y + offY, cNext.x, cNext.y); } } if (offX == 0 && offY == 0 && points.length > 2 && prevPt != null && nextPt != null) { double arrowLen = Double.MAX_VALUE; if (prevPoint >= 0) arrowLen = Math.min(thisPt.distance(prevPt), arrowLen); if (nextPoint >= 0) arrowLen = Math.min(thisPt.distance(nextPt), arrowLen); arrowLen /= 10; double angleOfArrow = Math.PI * 0.8; if (prevPoint >= 0) { Point2D prevCtr = new Point2D.Double((prevPt.getX()+thisPt.getX()) / 2, (prevPt.getY()+thisPt.getY()) / 2); double prevAngle = DBMath.figureAngleRadians(prevPt, thisPt); Point2D prevArrow1 = new Point2D.Double(prevCtr.getX() + Math.cos(prevAngle+angleOfArrow) * arrowLen, prevCtr.getY() + Math.sin(prevAngle+angleOfArrow) * arrowLen); Point2D prevArrow2 = new Point2D.Double(prevCtr.getX() + Math.cos(prevAngle-angleOfArrow) * arrowLen, prevCtr.getY() + Math.sin(prevAngle-angleOfArrow) * arrowLen); Point cPrevCtr = wnd.databaseToScreen(prevCtr); Point cPrevArrow1 = wnd.databaseToScreen(prevArrow1); Point cPrevArrow2 = wnd.databaseToScreen(prevArrow2); drawLine(g, wnd, cPrevCtr.x, cPrevCtr.y, cPrevArrow1.x, cPrevArrow1.y); drawLine(g, wnd, cPrevCtr.x, cPrevCtr.y, cPrevArrow2.x, cPrevArrow2.y); } if (nextPoint >= 0) { Point2D nextCtr = new Point2D.Double((nextPt.getX()+thisPt.getX()) / 2, (nextPt.getY()+thisPt.getY()) / 2); double nextAngle = DBMath.figureAngleRadians(thisPt, nextPt); Point2D nextArrow1 = new Point2D.Double(nextCtr.getX() + Math.cos(nextAngle+angleOfArrow) * arrowLen, nextCtr.getY() + Math.sin(nextAngle+angleOfArrow) * arrowLen); Point2D nextArrow2 = new Point2D.Double(nextCtr.getX() + Math.cos(nextAngle-angleOfArrow) * arrowLen, nextCtr.getY() + Math.sin(nextAngle-angleOfArrow) * arrowLen); Point cNextCtr = wnd.databaseToScreen(nextCtr); Point cNextArrow1 = wnd.databaseToScreen(nextArrow1); Point cNextArrow2 = wnd.databaseToScreen(nextArrow2); drawLine(g, wnd, cNextCtr.x, cNextCtr.y, cNextArrow1.x, cNextArrow1.y); drawLine(g, wnd, cNextCtr.x, cNextCtr.y, cNextArrow2.x, cNextArrow2.y); } } } offX = offY = 0; } } if ((offX == 0 && offY == 0) || point < 0) { Poly niPoly = getNodeInstOutline(ni); boolean niOpened = (niPoly.getStyle() == Poly.Type.OPENED); Point2D [] points = niPoly.getPoints(); drawOutlineFromPoints(wnd, g, points, offX, offY, niOpened, false); } if (pp != null) { Poly poly = ni.getShapeOfPort(pp); boolean opened = true; Point2D [] points = poly.getPoints(); if (poly.getStyle() == Poly.Type.FILLED || poly.getStyle() == Poly.Type.CLOSED) opened = false; if (poly.getStyle() == Poly.Type.CIRCLE || poly.getStyle() == Poly.Type.THICKCIRCLE || poly.getStyle() == Poly.Type.DISC) { double sX = points[0].distance(points[1]) * 2; Point2D [] pts = Artwork.fillEllipse(points[0], sX, sX, 0, 360); poly = new Poly(pts); poly.transform(ni.rotateOut()); points = poly.getPoints(); } else if (poly.getStyle() == Poly.Type.CIRCLEARC) { double [] angles = ni.getArcDegrees(); double sX = points[0].distance(points[1]) * 2; Point2D [] pts = Artwork.fillEllipse(points[0], sX, sX, angles[0], angles[1]); poly = new Poly(pts); poly.transform(ni.rotateOut()); points = poly.getPoints(); } drawOutlineFromPoints(wnd, g, points, offX, offY, opened, false); if (ni.isCellInstance() && (g instanceof Graphics2D)) { boolean wired = false; for(Iterator<Connection> cIt = ni.getConnections(); cIt.hasNext(); ) { Connection con = cIt.next(); if (con.getPortInst().getPortProto() == pp) { wired = true; break; } } if (wired) { Font font = new Font(User.getDefaultFont(), Font.PLAIN, (int)(1.5*EditWindow.getDefaultFontSize())); GlyphVector v = wnd.getGlyphs(pp.getName(), font); Point2D point = wnd.databaseToScreen(poly.getCenterX(), poly.getCenterY()); ((Graphics2D)g).drawGlyphVector(v, (float)point.getX()+offX, (float)point.getY()+offY); } } if (highlightConnected && onlyHighlight) { Netlist netlist = cell.acquireUserNetlist(); if (netlist == null) return; NodeInst originalNI = ni; if (ni.isIconOfParent()) { Export equiv = (Export)cell.findPortProto(pp.getName()); if (equiv != null) { originalPi = equiv.getOriginalPort(); ni = originalPi.getNodeInst(); pp = originalPi.getPortProto(); } } Set<Network> networks = new HashSet<Network>(); networks = NetworkTool.getNetworksOnPort(originalPi, netlist, networks); Set<Geometric> markObj = new HashSet<Geometric>(); for(Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); ) { ArcInst ai = it.next(); Name arcName = ai.getNameKey(); for (int i=0; i<arcName.busWidth(); i++) { if (networks.contains(netlist.getNetwork(ai, i))) { markObj.add(ai); markObj.add(ai.getHeadPortInst().getNodeInst()); markObj.add(ai.getTailPortInst().getNodeInst()); break; } } } for (Iterator<Nodable> it = netlist.getNodables(); it.hasNext(); ) { Nodable no = it.next(); NodeInst oNi = no.getNodeInst(); if (oNi == originalNI) continue; if (markObj.contains(ni)) continue; boolean highlightNo = false; for(Iterator<PortProto> eIt = no.getProto().getPorts(); eIt.hasNext(); ) { PortProto oPp = eIt.next(); Name opName = oPp.getNameKey(); for (int j=0; j<opName.busWidth(); j++) { if (networks.contains(netlist.getNetwork(no, oPp, j))) { highlightNo = true; break; } } if (highlightNo) break; } if (highlightNo) markObj.add(oNi); } Stroke origStroke = g2.getStroke(); g2.setStroke(dashedLine); for(Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); ) { ArcInst ai = it.next(); if (!markObj.contains(ai)) continue; Point c1 = wnd.databaseToScreen(ai.getHeadLocation()); Point c2 = wnd.databaseToScreen(ai.getTailLocation()); drawLine(g, wnd, c1.x, c1.y, c2.x, c2.y); } g2.setStroke(solidLine); for (Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); ) { NodeInst oNi = it.next(); if (!markObj.contains(oNi)) continue; Point c = wnd.databaseToScreen(oNi.getTrueCenter()); g.fillOval(c.x-4, c.y-4, 8, 8); Point2D nodeCenter = oNi.getTrueCenter(); for(Iterator<Connection> pIt = oNi.getConnections(); pIt.hasNext(); ) { Connection con = pIt.next(); ArcInst ai = con.getArc(); if (!markObj.contains(ai)) continue; Point2D arcEnd = con.getLocation(); if (arcEnd.getX() != nodeCenter.getX() || arcEnd.getY() != nodeCenter.getY()) { Point c1 = wnd.databaseToScreen(arcEnd); Point c2 = wnd.databaseToScreen(nodeCenter); drawLine(g, wnd, c1.x, c1.y, c2.x, c2.y); } } } g2.setStroke(origStroke); } } } if (oldColor != null) g.setColor(oldColor); }
public void showInternalHighlight(EditWindow wnd, Graphics g, int highOffX, int highOffY, boolean onlyHighlight, boolean setConnected) { Graphics2D g2 = (Graphics2D)g; highlightConnected = setConnected; if (eobj == null || !eobj.isLinked()) return; Color oldColor = null; if (color != null) { oldColor = g.getColor(); g.setColor(color); } if (eobj instanceof ArcInst) { ArcInst ai = (ArcInst)eobj; try { Poly poly = ai.makeLambdaPoly(ai.getGridBaseWidth(), Poly.Type.CLOSED); if (poly == null) return; drawOutlineFromPoints(wnd, g, poly.getPoints(), highOffX, highOffY, false, false); if (onlyHighlight) { String constraints = "X"; if (ai.isRigid()) constraints = "R"; else { if (ai.isFixedAngle()) { if (ai.isSlidable()) constraints = "FS"; else constraints = "F"; } else if (ai.isSlidable()) constraints = "S"; } Point p = wnd.databaseToScreen(ai.getTrueCenterX(), ai.getTrueCenterY()); Font font = wnd.getFont(null); if (font != null) { GlyphVector gv = wnd.getGlyphs(constraints, font); Rectangle2D glyphBounds = gv.getVisualBounds(); g.drawString(constraints, (int)(p.x - glyphBounds.getWidth()/2 + highOffX), p.y + font.getSize()/2 + highOffY); } } } catch (Error e) { throw e; } return; } PortProto pp = null; ElectricObject realEObj = eobj; PortInst originalPi = null; if (realEObj instanceof PortInst) { originalPi = ((PortInst)realEObj); pp = originalPi.getPortProto(); realEObj = ((PortInst)realEObj).getNodeInst(); } if (realEObj instanceof NodeInst) { NodeInst ni = (NodeInst)realEObj; AffineTransform trans = ni.rotateOutAboutTrueCenter(); int offX = highOffX; int offY = highOffY; if (point >= 0) { Point2D [] points = ni.getTrace(); if (points != null) { if (ni.getProto() == Artwork.tech().splineNode) { Point2D [] changedPoints = new Point2D[points.length]; for(int i=0; i<points.length; i++) { changedPoints[i] = points[i]; if (i == point) { double x = ni.getAnchorCenterX() + points[point].getX(); double y = ni.getAnchorCenterY() + points[point].getY(); Point2D thisPt = new Point2D.Double(x, y); trans.transform(thisPt, thisPt); Point cThis = wnd.databaseToScreen(thisPt); Point2D db = wnd.screenToDatabase(cThis.x+offX, cThis.y+offY); changedPoints[i] = new Point2D.Double(db.getX() - ni.getAnchorCenterX(), db.getY() - ni.getAnchorCenterY()); } } Point2D [] spPoints = Artwork.tech().fillSpline(ni.getAnchorCenterX(), ni.getAnchorCenterY(), changedPoints); Point cLast = wnd.databaseToScreen(spPoints[0]); for(int i=1; i<spPoints.length; i++) { Point cThis = wnd.databaseToScreen(spPoints[i]); drawLine(g, wnd, cLast.x, cLast.y, cThis.x, cThis.y); cLast = cThis; } } if (points[point] != null) { double x = ni.getAnchorCenterX() + points[point].getX(); double y = ni.getAnchorCenterY() + points[point].getY(); Point2D thisPt = new Point2D.Double(x, y); trans.transform(thisPt, thisPt); Point cThis = wnd.databaseToScreen(thisPt); int size = 3; drawLine(g, wnd, cThis.x + size + offX, cThis.y + size + offY, cThis.x - size + offX, cThis.y - size + offY); drawLine(g, wnd, cThis.x + size + offX, cThis.y - size + offY, cThis.x - size + offX, cThis.y + size + offY); boolean showWrap = ni.traceWraps(); Point2D prevPt = null, nextPt = null; int prevPoint = point - 1; if (prevPoint < 0 && showWrap) prevPoint = points.length - 1; if (prevPoint >= 0 && points[prevPoint] != null) { prevPt = new Point2D.Double(ni.getAnchorCenterX() + points[prevPoint].getX(), ni.getAnchorCenterY() + points[prevPoint].getY()); trans.transform(prevPt, prevPt); if (prevPt.getX() == thisPt.getX() && prevPt.getY() == thisPt.getY()) prevPoint = -1; else { Point cPrev = wnd.databaseToScreen(prevPt); drawLine(g, wnd, cThis.x + offX, cThis.y + offY, cPrev.x, cPrev.y); } } int nextPoint = point + 1; if (nextPoint >= points.length) { if (showWrap) nextPoint = 0; else nextPoint = -1; } if (nextPoint >= 0 && points[nextPoint] != null) { nextPt = new Point2D.Double(ni.getAnchorCenterX() + points[nextPoint].getX(), ni.getAnchorCenterY() + points[nextPoint].getY()); trans.transform(nextPt, nextPt); if (nextPt.getX() == thisPt.getX() && nextPt.getY() == thisPt.getY()) nextPoint = -1; else { Point cNext = wnd.databaseToScreen(nextPt); drawLine(g, wnd, cThis.x + offX, cThis.y + offY, cNext.x, cNext.y); } } if (offX == 0 && offY == 0 && points.length > 2 && prevPt != null && nextPt != null) { double arrowLen = Double.MAX_VALUE; if (prevPoint >= 0) arrowLen = Math.min(thisPt.distance(prevPt), arrowLen); if (nextPoint >= 0) arrowLen = Math.min(thisPt.distance(nextPt), arrowLen); arrowLen /= 10; double angleOfArrow = Math.PI * 0.8; if (prevPoint >= 0) { Point2D prevCtr = new Point2D.Double((prevPt.getX()+thisPt.getX()) / 2, (prevPt.getY()+thisPt.getY()) / 2); double prevAngle = DBMath.figureAngleRadians(prevPt, thisPt); Point2D prevArrow1 = new Point2D.Double(prevCtr.getX() + Math.cos(prevAngle+angleOfArrow) * arrowLen, prevCtr.getY() + Math.sin(prevAngle+angleOfArrow) * arrowLen); Point2D prevArrow2 = new Point2D.Double(prevCtr.getX() + Math.cos(prevAngle-angleOfArrow) * arrowLen, prevCtr.getY() + Math.sin(prevAngle-angleOfArrow) * arrowLen); Point cPrevCtr = wnd.databaseToScreen(prevCtr); Point cPrevArrow1 = wnd.databaseToScreen(prevArrow1); Point cPrevArrow2 = wnd.databaseToScreen(prevArrow2); drawLine(g, wnd, cPrevCtr.x, cPrevCtr.y, cPrevArrow1.x, cPrevArrow1.y); drawLine(g, wnd, cPrevCtr.x, cPrevCtr.y, cPrevArrow2.x, cPrevArrow2.y); } if (nextPoint >= 0) { Point2D nextCtr = new Point2D.Double((nextPt.getX()+thisPt.getX()) / 2, (nextPt.getY()+thisPt.getY()) / 2); double nextAngle = DBMath.figureAngleRadians(thisPt, nextPt); Point2D nextArrow1 = new Point2D.Double(nextCtr.getX() + Math.cos(nextAngle+angleOfArrow) * arrowLen, nextCtr.getY() + Math.sin(nextAngle+angleOfArrow) * arrowLen); Point2D nextArrow2 = new Point2D.Double(nextCtr.getX() + Math.cos(nextAngle-angleOfArrow) * arrowLen, nextCtr.getY() + Math.sin(nextAngle-angleOfArrow) * arrowLen); Point cNextCtr = wnd.databaseToScreen(nextCtr); Point cNextArrow1 = wnd.databaseToScreen(nextArrow1); Point cNextArrow2 = wnd.databaseToScreen(nextArrow2); drawLine(g, wnd, cNextCtr.x, cNextCtr.y, cNextArrow1.x, cNextArrow1.y); drawLine(g, wnd, cNextCtr.x, cNextCtr.y, cNextArrow2.x, cNextArrow2.y); } } } offX = offY = 0; } } if ((offX == 0 && offY == 0) || point < 0) { Poly niPoly = getNodeInstOutline(ni); boolean niOpened = (niPoly.getStyle() == Poly.Type.OPENED); Point2D [] points = niPoly.getPoints(); drawOutlineFromPoints(wnd, g, points, offX, offY, niOpened, false); } if (pp != null) { Poly poly = ni.getShapeOfPort(pp); boolean opened = true; Point2D [] points = poly.getPoints(); if (poly.getStyle() == Poly.Type.FILLED || poly.getStyle() == Poly.Type.CLOSED) opened = false; if (poly.getStyle() == Poly.Type.CIRCLE || poly.getStyle() == Poly.Type.THICKCIRCLE || poly.getStyle() == Poly.Type.DISC) { double sX = points[0].distance(points[1]) * 2; Point2D [] pts = Artwork.fillEllipse(points[0], sX, sX, 0, 360); poly = new Poly(pts); poly.transform(ni.rotateOut()); points = poly.getPoints(); } else if (poly.getStyle() == Poly.Type.CIRCLEARC) { double [] angles = ni.getArcDegrees(); double sX = points[0].distance(points[1]) * 2; Point2D [] pts = Artwork.fillEllipse(points[0], sX, sX, angles[0], angles[1]); poly = new Poly(pts); poly.transform(ni.rotateOut()); points = poly.getPoints(); } drawOutlineFromPoints(wnd, g, points, offX, offY, opened, false); if (ni.isCellInstance() && (g instanceof Graphics2D)) { boolean wired = false; for(Iterator<Connection> cIt = ni.getConnections(); cIt.hasNext(); ) { Connection con = cIt.next(); if (con.getPortInst().getPortProto() == pp) { wired = true; break; } } if (wired) { Font font = new Font(User.getDefaultFont(), Font.PLAIN, (int)(1.5*EditWindow.getDefaultFontSize())); GlyphVector v = wnd.getGlyphs(pp.getName(), font); Point2D point = wnd.databaseToScreen(poly.getCenterX(), poly.getCenterY()); ((Graphics2D)g).drawGlyphVector(v, (float)point.getX()+offX, (float)point.getY()+offY); } } if (highlightConnected && onlyHighlight) { Netlist netlist = cell.acquireUserNetlist(); if (netlist == null) return; NodeInst originalNI = ni; if (ni.isIconOfParent()) { Export equiv = (Export)cell.findPortProto(pp.getName()); if (equiv != null) { originalPi = equiv.getOriginalPort(); ni = originalPi.getNodeInst(); pp = originalPi.getPortProto(); } } Set<Network> networks = new HashSet<Network>(); networks = NetworkTool.getNetworksOnPort(originalPi, netlist, networks); Set<Geometric> markObj = new HashSet<Geometric>(); for(Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); ) { ArcInst ai = it.next(); Name arcName = ai.getNameKey(); for (int i=0; i<arcName.busWidth(); i++) { if (networks.contains(netlist.getNetwork(ai, i))) { markObj.add(ai); markObj.add(ai.getHeadPortInst().getNodeInst()); markObj.add(ai.getTailPortInst().getNodeInst()); break; } } } for (Iterator<Nodable> it = netlist.getNodables(); it.hasNext(); ) { Nodable no = it.next(); NodeInst oNi = no.getNodeInst(); if (oNi == originalNI) continue; if (markObj.contains(ni)) continue; boolean highlightNo = false; for(Iterator<PortProto> eIt = no.getProto().getPorts(); eIt.hasNext(); ) { PortProto oPp = eIt.next(); Name opName = oPp.getNameKey(); for (int j=0; j<opName.busWidth(); j++) { if (networks.contains(netlist.getNetwork(no, oPp, j))) { highlightNo = true; break; } } if (highlightNo) break; } if (highlightNo) markObj.add(oNi); } Stroke origStroke = g2.getStroke(); g2.setStroke(dashedLine); for(Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); ) { ArcInst ai = it.next(); if (!markObj.contains(ai)) continue; Point c1 = wnd.databaseToScreen(ai.getHeadLocation()); Point c2 = wnd.databaseToScreen(ai.getTailLocation()); drawLine(g, wnd, c1.x, c1.y, c2.x, c2.y); } g2.setStroke(solidLine); for (Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); ) { NodeInst oNi = it.next(); if (!markObj.contains(oNi)) continue; Point c = wnd.databaseToScreen(oNi.getTrueCenter()); g.fillOval(c.x-4, c.y-4, 8, 8); Point2D nodeCenter = oNi.getTrueCenter(); for(Iterator<Connection> pIt = oNi.getConnections(); pIt.hasNext(); ) { Connection con = pIt.next(); ArcInst ai = con.getArc(); if (!markObj.contains(ai)) continue; Point2D arcEnd = con.getLocation(); if (arcEnd.getX() != nodeCenter.getX() || arcEnd.getY() != nodeCenter.getY()) { Point c1 = wnd.databaseToScreen(arcEnd); Point c2 = wnd.databaseToScreen(nodeCenter); drawLine(g, wnd, c1.x, c1.y, c2.x, c2.y); } } } g2.setStroke(origStroke); } } } if (oldColor != null) g.setColor(oldColor); }
public static void setContextParams(HttpServletRequest request, HttpSession httpSession, XFormsProcessor processor, String sessionkey) { Map servletMap = new HashMap(); servletMap.put(WebProcessor.SESSION_ID, sessionkey); processor.setContextParam(XFormsProcessor.SUBMISSION_RESPONSE, servletMap); processor.setContextParam(WebProcessor.REQUEST_URI, WebUtil.getRequestURI(request)); String requestURL = request.getRequestURL().toString(); processor.setContextParam(WebProcessor.REQUEST_URL, requestURL); String contextRoot = WebUtil.getContextRoot(request); processor.setContextParam(WebProcessor.CONTEXTROOT, contextRoot); if (LOGGER.isDebugEnabled()) { LOGGER.debug("context root of webapp: " + processor.getContextParam(WebProcessor.CONTEXTROOT)); } String requestPath = ""; try { URL url = new URL(requestURL); requestPath = url.getPath(); } catch (MalformedURLException e) { e.printStackTrace(); } if(requestPath.length() != 0){ processor.setContextParam(WebProcessor.REQUEST_PATH, requestPath); String fileName = requestPath.substring(requestPath.lastIndexOf('/')+1,requestPath.length()); processor.setContextParam(FILENAME, fileName); String plainPath = requestPath.substring(contextRoot.length()+1,requestPath.length() - fileName.length()); processor.setContextParam(PLAIN_PATH, plainPath); processor.setContextParam(CONTEXT_PATH,contextRoot+"/"+plainPath); } processor.setContextParam(HTTP_SESSION_ID, httpSession.getId()); String s1=request.getPathInfo(); if(s1!=null){ processor.setContextParam(WebProcessor.PATH_INFO, s1); } processor.setContextParam(WebProcessor.QUERY_STRING, (request.getQueryString() != null ? request.getQueryString() : "")); String realPath = httpSession.getServletContext().getRealPath(""); if (realPath == null) { realPath = httpSession.getServletContext().getRealPath("."); } File f = new File(realPath); URI fileURI = null; fileURI = f.toURI(); processor.setContextParam(WebProcessor.REALPATH, fileURI.toString()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("real path of webapp: " + realPath); } processor.setContextParam(TransformerService.TRANSFORMER_SERVICE, httpSession.getServletContext().getAttribute(TransformerService.class.getName())); if (LOGGER.isDebugEnabled()) { LOGGER.debug("TransformerService: " + httpSession.getServletContext().getAttribute(TransformerService.class.getName())); } Enumeration params = request.getParameterNames(); String s; while (params.hasMoreElements()) { s = (String) params.nextElement(); String value = request.getParameter(s); processor.setContextParam(s, value); if (LOGGER.isDebugEnabled()) { LOGGER.debug("added request param '" + s + "' added to context"); LOGGER.debug("param value'" + value); } } }
public static void setContextParams(HttpServletRequest request, HttpSession httpSession, XFormsProcessor processor, String sessionkey) { Map servletMap = new HashMap(); servletMap.put(WebProcessor.SESSION_ID, sessionkey); processor.setContextParam(XFormsProcessor.SUBMISSION_RESPONSE, servletMap); processor.setContextParam(WebProcessor.REQUEST_URI, WebUtil.getRequestURI(request)); String requestURL = request.getRequestURL().toString(); processor.setContextParam(WebProcessor.REQUEST_URL, requestURL); String contextRoot = WebUtil.getContextRoot(request); processor.setContextParam(WebProcessor.CONTEXTROOT, contextRoot); if (LOGGER.isDebugEnabled()) { LOGGER.debug("context root of webapp: " + processor.getContextParam(WebProcessor.CONTEXTROOT)); } String requestPath = ""; URL url=null; String plainPath =""; try { url = new URL(requestURL); requestPath = url.getPath(); } catch (MalformedURLException e) { e.printStackTrace(); } if(requestPath.length() != 0){ processor.setContextParam(WebProcessor.REQUEST_PATH, requestPath); String fileName = requestPath.substring(requestPath.lastIndexOf('/')+1,requestPath.length()); processor.setContextParam(FILENAME, fileName); if(requestURL.contains(contextRoot)){ plainPath = requestPath.substring(contextRoot.length()+1,requestPath.length() - fileName.length()); processor.setContextParam(PLAIN_PATH, plainPath); } else{ String[] urlParts=requestURL.split("/"); plainPath=urlParts[urlParts.length-2]; } processor.setContextParam(CONTEXT_PATH,contextRoot+"/"+plainPath); } processor.setContextParam(HTTP_SESSION_ID, httpSession.getId()); String s1=request.getPathInfo(); if(s1!=null){ processor.setContextParam(WebProcessor.PATH_INFO, s1); } processor.setContextParam(WebProcessor.QUERY_STRING, (request.getQueryString() != null ? request.getQueryString() : "")); String realPath = httpSession.getServletContext().getRealPath(""); if (realPath == null) { realPath = httpSession.getServletContext().getRealPath("."); } File f = new File(realPath); URI fileURI = null; fileURI = f.toURI(); processor.setContextParam(WebProcessor.REALPATH, fileURI.toString()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("real path of webapp: " + realPath); } processor.setContextParam(TransformerService.TRANSFORMER_SERVICE, httpSession.getServletContext().getAttribute(TransformerService.class.getName())); if (LOGGER.isDebugEnabled()) { LOGGER.debug("TransformerService: " + httpSession.getServletContext().getAttribute(TransformerService.class.getName())); } Enumeration params = request.getParameterNames(); String s; while (params.hasMoreElements()) { s = (String) params.nextElement(); String value = request.getParameter(s); processor.setContextParam(s, value); if (LOGGER.isDebugEnabled()) { LOGGER.debug("added request param '" + s + "' added to context"); LOGGER.debug("param value'" + value); } } }
protected void setUp() throws Exception { final Context context = new IsolatedContext(null, getContext()) { @Override public Object getSystemService(final String pName) { return getContext().getSystemService(pName); } }; final MapTileProviderBasic mTileProvider = new MapTileProviderBasic(context); mOpenStreetMapView = new MapView(context, 256, new DefaultResourceProxyImpl(context), mTileProvider); final Bitmap bitmap = Bitmap.createBitmap(WIDTH, HEIGHT, Config.RGB_565); final Canvas canvas = new Canvas(bitmap); mOpenStreetMapView.onDraw(canvas); super.setUp(); }
protected void setUp() throws Exception { final Context context = new IsolatedContext(null, getContext()) { @Override public Object getSystemService(final String pName) { return getContext().getSystemService(pName); } }; final MapTileProviderBasic mTileProvider = new MapTileProviderBasic(context); mOpenStreetMapView = new MapView(context, 256, new DefaultResourceProxyImpl(context), mTileProvider); final Bitmap bitmap = Bitmap.createBitmap(WIDTH, HEIGHT, Config.RGB_565); final Canvas canvas = new Canvas(bitmap); mOpenStreetMapView.dispatchDraw(canvas); super.setUp(); }
private void initFromReader(Reader reader) { try { StringBuilder sb = new StringBuilder(); BufferedReader in = new BufferedReader(reader); String s = in.readLine(); while (s != null) { if (StringUtils.isNotBlank(s)) { sb.append(s); } sb.append("\n"); s = in.readLine(); } input = sb.toString(); if (StringUtils.isNotBlank(input)) { input = sb.toString().replaceAll("\\r\\n|\\r", "\\n"); } } catch (Exception e) { e.printStackTrace(); } }
private void initFromReader(Reader reader) { try { StringBuilder sb = new StringBuilder(); BufferedReader in = new BufferedReader(reader); String s = in.readLine(); while (s != null) { if (StringUtils.isNotBlank(s)) { sb.append(s); } sb.append("\n"); s = in.readLine(); } input = sb.toString(); if (StringUtils.isNotBlank(input)) { input = sb.toString().replaceAll("\\r\\n|\\r", "\\n"); } in.close(); reader.close(); } catch (Exception e) { e.printStackTrace(); } }
public static List<VariantInfo> getVariants(Class<?> sourceClass, Variant targetVariant) { List<VariantInfo> result = null; List<VariantInfo> helperVariants = null; for (ConverterHelper ch : Engine.getInstance() .getRegisteredConverters()) { helperVariants = ch.getVariants(sourceClass); if (helperVariants != null) { for (VariantInfo helperVariant : helperVariants) { if (helperVariant.includes(targetVariant)) { if (result == null) { result = new ArrayList<VariantInfo>(); } result .add(new VariantInfo(targetVariant .getMediaType())); } else if (targetVariant.includes(helperVariant)) { if (result == null) { result = new ArrayList<VariantInfo>(); } result.add(helperVariant); } } } } return result; }
public static List<VariantInfo> getVariants(Class<?> sourceClass, Variant targetVariant) { List<VariantInfo> result = null; List<VariantInfo> helperVariants = null; for (ConverterHelper ch : Engine.getInstance() .getRegisteredConverters()) { helperVariants = ch.getVariants(sourceClass); if (helperVariants != null) { for (VariantInfo helperVariant : helperVariants) { if (helperVariant.includes(targetVariant)) { if (result == null) { result = new ArrayList<VariantInfo>(); } result .add(new VariantInfo(targetVariant .getMediaType())); } else if (targetVariant == null || targetVariant.includes(helperVariant)) { if (result == null) { result = new ArrayList<VariantInfo>(); } result.add(helperVariant); } } } } return result; }
protected IStatus runImpl( IProgressMonitor monitor ) throws Exception { IResource resource = ((this.project == null) ? this.model : this.project); this.pvdbFile = getContext().getPreviewVdb(resource); if (this.pvdbFile.exists() && !this.pvdbFile.getLocation().toFile().exists()) { this.pvdbFile.delete(true, monitor); } if (!this.pvdbFile.exists()) { this.pvdbFile.create(new ByteArrayInputStream(new byte[0]), false, null); } this.pvdbFile.setHidden(true); try { Vdb pvdb = new Vdb(this.pvdbFile, true, monitor); if (resource instanceof IFile) { if (pvdb.getModelEntries().isEmpty()) { pvdb.addModelEntry(this.model.getFullPath(), monitor); } } if (pvdb.isModified()) { pvdb.save(monitor); } } catch (Exception e) { IPath path = ((this.project == null) ? this.model.getFullPath() : this.project.getFullPath()); throw new CoreException(new Status(IStatus.ERROR, PLUGIN_ID, NLS.bind(Messages.CreatePreviewVdbJobError, path), e)); } return new Status(IStatus.OK, PLUGIN_ID, NLS.bind(Messages.CreatePreviewVdbJobSuccessfullyCompleted, this.pvdbFile.getFullPath())); }
protected IStatus runImpl( IProgressMonitor monitor ) throws Exception { IResource resource = ((this.project == null) ? this.model : this.project); this.pvdbFile = getContext().getPreviewVdb(resource); if (this.pvdbFile.exists() && !this.pvdbFile.getLocation().toFile().exists()) { this.pvdbFile.delete(true, monitor); } boolean isNew = false; if (!this.pvdbFile.exists()) { isNew = true; this.pvdbFile.create(new ByteArrayInputStream(new byte[0]), false, null); } this.pvdbFile.setHidden(true); try { Vdb pvdb = new Vdb(this.pvdbFile, true, monitor); if (resource instanceof IFile) { if (pvdb.getModelEntries().isEmpty()) { pvdb.addModelEntry(this.model.getFullPath(), monitor); } } if (isNew || pvdb.isModified()) { pvdb.save(monitor); } } catch (Exception e) { IPath path = ((this.project == null) ? this.model.getFullPath() : this.project.getFullPath()); throw new CoreException(new Status(IStatus.ERROR, PLUGIN_ID, NLS.bind(Messages.CreatePreviewVdbJobError, path), e)); } return new Status(IStatus.OK, PLUGIN_ID, NLS.bind(Messages.CreatePreviewVdbJobSuccessfullyCompleted, this.pvdbFile.getFullPath())); }
public static File createEmptyWritableFile(String path) throws IOException { File out = new File(path); if (out.exists()) { if (!out.isFile()) { throw new IOException(path + " is not a file"); } if (!out.delete()) { throw new IOException("Unable to delete existing file: "+path); } } File parent = new File(out.getParent()); if (!parent.exists()) { parent.mkdirs(); } out.createNewFile(); if (!out.canWrite()) { throw new IOException("Cannot write to file " + path); } return out; }
public static File createEmptyWritableFile(String path) throws IOException { File out = new File(path); if (out.exists()) { if (!out.isFile()) { throw new IOException(path + " is not a file"); } if (!out.delete()) { throw new IOException("Unable to delete existing file: "+path); } } File parent = out.getParentFile(); if (parent != null && !parent.exists()) { parent.mkdirs(); } out.createNewFile(); if (!out.canWrite()) { throw new IOException("Cannot write to file " + path); } return out; }
public void testManualExternalization() throws IOException { MylarUsageMonitorPlugin.getPrefs().setValue(MylarMonitorPreferenceConstants.PREF_MONITORING_OBFUSCATE, false); List<InteractionEvent> events = new ArrayList<InteractionEvent>(); File f = new File(PATH); if (f.exists()) { f.delete(); } InteractionEventLogger logger = new InteractionEventLogger(f); logger.clearInteractionHistory(); logger.startMonitoring(); String handle = ""; for (int i = 0; i < 100; i++) { handle += "1"; InteractionEvent event = new InteractionEvent(InteractionEvent.Kind.SELECTION, "structureKind", handle, "originId", "navigatedRelation", "delta", 2f, new Date(), new Date()); events.add(event); logger.interactionObserved(event); } logger.stopMonitoring(); File infile = new File(PATH); List<InteractionEvent> readEvents = logger.getHistoryFromFile(infile); for (int i = 0; i < events.size(); i++) { assertEquals(events.get(i), readEvents.get(i)); } MylarUsageMonitorPlugin.getPrefs().setValue(MylarMonitorPreferenceConstants.PREF_MONITORING_OBFUSCATE, true); }
public void testManualExternalization() throws IOException { MylarUsageMonitorPlugin.getPrefs().setValue(MylarMonitorPreferenceConstants.PREF_MONITORING_OBFUSCATE, false); List<InteractionEvent> events = new ArrayList<InteractionEvent>(); File f = new File(PATH); if (f.exists()) { f.delete(); } InteractionEventLogger logger = new InteractionEventLogger(f); logger.clearInteractionHistory(); logger.startMonitoring(); String handle = ""; for (int i = 0; i < 100; i++) { handle += "1"; InteractionEvent event = new InteractionEvent(InteractionEvent.Kind.SELECTION, "structureKind", handle, "originId", "navigatedRelation", "delta", 2f, new Date(), new Date()); events.add(event); logger.interactionObserved(event); } logger.stopMonitoring(); File infile = new File(PATH); List<InteractionEvent> readEvents = logger.getHistoryFromFile(infile); for (int i = 0; i < events.size(); i++) { assertEquals(events.get(i), readEvents.get(i)); } infile.delete(); MylarUsageMonitorPlugin.getPrefs().setValue(MylarMonitorPreferenceConstants.PREF_MONITORING_OBFUSCATE, true); }
void accept(Environment env) throws TemplateException, IOException { for (int i = 0; i<nestedElements.size(); i++) { ConditionalBlock cblock = (ConditionalBlock) nestedElements.get(i); Expression condition = cblock.condition; env.replaceElemetStackTop(cblock); if (condition == null || condition.evalToBoolean(env)) { if (cblock.nestedBlock != null) { env.visit(cblock.nestedBlock); } return; } } }
void accept(Environment env) throws TemplateException, IOException { for (int i = 0; i<nestedElements.size(); i++) { ConditionalBlock cblock = (ConditionalBlock) nestedElements.get(i); Expression condition = cblock.condition; env.replaceElemetStackTop(cblock); if (condition == null || condition.evalToBoolean(env)) { if (cblock.nestedBlock != null) { env.visitByHiddingParent(cblock.nestedBlock); } return; } } }
public void call(Handler handler, HttpServletRequest request, HttpServletResponse response, Object target, ResourceDefinition rp) throws SDataException { SDataFunctionUtil.checkMethod(request.getMethod(), "POST"); GroupAwareEdit baseEdit = editEntity(handler, target, rp.getRepositoryPath()); ResourcePropertiesEdit baseProperties = baseEdit.getPropertiesEdit(); String[] items = request.getParameterValues(ITEM); String[] names = request.getParameterValues(NAME); String[] values = request.getParameterValues(VALUE); String[] actions = request.getParameterValues(ACTION); if (names == null || values == null || actions == null || names.length != values.length || names.length != actions.length) { throw new SDataException(HttpServletResponse.SC_BAD_REQUEST, "Request must contain the same number of name, value, and action parameters "); } GroupAwareEdit[] edit = new GroupAwareEdit[names.length]; boolean committed = false; try { ResourcePropertiesEdit[] properties = new ResourcePropertiesEdit[names.length]; for ( int i = 0; i < names.length; i++ ) { edit[i] = baseEdit; properties[i] = baseProperties; } if ( items != null ) { String repositoryPath = rp.getRepositoryPath(); if (!repositoryPath.endsWith("/")) { repositoryPath = repositoryPath + "/"; } for ( int i = 0; i < items.length; i++ ) { if ( items[i].length() > 0 ) { String p = repositoryPath+items[i]; edit[i] = editEntity(handler, null, p); properties[i] = edit[i].getPropertiesEdit(); } } } for (int i = 0; i < names.length; i++) { if ( log.isDebugEnabled() ) { log.debug("Property ref=["+edit[i].getId()+"] prop=["+names[i]+"] value=["+values[i]+"] action=["+actions[i]+"]"); } if (ADD.equals(actions[i])) { List<?> p = properties[i].getPropertyList(names[i]); if (p == null || p.size() == 0) { properties[i].addProperty(names[i], values[i]); } else if (p.size() == 1) { String value = properties[i].getProperty(names[i]); properties[i].removeProperty(names[i]); properties[i].addPropertyToList(names[i], value); properties[i].addPropertyToList(names[i], values[i]); } else { properties[i].addPropertyToList(names[i], values[i]); } } else if (REMOVE.equals(actions[i])) { properties[i].removeProperty(names[i]); } else if (REPLACE.equals(actions[i])) { properties[i].removeProperty(names[i]); properties[i].addProperty(names[i], values[i]); } } Map<GroupAwareEdit , GroupAwareEdit> committedEdit = new HashMap<GroupAwareEdit, GroupAwareEdit>(); for ( int i = 0; i < edit.length; i++) { log.info("Comitting "+edit[i].getId()); if (!committedEdit.containsKey(edit[i]) ) { commitEntity(edit[i]); committedEdit.put(edit[i], edit[i]); } } committed = true; }finally { if ( !committed ) { for ( int i = 0; i < edit.length; i++) { cancelEntity(edit[i]); } } } CHSNodeMap nm = new CHSNodeMap((ContentEntity) baseEdit, rp.getDepth(), rp); try { handler.sendMap(request, response, nm); } catch (IOException e) { throw new SDataException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "IO Error " + e.getMessage()); } }
public void call(Handler handler, HttpServletRequest request, HttpServletResponse response, Object target, ResourceDefinition rp) throws SDataException { SDataFunctionUtil.checkMethod(request.getMethod(), "POST"); GroupAwareEdit baseEdit = editEntity(handler, target, rp.getRepositoryPath()); ResourcePropertiesEdit baseProperties = baseEdit.getPropertiesEdit(); String[] items = request.getParameterValues(ITEM); String[] names = request.getParameterValues(NAME); String[] values = request.getParameterValues(VALUE); String[] actions = request.getParameterValues(ACTION); if (names == null || values == null || actions == null || names.length != values.length || names.length != actions.length) { throw new SDataException(HttpServletResponse.SC_BAD_REQUEST, "Request must contain the same number of name, value, and action parameters "); } GroupAwareEdit[] edit = new GroupAwareEdit[names.length]; boolean committed = false; try { ResourcePropertiesEdit[] properties = new ResourcePropertiesEdit[names.length]; for ( int i = 0; i < names.length; i++ ) { edit[i] = baseEdit; properties[i] = baseProperties; } if ( items != null ) { Map<String, GroupAwareEdit> edits = new HashMap<String, GroupAwareEdit>(); String repositoryPath = rp.getRepositoryPath(); if (!repositoryPath.endsWith("/")) { repositoryPath = repositoryPath + "/"; } for ( int i = 0; i < items.length; i++ ) { if ( items[i].length() > 0 ) { String p = repositoryPath+items[i]; edit[i] = edits.get(p); if ( edit[i] == null ) { edit[i] = editEntity(handler, null, p); edits.put(p, edit[i]); } properties[i] = edit[i].getPropertiesEdit(); } } } for (int i = 0; i < names.length; i++) { if ( log.isDebugEnabled() ) { log.debug("Property ref=["+edit[i].getId()+"] prop=["+names[i]+"] value=["+values[i]+"] action=["+actions[i]+"]"); } if (ADD.equals(actions[i])) { List<?> p = properties[i].getPropertyList(names[i]); if (p == null || p.size() == 0) { properties[i].addProperty(names[i], values[i]); } else if (p.size() == 1) { String value = properties[i].getProperty(names[i]); properties[i].removeProperty(names[i]); properties[i].addPropertyToList(names[i], value); properties[i].addPropertyToList(names[i], values[i]); } else { properties[i].addPropertyToList(names[i], values[i]); } } else if (REMOVE.equals(actions[i])) { properties[i].removeProperty(names[i]); } else if (REPLACE.equals(actions[i])) { properties[i].removeProperty(names[i]); properties[i].addProperty(names[i], values[i]); } } Map<GroupAwareEdit , GroupAwareEdit> committedEdit = new HashMap<GroupAwareEdit, GroupAwareEdit>(); for ( int i = 0; i < edit.length; i++) { log.info("Comitting "+edit[i].getId()); if (!committedEdit.containsKey(edit[i]) ) { commitEntity(edit[i]); committedEdit.put(edit[i], edit[i]); } } committed = true; }finally { if ( !committed ) { for ( int i = 0; i < edit.length; i++) { cancelEntity(edit[i]); } } cancelEntity(baseEdit); } CHSNodeMap nm = new CHSNodeMap((ContentEntity) baseEdit, rp.getDepth(), rp); try { handler.sendMap(request, response, nm); } catch (IOException e) { throw new SDataException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "IO Error " + e.getMessage()); } }
public void transition(LoaderState desiredState) { LoaderState oldState = state; state = state.transition(!errors.isEmpty()); if (state != desiredState) { Throwable toThrow = null; FMLLog.severe("Fatal errors were detected during the transition from %s to %s. Loading cannot continue", oldState, desiredState); StringBuilder sb = new StringBuilder(); printModStates(sb); FMLLog.severe(sb.toString()); FMLLog.severe("The following problems were captured during this phase"); for (Entry<String, Throwable> error : errors.entries()) { FMLLog.log(Level.SEVERE, error.getValue(), "Caught exception from %s", error.getKey()); if (error.getValue() instanceof IFMLHandledException) { toThrow = error.getValue(); } else if (toThrow == null) { toThrow = error.getValue(); } } if (toThrow != null && toThrow instanceof RuntimeException) { throw (RuntimeException)toThrow; } else { throw new LoaderException(toThrow); } } }
public void transition(LoaderState desiredState) { LoaderState oldState = state; state = state.transition(!errors.isEmpty()); if (state != desiredState) { Throwable toThrow = null; FMLLog.severe("Fatal errors were detected during the transition from %s to %s. Loading cannot continue", oldState, desiredState); StringBuilder sb = new StringBuilder(); printModStates(sb); FMLLog.getLogger().severe(sb.toString()); FMLLog.severe("The following problems were captured during this phase"); for (Entry<String, Throwable> error : errors.entries()) { FMLLog.log(Level.SEVERE, error.getValue(), "Caught exception from %s", error.getKey()); if (error.getValue() instanceof IFMLHandledException) { toThrow = error.getValue(); } else if (toThrow == null) { toThrow = error.getValue(); } } if (toThrow != null && toThrow instanceof RuntimeException) { throw (RuntimeException)toThrow; } else { throw new LoaderException(toThrow); } } }
private CommandExecutor buildCommanService(long sessionId, KnowledgeBase kbase, KnowledgeSessionConfiguration conf, Environment env) { try { Class< ? extends CommandExecutor> serviceClass = getCommandServiceClass(); Constructor< ? extends CommandExecutor> constructor = serviceClass.getConstructor( int.class, KnowledgeBase.class, KnowledgeSessionConfiguration.class, Environment.class ); return constructor.newInstance( sessionId, kbase, conf, env ); } catch ( SecurityException e ) { throw new IllegalStateException( e ); } catch ( NoSuchMethodException e ) { throw new IllegalStateException( e ); } catch ( IllegalArgumentException e ) { throw new IllegalStateException( e ); } catch ( InstantiationException e ) { throw new IllegalStateException( e ); } catch ( IllegalAccessException e ) { throw new IllegalStateException( e ); } catch ( InvocationTargetException e ) { throw new IllegalStateException( e ); } }
private CommandExecutor buildCommanService(long sessionId, KnowledgeBase kbase, KnowledgeSessionConfiguration conf, Environment env) { try { Class< ? extends CommandExecutor> serviceClass = getCommandServiceClass(); Constructor< ? extends CommandExecutor> constructor = serviceClass.getConstructor( long.class, KnowledgeBase.class, KnowledgeSessionConfiguration.class, Environment.class ); return constructor.newInstance( sessionId, kbase, conf, env ); } catch ( SecurityException e ) { throw new IllegalStateException( e ); } catch ( NoSuchMethodException e ) { throw new IllegalStateException( e ); } catch ( IllegalArgumentException e ) { throw new IllegalStateException( e ); } catch ( InstantiationException e ) { throw new IllegalStateException( e ); } catch ( IllegalAccessException e ) { throw new IllegalStateException( e ); } catch ( InvocationTargetException e ) { throw new IllegalStateException( e ); } }
protected InputStream handlePreImport(final String fileName, InputStream inputStream) throws MigrationException { CopyInputStream copyIs = null; try{ final InputStream is = super.handlePreImport(fileName, inputStream); copyIs = new CopyInputStream(is); Resource r = getTmpEMFResource("beforeImport", copyIs.getCopy()); try { r.load(Collections.EMPTY_MAP); } catch (IOException e) { BonitaStudioLog.error(e); } if(!r.getContents().isEmpty()){ final MainProcess diagram = (MainProcess) r.getContents().get(0); if(diagram != null){ String pVersion = diagram.getBonitaVersion(); String mVersion = diagram.getBonitaModelVersion(); if(!ConfigurationIdProvider.getConfigurationIdProvider().isConfigurationIdValid(diagram)){ Display.getDefault().syncExec(new Runnable() { @Override public void run() { BonitaStudioLog.log("Incompatible Version for "+fileName); MessageDialog.openWarning(Display.getDefault().getActiveShell(), Messages.incompatibleVersionTitle, Messages.incompatibleVersionMsg); } }); return null; } if(!ProductVersion.CURRENT_VERSION.equals(pVersion)){ diagram.setBonitaVersion(ProductVersion.CURRENT_VERSION); } if(!ModelVersion.CURRENT_VERSION.equals(mVersion)){ diagram.setBonitaModelVersion(ModelVersion.CURRENT_VERSION); } diagram.setConfigId(ConfigurationIdProvider.getConfigurationIdProvider().getConfigurationId(diagram)); try { r.save(Collections.EMPTY_MAP); } catch (IOException e) { BonitaStudioLog.error(e); } try { return new FileInputStream(new File(r.getURI().toFileString())); } catch (FileNotFoundException e) { BonitaStudioLog.error(e); }finally{ copyIs.close(); try { r.delete(Collections.EMPTY_MAP); } catch (IOException e) { BonitaStudioLog.error(e); } } }else{ return null; } } return copyIs.getCopy(); }catch(IOException e){ BonitaStudioLog.error(e); return null; }finally{ if(copyIs != null){ copyIs.close(); } } }
protected InputStream handlePreImport(final String fileName, InputStream inputStream) throws MigrationException { CopyInputStream copyIs = null; try{ final InputStream is = super.handlePreImport(fileName, inputStream); copyIs = new CopyInputStream(is); Resource r = getTmpEMFResource("beforeImport", copyIs.getCopy()); try { r.load(Collections.EMPTY_MAP); } catch (IOException e) { BonitaStudioLog.error(e); } if(!r.getContents().isEmpty()){ final MainProcess diagram = (MainProcess) r.getContents().get(0); if(diagram != null){ String pVersion = diagram.getBonitaVersion(); String mVersion = diagram.getBonitaModelVersion(); if(!ConfigurationIdProvider.getConfigurationIdProvider().isConfigurationIdValid(diagram)){ Display.getDefault().syncExec(new Runnable() { @Override public void run() { BonitaStudioLog.log("Incompatible Version for "+fileName); MessageDialog.openWarning(Display.getDefault().getActiveShell(), Messages.incompatibleVersionTitle, Messages.incompatibleVersionMsg); } }); return null; } if(!ProductVersion.CURRENT_VERSION.equals(pVersion)){ diagram.setBonitaVersion(ProductVersion.CURRENT_VERSION); } if(!ModelVersion.CURRENT_VERSION.equals(mVersion)){ diagram.setBonitaModelVersion(ModelVersion.CURRENT_VERSION); } diagram.setConfigId(ConfigurationIdProvider.getConfigurationIdProvider().getConfigurationId(diagram)); if(diagram.getAuthor() == null){ diagram.setAuthor(System.getProperty("user.name", "Unknown")); } try { r.save(Collections.EMPTY_MAP); } catch (IOException e) { BonitaStudioLog.error(e); } try { return new FileInputStream(new File(r.getURI().toFileString())); } catch (FileNotFoundException e) { BonitaStudioLog.error(e); }finally{ copyIs.close(); try { r.delete(Collections.EMPTY_MAP); } catch (IOException e) { BonitaStudioLog.error(e); } } }else{ return null; } } return copyIs.getCopy(); }catch(IOException e){ BonitaStudioLog.error(e); return null; }finally{ if(copyIs != null){ copyIs.close(); } } }
public void exec() { if ( cc < 0 ) return; int i, a, b, c, o, n, cb; LValue rkb, rkc, nvarargs, key, val; LValue i0, step, idx, limit, init, table; boolean back, body; LPrototype proto; LClosure newClosure; CallInfo ci = calls[cc]; LClosure cl = ci.closure; LPrototype p = cl.p; int[] code = p.code; LValue[] k = p.k; this.base = ci.base; while (true) { debugAssert( ci == calls[cc] ); ci.top = top; debugHooks( ci.pc ); if ( hooksenabled ) { debugBytecodeHooks( ci.pc ); } i = code[ci.pc++]; o = (i >> POS_OP) & MAX_OP; a = (i >> POS_A) & MAXARG_A; switch (o) { case LuaState.OP_MOVE: { b = LuaState.GETARG_B(i); this.stack[base + a] = this.stack[base + b]; continue; } case LuaState.OP_LOADK: { b = LuaState.GETARG_Bx(i); this.stack[base + a] = k[b]; continue; } case LuaState.OP_LOADBOOL: { b = LuaState.GETARG_B(i); c = LuaState.GETARG_C(i); this.stack[base + a] = (b != 0 ? LBoolean.TRUE : LBoolean.FALSE); if (c != 0) ci.pc++; continue; } case LuaState.OP_LOADNIL: { b = LuaState.GETARG_B(i); do { this.stack[base + b] = LNil.NIL; } while ((--b) >= a); continue; } case LuaState.OP_GETUPVAL: { b = LuaState.GETARG_B(i); this.stack[base + a] = cl.upVals[b].getValue(); continue; } case LuaState.OP_GETGLOBAL: { b = LuaState.GETARG_Bx(i); key = k[b]; table = cl.env; val = this.luaV_gettable(table, key); this.stack[base + a] = val; continue; } case LuaState.OP_GETTABLE: { b = LuaState.GETARG_B(i); key = GETARG_RKC(k, i); table = this.stack[base + b]; val = this.luaV_gettable(table, key); this.stack[base + a] = val; continue; } case LuaState.OP_SETGLOBAL: { b = LuaState.GETARG_Bx(i); key = k[b]; val = this.stack[base + a]; table = cl.env; this.luaV_settable(table, key, val); continue; } case LuaState.OP_SETUPVAL: { b = LuaState.GETARG_B(i); cl.upVals[b].setValue( this.stack[base + a] ); continue; } case LuaState.OP_SETTABLE: { key = GETARG_RKB(k, i); val = GETARG_RKC(k, i); table = this.stack[base + a]; this.luaV_settable(table, key, val); continue; } case LuaState.OP_NEWTABLE: { b = LuaState.GETARG_B(i); c = LuaState.GETARG_C(i); this.stack[base + a] = new LTable(b, c); continue; } case LuaState.OP_SELF: { rkb = stack[base + GETARG_B(i)]; rkc = GETARG_RKC(k, i); val = this.luaV_gettable(rkb, rkc); this.stack[base + a] = val; this.stack[base + a + 1] = rkb; continue; } case LuaState.OP_ADD: case LuaState.OP_SUB: case LuaState.OP_MUL: case LuaState.OP_DIV: case LuaState.OP_MOD: case LuaState.OP_POW: { rkb = GETARG_RKB(k, i); rkc = GETARG_RKC(k, i); this.stack[base + a] = rkc.luaBinOpUnknown(o, rkb); continue; } case LuaState.OP_UNM: { rkb = GETARG_RKB(k, i); this.stack[base + a] = rkb.luaUnaryMinus(); continue; } case LuaState.OP_NOT: { rkb = GETARG_RKB(k, i); this.stack[base + a] = (!rkb.toJavaBoolean() ? LBoolean.TRUE : LBoolean.FALSE); continue; } case LuaState.OP_LEN: { rkb = GETARG_RKB(k, i); this.stack[base + a] = LInteger.valueOf( rkb.luaLength() ); continue; } case LuaState.OP_CONCAT: { b = LuaState.GETARG_B(i); c = LuaState.GETARG_C(i); int numValues = c - b + 1; ByteArrayOutputStream baos = new ByteArrayOutputStream(); for (int j = b, l = 0; j <= c; j++, l++) { this.stack[base + j].luaConcatTo( baos ); } this.stack[base + a] = new LString( baos.toByteArray() ); continue; } case LuaState.OP_JMP: { ci.pc += LuaState.GETARG_sBx(i); continue; } case LuaState.OP_EQ: case LuaState.OP_LT: case LuaState.OP_LE: { rkb = GETARG_RKB(k, i); rkc = GETARG_RKC(k, i); boolean test = rkc.luaBinCmpUnknown(o, rkb); if (test == (a == 0)) ci.pc++; continue; } case LuaState.OP_TEST: { c = LuaState.GETARG_C(i); if (this.stack[base + a].toJavaBoolean() != (c != 0)) ci.pc++; continue; } case LuaState.OP_TESTSET: { rkb = stack[base + GETARG_B(i)]; c = LuaState.GETARG_C(i); if (rkb.toJavaBoolean() != (c != 0)) ci.pc++; else this.stack[base + a] = rkb; continue; } case LuaState.OP_CALL: { this.base += a; b = LuaState.GETARG_B(i); if (b != 0) luaV_settop_fillabove( base + b ); c = LuaState.GETARG_C(i); this.nresults = c - 1; if (this.stack[base].luaStackCall(this)) { if ( hooksenabled ) { debugCallHooks( ); } return; } if (c > 0) luaV_adjusttop(base + c - 1); base = ci.base; if ( hooksenabled ) { debugReturnHooks( ); } continue; } case LuaState.OP_TAILCALL: { if ( hooksenabled ) { debugTailReturnHooks( ); } closeUpVals(base); b = LuaState.GETARG_B(i); if (b != 0) luaV_settop_fillabove( base + a + b ); else b = top - (base + a); System.arraycopy(stack, base + a, stack, ci.resultbase, b); this.base = ci.resultbase; luaV_settop_fillabove( base + b ); this.nresults = ci.nresults; --cc; try { if (this.stack[base].luaStackCall(this)) { if ( hooksenabled ) { debugCallHooks( ); } return; } } catch (LuaErrorException e) { cc++; throw e; } if (ci.nresults >= 0) luaV_adjusttop(base + ci.nresults); return; } case LuaState.OP_RETURN: { if ( hooksenabled ) { debugReturnHooks( ); } closeUpVals( base ); b = LuaState.GETARG_B(i) - 1; if (b >= 0) luaV_settop_fillabove( base + a + b ); else b = top - (base + a); System.arraycopy(stack, base + a, stack, ci.resultbase, b); debugAssert( ci.resultbase + b <= top ); luaV_settop_fillabove( ci.resultbase + b ); if (ci.nresults >= 0) luaV_adjusttop(ci.resultbase + ci.nresults); calls[cc--] = null; return; } case LuaState.OP_FORLOOP: { i0 = this.stack[base + a]; step = this.stack[base + a + 2]; idx = step.luaBinOpUnknown(Lua.OP_ADD, i0); limit = this.stack[base + a + 1]; back = step.luaBinCmpInteger(Lua.OP_LT, 0); body = (back ? idx.luaBinCmpUnknown(Lua.OP_LE, limit) : limit .luaBinCmpUnknown(Lua.OP_LE, idx)); if (body) { this.stack[base + a] = idx; this.stack[base + a + 3] = idx; ci.pc += LuaState.GETARG_sBx(i); } continue; } case LuaState.OP_FORPREP: { init = this.stack[base + a].luaToNumber(); limit = this.stack[base + a + 1].luaToNumber(); step = this.stack[base + a + 2].luaToNumber(); if ( init.isNil() ) error("'for' initial value must be a number"); if ( limit.isNil() ) error("'for' limit must be a number"); if ( step.isNil() ) error("'for' step must be a number"); this.stack[base + a] = step.luaBinOpUnknown(Lua.OP_SUB, init); this.stack[base + a + 1] = limit; this.stack[base + a + 2] = step; b = LuaState.GETARG_sBx(i); ci.pc += b; continue; } case LuaState.OP_TFORLOOP: { cb = base + a + 3; base = cb; System.arraycopy(this.stack, cb-3, this.stack, cb, 3); luaV_settop_fillabove( cb + 3 ); c = LuaState.GETARG_C(i); this.nresults = c; if (this.stack[cb].luaStackCall(this)) execute(); base = ci.base; luaV_adjusttop( cb + c ); if (!this.stack[cb].isNil() ) { this.stack[cb-1] = this.stack[cb]; } else { ci.pc++; } continue; } case LuaState.OP_SETLIST: { b = LuaState.GETARG_B(i); c = LuaState.GETARG_C(i); int listBase = base + a; if (b == 0) { b = top - listBase - 1; } if (c == 0) { c = code[ci.pc++]; } int offset = (c-1) * LFIELDS_PER_FLUSH; LTable tbl = (LTable) this.stack[base + a]; tbl.arrayPresize( offset + b ); for (int j=1; j<=b; j++) { tbl.put(offset+j, stack[listBase + j]); } continue; } case LuaState.OP_CLOSE: { closeUpVals( base + a ); continue; } case LuaState.OP_CLOSURE: { b = LuaState.GETARG_Bx(i); proto = cl.p.p[b]; newClosure = proto.newClosure(cl.env); for (int j = 0; j < newClosure.upVals.length; j++, ci.pc++) { i = code[ci.pc]; o = LuaState.GET_OPCODE(i); b = LuaState.GETARG_B(i); if (o == LuaState.OP_GETUPVAL) { newClosure.upVals[j] = cl.upVals[b]; } else if (o == LuaState.OP_MOVE) { newClosure.upVals[j] = findUpVal( base + b ); } else { throw new java.lang.IllegalArgumentException( "bad opcode: " + o); } } this.stack[base + a] = newClosure; continue; } case LuaState.OP_VARARG: { b = LuaState.GETARG_B(i) - 1; nvarargs = this.stack[base - 1]; n = nvarargs.toJavaInt(); if (b == LuaState.LUA_MULTRET) { b = n; } checkstack(a+b); for (int j = 0; j < b; j++) this.stack[base + a + j] = (j < n ? this.stack[base - n + j - 1] : LNil.NIL); luaV_settop_fillabove( base + a + b ); continue; } } } }
public void exec() { if ( cc < 0 ) return; int i, a, b, c, o, n, cb; LValue rkb, rkc, nvarargs, key, val; LValue i0, step, idx, limit, init, table; boolean back, body; LPrototype proto; LClosure newClosure; CallInfo ci = calls[cc]; LClosure cl = ci.closure; LPrototype p = cl.p; int[] code = p.code; LValue[] k = p.k; this.base = ci.base; while (true) { debugAssert( ci == calls[cc] ); ci.top = top; debugHooks( ci.pc ); if ( hooksenabled ) { debugBytecodeHooks( ci.pc ); } i = code[ci.pc++]; o = (i >> POS_OP) & MAX_OP; a = (i >> POS_A) & MAXARG_A; switch (o) { case LuaState.OP_MOVE: { b = LuaState.GETARG_B(i); this.stack[base + a] = this.stack[base + b]; continue; } case LuaState.OP_LOADK: { b = LuaState.GETARG_Bx(i); this.stack[base + a] = k[b]; continue; } case LuaState.OP_LOADBOOL: { b = LuaState.GETARG_B(i); c = LuaState.GETARG_C(i); this.stack[base + a] = (b != 0 ? LBoolean.TRUE : LBoolean.FALSE); if (c != 0) ci.pc++; continue; } case LuaState.OP_LOADNIL: { b = LuaState.GETARG_B(i); do { this.stack[base + b] = LNil.NIL; } while ((--b) >= a); continue; } case LuaState.OP_GETUPVAL: { b = LuaState.GETARG_B(i); this.stack[base + a] = cl.upVals[b].getValue(); continue; } case LuaState.OP_GETGLOBAL: { b = LuaState.GETARG_Bx(i); key = k[b]; table = cl.env; val = this.luaV_gettable(table, key); this.stack[base + a] = val; continue; } case LuaState.OP_GETTABLE: { b = LuaState.GETARG_B(i); key = GETARG_RKC(k, i); table = this.stack[base + b]; val = this.luaV_gettable(table, key); this.stack[base + a] = val; continue; } case LuaState.OP_SETGLOBAL: { b = LuaState.GETARG_Bx(i); key = k[b]; val = this.stack[base + a]; table = cl.env; this.luaV_settable(table, key, val); continue; } case LuaState.OP_SETUPVAL: { b = LuaState.GETARG_B(i); cl.upVals[b].setValue( this.stack[base + a] ); continue; } case LuaState.OP_SETTABLE: { key = GETARG_RKB(k, i); val = GETARG_RKC(k, i); table = this.stack[base + a]; this.luaV_settable(table, key, val); continue; } case LuaState.OP_NEWTABLE: { b = LuaState.GETARG_B(i); c = LuaState.GETARG_C(i); this.stack[base + a] = new LTable(b, c); continue; } case LuaState.OP_SELF: { rkb = stack[base + GETARG_B(i)]; rkc = GETARG_RKC(k, i); val = this.luaV_gettable(rkb, rkc); this.stack[base + a] = val; this.stack[base + a + 1] = rkb; continue; } case LuaState.OP_ADD: case LuaState.OP_SUB: case LuaState.OP_MUL: case LuaState.OP_DIV: case LuaState.OP_MOD: case LuaState.OP_POW: { rkb = GETARG_RKB(k, i); rkc = GETARG_RKC(k, i); this.stack[base + a] = rkc.luaBinOpUnknown(o, rkb); continue; } case LuaState.OP_UNM: { rkb = GETARG_RKB(k, i); this.stack[base + a] = rkb.luaUnaryMinus(); continue; } case LuaState.OP_NOT: { rkb = GETARG_RKB(k, i); this.stack[base + a] = (!rkb.toJavaBoolean() ? LBoolean.TRUE : LBoolean.FALSE); continue; } case LuaState.OP_LEN: { rkb = GETARG_RKB(k, i); this.stack[base + a] = LInteger.valueOf( rkb.luaLength() ); continue; } case LuaState.OP_CONCAT: { b = LuaState.GETARG_B(i); c = LuaState.GETARG_C(i); int numValues = c - b + 1; ByteArrayOutputStream baos = new ByteArrayOutputStream(); for (int j = b, l = 0; j <= c; j++, l++) { this.stack[base + j].luaConcatTo( baos ); } this.stack[base + a] = new LString( baos.toByteArray() ); continue; } case LuaState.OP_JMP: { ci.pc += LuaState.GETARG_sBx(i); continue; } case LuaState.OP_EQ: case LuaState.OP_LT: case LuaState.OP_LE: { rkb = GETARG_RKB(k, i); rkc = GETARG_RKC(k, i); boolean test = rkc.luaBinCmpUnknown(o, rkb); if (test == (a == 0)) ci.pc++; continue; } case LuaState.OP_TEST: { c = LuaState.GETARG_C(i); if (this.stack[base + a].toJavaBoolean() != (c != 0)) ci.pc++; continue; } case LuaState.OP_TESTSET: { rkb = stack[base + GETARG_B(i)]; c = LuaState.GETARG_C(i); if (rkb.toJavaBoolean() != (c != 0)) ci.pc++; else this.stack[base + a] = rkb; continue; } case LuaState.OP_CALL: { this.base += a; b = LuaState.GETARG_B(i); if (b != 0) luaV_settop_fillabove( base + b ); c = LuaState.GETARG_C(i); this.nresults = c - 1; if (this.stack[base].luaStackCall(this)) { if ( hooksenabled ) { debugCallHooks( ); } return; } if (c > 0) luaV_adjusttop(base + c - 1); base = ci.base; if ( hooksenabled ) { debugReturnHooks( ); } continue; } case LuaState.OP_TAILCALL: { if ( hooksenabled ) { debugTailReturnHooks( ); } closeUpVals(base); b = LuaState.GETARG_B(i); if (b != 0) luaV_settop_fillabove( base + a + b ); else b = top - (base + a); System.arraycopy(stack, base + a, stack, ci.resultbase, b); this.base = ci.resultbase; luaV_settop_fillabove( base + b ); this.nresults = ci.nresults; --cc; try { if (this.stack[base].luaStackCall(this)) { if ( hooksenabled ) { debugCallHooks( ); } return; } } catch (LuaErrorException e) { cc++; throw e; } if (ci.nresults >= 0) luaV_adjusttop(base + ci.nresults); return; } case LuaState.OP_RETURN: { if ( hooksenabled ) { debugReturnHooks( ); } closeUpVals( base ); b = LuaState.GETARG_B(i) - 1; if (b >= 0) luaV_settop_fillabove( base + a + b ); else b = top - (base + a); System.arraycopy(stack, base + a, stack, ci.resultbase, b); debugAssert( ci.resultbase + b <= top ); luaV_settop_fillabove( ci.resultbase + b ); if (ci.nresults >= 0) luaV_adjusttop(ci.resultbase + ci.nresults); calls[cc--] = null; return; } case LuaState.OP_FORLOOP: { i0 = this.stack[base + a]; step = this.stack[base + a + 2]; idx = step.luaBinOpUnknown(Lua.OP_ADD, i0); limit = this.stack[base + a + 1]; back = step.luaBinCmpInteger(Lua.OP_LT, 0); body = (back ? idx.luaBinCmpUnknown(Lua.OP_LE, limit) : limit .luaBinCmpUnknown(Lua.OP_LE, idx)); if (body) { this.stack[base + a] = idx; this.stack[base + a + 3] = idx; ci.pc += LuaState.GETARG_sBx(i); } continue; } case LuaState.OP_FORPREP: { init = this.stack[base + a].luaToNumber(); limit = this.stack[base + a + 1].luaToNumber(); step = this.stack[base + a + 2].luaToNumber(); if ( init.isNil() ) error("'for' initial value must be a number"); if ( limit.isNil() ) error("'for' limit must be a number"); if ( step.isNil() ) error("'for' step must be a number"); this.stack[base + a] = step.luaBinOpUnknown(Lua.OP_SUB, init); this.stack[base + a + 1] = limit; this.stack[base + a + 2] = step; b = LuaState.GETARG_sBx(i); ci.pc += b; continue; } case LuaState.OP_TFORLOOP: { cb = base + a + 3; base = cb; System.arraycopy(this.stack, cb-3, this.stack, cb, 3); luaV_settop_fillabove( cb + 3 ); c = LuaState.GETARG_C(i); this.nresults = c; if (this.stack[cb].luaStackCall(this)) execute(); base = ci.base; luaV_adjusttop( cb + c ); if (!this.stack[cb].isNil() ) { this.stack[cb-1] = this.stack[cb]; } else { ci.pc++; } continue; } case LuaState.OP_SETLIST: { b = LuaState.GETARG_B(i); c = LuaState.GETARG_C(i); int listBase = base + a; if (b == 0) { b = top - listBase - 1; } if (c == 0) { c = code[ci.pc++]; } int offset = (c-1) * LFIELDS_PER_FLUSH; LTable tbl = (LTable) this.stack[base + a]; tbl.arrayPresize( offset + b ); for (int j=1; j<=b; j++) { tbl.put(offset+j, stack[listBase + j]); } continue; } case LuaState.OP_CLOSE: { closeUpVals( base + a ); continue; } case LuaState.OP_CLOSURE: { b = LuaState.GETARG_Bx(i); proto = cl.p.p[b]; newClosure = proto.newClosure(cl.env); for (int j = 0; j < newClosure.upVals.length; j++, ci.pc++) { i = code[ci.pc]; o = LuaState.GET_OPCODE(i); b = LuaState.GETARG_B(i); if (o == LuaState.OP_GETUPVAL) { newClosure.upVals[j] = cl.upVals[b]; } else if (o == LuaState.OP_MOVE) { newClosure.upVals[j] = findUpVal( base + b ); } else { throw new java.lang.IllegalArgumentException( "bad opcode: " + o); } } this.stack[base + a] = newClosure; continue; } case LuaState.OP_VARARG: { b = LuaState.GETARG_B(i) - 1; nvarargs = this.stack[base - 1]; n = nvarargs.toJavaInt(); if (b == LuaState.LUA_MULTRET) { b = n; luaV_settop_fillabove( base + a + b ); } checkstack(a+b); for (int j = 0; j < b; j++) this.stack[base + a + j] = (j < n ? this.stack[base - n + j - 1] : LNil.NIL); continue; } } } }
public BufferedImage parseUserSkin(BufferedImage par1BufferedImage) { if (par1BufferedImage == null) { return null; } else { this.imageWidth = (par1BufferedImage.getWidth((ImageObserver)null) <= 64) ? 64: (par1BufferedImage.getWidth((ImageObserver)null)); this.imageHeight = (par1BufferedImage.getHeight((ImageObserver)null) <= 32) ? 32: (par1BufferedImage.getWidth((ImageObserver)null)); BufferedImage capeImage = new BufferedImage(this.imageWidth, this.imageHeight, 2); Graphics graphics = capeImage.getGraphics(); graphics.drawImage(par1BufferedImage, 0, 0, (ImageObserver)null); graphics.dispose(); return capeImage; } }
public BufferedImage parseUserSkin(BufferedImage par1BufferedImage) { if (par1BufferedImage == null) { return null; } else { this.imageWidth = (par1BufferedImage.getWidth((ImageObserver)null) <= 64) ? 64: (par1BufferedImage.getWidth((ImageObserver)null)); this.imageHeight = (par1BufferedImage.getHeight((ImageObserver)null) <= 32) ? 32: (par1BufferedImage.getHeight((ImageObserver)null)); BufferedImage capeImage = new BufferedImage(this.imageWidth, this.imageHeight, 2); Graphics graphics = capeImage.getGraphics(); graphics.drawImage(par1BufferedImage, 0, 0, (ImageObserver)null); graphics.dispose(); return capeImage; } }
public Day buildDay(CurrentDate today) { Period tp = new Period(); Period tp2 = new Period(); Period lunch = new Period(); Day temp = null; for (Entry<CurrentDate, Day> c : calStorage.entrySet()) { if (c.getKey().equals(today)) { temp = c.getValue(); } } if (temp != null) { int firstPeriod = temp.getD().peek().getNumber(); PriorityQueue<Period> tempQueue = new PriorityQueue<Period>(); int breakStart; for (Period p : temp.getD()) { tempQueue.offer(p); } if (temp.getD().peek().getStartTime() == adjustTime(900, today, 1)) { switch (firstPeriod) { case 1: temp.setDayType('A'); case 2: temp.setDayType('B'); case 3: temp.setDayType('C'); case 4: temp.setDayType('D'); case 5: temp.setDayType('E'); case 6: temp.setDayType('F'); case 7: temp.setDayType('G'); default: break; } tempQueue.poll(); breakStart = tempQueue.poll().getEndTime(); tp.setStartTime(breakStart); tp.setEndTime(breakStart + 60); tp.setNumber(-1); temp.add(tp); lunch.setStartTime(adjustTime(1230, today, 1)); lunch.setEndTime(adjustTime(1330, today, 1)); lunch.setNumber(-7); temp.add(lunch); System.out.println("Wednesday"); return temp; } switch (firstPeriod) { case 1: temp.setDayType('A'); tempQueue.poll(); breakStart = tempQueue.poll().getEndTime(); tp.setStartTime(breakStart); tp.setEndTime(breakStart + 20); tp.setNumber(-1); temp.add(tp); tp2.setStartTime(breakStart + 20); tp2.setEndTime(breakStart + 40); tp2.setNumber(-2); temp.add(tp2); lunch.setStartTime(adjustTime(1205, today, 1)); lunch.setEndTime(adjustTime(1305, today, 1)); lunch.setNumber(-7); temp.add(lunch); break; case 2: temp.setDayType('B'); tempQueue.poll(); breakStart = tempQueue.poll().getEndTime(); tp.setStartTime(breakStart); tp.setEndTime(breakStart + 20); tp.setNumber(-1); temp.add(tp); breakStart = tempQueue.poll().getEndTime(); tp2.setStartTime(breakStart + 5); tp2.setEndTime(breakStart + 65); tp2.setNumber(-5); temp.add(tp2); lunch.setStartTime(adjustTime(1205, today, 1)); lunch.setEndTime(adjustTime(1305, today, 1)); lunch.setNumber(-7); temp.add(lunch); break; case 3: temp.setDayType('C'); tempQueue.poll(); breakStart = tempQueue.poll().getEndTime(); tp.setStartTime(breakStart); tp.setEndTime(breakStart + 20); tp.setNumber(-1); temp.add(tp); tp2.setStartTime(breakStart + 20); tp2.setEndTime(breakStart + 40); tp2.setNumber(-3); temp.add(tp2); lunch.setStartTime(adjustTime(1205, today, 1)); lunch.setEndTime(adjustTime(1305, today, 1)); lunch.setNumber(-7); temp.add(lunch); break; case 4: temp.setDayType('D'); tempQueue.poll(); breakStart = tempQueue.poll().getEndTime(); tp.setStartTime(breakStart); tp.setEndTime(breakStart + 20); tp.setNumber(-1); temp.add(tp); tp2.setStartTime(breakStart + 20); tp2.setEndTime(breakStart + 40); tp2.setNumber(-4); temp.add(tp2); lunch.setStartTime(adjustTime(1205, today, 1)); lunch.setEndTime(adjustTime(1305, today, 1)); lunch.setNumber(-7); temp.add(lunch); break; case 5: temp.setDayType('E'); tempQueue.poll(); breakStart = tempQueue.poll().getEndTime(); tp.setStartTime(breakStart); tp.setEndTime(breakStart + 20); tp.setNumber(-1); temp.add(tp); tp2.setStartTime(breakStart + 20); tp2.setEndTime(breakStart + 40); tp2.setNumber(-2); temp.add(tp2); lunch.setStartTime(adjustTime(1205, today, 1)); lunch.setEndTime(adjustTime(1305, today, 1)); lunch.setNumber(-7); temp.add(lunch); break; case 6: temp.setDayType('F'); tempQueue.poll(); breakStart = tempQueue.poll().getEndTime(); tp.setStartTime(breakStart); tp.setEndTime(breakStart + 20); tp.setNumber(-1); temp.add(tp); tp2.setStartTime(breakStart + 20); tp2.setEndTime(breakStart + 40); tp2.setNumber(-4); temp.add(tp2); lunch.setStartTime(adjustTime(1205, today, 1)); lunch.setEndTime(adjustTime(1305, today, 1)); lunch.setNumber(-7); temp.add(lunch); break; case 7: temp.setDayType('G'); tempQueue.poll(); breakStart = tempQueue.poll().getEndTime(); tp.setStartTime(breakStart); tp.setEndTime(breakStart + 20); tp.setNumber(-1); temp.add(tp); breakStart = tempQueue.poll().getEndTime(); tp2.setStartTime(breakStart + 5); tp2.setEndTime(breakStart + 65); tp2.setNumber(-5); temp.add(tp2); lunch.setStartTime(adjustTime(1205, today, 1)); lunch.setEndTime(adjustTime(1305, today, 1)); lunch.setNumber(-7); temp.add(lunch); break; default: break; } } return temp; }
public Day buildDay(CurrentDate today) { Period tp = new Period(); Period tp2 = new Period(); Period lunch = new Period(); Day temp = null; for (Entry<CurrentDate, Day> c : calStorage.entrySet()) { if (c.getKey().equals(today)) { temp = c.getValue(); } } if (temp != null) { int firstPeriod = temp.getD().peek().getNumber(); PriorityQueue<Period> tempQueue = new PriorityQueue<Period>(); int breakStart; for (Period p : temp.getD()) { tempQueue.offer(p); } if (temp.getD().peek().getStartTime() == adjustTime(900, today, 1)) { switch (firstPeriod) { case 1: temp.setDayType('A'); break; case 2: temp.setDayType('B'); break; case 3: temp.setDayType('C'); break; case 4: temp.setDayType('D'); break; case 5: temp.setDayType('E'); break; case 6: temp.setDayType('F'); break; case 7: temp.setDayType('G'); break; default: break; } tempQueue.poll(); breakStart = tempQueue.poll().getEndTime(); tp.setStartTime(breakStart); tp.setEndTime(breakStart + 60); tp.setNumber(-1); temp.add(tp); lunch.setStartTime(adjustTime(1230, today, 1)); lunch.setEndTime(adjustTime(1330, today, 1)); lunch.setNumber(-7); temp.add(lunch); return temp; } switch (firstPeriod) { case 1: temp.setDayType('A'); tempQueue.poll(); breakStart = tempQueue.poll().getEndTime(); tp.setStartTime(breakStart); tp.setEndTime(breakStart + 20); tp.setNumber(-1); temp.add(tp); tp2.setStartTime(breakStart + 20); tp2.setEndTime(breakStart + 40); tp2.setNumber(-2); temp.add(tp2); lunch.setStartTime(adjustTime(1205, today, 1)); lunch.setEndTime(adjustTime(1305, today, 1)); lunch.setNumber(-7); temp.add(lunch); break; case 2: temp.setDayType('B'); tempQueue.poll(); breakStart = tempQueue.poll().getEndTime(); tp.setStartTime(breakStart); tp.setEndTime(breakStart + 20); tp.setNumber(-1); temp.add(tp); breakStart = tempQueue.poll().getEndTime(); tp2.setStartTime(breakStart + 5); tp2.setEndTime(breakStart + 65); tp2.setNumber(-5); temp.add(tp2); lunch.setStartTime(adjustTime(1205, today, 1)); lunch.setEndTime(adjustTime(1305, today, 1)); lunch.setNumber(-7); temp.add(lunch); break; case 3: temp.setDayType('C'); tempQueue.poll(); breakStart = tempQueue.poll().getEndTime(); tp.setStartTime(breakStart); tp.setEndTime(breakStart + 20); tp.setNumber(-1); temp.add(tp); tp2.setStartTime(breakStart + 20); tp2.setEndTime(breakStart + 40); tp2.setNumber(-3); temp.add(tp2); lunch.setStartTime(adjustTime(1205, today, 1)); lunch.setEndTime(adjustTime(1305, today, 1)); lunch.setNumber(-7); temp.add(lunch); break; case 4: temp.setDayType('D'); tempQueue.poll(); breakStart = tempQueue.poll().getEndTime(); tp.setStartTime(breakStart); tp.setEndTime(breakStart + 20); tp.setNumber(-1); temp.add(tp); tp2.setStartTime(breakStart + 20); tp2.setEndTime(breakStart + 40); tp2.setNumber(-4); temp.add(tp2); lunch.setStartTime(adjustTime(1205, today, 1)); lunch.setEndTime(adjustTime(1305, today, 1)); lunch.setNumber(-7); temp.add(lunch); break; case 5: temp.setDayType('E'); tempQueue.poll(); breakStart = tempQueue.poll().getEndTime(); tp.setStartTime(breakStart); tp.setEndTime(breakStart + 20); tp.setNumber(-1); temp.add(tp); tp2.setStartTime(breakStart + 20); tp2.setEndTime(breakStart + 40); tp2.setNumber(-2); temp.add(tp2); lunch.setStartTime(adjustTime(1205, today, 1)); lunch.setEndTime(adjustTime(1305, today, 1)); lunch.setNumber(-7); temp.add(lunch); break; case 6: temp.setDayType('F'); tempQueue.poll(); breakStart = tempQueue.poll().getEndTime(); tp.setStartTime(breakStart); tp.setEndTime(breakStart + 20); tp.setNumber(-1); temp.add(tp); tp2.setStartTime(breakStart + 20); tp2.setEndTime(breakStart + 40); tp2.setNumber(-4); temp.add(tp2); lunch.setStartTime(adjustTime(1205, today, 1)); lunch.setEndTime(adjustTime(1305, today, 1)); lunch.setNumber(-7); temp.add(lunch); break; case 7: temp.setDayType('G'); tempQueue.poll(); breakStart = tempQueue.poll().getEndTime(); tp.setStartTime(breakStart); tp.setEndTime(breakStart + 20); tp.setNumber(-1); temp.add(tp); breakStart = tempQueue.poll().getEndTime(); tp2.setStartTime(breakStart + 5); tp2.setEndTime(breakStart + 65); tp2.setNumber(-5); temp.add(tp2); lunch.setStartTime(adjustTime(1205, today, 1)); lunch.setEndTime(adjustTime(1305, today, 1)); lunch.setNumber(-7); temp.add(lunch); break; default: break; } } return temp; }
private void createElementsForRowGroup(LayoutContext context, int alignment, int bodyType, LinkedList returnList, EffRow[] rowGroup) { log.debug("Handling row group with " + rowGroup.length + " rows..."); MinOptMax[] rowHeights = new MinOptMax[rowGroup.length]; MinOptMax[] explicitRowHeights = new MinOptMax[rowGroup.length]; EffRow row; int maxColumnCount = 0; List pgus = new java.util.ArrayList(); for (int rgi = 0; rgi < rowGroup.length; rgi++) { row = rowGroup[rgi]; rowHeights[rgi] = new MinOptMax(0, 0, Integer.MAX_VALUE); explicitRowHeights[rgi] = new MinOptMax(0, 0, Integer.MAX_VALUE); pgus.clear(); TableRow tableRow = null; int minContentHeight = 0; int maxCellHeight = 0; for (int j = 0; j < row.getGridUnits().size(); j++) { maxColumnCount = Math.max(maxColumnCount, row.getGridUnits().size()); GridUnit gu = row.getGridUnit(j); if ((gu.isPrimary() || (gu.getColSpanIndex() == 0 && gu.isLastGridUnitRowSpan())) && !gu.isEmpty()) { PrimaryGridUnit primary = gu.getPrimary(); if (gu.isPrimary()) { primary.getCellLM().setParent(tableLM); if (tableRow == null && primary.getRow() != null) { tableRow = primary.getRow(); LengthRangeProperty bpd = tableRow.getBlockProgressionDimension(); if (!bpd.getMinimum().isAuto()) { minContentHeight = Math.max(minContentHeight, bpd.getMinimum().getLength().getValue()); } MinOptMaxUtil.restrict(explicitRowHeights[rgi], bpd); } int spanWidth = 0; for (int i = primary.getStartCol(); i < primary.getStartCol() + primary.getCell().getNumberColumnsSpanned(); i++) { spanWidth += getTableLM().getColumns().getColumn(i + 1) .getColumnWidth().getValue(); } LayoutContext childLC = new LayoutContext(0); childLC.setStackLimit(context.getStackLimit()); childLC.setRefIPD(spanWidth); LinkedList elems = primary.getCellLM().getNextKnuthElements( childLC, alignment); while (!primary.getCellLM().isFinished()) { LinkedList additionalElems = primary.getCellLM().getNextKnuthElements( childLC, alignment); elems.addAll(additionalElems); } ElementListObserver.observe(elems, "table-cell", primary.getCell().getId()); if (((KnuthElement)elems.getLast()).isPenalty() && ((KnuthPenalty)elems.getLast()).getP() == -KnuthElement.INFINITE) { log.warn("Descendant of table-cell signals break: " + primary.getCellLM().isFinished()); } primary.setElements(elems); if (childLC.isKeepWithNextPending()) { log.debug("child LM signals pending keep-with-next"); primary.setFlag(GridUnit.KEEP_WITH_NEXT_PENDING, true); } if (childLC.isKeepWithPreviousPending()) { log.debug("child LM signals pending keep-with-previous"); primary.setFlag(GridUnit.KEEP_WITH_PREVIOUS_PENDING, true); } } primary.setContentLength(ElementListUtils.calcContentLength( primary.getElements())); maxCellHeight = Math.max(maxCellHeight, primary.getContentLength()); if (gu.isLastGridUnitRowSpan()) { int effCellContentHeight = minContentHeight; LengthRangeProperty bpd = primary.getCell().getBlockProgressionDimension(); if (!bpd.getMinimum().isAuto()) { effCellContentHeight = Math.max(effCellContentHeight, bpd.getMinimum().getLength().getValue()); } if (gu.getRowSpanIndex() == 0) { MinOptMaxUtil.restrict(explicitRowHeights[rgi], bpd); } effCellContentHeight = Math.max(effCellContentHeight, primary.getContentLength()); int borderWidths; if (isSeparateBorderModel()) { borderWidths = primary.getBorders().getBorderBeforeWidth(false) + primary.getBorders().getBorderAfterWidth(false); } else { borderWidths = primary.getHalfMaxBorderWidth(); } int padding = 0; CommonBorderPaddingBackground cbpb = primary.getCell().getCommonBorderPaddingBackground(); padding += cbpb.getPaddingBefore(false); padding += cbpb.getPaddingAfter(false); int effRowHeight = effCellContentHeight + padding + borderWidths; for (int previous = 0; previous < gu.getRowSpanIndex(); previous++) { effRowHeight -= rowHeights[rgi - previous - 1].opt; } if (effRowHeight > rowHeights[rgi].min) { MinOptMaxUtil.extendMinimum(rowHeights[rgi], effRowHeight, false); row.setHeight(rowHeights[rgi]); } } if (gu.isPrimary()) { pgus.add(primary); } } } row.setExplicitHeight(explicitRowHeights[rgi]); if (row.getHeight().opt > row.getExplicitHeight().max) { log.warn("Contents of row " + row.getIndex() + " violate a maximum constraint " + "in block-progression-dimension. Due to its contents the row grows " + "to " + row.getHeight().opt + " millipoints. The row constraint resolve " + "to " + row.getExplicitHeight()); } } if (log.isDebugEnabled()) { log.debug("rowGroup:"); for (int i = 0; i < rowHeights.length; i++) { log.debug(" height=" + rowHeights[i] + " explicit=" + explicitRowHeights[i]); } } TableStepper stepper = new TableStepper(this); LinkedList returnedList = stepper.getCombinedKnuthElementsForRowGroup( context, rowGroup, maxColumnCount, bodyType); if (returnedList != null) { returnList.addAll(returnedList); } }
private void createElementsForRowGroup(LayoutContext context, int alignment, int bodyType, LinkedList returnList, EffRow[] rowGroup) { log.debug("Handling row group with " + rowGroup.length + " rows..."); MinOptMax[] rowHeights = new MinOptMax[rowGroup.length]; MinOptMax[] explicitRowHeights = new MinOptMax[rowGroup.length]; EffRow row; int maxColumnCount = 0; List pgus = new java.util.ArrayList(); for (int rgi = 0; rgi < rowGroup.length; rgi++) { row = rowGroup[rgi]; rowHeights[rgi] = new MinOptMax(0, 0, Integer.MAX_VALUE); explicitRowHeights[rgi] = new MinOptMax(0, 0, Integer.MAX_VALUE); pgus.clear(); TableRow tableRow = null; int minContentHeight = 0; int maxCellHeight = 0; for (int j = 0; j < row.getGridUnits().size(); j++) { maxColumnCount = Math.max(maxColumnCount, row.getGridUnits().size()); GridUnit gu = row.getGridUnit(j); if ((gu.isPrimary() || (gu.getColSpanIndex() == 0 && gu.isLastGridUnitRowSpan())) && !gu.isEmpty()) { PrimaryGridUnit primary = gu.getPrimary(); if (gu.isPrimary()) { primary.getCellLM().setParent(tableLM); if (tableRow == null && primary.getRow() != null) { tableRow = primary.getRow(); LengthRangeProperty bpd = tableRow.getBlockProgressionDimension(); if (!bpd.getMinimum().isAuto()) { minContentHeight = Math.max(minContentHeight, bpd.getMinimum().getLength().getValue()); } MinOptMaxUtil.restrict(explicitRowHeights[rgi], bpd); } int spanWidth = 0; for (int i = primary.getStartCol(); i < primary.getStartCol() + primary.getCell().getNumberColumnsSpanned(); i++) { spanWidth += getTableLM().getColumns().getColumn(i + 1) .getColumnWidth().getValue(); } LayoutContext childLC = new LayoutContext(0); childLC.setStackLimit(context.getStackLimit()); childLC.setRefIPD(spanWidth); LinkedList elems = primary.getCellLM().getNextKnuthElements( childLC, alignment); while (!primary.getCellLM().isFinished()) { LinkedList additionalElems = primary.getCellLM().getNextKnuthElements( childLC, alignment); elems.addAll(additionalElems); } ElementListObserver.observe(elems, "table-cell", primary.getCell().getId()); if ((elems.size() > 0) && ((KnuthElement)elems.getLast()).isPenalty() && ((KnuthPenalty)elems.getLast()).getP() == -KnuthElement.INFINITE) { log.warn("Descendant of table-cell signals break: " + primary.getCellLM().isFinished()); } primary.setElements(elems); if (childLC.isKeepWithNextPending()) { log.debug("child LM signals pending keep-with-next"); primary.setFlag(GridUnit.KEEP_WITH_NEXT_PENDING, true); } if (childLC.isKeepWithPreviousPending()) { log.debug("child LM signals pending keep-with-previous"); primary.setFlag(GridUnit.KEEP_WITH_PREVIOUS_PENDING, true); } } primary.setContentLength(ElementListUtils.calcContentLength( primary.getElements())); maxCellHeight = Math.max(maxCellHeight, primary.getContentLength()); if (gu.isLastGridUnitRowSpan()) { int effCellContentHeight = minContentHeight; LengthRangeProperty bpd = primary.getCell().getBlockProgressionDimension(); if (!bpd.getMinimum().isAuto()) { effCellContentHeight = Math.max(effCellContentHeight, bpd.getMinimum().getLength().getValue()); } if (gu.getRowSpanIndex() == 0) { MinOptMaxUtil.restrict(explicitRowHeights[rgi], bpd); } effCellContentHeight = Math.max(effCellContentHeight, primary.getContentLength()); int borderWidths; if (isSeparateBorderModel()) { borderWidths = primary.getBorders().getBorderBeforeWidth(false) + primary.getBorders().getBorderAfterWidth(false); } else { borderWidths = primary.getHalfMaxBorderWidth(); } int padding = 0; CommonBorderPaddingBackground cbpb = primary.getCell().getCommonBorderPaddingBackground(); padding += cbpb.getPaddingBefore(false); padding += cbpb.getPaddingAfter(false); int effRowHeight = effCellContentHeight + padding + borderWidths; for (int previous = 0; previous < gu.getRowSpanIndex(); previous++) { effRowHeight -= rowHeights[rgi - previous - 1].opt; } if (effRowHeight > rowHeights[rgi].min) { MinOptMaxUtil.extendMinimum(rowHeights[rgi], effRowHeight, false); } } if (gu.isPrimary()) { pgus.add(primary); } } } row.setHeight(rowHeights[rgi]); row.setExplicitHeight(explicitRowHeights[rgi]); if (row.getHeight().opt > row.getExplicitHeight().max) { log.warn("Contents of row " + row.getIndex() + " violate a maximum constraint " + "in block-progression-dimension. Due to its contents the row grows " + "to " + row.getHeight().opt + " millipoints. The row constraint resolve " + "to " + row.getExplicitHeight()); } } if (log.isDebugEnabled()) { log.debug("rowGroup:"); for (int i = 0; i < rowHeights.length; i++) { log.debug(" height=" + rowHeights[i] + " explicit=" + explicitRowHeights[i]); } } TableStepper stepper = new TableStepper(this); LinkedList returnedList = stepper.getCombinedKnuthElementsForRowGroup( context, rowGroup, maxColumnCount, bodyType); if (returnedList != null) { returnList.addAll(returnedList); } }
void readStateFromFileLocked(File file) { FileInputStream stream = null; boolean success = false; try { stream = new FileInputStream(file); XmlPullParser parser = Xml.newPullParser(); parser.setInput(stream, null); int type; int providerIndex = 0; HashMap<Integer,Provider> loadedProviders = new HashMap<Integer, Provider>(); do { type = parser.next(); if (type == XmlPullParser.START_TAG) { String tag = parser.getName(); if ("p".equals(tag)) { String pkg = parser.getAttributeValue(null, "pkg"); String cl = parser.getAttributeValue(null, "cl"); Provider p = lookupProviderLocked(new ComponentName(pkg, cl)); if (p == null && mSafeMode) { p = new Provider(); p.info = new AppWidgetProviderInfo(); p.info.provider = new ComponentName(pkg, cl); p.zombie = true; mInstalledProviders.add(p); } if (p != null) { loadedProviders.put(providerIndex, p); } providerIndex++; } else if ("h".equals(tag)) { Host host = new Host(); host.packageName = parser.getAttributeValue(null, "pkg"); try { host.uid = getUidForPackage(host.packageName); } catch (PackageManager.NameNotFoundException ex) { host.zombie = true; } if (!host.zombie || mSafeMode) { host.hostId = Integer.parseInt( parser.getAttributeValue(null, "id"), 16); mHosts.add(host); } } else if ("g".equals(tag)) { AppWidgetId id = new AppWidgetId(); id.appWidgetId = Integer.parseInt(parser.getAttributeValue(null, "id"), 16); if (id.appWidgetId >= mNextAppWidgetId) { mNextAppWidgetId = id.appWidgetId + 1; } String providerString = parser.getAttributeValue(null, "p"); if (providerString != null) { int pIndex = Integer.parseInt(providerString, 16); id.provider = loadedProviders.get(pIndex); if (false) { Log.d(TAG, "bound appWidgetId=" + id.appWidgetId + " to provider " + pIndex + " which is " + id.provider); } if (id.provider == null) { continue; } } int hIndex = Integer.parseInt(parser.getAttributeValue(null, "h"), 16); id.host = mHosts.get(hIndex); if (id.host == null) { continue; } if (id.provider != null) { id.provider.instances.add(id); } id.host.instances.add(id); mAppWidgetIds.add(id); } } } while (type != XmlPullParser.END_DOCUMENT); success = true; } catch (NullPointerException e) { Log.w(TAG, "failed parsing " + file, e); } catch (NumberFormatException e) { Log.w(TAG, "failed parsing " + file, e); } catch (XmlPullParserException e) { Log.w(TAG, "failed parsing " + file, e); } catch (IOException e) { Log.w(TAG, "failed parsing " + file, e); } catch (IndexOutOfBoundsException e) { Log.w(TAG, "failed parsing " + file, e); } try { if (stream != null) { stream.close(); } } catch (IOException e) { } if (success) { final int N = mHosts.size(); for (int i=0; i<N; i++) { pruneHostLocked(mHosts.get(i)); } } else { mAppWidgetIds.clear(); mHosts.clear(); final int N = mInstalledProviders.size(); for (int i=0; i<N; i++) { mInstalledProviders.get(i).instances.clear(); } } }
void readStateFromFileLocked(File file) { FileInputStream stream = null; boolean success = false; try { stream = new FileInputStream(file); XmlPullParser parser = Xml.newPullParser(); parser.setInput(stream, null); int type; int providerIndex = 0; HashMap<Integer,Provider> loadedProviders = new HashMap<Integer, Provider>(); do { type = parser.next(); if (type == XmlPullParser.START_TAG) { String tag = parser.getName(); if ("p".equals(tag)) { String pkg = parser.getAttributeValue(null, "pkg"); String cl = parser.getAttributeValue(null, "cl"); Provider p = lookupProviderLocked(new ComponentName(pkg, cl)); if (p == null && mSafeMode) { p = new Provider(); p.info = new AppWidgetProviderInfo(); p.info.provider = new ComponentName(pkg, cl); p.zombie = true; mInstalledProviders.add(p); } if (p != null) { loadedProviders.put(providerIndex, p); } providerIndex++; } else if ("h".equals(tag)) { Host host = new Host(); host.packageName = parser.getAttributeValue(null, "pkg"); try { host.uid = getUidForPackage(host.packageName); } catch (PackageManager.NameNotFoundException ex) { host.zombie = true; } if (!host.zombie || mSafeMode) { host.hostId = Integer.parseInt( parser.getAttributeValue(null, "id"), 16); mHosts.add(host); } } else if ("g".equals(tag)) { AppWidgetId id = new AppWidgetId(); id.appWidgetId = Integer.parseInt(parser.getAttributeValue(null, "id"), 16); if (id.appWidgetId >= mNextAppWidgetId) { mNextAppWidgetId = id.appWidgetId + 1; } String providerString = parser.getAttributeValue(null, "p"); if (providerString != null) { int pIndex = Integer.parseInt(providerString, 16); id.provider = loadedProviders.get(pIndex); if (false) { Log.d(TAG, "bound appWidgetId=" + id.appWidgetId + " to provider " + pIndex + " which is " + id.provider); } if (id.provider == null) { continue; } } int hIndex = Integer.parseInt(parser.getAttributeValue(null, "h"), 16); id.host = mHosts.get(hIndex); if (id.host == null) { continue; } if (id.provider != null) { id.provider.instances.add(id); } id.host.instances.add(id); mAppWidgetIds.add(id); } } } while (type != XmlPullParser.END_DOCUMENT); success = true; } catch (NullPointerException e) { Log.w(TAG, "failed parsing " + file, e); } catch (NumberFormatException e) { Log.w(TAG, "failed parsing " + file, e); } catch (XmlPullParserException e) { Log.w(TAG, "failed parsing " + file, e); } catch (IOException e) { Log.w(TAG, "failed parsing " + file, e); } catch (IndexOutOfBoundsException e) { Log.w(TAG, "failed parsing " + file, e); } try { if (stream != null) { stream.close(); } } catch (IOException e) { } if (success) { for (int i=mHosts.size()-1; i>=0; i--) { pruneHostLocked(mHosts.get(i)); } } else { mAppWidgetIds.clear(); mHosts.clear(); final int N = mInstalledProviders.size(); for (int i=0; i<N; i++) { mInstalledProviders.get(i).instances.clear(); } } }
public Player(String name) { m_name = name; m_bank = 0; m_hand = new ArrayList<Card>(); }
public Player(String name) { m_name = name; m_bank = 0; m_hand = new ArrayList<Card>(); }
void appendAccess (final int access) { boolean first = true; if ((access & Constants.ACC_PUBLIC) != 0) { buf.append("ACC_PUBLIC"); first = false; } if ((access & Constants.ACC_PRIVATE) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_PRIVATE"); first = false; } if ((access & Constants.ACC_PROTECTED) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_PROTECTED"); first = false; } if ((access & Constants.ACC_FINAL) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_FINAL"); first = false; } if ((access & Constants.ACC_STATIC) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_STATIC"); first = false; } if ((access & Constants.ACC_SYNCHRONIZED) != 0) { if (!first) { buf.append(" + "); } if ((access & 262144) != 0) { buf.append("ACC_SUPER"); } else { buf.append("ACC_SYNCHRONIZED"); } first = false; } if ((access & Constants.ACC_VOLATILE) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_VOLATILE"); first = false; } if ((access & Constants.ACC_TRANSIENT) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_TRANSIENT"); first = false; } if ((access & Constants.ACC_NATIVE) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_NATIVE"); first = false; } if ((access & Constants.ACC_ABSTRACT) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_ABSTRACT"); first = false; } if ((access & Constants.ACC_STRICT) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_STRICT"); first = false; } if ((access & Constants.ACC_STRICT) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_STRICT"); first = false; } if ((access & Constants.ACC_INTERFACE) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_INTERFACE"); first = false; } if ((access & Constants.ACC_DEPRECATED) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_DEPRECATED"); first = false; } if (first) { buf.append("0"); } }
void appendAccess (final int access) { boolean first = true; if ((access & Constants.ACC_PUBLIC) != 0) { buf.append("ACC_PUBLIC"); first = false; } if ((access & Constants.ACC_PRIVATE) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_PRIVATE"); first = false; } if ((access & Constants.ACC_PROTECTED) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_PROTECTED"); first = false; } if ((access & Constants.ACC_FINAL) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_FINAL"); first = false; } if ((access & Constants.ACC_STATIC) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_STATIC"); first = false; } if ((access & Constants.ACC_SYNCHRONIZED) != 0) { if (!first) { buf.append(" + "); } if ((access & 262144) != 0) { buf.append("ACC_SUPER"); } else { buf.append("ACC_SYNCHRONIZED"); } first = false; } if ((access & Constants.ACC_VOLATILE) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_VOLATILE"); first = false; } if ((access & Constants.ACC_TRANSIENT) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_TRANSIENT"); first = false; } if ((access & Constants.ACC_NATIVE) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_NATIVE"); first = false; } if ((access & Constants.ACC_ABSTRACT) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_ABSTRACT"); first = false; } if ((access & Constants.ACC_INTERFACE) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_INTERFACE"); first = false; } if ((access & Constants.ACC_STRICT) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_STRICT"); first = false; } if ((access & Constants.ACC_SYNTHETIC) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_SYNTHETIC"); first = false; } if ((access & Constants.ACC_DEPRECATED) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_DEPRECATED"); first = false; } if (first) { buf.append("0"); } }
public void onPlayerInteract(PlayerInteractEvent event) { if (event.isCancelled()) return; Player player = event.getPlayer(); String playerName = player.getName(); if (!plugin.getPlayerData().containsKey(playerName)) { plugin.getPlayerData().put(playerName, new PlayerData(plugin, playerName)); } if (plugin.getPlayerData().get(playerName).isSelecting() && player.getItemInHand().getType() == Material.AIR && event.getClickedBlock().getType() == Material.WOODEN_DOOR) { int x, y, z; Location loc = event.getClickedBlock().getLocation(); x = loc.getBlockX(); y = loc.getBlockY(); z = loc.getBlockZ(); ILogger.info(Integer.toString(event.getClickedBlock().getTypeId())); PlayerData pData = plugin.getPlayerData().get(playerName); if (event.getAction() == Action.LEFT_CLICK_BLOCK) { int[] xyz = { x, y, z }; pData.setPositionA(xyz); if(pData.checkSize()) { player.sendMessage(ChatColor.DARK_AQUA + "Door selected"); if(pData.getPositionA() != null && pData.getPositionB() == null) { player.sendMessage(ChatColor.DARK_AQUA + "Now, right click to select the far upper corner for the inn."); } else if(pData.getPositionA() != null) { player.sendMessage(ChatColor.DARK_AQUA + "Type " + ChatColor.WHITE + "/inn create [Price]" + ChatColor.DARK_AQUA + ", if you're happy with your selection, otherwise keep selecting!"); } } } } }
public void onPlayerInteract(PlayerInteractEvent event) { if (event.isCancelled()) return; Player player = event.getPlayer(); String playerName = player.getName(); if (!plugin.getPlayerData().containsKey(playerName)) { plugin.getPlayerData().put(playerName, new PlayerData(plugin, playerName)); } if (plugin.getPlayerData().get(playerName).isSelecting() && player.getItemInHand().getType() == Material.AIR && event.getClickedBlock().getType() == Material.WOODEN_DOOR) { int x, y, z; Location loc = event.getClickedBlock().getLocation(); x = loc.getBlockX(); y = loc.getBlockY(); z = loc.getBlockZ(); PlayerData pData = plugin.getPlayerData().get(playerName); if (event.getAction() == Action.LEFT_CLICK_BLOCK) { int[] xyz = { x, y, z }; pData.setPositionA(xyz); if(pData.checkSize()) { player.sendMessage(ChatColor.DARK_AQUA + "Door selected"); if(pData.getPositionA() != null) { player.sendMessage(ChatColor.DARK_AQUA + "Type " + ChatColor.WHITE + "/inn create [Price]" + ChatColor.DARK_AQUA + ", if you're happy with your selection, otherwise keep selecting!"); } } } } }
public void configure(Properties props) { String staticConfigFile = props.getProperty("static.config.file"); String dynMetadataFile = props.getProperty("dyn.metadata.file"); if (staticConfigFile != null) { try { this.taskConfig.getProperties().load( new FileInputStream(new File(staticConfigFile))); } catch (RuntimeException ex) { throw ex; } catch (Exception ignore) { } } if (dynMetadataFile != null) { InputStream in = null; try { this.dynMetadata = new Metadata(); Properties fileProps = new Properties(); in = new BufferedInputStream(new FileInputStream(new File(dynMetadataFile))); fileProps.load(in); for (String key: fileProps.stringPropertyNames()) this.dynMetadata.addMetadata(key, fileProps.getProperty(key)); } catch (RuntimeException ex) { throw ex; } catch (Exception ignore) { } finally { if (in != null) try { in.close(); } catch (IOException ignore) {} } } }
public void configure(Properties props) { String staticConfigFile = props.getProperty("static.config.file"); String dynMetadataFile = props.getProperty("dyn.metadata.file"); if (staticConfigFile != null) { try { this.taskConfig.getProperties().load( new FileInputStream(new File(staticConfigFile))); } catch (RuntimeException ex) { throw ex; } catch (Exception ignore) { } } if (dynMetadataFile != null) { InputStream in = null; try { this.dynMetadata = new Metadata(); Properties fileProps = new Properties(); in = new BufferedInputStream(new FileInputStream(new File(dynMetadataFile))); fileProps.load(in); for (Object key: fileProps.keySet()){ String keyStr = (String)key; this.dynMetadata.addMetadata(keyStr, fileProps.getProperty(keyStr)); } } catch (RuntimeException ex) { throw ex; } catch (Exception ignore) { } finally { if (in != null) try { in.close(); } catch (IOException ignore) {} } } }
@Override protected Response serve() { int [] cols = _columns.value(); ValueArray ary = _key.value(); final boolean did_trim_columns; final int max_columns_to_display; if (_max_column.value() >= 0) max_columns_to_display = Math.min(_max_column.value(), cols.length == 0 ? ary._cols.length : cols.length); else max_columns_to_display = Math.min(MAX_COLUMNS_TO_DISPLAY, cols.length == 0 ? ary._cols.length : cols.length); if(cols.length == 0){ did_trim_columns = ary._cols.length > max_columns_to_display; cols = new int[ Math.min(ary._cols.length, max_columns_to_display) ]; for(int i = 0; i < cols.length; ++i) cols[i] = i; } else if (cols.length > max_columns_to_display){ int [] cols2 = new int[ max_columns_to_display ]; for (int j=0; j < max_columns_to_display; j++) cols2[ j ] = cols[ j ]; cols = cols2; did_trim_columns = true; } else { did_trim_columns = false; } ColSummaryTask sum = new ColSummaryTask(ary,cols); sum.invoke(ary._key); JsonObject res = new JsonObject(); res.add("summary", sum.result().toJson()); Response r = Response.done(res); r.setBuilder(ROOT_OBJECT, new Builder() { @Override public String build(Response response, JsonElement element, String contextName) { StringBuilder pageBldr = new StringBuilder("<div class=container-fluid'><div class='row-fluid'><div class='span2' style='text-align:right;overflow-x:scroll;'><h5>Columns</h5>"); StringBuilder sb = new StringBuilder("<div class='span10' style='height:90%;overflow-y:scroll'>"); JsonArray cols = element.getAsJsonObject().get("summary").getAsJsonObject().get("columns").getAsJsonArray(); Iterator<JsonElement> it = cols.iterator(); if (did_trim_columns ) sb.append("<p style='text-align:center;'><center><h4 style='font-weight:800; color:red;'>Columns trimmed to " + max_columns_to_display + "</h4></center></p>"); while(it.hasNext()){ JsonObject o = it.next().getAsJsonObject(); String cname = o.get("name").getAsString(); pageBldr.append("<div><a href='#col_" + cname + "'>" + cname + "</a></div>"); long N = o.get("N").getAsLong(); sb.append("<div class='table' id='col_" + cname + "' style='width:90%;heigth:90%;overflow-y:scroll;border-top-style:solid;'><div class='alert-success'><h4>Column: " + cname + "</h4></div>\n"); if(o.has("min") && o.has("max")){ StringBuilder baseStats = new StringBuilder("<div style='width:100%;overflow:scroll;'><table class='table-bordered'>"); baseStats.append("<tr><th colspan='" + 100 + "' style='text-align:center;'>Base Stats</th></tr>"); baseStats.append("<th>avg</th><td>" + Utils.p2d(o.get("mean").getAsDouble())+"</td>"); baseStats.append("<th>sd</th><td>" + Utils.p2d(o.get("sigma").getAsDouble()) + "</td>"); baseStats.append("<th>NAs</th> <td>" + o.get("na").getAsLong() + "</td>"); baseStats.append("<th>zeros</th>"); baseStats.append("<td>" + o.get("zeros").getAsLong() + "</td>"); StringBuilder minmax = new StringBuilder(); int min_count = 0; Iterator<JsonElement> iter = o.get("min").getAsJsonArray().iterator(); while(iter.hasNext()){ min_count++; minmax.append("<td>" + Utils.p2d(iter.next().getAsDouble()) + "</td>"); } baseStats.append("<th>min[" + min_count + "]</th>"); baseStats.append(minmax.toString()); baseStats.append("<th>max[" + min_count + "]</th>"); iter = o.get("max").getAsJsonArray().iterator(); while(iter.hasNext()) baseStats.append("<td>" + Utils.p2d(iter.next().getAsDouble()) + "</td>"); baseStats.append("</tr> </table>"); baseStats.append("</div>"); sb.append( baseStats.toString()); StringBuilder threshold = new StringBuilder(); StringBuilder value = new StringBuilder(); if(o.has("percentiles")){ JsonObject percentiles = o.get("percentiles").getAsJsonObject(); JsonArray thresholds = percentiles.get("thresholds").getAsJsonArray(); JsonArray values = percentiles.get("values").getAsJsonArray(); Iterator<JsonElement> tIter = thresholds.iterator(); Iterator<JsonElement> vIter = values.iterator(); threshold.append("<tr><th>Threshold</th>"); value.append("<tr><th>Value</th>"); while(tIter.hasNext() && vIter.hasNext()){ threshold.append("<td>" + tIter.next().getAsString() + "</td>"); value.append("<td>" + Utils.p2d(vIter.next().getAsDouble()) + "</td>"); } threshold.append("</tr>"); value.append("</tr>"); sb.append("<div style='width:100%;overflow:scroll;'><table class='table-bordered'>"); sb.append("<th colspan='12' style='text-align:center;'>Percentiles</th>"); sb.append(threshold.toString()); sb.append(value.toString()); sb.append("</table>"); sb.append("</div>"); } } else { sb.append("<div style='width:100%;overflow:scroll;'><table class='table-bordered'>"); sb.append("<tr><th colspan='" + 4 + "' style='text-align:center;'>Base Stats</th></tr>"); sb.append("<tr><th>NAs</th> <td>" + o.get("na").getAsLong() + "</td>"); sb.append("<th>cardinality</th> <td>" + o.get("enumCardinality").getAsLong() + "</td></tr>"); sb.append("</table></div>"); } JsonObject histo = o.get("histogram").getAsJsonObject(); JsonArray bins = histo.get("bins").getAsJsonArray(); JsonArray names = histo.get("bin_names").getAsJsonArray(); Iterator<JsonElement> bIter = bins.iterator(); Iterator<JsonElement> nIter = names.iterator(); StringBuilder n = new StringBuilder("<tr>"); StringBuilder b = new StringBuilder("<tr>"); StringBuilder p = new StringBuilder("<tr>"); int i = 0; while(bIter.hasNext() && nIter.hasNext() && i++ < MAX_HISTO_BINS_DISPLAYED){ n.append("<th>" + nIter.next().getAsString() + "</th>"); long cnt = bIter.next().getAsLong(); b.append("<td>" + cnt + "</td>"); p.append(String.format("<td>%.1f%%</td>",(100.0*cnt/N))); } if(i >= MAX_HISTO_BINS_DISPLAYED && bIter.hasNext()) sb.append("<div class='alert'>Histogram for this column was too big and was truncated to 1000 values!</div>"); n.append("</tr>\n"); b.append("</tr>\n"); p.append("</tr>\n"); sb.append("<div style='width:100%;overflow:scroll;'><table class='table-bordered'>"); sb.append("<thead> <th colspan=" + (MAX_HISTO_BINS_DISPLAYED + 1) + " style='text-align:center;'>Histogram </th> </thead>"); sb.append(n.toString() + b.toString() + p.toString() + "</table></div>"); sb.append("\n</div>\n"); } sb.append("</div>"); pageBldr.append("</div>"); pageBldr.append(sb); pageBldr.append("</div>"); return pageBldr.toString(); } }); return r; }
@Override protected Response serve() { int [] cols = _columns.value(); ValueArray ary = _key.value(); final boolean did_trim_columns; final int max_columns_to_display; if (_max_column.value() >= 0) max_columns_to_display = Math.min(_max_column.value(), cols.length == 0 ? ary._cols.length : cols.length); else max_columns_to_display = Math.min(MAX_COLUMNS_TO_DISPLAY, cols.length == 0 ? ary._cols.length : cols.length); if(cols.length == 0){ did_trim_columns = ary._cols.length > max_columns_to_display; cols = new int[ Math.min(ary._cols.length, max_columns_to_display) ]; for(int i = 0; i < cols.length; ++i) cols[i] = i; } else if (cols.length > max_columns_to_display){ int [] cols2 = new int[ max_columns_to_display ]; for (int j=0; j < max_columns_to_display; j++) cols2[ j ] = cols[ j ]; cols = cols2; did_trim_columns = true; } else { did_trim_columns = false; } ColSummaryTask sum = new ColSummaryTask(ary,cols); sum.invoke(ary._key); JsonObject res = new JsonObject(); res.add("summary", sum.result().toJson()); Response r = Response.done(res); r.setBuilder(ROOT_OBJECT, new Builder() { @Override public String build(Response response, JsonElement element, String contextName) { StringBuilder pageBldr = new StringBuilder("<div class=container-fluid'><div class='row-fluid' style='position:relative'><div class='span2' style='margin:0;left:0;text-align:right;overflow-x:scroll;position:fixed'><h5>Columns</h5>"); StringBuilder sb = new StringBuilder("<div class='span10' style='height:90%;overflow-y:scroll'>"); JsonArray cols = element.getAsJsonObject().get("summary").getAsJsonObject().get("columns").getAsJsonArray(); Iterator<JsonElement> it = cols.iterator(); if (did_trim_columns ) sb.append("<p style='text-align:center;'><center><h4 style='font-weight:800; color:red;'>Columns trimmed to " + max_columns_to_display + "</h4></center></p>"); while(it.hasNext()){ JsonObject o = it.next().getAsJsonObject(); String cname = o.get("name").getAsString(); pageBldr.append("<div><a href='#col_" + cname + "'>" + cname + "</a></div>"); long N = o.get("N").getAsLong(); sb.append("<div class='table' id='col_" + cname + "' style='width:90%;heigth:90%;overflow-y:scroll;border-top-style:solid;'><div class='alert-success'><h4>Column: " + cname + "</h4></div>\n"); if(o.has("min") && o.has("max")){ StringBuilder baseStats = new StringBuilder("<div style='width:100%;overflow:scroll;'><table class='table-bordered'>"); baseStats.append("<tr><th colspan='" + 100 + "' style='text-align:center;'>Base Stats</th></tr>"); baseStats.append("<th>avg</th><td>" + Utils.p2d(o.get("mean").getAsDouble())+"</td>"); baseStats.append("<th>sd</th><td>" + Utils.p2d(o.get("sigma").getAsDouble()) + "</td>"); baseStats.append("<th>NAs</th> <td>" + o.get("na").getAsLong() + "</td>"); baseStats.append("<th>zeros</th>"); baseStats.append("<td>" + o.get("zeros").getAsLong() + "</td>"); StringBuilder minmax = new StringBuilder(); int min_count = 0; Iterator<JsonElement> iter = o.get("min").getAsJsonArray().iterator(); while(iter.hasNext()){ min_count++; minmax.append("<td>" + Utils.p2d(iter.next().getAsDouble()) + "</td>"); } baseStats.append("<th>min[" + min_count + "]</th>"); baseStats.append(minmax.toString()); baseStats.append("<th>max[" + min_count + "]</th>"); iter = o.get("max").getAsJsonArray().iterator(); while(iter.hasNext()) baseStats.append("<td>" + Utils.p2d(iter.next().getAsDouble()) + "</td>"); baseStats.append("</tr> </table>"); baseStats.append("</div>"); sb.append( baseStats.toString()); StringBuilder threshold = new StringBuilder(); StringBuilder value = new StringBuilder(); if(o.has("percentiles")){ JsonObject percentiles = o.get("percentiles").getAsJsonObject(); JsonArray thresholds = percentiles.get("thresholds").getAsJsonArray(); JsonArray values = percentiles.get("values").getAsJsonArray(); Iterator<JsonElement> tIter = thresholds.iterator(); Iterator<JsonElement> vIter = values.iterator(); threshold.append("<tr><th>Threshold</th>"); value.append("<tr><th>Value</th>"); while(tIter.hasNext() && vIter.hasNext()){ threshold.append("<td>" + tIter.next().getAsString() + "</td>"); value.append("<td>" + Utils.p2d(vIter.next().getAsDouble()) + "</td>"); } threshold.append("</tr>"); value.append("</tr>"); sb.append("<div style='width:100%;overflow:scroll;'><table class='table-bordered'>"); sb.append("<th colspan='12' style='text-align:center;'>Percentiles</th>"); sb.append(threshold.toString()); sb.append(value.toString()); sb.append("</table>"); sb.append("</div>"); } } else { sb.append("<div style='width:100%;overflow:scroll;'><table class='table-bordered'>"); sb.append("<tr><th colspan='" + 4 + "' style='text-align:center;'>Base Stats</th></tr>"); sb.append("<tr><th>NAs</th> <td>" + o.get("na").getAsLong() + "</td>"); sb.append("<th>cardinality</th> <td>" + o.get("enumCardinality").getAsLong() + "</td></tr>"); sb.append("</table></div>"); } JsonObject histo = o.get("histogram").getAsJsonObject(); JsonArray bins = histo.get("bins").getAsJsonArray(); JsonArray names = histo.get("bin_names").getAsJsonArray(); Iterator<JsonElement> bIter = bins.iterator(); Iterator<JsonElement> nIter = names.iterator(); StringBuilder n = new StringBuilder("<tr>"); StringBuilder b = new StringBuilder("<tr>"); StringBuilder p = new StringBuilder("<tr>"); int i = 0; while(bIter.hasNext() && nIter.hasNext() && i++ < MAX_HISTO_BINS_DISPLAYED){ n.append("<th>" + nIter.next().getAsString() + "</th>"); long cnt = bIter.next().getAsLong(); b.append("<td>" + cnt + "</td>"); p.append(String.format("<td>%.1f%%</td>",(100.0*cnt/N))); } if(i >= MAX_HISTO_BINS_DISPLAYED && bIter.hasNext()) sb.append("<div class='alert'>Histogram for this column was too big and was truncated to 1000 values!</div>"); n.append("</tr>\n"); b.append("</tr>\n"); p.append("</tr>\n"); sb.append("<div style='width:100%;overflow:scroll;'><table class='table-bordered'>"); sb.append("<thead> <th colspan=" + (MAX_HISTO_BINS_DISPLAYED + 1) + " style='text-align:center;'>Histogram </th> </thead>"); sb.append(n.toString() + b.toString() + p.toString() + "</table></div>"); sb.append("\n</div>\n"); } sb.append("</div>"); pageBldr.append("</div>"); pageBldr.append(sb); pageBldr.append("</div>"); return pageBldr.toString(); } }); return r; }
public void process(Exchange exchange) throws Exception { LOGGER.trace("Get the Camel in message"); Message in = exchange.getIn(); LOGGER.trace("Get the Camel out message"); Message out = exchange.getOut(); LOGGER.trace("Get the {} header", MASHUP_ID_HEADER); String mashupId = (String) in.getHeader(MASHUP_ID_HEADER); LOGGER.debug("Mashup ID: {}", mashupId); LOGGER.trace("Get the {} header", MASHUP_STORE_HEADER); String store = (String) in.getHeader(MASHUP_STORE_HEADER); LOGGER.debug("Mashup Store: {}", store); LOGGER.debug("Digesting the navigation file {}/{}.xml", store, mashupId); FileInputStream fileInputStream = new FileInputStream(store + "/" + mashupId + ".xml"); Mashup mashup = new Mashup(); mashup.digeste(fileInputStream); LOGGER.trace("Create the HTTP client"); DefaultHttpClient httpClient = new DefaultHttpClient(); if (mashup.getProxy() != null) { LOGGER.trace("Registering the HTTP client proxy"); if (mashup.getProxy().getScheme().equalsIgnoreCase("NTLM")) { LOGGER.trace("Registering a NTLM authenticated proxy"); httpClient.getAuthSchemes().register("ntlm", new NTLMSchemeFactory()); NTCredentials credentials = new NTCredentials(mashup.getProxy().getUsername(), mashup.getProxy().getPassword(), mashup.getProxy().getWorkstation(), mashup.getProxy().getDomain()); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); HttpHost proxy = new HttpHost(mashup.getProxy().getHost(), Integer.parseInt(mashup.getProxy().getPort())); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } else if (mashup.getProxy().getScheme().equalsIgnoreCase("Basic")) { LOGGER.trace("Registering a Basic authenticated proxy"); httpClient.getAuthSchemes().register("basic", new BasicSchemeFactory()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(mashup.getProxy().getUsername(), mashup.getProxy().getPassword()); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); HttpHost proxy = new HttpHost(mashup.getProxy().getHost(), Integer.parseInt(mashup.getProxy().getPort())); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } else { throw new IllegalArgumentException("Proxy authentication " + mashup.getProxy().getScheme() + " not supported"); } } CookieStore cookieStore = CookieStore.getInstance(); LOGGER.trace("Iterate in the pages"); for (Page page : mashup.getPages()) { LOGGER.trace("Replacing the headers in the URL"); String url = page.getUrl(); for (String header : in.getHeaders().keySet()) { LOGGER.trace("Replace %{}% with {}", header, in.getHeader(header).toString()); url = url.replace("%" + header + "%", in.getHeader(header).toString()); } LOGGER.trace("Replace params with param tags if exist"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); if (page.getParams() != null && page.getParams().size() > 0) { for (Param param : page.getParams()) { String value = param.getValue(); for (String header : in.getHeaders().keySet()) { value = value.replace("%" + header + "%", in.getHeader(header).toString()); } nvps.add(new BasicNameValuePair(param.getName(), value)); } } LOGGER.trace("Constructing the HTTP request"); HttpUriRequest request = null; if (page.getMethod() != null && page.getMethod().equalsIgnoreCase("POST")) { HttpPost postRequest = new HttpPost(url); if (nvps.size() > 0) { postRequest.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); } request = postRequest; } else { if ((nvps.size() > 0)) { if (!url.contains("?")) { url = url + "?"; } for (NameValuePair nvp : nvps) { if (!url.endsWith("&") && (!url.endsWith("?"))) { url = url + "&"; } url = url + nvp.getName() + "=" + nvp.getValue(); } } request = new HttpGet(url); } if (mashup.getCookieStore() != null) { LOGGER.trace("Looking cookies in the cookie store"); String cookieKey = mashup.getCookieStore().getKey(); if (cookieKey == null) { throw new IllegalArgumentException("CookieStore key is mandatory"); } for (String header : in.getHeaders().keySet()) { cookieKey = cookieKey.replace("%" + header + "%", in.getHeader(header).toString()); } List<org.apache.http.cookie.Cookie> storedCookies = cookieStore.getCookies(cookieKey); for (org.apache.http.cookie.Cookie cookie : storedCookies) { LOGGER.trace("Adding cookie " + cookie.getName() + " in the HTTP client"); BasicCookieStore basicCookieStore = new BasicCookieStore(); basicCookieStore.addCookie(cookie); httpClient.setCookieStore(basicCookieStore); } } else { LOGGER.warn("No cookie configuration defined"); } HttpResponse response = httpClient.execute(request); HttpEntity entity = response.getEntity(); if (mashup.getCookieStore() != null) { String cookieKey = mashup.getCookieStore().getKey(); if (cookieKey == null) { throw new IllegalArgumentException("CookieStore key is mandatory"); } for (String header : in.getHeaders().keySet()) { cookieKey = cookieKey.replace("%" + header + "%", in.getHeader(header).toString()); } LOGGER.trace("Populating the cookie store"); List<org.apache.http.cookie.Cookie> cookies = httpClient.getCookieStore().getCookies(); for (org.apache.http.cookie.Cookie cookie : cookies) { LOGGER.trace("Storing cookie " + cookie.getName()); cookieStore.addCookie(cookieKey, cookie); } } if (page.getExtractors() != null && page.getExtractors().size() > 0) { LOGGER.trace("Populate content to be used by extractors"); String content = EntityUtils.toString(entity); try { for (Extractor extractor : page.getExtractors()) { IExtractor extractorBean = this.instantiateExtractor(extractor); String extractedData = extractorBean.extract(content); if (extractor.isMandatory() && (extractedData == null || extractedData.isEmpty())) { throw new IllegalStateException("Extracted data is empty"); } if (extractor.isAppend()) { if (out.getBody() == null) { out.setBody("<extract id=\"" + extractor.getId() + "\"><![CDATA[" + extractedData + "]]></extract>"); } else { out.setBody(out.getBody() + "<extract id=\"" + extractor.getId() + "\"><![CDATA[" + extractedData + "]]></extract>"); } } } } catch (Exception e) { e.printStackTrace(); LOGGER.warn("An exception occurs during the extraction", e); LOGGER.warn("Calling the error handler"); exchange.setException(e); out.setFault(true); out.setBody(null); if (page.getErrorHandler() != null && page.getErrorHandler().getExtractors() != null && page.getErrorHandler().getExtractors().size() > 0) { LOGGER.trace("Processing the error handler extractor"); for (Extractor extractor : page.getErrorHandler().getExtractors()) { IExtractor extractorBean = this.instantiateExtractor(extractor); String extractedData = extractorBean.extract(content); if (extractedData != null) { out.setBody(out.getBody() + extractedData); } } } } } else { EntityUtils.toString(entity); } if (page.getWait() > 0) { Thread.sleep(page.getWait() * 1000); } } }
public void process(Exchange exchange) throws Exception { LOGGER.trace("Get the Camel in message"); Message in = exchange.getIn(); LOGGER.trace("Get the Camel out message"); Message out = exchange.getOut(); LOGGER.trace("Get the {} header", MASHUP_ID_HEADER); String mashupId = (String) in.getHeader(MASHUP_ID_HEADER); LOGGER.debug("Mashup ID: {}", mashupId); LOGGER.trace("Get the {} header", MASHUP_STORE_HEADER); String store = (String) in.getHeader(MASHUP_STORE_HEADER); LOGGER.debug("Mashup Store: {}", store); LOGGER.debug("Digesting the navigation file {}/{}.xml", store, mashupId); FileInputStream fileInputStream = new FileInputStream(store + "/" + mashupId + ".xml"); Mashup mashup = new Mashup(); mashup.digeste(fileInputStream); LOGGER.trace("Create the HTTP client"); DefaultHttpClient httpClient = new DefaultHttpClient(); if (mashup.getProxy() != null) { LOGGER.trace("Registering the HTTP client proxy"); if (mashup.getProxy().getScheme().equalsIgnoreCase("NTLM")) { LOGGER.trace("Registering a NTLM authenticated proxy"); httpClient.getAuthSchemes().register("ntlm", new NTLMSchemeFactory()); NTCredentials credentials = new NTCredentials(mashup.getProxy().getUsername(), mashup.getProxy().getPassword(), mashup.getProxy().getWorkstation(), mashup.getProxy().getDomain()); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); HttpHost proxy = new HttpHost(mashup.getProxy().getHost(), Integer.parseInt(mashup.getProxy().getPort())); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } else if (mashup.getProxy().getScheme().equalsIgnoreCase("Basic")) { LOGGER.trace("Registering a Basic authenticated proxy"); httpClient.getAuthSchemes().register("basic", new BasicSchemeFactory()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(mashup.getProxy().getUsername(), mashup.getProxy().getPassword()); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); HttpHost proxy = new HttpHost(mashup.getProxy().getHost(), Integer.parseInt(mashup.getProxy().getPort())); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } else { throw new IllegalArgumentException("Proxy authentication " + mashup.getProxy().getScheme() + " not supported"); } } CookieStore cookieStore = CookieStore.getInstance(); LOGGER.trace("Iterate in the pages"); for (Page page : mashup.getPages()) { LOGGER.trace("Replacing the headers in the URL"); String url = page.getUrl(); for (String header : in.getHeaders().keySet()) { LOGGER.trace("Replace %{}% with {}", header, in.getHeader(header).toString()); url = url.replace("%" + header + "%", in.getHeader(header).toString()); } LOGGER.trace("Replace params with param tags if exist"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); if (page.getParams() != null && page.getParams().size() > 0) { for (Param param : page.getParams()) { String value = param.getValue(); for (String header : in.getHeaders().keySet()) { value = value.replace("%" + header + "%", in.getHeader(header).toString()); } nvps.add(new BasicNameValuePair(param.getName(), value)); } } LOGGER.trace("Constructing the HTTP request"); HttpUriRequest request = null; if (page.getMethod() != null && page.getMethod().equalsIgnoreCase("POST")) { HttpPost postRequest = new HttpPost(url); if (nvps.size() > 0) { postRequest.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); } request = postRequest; } else { if ((nvps.size() > 0)) { if (!url.contains("?")) { url = url + "?"; } for (NameValuePair nvp : nvps) { if (!url.endsWith("&") && (!url.endsWith("?"))) { url = url + "&"; } url = url + nvp.getName() + "=" + nvp.getValue(); } } request = new HttpGet(url); } if (mashup.getCookieStore() != null) { LOGGER.trace("Looking cookies in the cookie store"); String cookieKey = mashup.getCookieStore().getKey(); if (cookieKey == null) { throw new IllegalArgumentException("CookieStore key is mandatory"); } for (String header : in.getHeaders().keySet()) { cookieKey = cookieKey.replace("%" + header + "%", in.getHeader(header).toString()); } List<org.apache.http.cookie.Cookie> storedCookies = cookieStore.getCookies(cookieKey); if (storedCookies != null) { for (org.apache.http.cookie.Cookie cookie : storedCookies) { LOGGER.trace("Adding cookie " + cookie.getName() + " in the HTTP client"); BasicCookieStore basicCookieStore = new BasicCookieStore(); basicCookieStore.addCookie(cookie); httpClient.setCookieStore(basicCookieStore); } } else { LOGGER.trace("No cookie yet exist for {}", cookieKey); } } else { LOGGER.warn("No cookie configuration defined"); } HttpResponse response = httpClient.execute(request); HttpEntity entity = response.getEntity(); if (mashup.getCookieStore() != null) { String cookieKey = mashup.getCookieStore().getKey(); if (cookieKey == null) { throw new IllegalArgumentException("CookieStore key is mandatory"); } for (String header : in.getHeaders().keySet()) { cookieKey = cookieKey.replace("%" + header + "%", in.getHeader(header).toString()); } LOGGER.trace("Populating the cookie store"); List<org.apache.http.cookie.Cookie> cookies = httpClient.getCookieStore().getCookies(); for (org.apache.http.cookie.Cookie cookie : cookies) { LOGGER.trace("Storing cookie " + cookie.getName()); cookieStore.addCookie(cookieKey, cookie); } } if (page.getExtractors() != null && page.getExtractors().size() > 0) { LOGGER.trace("Populate content to be used by extractors"); String content = EntityUtils.toString(entity); try { for (Extractor extractor : page.getExtractors()) { IExtractor extractorBean = this.instantiateExtractor(extractor); String extractedData = extractorBean.extract(content); if (extractor.isMandatory() && (extractedData == null || extractedData.isEmpty())) { throw new IllegalStateException("Extracted data is empty"); } if (extractor.isAppend()) { if (out.getBody() == null) { out.setBody("<extract id=\"" + extractor.getId() + "\"><![CDATA[" + extractedData + "]]></extract>"); } else { out.setBody(out.getBody() + "<extract id=\"" + extractor.getId() + "\"><![CDATA[" + extractedData + "]]></extract>"); } } } if (out.getBody() != null) { out.setBody("<mashup>" + out.getBody() + "</mashup>"); } } catch (Exception e) { e.printStackTrace(); LOGGER.warn("An exception occurs during the extraction", e); LOGGER.warn("Calling the error handler"); exchange.setException(e); out.setFault(true); out.setBody(null); if (page.getErrorHandler() != null && page.getErrorHandler().getExtractors() != null && page.getErrorHandler().getExtractors().size() > 0) { LOGGER.trace("Processing the error handler extractor"); for (Extractor extractor : page.getErrorHandler().getExtractors()) { IExtractor extractorBean = this.instantiateExtractor(extractor); String extractedData = extractorBean.extract(content); if (extractor.isMandatory() && (extractedData == null || extractedData.isEmpty())) { throw new IllegalStateException("Extracted data is empty"); } if (extractor.isAppend()) { if (out.getBody() == null) { out.setBody("<extract id=\"" + extractor.getId() + "\"><![CDATA[" + extractedData + "]]></extract>"); } else { out.setBody(out.getBody() + "<extract id=\"" + extractor.getId() + "\"><![CDATA[" + extractedData + "]]></extract>"); } } } if (out.getBody() != null) { out.setBody("<mashup>" + out.getBody() + "</mashup>"); } } } } else { EntityUtils.toString(entity); } if (page.getWait() > 0) { Thread.sleep(page.getWait() * 1000); } } }
public void testList() throws Exception { PagableResponseList<UserList> userLists; userLists = twitterAPI1.getUserLists(id1.screenName,-1l); for(UserList alist : userLists){ twitterAPI1.destroyUserList(alist.getId()); } UserList userList; userList = twitterAPI3.createUserList("api3 is email", false, null); assertFalse(userList.isPublic()); twitterAPI3.destroyUserList(userList.getId()); userList = twitterAPI1.createUserList("testpoint1", false, "description1"); assertNotNull(userList); assertEquals("testpoint1", userList.getName()); assertEquals("description1", userList.getDescription()); userList = twitterAPI1.updateUserList(userList.getId(), "testpoint2", true, "description2"); assertTrue(userList.isPublic()); assertNotNull(userList); assertEquals("testpoint2", userList.getName()); assertEquals("description2", userList.getDescription()); userLists = twitterAPI1.getUserLists(id1.screenName, -1l); assertFalse(userLists.size() == 0); userList = twitterAPI1.showUserList(id1.screenName, userList.getId()); assertNotNull(userList); List<Status> statuses = twitterAPI1.getUserListStatuses(id1.screenName, userList.getId(), new Paging()); assertNotNull(statuses); User user; try { user = twitterAPI1.checkUserListMembership(id1.screenName, id2.id, userList.getId()); fail("id2 shouldn't be a member of the userList yet. expecting a TwitterException"); } catch (TwitterException te) { assertEquals(404, te.getStatusCode()); } userList = twitterAPI1.addUserListMember(userList.getId(), id2.id); userList = twitterAPI1.addUserListMember(userList.getId(), id4.id); assertNotNull(userList); List<User> users = twitterAPI1.getUserListMembers(id1.screenName, userList.getId(), -1); assertTrue(0 < users.size()); userList = twitterAPI1.deleteUserListMember(userList.getId(), id2.id); assertNotNull(userList); user = twitterAPI1.checkUserListMembership(id1.screenName, userList.getId(), id4.id); assertEquals(id4.id, user.getId()); userLists = twitterAPI1.getUserListMemberships(id1.screenName, -1l); assertNotNull(userLists); userLists = twitterAPI1.getUserListSubscriptions(id1.screenName, -1l); assertNotNull(userLists); assertEquals(0, userLists.size()); users = twitterAPI1.getUserListSubscribers(id1.screenName, userList.getId(), -1); assertEquals(0, users.size()); try { twitterAPI2.subscribeUserList(id1.screenName, userList.getId()); } catch (TwitterException te) { assertEquals(404,te.getStatusCode()); } try { twitterAPI4.subscribeUserList(id1.screenName, userList.getId()); } catch (TwitterException te) { assertEquals(404, te.getStatusCode()); } try { twitterAPI2.unsubscribeUserList(id1.screenName, userList.getId()); } catch (TwitterException te) { assertEquals(404, te.getStatusCode()); } users = twitterAPI1.getUserListSubscribers(id1.screenName, userList.getId(), -1); assertTrue(0 <= users.size()); try { user = twitterAPI1.checkUserListSubscription(id1.screenName, userList.getId(), id4.id); assertEquals(id4.id, user.getId()); } catch (TwitterException te) { assertEquals(404, te.getStatusCode()); } userLists = twitterAPI1.getUserListSubscriptions(id4.screenName, -1l); assertNotNull(userLists); try { user = twitterAPI1.checkUserListSubscription(id1.screenName, id2.id, userList.getId()); fail("id2 shouldn't be a subscriber the userList. expecting a TwitterException"); } catch (TwitterException ignore) { assertEquals(404, ignore.getStatusCode()); } userList = twitterAPI1.destroyUserList(userList.getId()); assertNotNull(userList); }
public void testList() throws Exception { PagableResponseList<UserList> userLists; userLists = twitterAPI1.getUserLists(id1.screenName,-1l); for(UserList alist : userLists){ twitterAPI1.destroyUserList(alist.getId()); } UserList userList; userList = twitterAPI1.createUserList("testpoint1", false, "description1"); assertNotNull(userList); assertEquals("testpoint1", userList.getName()); assertEquals("description1", userList.getDescription()); userList = twitterAPI1.updateUserList(userList.getId(), "testpoint2", true, "description2"); assertTrue(userList.isPublic()); assertNotNull(userList); assertEquals("testpoint2", userList.getName()); assertEquals("description2", userList.getDescription()); userLists = twitterAPI1.getUserLists(id1.screenName, -1l); assertFalse(userLists.size() == 0); userList = twitterAPI1.showUserList(id1.screenName, userList.getId()); assertNotNull(userList); List<Status> statuses = twitterAPI1.getUserListStatuses(id1.screenName, userList.getId(), new Paging()); assertNotNull(statuses); User user; try { user = twitterAPI1.checkUserListMembership(id1.screenName, id2.id, userList.getId()); fail("id2 shouldn't be a member of the userList yet. expecting a TwitterException"); } catch (TwitterException te) { assertEquals(404, te.getStatusCode()); } userList = twitterAPI1.addUserListMember(userList.getId(), id2.id); userList = twitterAPI1.addUserListMember(userList.getId(), id4.id); assertNotNull(userList); List<User> users = twitterAPI1.getUserListMembers(id1.screenName, userList.getId(), -1); assertTrue(0 < users.size()); userList = twitterAPI1.deleteUserListMember(userList.getId(), id2.id); assertNotNull(userList); user = twitterAPI1.checkUserListMembership(id1.screenName, userList.getId(), id4.id); assertEquals(id4.id, user.getId()); userLists = twitterAPI1.getUserListMemberships(id1.screenName, -1l); assertNotNull(userLists); userLists = twitterAPI1.getUserListSubscriptions(id1.screenName, -1l); assertNotNull(userLists); assertEquals(0, userLists.size()); users = twitterAPI1.getUserListSubscribers(id1.screenName, userList.getId(), -1); assertEquals(0, users.size()); try { twitterAPI2.subscribeUserList(id1.screenName, userList.getId()); } catch (TwitterException te) { assertEquals(404,te.getStatusCode()); } try { twitterAPI4.subscribeUserList(id1.screenName, userList.getId()); } catch (TwitterException te) { assertEquals(404, te.getStatusCode()); } try { twitterAPI2.unsubscribeUserList(id1.screenName, userList.getId()); } catch (TwitterException te) { assertEquals(404, te.getStatusCode()); } users = twitterAPI1.getUserListSubscribers(id1.screenName, userList.getId(), -1); assertTrue(0 <= users.size()); try { user = twitterAPI1.checkUserListSubscription(id1.screenName, userList.getId(), id4.id); assertEquals(id4.id, user.getId()); } catch (TwitterException te) { assertEquals(404, te.getStatusCode()); } userLists = twitterAPI1.getUserListSubscriptions(id4.screenName, -1l); assertNotNull(userLists); try { user = twitterAPI1.checkUserListSubscription(id1.screenName, id2.id, userList.getId()); fail("id2 shouldn't be a subscriber the userList. expecting a TwitterException"); } catch (TwitterException ignore) { assertEquals(404, ignore.getStatusCode()); } userList = twitterAPI1.destroyUserList(userList.getId()); assertNotNull(userList); }
public static void main(String[] args) { try { System.out.println("Generating Doco..."); ArrayList<String> inplin=getFileContents("../charFunk-1.1.0.js"); ArrayList<String> inpmkd=getFileContents("../../readme.md"); ArrayList<String> outmkd=new ArrayList<String>(); for(String lin : inpmkd) { outmkd.add(lin); if(lin.equals("---")) break; } outmkd.add("##API"); int fncidx=-1; boolean nxtfnc=false; boolean ign=true; boolean prvats=false; for(String lin : inplin) { lin=lin.trim(); if(ign) { if(lin.equals("*/")) ign=false; continue; } if(nxtfnc && lin.indexOf("function(")>-1) { String fncnam="CharFunk."+lin.substring(0,lin.indexOf("=")); String fncarg=lin.substring(lin.indexOf("(")+1,lin.indexOf(")")); outmkd.set(fncidx,"\n\n###"+fncnam+"("+fncarg+")"); nxtfnc=false; } else if(lin.startsWith("/*")) { fncidx=outmkd.size(); outmkd.add("placeholder"); } else if(lin.startsWith("*/")) { nxtfnc=true; } else if(lin.startsWith("*")) { if(lin.indexOf(" @")>-1) { if(!prvats) outmkd.add(""); int endquo=lin.length(); int dshidx=lin.indexOf("-"); int crlidx=lin.indexOf("}"); if(crlidx>-1) endquo=crlidx+1; if(dshidx>-1) endquo=dshidx; outmkd.add("\n`"+lin.substring(1,endquo).trim()+"` "+lin.substring(endquo).trim()); } else { outmkd.add(lin.substring(Math.min(lin.length(),3))); } } prvats=(lin.indexOf(" @")>-1); } PrintWriter outwri=new PrintWriter(new File("../../readme.md")); for(String lin : outmkd) { outwri.println(lin); } outwri.flush(); outwri.close(); } catch(Exception exc) { exc.printStackTrace(); } System.out.println("Doco output complete"); }
public static void main(String[] args) { try { System.out.println("Generating Doco..."); ArrayList<String> inplin=getFileContents("../charFunk-1.1.0.js"); ArrayList<String> inpmkd=getFileContents("../../readme.md"); ArrayList<String> outmkd=new ArrayList<String>(); for(String lin : inpmkd) { outmkd.add(lin); if(lin.equals("##API")) break; } int fncidx=-1; boolean nxtfnc=false; boolean ign=true; boolean prvats=false; for(String lin : inplin) { lin=lin.trim(); if(ign) { if(lin.equals("*/")) ign=false; continue; } if(nxtfnc && lin.indexOf("function(")>-1) { String fncnam="CharFunk."+lin.substring(0,lin.indexOf("=")); String fncarg=lin.substring(lin.indexOf("(")+1,lin.indexOf(")")); outmkd.set(fncidx,"\n\n###"+fncnam+"("+fncarg+")"); nxtfnc=false; } else if(lin.startsWith("/*")) { fncidx=outmkd.size(); outmkd.add("placeholder"); } else if(lin.startsWith("*/")) { nxtfnc=true; } else if(lin.startsWith("*")) { if(lin.indexOf(" @")>-1) { if(!prvats) outmkd.add(""); int endquo=lin.length(); int dshidx=lin.indexOf("-"); int crlidx=lin.indexOf("}"); if(crlidx>-1) endquo=crlidx+1; if(dshidx>-1) endquo=dshidx; outmkd.add("\n`"+lin.substring(1,endquo).trim()+"` "+lin.substring(endquo).trim()); } else { outmkd.add(lin.substring(Math.min(lin.length(),3))); } } prvats=(lin.indexOf(" @")>-1); } PrintWriter outwri=new PrintWriter(new File("../../readme.md")); for(String lin : outmkd) { outwri.println(lin); } outwri.flush(); outwri.close(); } catch(Exception exc) { exc.printStackTrace(); } System.out.println("Doco output complete"); }
public void testCreate() throws Exception { Topic t1 = new Topic(); t1.setName("T1"); t1.setNs("http://foo"); t1.setPrefix("pre"); Topic t2 = new Topic(); t2.setName("T2"); t2.setNs("http://foo"); t2.setPrefix("pre"); final List<Topic> topics = new ArrayList<Topic>(); topics.add(t1); topics.add(t2); final List<Topic> filtered = new ArrayList<Topic>(); filtered.add(t1); String ecEndpoint = "http://localhost:4568/EventCloudService"; String subscriberEndpoint = "http://localhost:4569/SubscriberService"; DSBSubscribesToECBootstrapServiceImpl service = new DSBSubscribesToECBootstrapServiceImpl(); service.setEventCloudClientFactory(new EventCloudClientFactoryMock( ecEndpoint)); service.setTopicManager(new TopicManagerMock()); service.setGovernanceClient(new GovernanceClient() { @Override public void loadResources(InputStream arg0) throws GovernanceExeption { } @Override public List<Topic> getTopics() { return topics; } @Override public List<QName> findTopicsByElement(QName arg0) throws GovernanceExeption { return null; } @Override public List<W3CEndpointReference> findEventProducersByTopics( List<QName> arg0) throws GovernanceExeption { return null; } @Override public List<W3CEndpointReference> findEventProducersByElements( List<QName> arg0) throws GovernanceExeption { return null; } @Override public void createTopic(Topic arg0) throws GovernanceExeption { } @Override public void removeMetadata(Topic arg0, Metadata arg1) throws GovernanceExeption { } @Override public List<Topic> getTopicsWithMeta(List<Metadata> arg0) throws GovernanceExeption { System.out.println("Get topics with meta " + arg0); return filtered; } @Override public Metadata getMetadataValue(Topic arg0, String arg1) throws GovernanceExeption { return null; } @Override public List<Metadata> getMetaData(Topic arg0) throws GovernanceExeption { return null; } @Override public boolean deleteMetaData(Topic arg0) throws GovernanceExeption { return false; } @Override public void addMetadata(Topic arg0, Metadata arg1) throws GovernanceExeption { } }); List<Subscription> result = service.bootstrap(ecEndpoint, subscriberEndpoint); System.out.println(result); Assert.assertTrue(result.size() == 1); }
public void testCreate() throws Exception { Topic t1 = new Topic(); t1.setName("T1"); t1.setNs("http://foo"); t1.setPrefix("pre"); Topic t2 = new Topic(); t2.setName("T2"); t2.setNs("http://foo"); t2.setPrefix("pre"); final List<Topic> topics = new ArrayList<Topic>(); topics.add(t1); topics.add(t2); final List<Topic> filtered = new ArrayList<Topic>(); filtered.add(t1); String ecEndpoint = "http://localhost:4568/EventCloudService"; String subscriberEndpoint = "http://localhost:4569/SubscriberService"; DSBSubscribesToECBootstrapServiceImpl service = new DSBSubscribesToECBootstrapServiceImpl(); service.setEventCloudClientFactory(new EventCloudClientFactoryMock( ecEndpoint)); service.setTopicManager(new TopicManagerMock()); service.setSubscriptionRegistry(new SubscriptionRegistryServiceImpl()); service.setGovernanceClient(new GovernanceClient() { @Override public void loadResources(InputStream arg0) throws GovernanceExeption { } @Override public List<Topic> getTopics() { return topics; } @Override public List<QName> findTopicsByElement(QName arg0) throws GovernanceExeption { return null; } @Override public List<W3CEndpointReference> findEventProducersByTopics( List<QName> arg0) throws GovernanceExeption { return null; } @Override public List<W3CEndpointReference> findEventProducersByElements( List<QName> arg0) throws GovernanceExeption { return null; } @Override public void createTopic(Topic arg0) throws GovernanceExeption { } @Override public void removeMetadata(Topic arg0, Metadata arg1) throws GovernanceExeption { } @Override public List<Topic> getTopicsWithMeta(List<Metadata> arg0) throws GovernanceExeption { System.out.println("Get topics with meta " + arg0); return filtered; } @Override public Metadata getMetadataValue(Topic arg0, String arg1) throws GovernanceExeption { return null; } @Override public List<Metadata> getMetaData(Topic arg0) throws GovernanceExeption { return null; } @Override public boolean deleteMetaData(Topic arg0) throws GovernanceExeption { return false; } @Override public void addMetadata(Topic arg0, Metadata arg1) throws GovernanceExeption { } }); List<Subscription> result = service.bootstrap(ecEndpoint, subscriberEndpoint); System.out.println(result); Assert.assertTrue(result.size() == 1); }
static public void assertValidMessageForSending(Message message) { MessageEnvelope env = message.getEnvelope(); if (env.getRecipient() == null) { throw new IllegalArgumentException("Zprava nema prijemce."); } if (env.getRecipient().getdataBoxID() == null) { throw new IllegalArgumentException("ID prijemce zpravy je null."); } List<Attachment> attachments = message.getAttachments(); if (attachments == null || attachments.size() == 0) { throw new IllegalArgumentException("Zprava musi obsahovat alespon jednu prilohu."); } LegalTitle legalTitle = message.getEnvelope().getLegalTitle(); if (legalTitle != null) { if (legalTitle.getLaw() != null) { try { Long.parseLong(legalTitle.getLaw()); } catch(Exception e) { throw new IllegalArgumentException("Cislo paragrafu zmocneni neni prirozene cislo"); } } if (legalTitle.getYear() != null) { try { Long.parseLong(legalTitle.getYear()); } catch(Exception e) { throw new IllegalArgumentException("Rok zmocneni neni prirozene cislo"); } } } Attachment first = attachments.get(0); if (!first.getMetaType().equals("main")) { throw new IllegalArgumentException(String.format("Druh (metatype) prvni pisemnosti " +" v prilohach musí být main, tady je %s.", first.getMetaType())); } for (Attachment attach : attachments) { if (!enabledMetaTypes.contains(attach.getMetaType())) { throw new IllegalArgumentException(String.format("%s není povoleny " + "druh pisemnosti (metatype). Povolen jsou: %s.", attach.getMetaType(), enabledMetaTypes.toString())); } if (attach.getDescription() == null) { throw new IllegalArgumentException("Popis přílohy je null"); } if (attach.getMimeType() == null) { throw new IllegalArgumentException("Příloha nemá vyplněný MIME type."); } } }
static public void assertValidMessageForSending(Message message) { MessageEnvelope env = message.getEnvelope(); if (env.getRecipient() == null) { throw new IllegalArgumentException("Zprava nema prijemce."); } if (env.getRecipient().getdataBoxID() == null) { throw new IllegalArgumentException("ID prijemce zpravy je null."); } List<Attachment> attachments = message.getAttachments(); if (attachments == null || attachments.size() == 0) { throw new IllegalArgumentException("Zprava musi obsahovat alespon jednu prilohu."); } LegalTitle legalTitle = message.getEnvelope().getLegalTitle(); if (legalTitle != null) { if (legalTitle.getLaw() != null) { try { Long.parseLong(legalTitle.getLaw()); } catch(Exception e) { throw new IllegalArgumentException("Cislo paragrafu zmocneni neni prirozene cislo"); } } if (legalTitle.getYear() != null) { try { Long.parseLong(legalTitle.getYear()); } catch(Exception e) { throw new IllegalArgumentException("Rok zmocneni neni prirozene cislo"); } } } Attachment first = attachments.get(0); if (!first.getMetaType().equals("main")) { throw new IllegalArgumentException(String.format("Druh (metatype) prvni pisemnosti " +" v prilohach musí být main, tady je %s.", first.getMetaType())); } for (Attachment attach : attachments) { if (!enabledMetaTypes.contains(attach.getMetaType())) { throw new IllegalArgumentException(String.format("%s není povoleny " + "druh pisemnosti (metatype). Povolen jsou: %s.", attach.getMetaType(), enabledMetaTypes.toString())); } if (attach.getDescription() == null) { throw new IllegalArgumentException("Popis přílohy je null"); } if (attach.getMimeType() == null) { throw new IllegalArgumentException("Příloha nemá vyplněný MIME type."); } } }
public Collection<File> getRandomFiles(FileRepository repository, int numberOfFiles) { if (repository.size() < numberOfFiles) { throw new IllegalArgumentException("Repository's size is less than requested numberOfFiles"); } Set<File> res = new HashSet<File>(numberOfFiles); int repositorySize = repository.size(); for(int i = repositorySize - numberOfFiles; i < repositorySize; i++) { int pos = RandomHelper.getRandomValue(i + 1); File file = repository.get(pos); if (res.contains(file)) { res.add(repository.get(i)); } else { res.add(file); } } return Collections.unmodifiableCollection(res); }
public Collection<File> getRandomFiles(FileRepository repository, int numberOfFiles) { if (repository.size() < numberOfFiles) { throw new IllegalArgumentException("Repository's size is less than requested numberOfFiles"); } Set<File> res = new HashSet<File>(numberOfFiles); int repositorySize = repository.size(); for(int i = repositorySize - numberOfFiles; i < repositorySize; i++) { int pos = RandomHelper.getRandomValue(i); File file = repository.get(pos); if (res.contains(file)) { res.add(repository.get(i)); } else { res.add(file); } } return Collections.unmodifiableCollection(res); }
public static List<Object> xLocListToList(XLocList xLocList) { if (xLocList == null) return null; List<Object> replicaList = new LinkedList<Object>(); List<Object> list = new LinkedList<Object>(); for (int i = 0; i < xLocList.getReplicaCount(); i++) { XLoc replica = xLocList.getReplica(i); List<Object> replicaAsList = new ArrayList<Object>(2); Map<String, Object> policyMap = stripingPolicyToMap(replica.getStripingPolicy()); List<String> osdList = new ArrayList<String>(replica.getOSDCount()); for (int j = 0; j < replica.getOSDCount(); j++) osdList.add(replica.getOSD(i)); replicaAsList.add(policyMap); replicaAsList.add(osdList); replicaList.add(replicaAsList); } list.add(replicaList); list.add(xLocList.getVersion()); return list; }
public static List<Object> xLocListToList(XLocList xLocList) { if (xLocList == null) return null; List<Object> replicaList = new LinkedList<Object>(); List<Object> list = new LinkedList<Object>(); for (int i = 0; i < xLocList.getReplicaCount(); i++) { XLoc replica = xLocList.getReplica(i); List<Object> replicaAsList = new ArrayList<Object>(2); Map<String, Object> policyMap = stripingPolicyToMap(replica.getStripingPolicy()); List<String> osdList = new ArrayList<String>(replica.getOSDCount()); for (int j = 0; j < replica.getOSDCount(); j++) osdList.add(replica.getOSD(j)); replicaAsList.add(policyMap); replicaAsList.add(osdList); replicaList.add(replicaAsList); } list.add(replicaList); list.add(xLocList.getVersion()); return list; }
public boolean loadByID(int id) { boolean ret = true; try { Connection conn = Main.Database.getConnection(); PreparedStatement ps; String strg = (new StringBuilder()).append("SELECT pricexp,world,bx,`by`,bz,tx,ty,tz, price, paid, blockx,blocky,blockz, sold, buyer, pass, ruleset, level, lastonline, lastpay, noloose, kaufzeit, UNIX_TIMESTAMP() as `timestamp` FROM ").append(configManager.SQLTable).append("_krimbuy WHERE id = ? LIMIT 0,1").toString(); ps = conn.prepareStatement(strg); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); if(rs.next()) { this.id = id; this.world = rs.getString("world"); this.pass = rs.getString("pass"); this.owner = rs.getString("buyer"); this.ruleset = rs.getString("ruleset"); this.bx = rs.getInt("bx"); this.by = rs.getInt("by"); this.bz = rs.getInt("bz"); this.tx = rs.getInt("tx"); this.ty = rs.getInt("ty"); this.tz = rs.getInt("tz"); this.ix = rs.getInt("blockx"); this.iy = rs.getInt("blocky"); this.iz = rs.getInt("blockz"); this.sold = rs.getInt("sold"); this.lastpay = rs.getInt("lastpay"); this.price = rs.getInt("price"); this.paid = rs.getInt("paid"); this.level = rs.getInt("level"); this.lastonline = rs.getInt("lastonline"); this.noloose = rs.getInt("noloose"); this.kaufzeit = rs.getInt("kaufzeit"); this.pricexp = rs.getInt("pricexp"); if(this.ruleset.length() > 0) { PreparedStatement ps2; ps2 = conn.prepareStatement((new StringBuilder()).append("SELECT price,pricexp FROM ").append(configManager.SQLTable).append("_krimbuy_rules WHERE ruleset = ? AND level = ? LIMIT 0,1").toString()); ps2.setString(1, rs.getString("ruleset")); int level = rs.getInt("level") +1 ; ps2.setInt(2, level); ResultSet rs3 = ps2.executeQuery(); if(rs3.next()) { this.upgradeprice = rs3.getInt("price"); this.upgradexp = rs3.getInt("pricexp"); } ps2 = conn.prepareStatement((new StringBuilder()).append("SELECT pvp,indoor,height,deep,miet,autofree,blocks,bottom,controlblockheight,clear,cansell,permissionnode,nobuild,onlyamount,gruppe,nobuy FROM ").append(configManager.SQLTable).append("_krimbuy_rules WHERE ruleset = ? AND level = ? LIMIT 0,1").toString()); ps2.setString(1, rs.getString("ruleset")); level = rs.getInt("level"); if(level == 0) level = 1; ps2.setInt(2, level); ResultSet rs2 = ps2.executeQuery(); if(rs2.next()) { this.height = rs2.getInt("height"); this.deep = rs2.getInt("deep"); this.miet = rs2.getInt("miet"); this.autofree = rs2.getInt("autofree"); this.bh = rs2.getInt("controlblockheight"); this.clear = rs2.getInt("clear"); this.cansell = rs2.getInt("cansell"); this.onlyamount = rs2.getInt("onlyamount"); this.nobuild = rs2.getInt("nobuild"); this.perm = rs2.getString("permissionnode"); this.gruppe = rs2.getString("gruppe"); this.nobuy = rs2.getInt("nobuy"); this.indoor = rs2.getInt("indoor"); int prvp = rs2.getInt("pvp"); if(prvp == 1) this.pvp = true; if(this.gruppe.length() == 0) this.gruppe = this.ruleset; String blocks = rs2.getString("blocks"); this.boh = new ArrayList<Integer>(); if(blocks != null && blocks.length() > 0) { String[] tmpBoh = blocks.split(","); for (String bl: tmpBoh) { if(bl.equalsIgnoreCase("!")) this.invers = true; else this.boh.add(Integer.parseInt(bl)); } } String bottom = rs2.getString("bottom"); this.bot = new ArrayList<Integer>(); if(bottom != null && bottom.length() > 0) { String[] tmpBoh = bottom.split(","); for (String bl: tmpBoh) { this.bot.add(Integer.parseInt(bl)); } } } if(ps2 != null) ps2.close(); if(rs2 != null) rs2.close(); } } else { ret = false; } if(ps != null) ps.close(); if(rs != null) rs.close(); return ret; } catch(SQLException e) { System.out.println((new StringBuilder()).append("[KB] unable to get KBArea from ID: ").append(e).toString()); } return false; }
public boolean loadByID(int id) { boolean ret = true; try { Connection conn = Main.Database.getConnection(); PreparedStatement ps; String strg = (new StringBuilder()).append("SELECT pricexp,world,bx,`by`,bz,tx,ty,tz, price, paid, blockx,blocky,blockz, sold, buyer, pass, ruleset, level, lastonline, lastpay, noloose, kaufzeit, UNIX_TIMESTAMP() as `timestamp` FROM ").append(configManager.SQLTable).append("_krimbuy WHERE id = ? LIMIT 0,1").toString(); ps = conn.prepareStatement(strg); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); if(rs.next()) { this.id = id; this.world = rs.getString("world"); this.pass = rs.getString("pass"); this.owner = rs.getString("buyer"); this.ruleset = rs.getString("ruleset"); this.bx = rs.getInt("bx"); this.by = rs.getInt("by"); this.bz = rs.getInt("bz"); this.tx = rs.getInt("tx"); this.ty = rs.getInt("ty"); this.tz = rs.getInt("tz"); this.ix = rs.getInt("blockx"); this.iy = rs.getInt("blocky"); this.iz = rs.getInt("blockz"); this.sold = rs.getInt("sold"); this.lastpay = rs.getInt("lastpay"); this.price = rs.getInt("price"); this.paid = rs.getInt("paid"); this.level = rs.getInt("level"); this.lastonline = rs.getInt("lastonline"); this.noloose = rs.getInt("noloose"); this.kaufzeit = rs.getInt("kaufzeit"); this.pricexp = rs.getInt("pricexp"); if(this.ruleset.length() > 0) { PreparedStatement ps2; ps2 = conn.prepareStatement((new StringBuilder()).append("SELECT price,pricexp FROM ").append(configManager.SQLTable).append("_krimbuy_rules WHERE ruleset = ? AND level = ? LIMIT 0,1").toString()); ps2.setString(1, rs.getString("ruleset")); int level = rs.getInt("level") +1 ; ps2.setInt(2, level); ResultSet rs3 = ps2.executeQuery(); if(rs3.next()) { this.upgradeprice = rs3.getInt("price"); this.upgradexp = rs3.getInt("pricexp"); } ps2 = conn.prepareStatement((new StringBuilder()).append("SELECT pvp,indoor,height,deep,miet,autofree,blocks,bottom,controlblockheight,clear,cansell,permissionnode,nobuild,onlyamount,gruppe,nobuy FROM ").append(configManager.SQLTable).append("_krimbuy_rules WHERE ruleset = ? AND level = ? LIMIT 0,1").toString()); ps2.setString(1, rs.getString("ruleset")); level = rs.getInt("level"); if(level == 0) level = 1; ps2.setInt(2, level); ResultSet rs2 = ps2.executeQuery(); if(rs2.next()) { this.height = rs2.getInt("height"); this.deep = rs2.getInt("deep"); this.miet = rs2.getInt("miet"); this.autofree = rs2.getInt("autofree"); this.bh = rs2.getInt("controlblockheight"); this.clear = rs2.getInt("clear"); this.cansell = rs2.getInt("cansell"); this.onlyamount = rs2.getInt("onlyamount"); this.nobuild = rs2.getInt("nobuild"); this.perm = rs2.getString("permissionnode"); this.gruppe = rs2.getString("gruppe"); this.nobuy = rs2.getInt("nobuy"); this.indoor = rs2.getInt("indoor"); int prvp = rs2.getInt("pvp"); if(prvp == 1) this.pvp = true; if(this.gruppe.length() == 0) this.gruppe = this.ruleset; String blocks = rs2.getString("blocks"); this.boh = new ArrayList<Integer>(); if(blocks != null && blocks.length() > 0) { String[] tmpBoh = blocks.split(","); for (String bl: tmpBoh) { if(bl.equalsIgnoreCase("!")) this.invers = true; else { try { this.boh.add(Integer.parseInt(bl)); } catch(Exception e) { System.out.println("[KB] ERROR: Blocks in Ruleset MUST be Numeric!"); } } } } String bottom = rs2.getString("bottom"); this.bot = new ArrayList<Integer>(); if(bottom != null && bottom.length() > 0) { String[] tmpBoh = bottom.split(","); for (String bl: tmpBoh) { try { this.bot.add(Integer.parseInt(bl)); } catch(Exception e) { System.out.println("[KB] ERROR: Bottom in Ruleset MUST be Numeric!"); } } } } if(ps2 != null) ps2.close(); if(rs2 != null) rs2.close(); } } else { ret = false; } if(ps != null) ps.close(); if(rs != null) rs.close(); return ret; } catch(SQLException e) { System.out.println((new StringBuilder()).append("[KB] unable to get KBArea from ID: ").append(e).toString()); } return false; }
private void saveSettings() { setResult(RESULT_OK); String oldName = tagData.getValue(TagData.NAME); String newName = tagName.getText().toString(); if (TextUtils.isEmpty(newName)) { return; } boolean nameChanged = !oldName.equals(newName); TagService service = TagService.getInstance(); if (nameChanged) { if (oldName.equalsIgnoreCase(newName)) { tagData.setValue(TagData.NAME, newName); service.renameCaseSensitive(oldName, newName); tagData.setFlag(TagData.FLAGS, TagData.FLAG_EMERGENT, false); } else { newName = service.getTagWithCase(newName); tagName.setText(newName); if (!newName.equals(oldName)) { tagData.setValue(TagData.NAME, newName); service.rename(oldName, newName); tagData.setFlag(TagData.FLAGS, TagData.FLAG_EMERGENT, false); } else { nameChanged = false; } } } JSONArray members = tagMembers.toJSONArray(); if(members.length() > 0 && !actFmPreferenceService.isLoggedIn()) { if(newName.length() > 0 && oldName.length() == 0) { tagDataService.save(tagData); } startActivityForResult(new Intent(this, ActFmLoginActivity.class), REQUEST_ACTFM_LOGIN); return; } int oldMemberCount = tagData.getValue(TagData.MEMBER_COUNT); if (members.length() > oldMemberCount) { StatisticsService.reportEvent(StatisticsConstants.ACTFM_LIST_SHARED); } tagData.setValue(TagData.MEMBERS, members.toString()); tagData.setValue(TagData.MEMBER_COUNT, members.length()); tagData.setFlag(TagData.FLAGS, TagData.FLAG_SILENT, isSilent.isChecked()); if(actFmPreferenceService.isLoggedIn()) Flags.set(Flags.TOAST_ON_SAVE); else Toast.makeText(this, R.string.tag_list_saved, Toast.LENGTH_LONG).show(); tagDataService.save(tagData); InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(tagName.getWindowToken(), 0); if (isNewTag) { Intent intent = new Intent(this, TagViewActivity.class); intent.putExtra(TagViewActivity.EXTRA_TAG_NAME, newName); intent.putExtra(TagViewActivity.TOKEN_FILTER, TagFilterExposer.filterFromTagData(this, tagData)); super.finish(); startActivity(intent); AndroidUtilities.callOverridePendingTransition(this, R.anim.slide_left_in, R.anim.slide_left_out); return; } refreshSettingsPage(); finish(); }
private void saveSettings() { setResult(RESULT_OK); String oldName = tagData.getValue(TagData.NAME); String newName = tagName.getText().toString(); if (TextUtils.isEmpty(newName)) { return; } boolean nameChanged = !oldName.equals(newName); TagService service = TagService.getInstance(); if (nameChanged) { if (oldName.equalsIgnoreCase(newName)) { tagData.setValue(TagData.NAME, newName); service.renameCaseSensitive(oldName, newName); tagData.setFlag(TagData.FLAGS, TagData.FLAG_EMERGENT, false); } else { newName = service.getTagWithCase(newName); tagName.setText(newName); if (!newName.equals(oldName)) { tagData.setValue(TagData.NAME, newName); service.rename(oldName, newName); tagData.setFlag(TagData.FLAGS, TagData.FLAG_EMERGENT, false); } else { nameChanged = false; } } } JSONArray members = tagMembers.toJSONArray(); if(members.length() > 0 && !actFmPreferenceService.isLoggedIn()) { if(newName.length() > 0 && oldName.length() == 0) { tagDataService.save(tagData); } startActivityForResult(new Intent(this, ActFmLoginActivity.class), REQUEST_ACTFM_LOGIN); return; } int oldMemberCount = tagData.getValue(TagData.MEMBER_COUNT); if (members.length() > oldMemberCount) { StatisticsService.reportEvent(StatisticsConstants.ACTFM_LIST_SHARED); } tagData.setValue(TagData.MEMBERS, members.toString()); tagData.setValue(TagData.MEMBER_COUNT, members.length()); tagData.setFlag(TagData.FLAGS, TagData.FLAG_SILENT, isSilent.isChecked()); if(actFmPreferenceService.isLoggedIn()) Flags.set(Flags.TOAST_ON_SAVE); else Toast.makeText(this, R.string.tag_list_saved, Toast.LENGTH_LONG).show(); tagDataService.save(tagData); InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(tagName.getWindowToken(), 0); if (isNewTag) { Intent intent = new Intent(this, TagViewWrapperActivity.class); intent.putExtra(TagViewActivity.EXTRA_TAG_NAME, newName); intent.putExtra(TagViewActivity.TOKEN_FILTER, TagFilterExposer.filterFromTagData(this, tagData)); super.finish(); startActivity(intent); AndroidUtilities.callOverridePendingTransition(this, R.anim.slide_left_in, R.anim.slide_left_out); return; } refreshSettingsPage(); finish(); }
public static Plugin[] findPlugins(List<StackTraceElement> stackTrace) { Plugin[] plugins = Bukkit.getServer().getPluginManager().getPlugins(); String[] packages = new String[plugins.length]; int i; for (i = 0; i < plugins.length; i++) { packages[i] = plugins[i].getDescription().getMain().toLowerCase(); packages[i] = packages[i].substring(0, packages[i].lastIndexOf('.')); } LinkedHashSet<Plugin> found = new LinkedHashSet<Plugin>(3); for (StackTraceElement elem : stackTrace) { String className = elem.getClassName().toLowerCase(); for (i = 0; i < plugins.length; i++) { if (className.startsWith(packages[i])) { found.add(plugins[i]); } } } return found.toArray(new Plugin[0]); }
public static Plugin[] findPlugins(List<StackTraceElement> stackTrace) { Plugin[] plugins = Bukkit.getServer().getPluginManager().getPlugins(); String[] packages = new String[plugins.length]; int i; for (i = 0; i < plugins.length; i++) { packages[i] = plugins[i].getDescription().getMain().toLowerCase(); int packidx = packages[i].lastIndexOf('.'); if (packidx == -1) { packages[i] = ""; } else { packages[i] = packages[i].substring(0, packidx); } } LinkedHashSet<Plugin> found = new LinkedHashSet<Plugin>(3); for (StackTraceElement elem : stackTrace) { String className = elem.getClassName().toLowerCase(); for (i = 0; i < plugins.length; i++) { if (packages[i].isEmpty()) { if (!className.contains(".")) { found.add(plugins[i]); } } else { if (className.startsWith(packages[i])) { found.add(plugins[i]); } } } } return found.toArray(new Plugin[0]); }
public ArrayList<Mouvement> moveEntity(Entity e, Position dirP) { this.run = true; Position oldP = this.getPosition(e); ArrayList<Mouvement> mouv = new ArrayList<Mouvement>(); for (int i = 0; i != this.getMovable(e); i++) { Position newP = PosOperation.sum(oldP, dirP); if (i > this.getBoost(e)) { e.getComponent(Pusher.class).setPusher(true); } if (this.positionIsVoid(newP)) { Square s = index.getSquare(newP.getX(), newP.getY()); if (this.testStopOnPlate(e, s)) { mouv.add(runValideMove(oldP, newP, e)); if (this.getBoost(e) != 20) { e.getComponent(Pusher.class).setPusher(false); } return mouv; } if (!this.testBlockedPlate(e, s)) { mouv.add(runValideMove(oldP, newP, e)); } } else { if (this.isPusherEntity(e)) { ArrayList<Entity> aNextE = index.getSquare(newP.getX(), newP.getY()).getWith(Pushable.class); if (!aNextE.isEmpty()) { Entity nextE = aNextE.get(0); if (this.isPushableEntity(nextE)) { mouv.addAll(this.moveEntity(nextE, dirP)); mouv.add(runValideMove(oldP, newP, e)); } } } if (this.getBoost(e) != 20) { e.getComponent(Pusher.class).setPusher(false); } return mouv; } } return mouv; }
public ArrayList<Mouvement> moveEntity(Entity e, Position dirP) { this.run = true; Position oldP = this.getPosition(e); ArrayList<Mouvement> mouv = new ArrayList<Mouvement>(); for (int i = 0; i != this.getMovable(e); i++) { Position newP = PosOperation.sum(oldP, dirP); if (i > this.getBoost(e)) { e.getComponent(Pusher.class).setPusher(true); } if (this.positionIsVoid(newP)) { Square s = index.getSquare(newP.getX(), newP.getY()); if (this.testStopOnPlate(e, s)) { mouv.add(runValideMove(oldP, newP, e)); if (this.getBoost(e) != 20) { e.getComponent(Pusher.class).setPusher(false); } return mouv; } if (!this.testBlockedPlate(e, s)) { mouv.add(runValideMove(oldP, newP, e)); } } else { if (this.isPusherEntity(e)) { ArrayList<Entity> aNextE = index.getSquare(newP.getX(), newP.getY()).getWith(Pushable.class); if (!aNextE.isEmpty()) { Entity nextE = aNextE.get(0); if (this.isPushableEntity(nextE)) { ArrayList<Mouvement> recMouv = this.moveEntity(nextE, dirP); if(recMouv.size() != 0) { mouv.addAll(recMouv); mouv.add(runValideMove(oldP, newP, e)); } } } } if (this.getBoost(e) != 20) { e.getComponent(Pusher.class).setPusher(false); } return mouv; } } return mouv; }
public Parser getParser(final MyInfo myInfo, final IrcAddress address) { final ServerInfo info = new ServerInfo(address.getServer(), address.getPort(6667), address.getPassword()); info.setSSL(address.isSSL()); if ("irc-test".equals(address.getProtocol())) { try { return (Parser) Class.forName("com.dmdirc.harness.parser.TestParser") .getConstructor(MyInfo.class, ServerInfo.class) .newInstance(myInfo, info); } catch (Exception ex) { Logger.userError(ErrorLevel.UNKNOWN, "Unable to create parser", ex); } } if (address.getProtocol() != null) { try { final Service service = PluginManager.getPluginManager().getService("parser", address.getProtocol()); if (service != null) { final ServiceProvider provider = service.getProviders().get(0); if (provider != null) { provider.activateServices(); final ExportedService exportService = provider.getExportedService("getParser"); final Object obj = exportService.execute(myInfo, address); if (obj != null && obj instanceof Parser) { return (Parser)obj; } else { Logger.userError(ErrorLevel.UNKNOWN, "Unable to create parser for: " + address.getProtocol()); } } } } catch (NoSuchProviderException nspe) { Logger.userError(ErrorLevel.UNKNOWN, "No parser found for: " + address.getProtocol()); } } return new IRCParser(myInfo, info); }
public Parser getParser(final MyInfo myInfo, final IrcAddress address) { final ServerInfo info = new ServerInfo(address.getServer(), address.getPort(6667), address.getPassword()); info.setSSL(address.isSSL()); if ("irc-test".equals(address.getProtocol())) { try { return (Parser) Class.forName("com.dmdirc.harness.parser.TestParser") .getConstructor(MyInfo.class, ServerInfo.class) .newInstance(myInfo, info); } catch (Exception ex) { Logger.userError(ErrorLevel.UNKNOWN, "Unable to create parser", ex); } } if (address.getProtocol() != null) { try { final Service service = PluginManager.getPluginManager().getService("parser", address.getProtocol()); if (service != null && !service.getProviders().isEmpty()) { final ServiceProvider provider = service.getProviders().get(0); if (provider != null) { provider.activateServices(); final ExportedService exportService = provider.getExportedService("getParser"); final Object obj = exportService.execute(myInfo, address); if (obj != null && obj instanceof Parser) { return (Parser)obj; } else { Logger.userError(ErrorLevel.UNKNOWN, "Unable to create parser for: " + address.getProtocol()); } } } } catch (NoSuchProviderException nspe) { Logger.userError(ErrorLevel.UNKNOWN, "No parser found for: " + address.getProtocol()); } } return new IRCParser(myInfo, info); }
protected void setTotalMoneyRaised(String totalMoney) { int len = totalMoney.length(); char type = totalMoney.charAt(len - 1); double mult = 1; if (!Character.isDigit(type)) { type = Character.toLowerCase(type); totalMoney = totalMoney.substring(1, len - 1); if (type == 'm') { mult = 1e6; } else if (type == 'b') { mult = 1e9; } else if (type == 'k') { mult = 1e3; } } StringBuffer sb = new StringBuffer(); for (char c : totalMoney.toCharArray()) { if (Character.isDigit(c) || c == '.') { sb.append(c); } } _totalMoneyRaised = Double.parseDouble(sb.toString()) * mult; }
protected void setTotalMoneyRaised(String totalMoney) { int len = totalMoney.length(); char type = totalMoney.charAt(len - 1); double mult = 1; if (!Character.isDigit(type)) { type = Character.toLowerCase(type); totalMoney = totalMoney.substring(1, len - 1); if (type == 'm') { mult = 1000000; } else if (type == 'b') { mult = 1000000000; } else if (type == 'k') { mult = 1000; } } StringBuffer sb = new StringBuffer(); for (char c : totalMoney.toCharArray()) { if (Character.isDigit(c) || c == '.') { sb.append(c); } } _totalMoneyRaised = Double.parseDouble(sb.toString()) * mult; }
public void onBindView(View view) { super.onBindView(view); final TextView scanning = (TextView) view.findViewById(R.id.scanning_text); final View progressBar = view.findViewById(R.id.scanning_progress); scanning.setText(mProgress ? R.string.progress_scanning : R.string.progress_tap_to_pair); boolean noDeviceFound = (getPreferenceCount() == 0 || (getPreferenceCount() == 1 && getPreference(0) == mNoDeviceFoundPreference)); scanning.setVisibility(noDeviceFound ? View.GONE : View.VISIBLE); progressBar.setVisibility(mProgress ? View.VISIBLE : View.GONE); if (mProgress || !noDeviceFound) { if (mNoDeviceFoundAdded) { removePreference(mNoDeviceFoundPreference); mNoDeviceFoundAdded = false; } } else { if (!mNoDeviceFoundAdded) { if (mNoDeviceFoundPreference == null) { mNoDeviceFoundPreference = new Preference(getContext()); mNoDeviceFoundPreference.setLayoutResource(R.layout.preference_empty_list); mNoDeviceFoundPreference.setTitle(R.string.bluetooth_no_devices_found); mNoDeviceFoundPreference.setSelectable(false); } addPreference(mNoDeviceFoundPreference); mNoDeviceFoundAdded = true; } } }
public void onBindView(View view) { super.onBindView(view); final View progressBar = view.findViewById(R.id.scanning_progress); boolean noDeviceFound = (getPreferenceCount() == 0 || (getPreferenceCount() == 1 && getPreference(0) == mNoDeviceFoundPreference)); progressBar.setVisibility(mProgress ? View.VISIBLE : View.GONE); if (mProgress || !noDeviceFound) { if (mNoDeviceFoundAdded) { removePreference(mNoDeviceFoundPreference); mNoDeviceFoundAdded = false; } } else { if (!mNoDeviceFoundAdded) { if (mNoDeviceFoundPreference == null) { mNoDeviceFoundPreference = new Preference(getContext()); mNoDeviceFoundPreference.setLayoutResource(R.layout.preference_empty_list); mNoDeviceFoundPreference.setTitle(R.string.bluetooth_no_devices_found); mNoDeviceFoundPreference.setSelectable(false); } addPreference(mNoDeviceFoundPreference); mNoDeviceFoundAdded = true; } } }
public void reportError(RecognitionException exception) { hasFoundError = true; for (IErrorLogger logger : errorLoggers) { logger.log(new TSPHPException(exception)); } }
public void reportError(RecognitionException exception) { hasFoundError = true; for (IErrorLogger logger : errorLoggers) { logger.log(new TSPHPException("Line " + exception.line + "|" + exception.charPositionInLine + " translator php 5.4 exception occured. Unexpected token: " + exception.token.getText(), exception)); } }