input
stringlengths
20
285k
output
stringlengths
20
285k
public View getView(int position, View convertView, ViewGroup parent) { TwoLineListItem view = (convertView != null) ? (TwoLineListItem) convertView : createView(parent); String name = getDirectory(position).getName(); view.getText1().setText(name); if (name != null && name.equals(SettingsStorage.getInstance().getCurrentConfiguration())) { view.getText1().setTextColor(view.getResources().getColor(R.color.cputuner_green)); } StringBuilder savedAtStr = new StringBuilder(); savedAtStr.append(parent.getResources().getText(R.string.saved_at)).append(" "); savedAtStr.append(SettingsStorage.getInstance().getSimpledateformat().format(new Date(getNewestFile(position)))); view.getText2().setText(savedAtStr); return view; }
public View getView(int position, View convertView, ViewGroup parent) { TwoLineListItem view = (convertView != null) ? (TwoLineListItem) convertView : createView(parent); String name = getDirectory(position).getName(); view.getText1().setText(name); if (name != null && name.equals(SettingsStorage.getInstance().getCurrentConfiguration())) { view.getText1().setTextColor(view.getResources().getColor(R.color.cputuner_green)); } else { view.getText1().setTextColor(view.getResources().getColor(android.R.color.white)); } StringBuilder savedAtStr = new StringBuilder(); savedAtStr.append(parent.getResources().getText(R.string.saved_at)).append(" "); savedAtStr.append(SettingsStorage.getInstance().getSimpledateformat().format(new Date(getNewestFile(position)))); view.getText2().setText(savedAtStr); return view; }
public boolean isFullyConfigured() { boolean fullyConfigured = consumerKey != null && consumerSecret != null && !consumerKey.isEmpty() && !consumerSecret.isEmpty(); fullyConfigured = false; if (!fullyConfigured) { logger.warn("No configuration for Twitter found.\n" + "The search service is disabled and will only return mock data!\n" + "Please provide 'consumerKey' and 'consumerSecret' variables as environment variable OR as system property."); } else { logger.info("Found Twitter access tokes (consumerKey and consumerSecret)."); } return fullyConfigured; }
public boolean isFullyConfigured() { boolean fullyConfigured = consumerKey != null && consumerSecret != null && !consumerKey.isEmpty() && !consumerSecret.isEmpty(); if (!fullyConfigured) { logger.warn("No configuration for Twitter found.\n" + "The search service is disabled and will only return mock data!\n" + "Please provide 'consumerKey' and 'consumerSecret' variables as environment variable OR as system property."); } else { logger.info("Found Twitter access tokes (consumerKey and consumerSecret)."); } return fullyConfigured; }
public static String getAbsoluteURI(String urlString, String base) throws TransformerException { boolean isAbsouteUrl = false; boolean needToResolve = false; if (urlString.indexOf(':') > 0) { isAbsouteUrl = true; } else if (urlString.startsWith(File.separator)) { urlString = "file://" + urlString; isAbsouteUrl = true; } if ((!isAbsouteUrl) && ((null == base) || (base.indexOf(':') < 0))) { if (base != null && base.startsWith(File.separator)) base = "file://" + base; else base = getAbsoluteURIFromRelative(base); } if ((null != base) && needToResolve) { if(base.equals(urlString)) { base = ""; } else { urlString = urlString.substring(5); isAbsouteUrl = false; } } if (null != base && (base.indexOf('\\') > -1)) base = base.replace('\\', '/'); if (null != urlString && (urlString.indexOf('\\') > -1)) urlString = urlString.replace('\\', '/'); URI uri; try { if ((null == base) || (base.length() == 0) || (isAbsouteUrl)) { uri = new URI(urlString); } else { URI baseURI = new URI(base); uri = new URI(baseURI, urlString); } } catch (MalformedURIException mue) { throw new TransformerException(mue); } String uriStr = uri.toString(); if((Character.isLetter(uriStr.charAt(0)) && (uriStr.charAt(1) == ':') && (uriStr.charAt(2) == '/') && (uriStr.charAt(3) != '/')) || ((uriStr.charAt(0) == '/') && (uriStr.charAt(1) != '/'))) { uriStr = "file:///"+uriStr; } return uriStr; }
public static String getAbsoluteURI(String urlString, String base) throws TransformerException { boolean isAbsouteUrl = false; boolean needToResolve = false; if (urlString.indexOf(':') > 0) { isAbsouteUrl = true; } else if (urlString.startsWith(File.separator)) { urlString = "file://" + urlString; isAbsouteUrl = true; } if ((!isAbsouteUrl) && ((null == base) || (base.indexOf(':') < 0))) { if (base != null && base.startsWith(File.separator)) base = "file://" + base; else base = getAbsoluteURIFromRelative(base); } if ((null != base) && needToResolve) { if(base.equals(urlString)) { base = ""; } else { urlString = urlString.substring(5); isAbsouteUrl = false; } } if (null != base && (base.indexOf('\\') > -1)) base = base.replace('\\', '/'); if (null != urlString && (urlString.indexOf('\\') > -1)) urlString = urlString.replace('\\', '/'); URI uri; try { if ((null == base) || (base.length() == 0) || (isAbsouteUrl)) { uri = new URI(urlString); } else { URI baseURI = new URI(base); uri = new URI(baseURI, urlString); } } catch (MalformedURIException mue) { throw new TransformerException(mue); } String uriStr = uri.toString(); if((Character.isLetter(uriStr.charAt(0)) && (uriStr.charAt(1) == ':') && (uriStr.charAt(2) == '/') && (uriStr.length() == 3 || uriStr.charAt(3) != '/')) || ((uriStr.charAt(0) == '/') && (uriStr.length() == 1 || uriStr.charAt(1) != '/'))) { uriStr = "file:///"+uriStr; } return uriStr; }
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){ if (cmd.getName().equalsIgnoreCase("MonsterFaces")) { if (args.length == 0) { sender.sendMessage("["+label+"] Subcommands: config"); } else { if (args[0].equalsIgnoreCase("config")) { if (args.length == 1) { sender.sendMessage("["+label+":config] Subcommands: get, set, reload"); } else { if (args[1].equalsIgnoreCase("get") || args[1].equalsIgnoreCase("view")) { if (sender.hasPermission("monsterfaces.config.get")) { if (args.length == 2) { sender.sendMessage("["+label+":config:get] Config variable: Playername, Rate"); } else if (args.length == 3) { sender.sendMessage("["+label+":config:get] "+args[2].toLowerCase()+": "+config.get(args[2].toLowerCase())); } else { sender.sendMessage("["+label+":config:get] Too many params!"); } } else { sender.sendMessage("["+label+":config:get] You don't have permission to use that command"); } } else if (args[1].equalsIgnoreCase("set")) { if (sender.hasPermission("monsterfaces.config.set")) { if (args.length == 2 || args.length == 3) { sender.sendMessage("["+label+":config:set] Config variables: Playername"); } else if (args.length == 4) { if (args[2].equalsIgnoreCase("playername")) { config.set("playername", args[3]); } else if (args[2].equalsIgnoreCase("rate")) { try { config.set("rate", Integer.parseInt(args[3])); } catch (NumberFormatException e) { sender.sendMessage("["+label+":config:set] ERROR: Can not convert "+args[3].toLowerCase()+" to a number"); } } else { config.set(args[2].toLowerCase(), args[3]); } saveConfig(); sender.sendMessage("["+label+":config:set] "+args[2].toLowerCase()+": "+config.get(args[2].toLowerCase())); } else { sender.sendMessage("["+label+":config:set] Too many params!"); } } else { sender.sendMessage("["+label+":config:set] You don't have permission to use that command"); } } else if (args[1].equalsIgnoreCase("reload")) { if (sender.hasPermission("monsterfaces.config.set")) { reloadConfig(); initConfig(false); sender.sendMessage("["+label+":config:reload] Config reloaded"); } else { sender.sendMessage("["+label+":config:reload] You don't have permission to use that command"); } } else { sender.sendMessage("["+label+":config:??] Invalid subcommand"); } } } else { sender.sendMessage("["+label+":??] Invalid subcommand"); } } return true; } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){ if (cmd.getName().equalsIgnoreCase("MonsterFaces")) { if (args.length == 0) { sender.sendMessage("["+label+"] Subcommands: config"); } else { if (args[0].equalsIgnoreCase("config")) { if (args.length == 1) { sender.sendMessage("["+label+":config] Subcommands: get, set, reload"); } else { if (args[1].equalsIgnoreCase("get") || args[1].equalsIgnoreCase("view")) { if (sender.hasPermission("monsterfaces.config.get")) { if (args.length == 2) { sender.sendMessage("["+label+":config:get] Config variable: Playername, Rate"); } else if (args.length == 3) { sender.sendMessage("["+label+":config:get] "+args[2].toLowerCase()+": "+config.get(args[2].toLowerCase())); } else { sender.sendMessage("["+label+":config:get] Too many params!"); } } else { sender.sendMessage("["+label+":config:get] You don't have permission to use that command"); } } else if (args[1].equalsIgnoreCase("set")) { if (sender.hasPermission("monsterfaces.config.set")) { if (args.length == 2 || args.length == 3) { sender.sendMessage("["+label+":config:set] Config variables: Playername"); } else if (args.length == 4) { if (args[2].equalsIgnoreCase("playername")) { config.set("playername", args[3]); } else if (args[2].equalsIgnoreCase("rate")) { try { config.set("rate", Double.parseDouble(args[3])); } catch (NumberFormatException e) { sender.sendMessage("["+label+":config:set] ERROR: Can not convert "+args[3].toLowerCase()+" to a number"); } } else { config.set(args[2].toLowerCase(), args[3]); } saveConfig(); sender.sendMessage("["+label+":config:set] "+args[2].toLowerCase()+": "+config.get(args[2].toLowerCase())); } else { sender.sendMessage("["+label+":config:set] Too many params!"); } } else { sender.sendMessage("["+label+":config:set] You don't have permission to use that command"); } } else if (args[1].equalsIgnoreCase("reload")) { if (sender.hasPermission("monsterfaces.config.set")) { reloadConfig(); initConfig(false); sender.sendMessage("["+label+":config:reload] Config reloaded"); } else { sender.sendMessage("["+label+":config:reload] You don't have permission to use that command"); } } else { sender.sendMessage("["+label+":config:??] Invalid subcommand"); } } } else { sender.sendMessage("["+label+":??] Invalid subcommand"); } } return true; } return false; }
void merge(ProfileReportImpl report) { if (report.taskCounters != null) { if (taskCounters == null) { taskCounters = new HashMap<String,Long>(report.taskCounters); } else { for (Map.Entry<String,Long> e : report.taskCounters.entrySet()) { Long curCount = taskCounters.get(e.getKey()); taskCounters.put(e.getKey(), (curCount == null) ? e.getValue() : curCount + e.getValue()); } } } if (report.localSamples != null) { if (localSamples == null) { localSamples = new HashMap<String,List<Long>>(); for (Map.Entry<String,List<Long>> e : report.localSamples.entrySet()) { List<Long> samples = new LinkedList<Long>(e.getValue()); localSamples.put(e.getKey(), samples); } } else { for (Map.Entry<String,List<Long>> e : report.localSamples.entrySet()) { List<Long> samples = localSamples.get(e.getKey()); if (samples == null) localSamples.put(e.getKey(), new LinkedList<Long>(e.getValue())); else samples.addAll(e.getValue()); } } } if (report.ops != null) { if (ops == null) { ops = new LinekdList<ProfileOperation>(report.ops); } else { ops.addAll(report.ops); } } }
void merge(ProfileReportImpl report) { if (report.taskCounters != null) { if (taskCounters == null) { taskCounters = new HashMap<String,Long>(report.taskCounters); } else { for (Map.Entry<String,Long> e : report.taskCounters.entrySet()) { Long curCount = taskCounters.get(e.getKey()); taskCounters.put(e.getKey(), (curCount == null) ? e.getValue() : curCount + e.getValue()); } } } if (report.localSamples != null) { if (localSamples == null) { localSamples = new HashMap<String,List<Long>>(); for (Map.Entry<String,List<Long>> e : report.localSamples.entrySet()) { List<Long> samples = new LinkedList<Long>(e.getValue()); localSamples.put(e.getKey(), samples); } } else { for (Map.Entry<String,List<Long>> e : report.localSamples.entrySet()) { List<Long> samples = localSamples.get(e.getKey()); if (samples == null) localSamples.put(e.getKey(), new LinkedList<Long>(e.getValue())); else samples.addAll(e.getValue()); } } } if (report.ops != null) { if (ops == null) { ops = new LinkedList<ProfileOperation>(report.ops); } else { ops.addAll(report.ops); } } }
public static byte[] patchEntityRenderer(String name, byte[] bytes, boolean obfuscated) { String targetMethodName = ""; if (obfuscated) targetMethodName ="i"; else targetMethodName ="updateFogColor"; ClassNode classNode = new ClassNode(); ClassReader classReader = new ClassReader(bytes); classReader.accept(classNode, 0); Iterator<MethodNode> methods = classNode.methods.iterator(); while (methods.hasNext()) { MethodNode m = methods.next(); int fdiv_index = -1; if (m.name.equals(targetMethodName) && (m.desc.equals("(F)V"))) { AbstractInsnNode currentNode = null; AbstractInsnNode targetNode = null; Iterator<AbstractInsnNode> iter = m.instructions.iterator(); int index = -1; int timesFound = 0; while (iter.hasNext()) { index++; currentNode = iter.next(); if (currentNode.getOpcode() == INVOKEVIRTUAL) { if (timesFound == 1) { targetNode = currentNode; fdiv_index = index; break; } else { timesFound++; } } } InsnList toInject = new InsnList(); toInject.add(new VarInsnNode(ALOAD, 3)); toInject.add(new VarInsnNode(ALOAD, 2)); toInject.add(new VarInsnNode(FLOAD, 1)); toInject.add(new MethodInsnNode(INVOKESTATIC, "biomesoplenty/asm/BOPFogColour", "getFogVec", "(Lnn;Labw;F)Latc;")); toInject.add(new VarInsnNode(ASTORE, 9)); m.instructions.insert(m.instructions.get(fdiv_index + 1), toInject); List<AbstractInsnNode> remNodes = new ArrayList(); for (int i = -2; i <= 1; i++) { remNodes.add(m.instructions.get(fdiv_index + i)); } for (AbstractInsnNode remNode : remNodes) { m.instructions.remove(remNode); } break; } } ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); classNode.accept(writer); return writer.toByteArray(); }
public static byte[] patchEntityRenderer(String name, byte[] bytes, boolean obfuscated) { String targetMethodName = ""; if (obfuscated) targetMethodName ="i"; else targetMethodName ="updateFogColor"; ClassNode classNode = new ClassNode(); ClassReader classReader = new ClassReader(bytes); classReader.accept(classNode, 0); Iterator<MethodNode> methods = classNode.methods.iterator(); while (methods.hasNext()) { MethodNode m = methods.next(); int fdiv_index = -1; if (m.name.equals(targetMethodName) && (m.desc.equals("(F)V"))) { AbstractInsnNode currentNode = null; AbstractInsnNode targetNode = null; Iterator<AbstractInsnNode> iter = m.instructions.iterator(); int index = -1; int timesFound = 0; while (iter.hasNext()) { index++; currentNode = iter.next(); if (currentNode.getOpcode() == INVOKEVIRTUAL) { if (timesFound == 1) { targetNode = currentNode; fdiv_index = index; break; } else { timesFound++; } } } InsnList toInject = new InsnList(); toInject.add(new VarInsnNode(ALOAD, 3)); toInject.add(new VarInsnNode(ALOAD, 2)); toInject.add(new VarInsnNode(FLOAD, 1)); if (obfuscated) toInject.add(new MethodInsnNode(INVOKESTATIC, "biomesoplenty/asm/BOPFogColour", "getFogVec", "(Lnn;Labw;F)Latc;")); else toInject.add(new MethodInsnNode(INVOKESTATIC, "biomesoplenty/asm/BOPFogColour", "getFogVec", "(Lnet/minecraft/entity/Entity;Lnet/minecraft/world/World;F)Lnet/minecraft/util/Vec3;")); toInject.add(new VarInsnNode(ASTORE, 9)); m.instructions.insert(m.instructions.get(fdiv_index + 1), toInject); List<AbstractInsnNode> remNodes = new ArrayList(); for (int i = -2; i <= 1; i++) { remNodes.add(m.instructions.get(fdiv_index + i)); } for (AbstractInsnNode remNode : remNodes) { m.instructions.remove(remNode); } break; } } ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); classNode.accept(writer); return writer.toByteArray(); }
private DateField createDateField(final DateWidgetElement dwe) { SimpleDateFormat sdf; try { sdf = new SimpleDateFormat(dwe.getFormat()); } catch (Exception e) { logException(getMessage("processdata.block.error.unparsable.format").replaceFirst("%s", dwe.getFormat()), e); return null; } final PopupDateField field = new PopupDateField(); field.setDateFormat(dwe.getFormat()); field.setResolution(dwe.getShowMinutes() != null && dwe.getShowMinutes() ? DateField.RESOLUTION_MIN : DateField.RESOLUTION_DAY); if (hasText(dwe.getNotAfter())) { try { final Date notAfter = XmlConstants.DATE_CURRENT.equalsIgnoreCase(dwe.getNotAfter()) ? new Date() : sdf.parse(dwe.getNotAfter()); field.addListener(new ValueChangeListener() { @Override public void valueChange(ValueChangeEvent event) { Object value = event.getProperty().getValue(); if (value != null && value instanceof Date) { if (notAfter.before((Date) value)) { VaadinUtility.validationNotification(getApplication(), i18NSource, getMessage("processdata.block.error.date.notafter").replaceFirst("%s", dwe.getNotAfter())); field.setValue(notAfter); } } } }); } catch (ParseException e) { logException(getMessage("processdata.block.error.unparsable.date").replaceFirst("%s", dwe.getNotAfter()), e); } } if (hasText(dwe.getNotBefore())) { try { final Date notBefore = XmlConstants.DATE_CURRENT.equalsIgnoreCase(dwe.getNotBefore()) ? new Date() : sdf.parse(dwe.getNotBefore()); field.addListener(new ValueChangeListener() { @Override public void valueChange(ValueChangeEvent event) { Object value = event.getProperty().getValue(); if (value != null && value instanceof Date) { if (notBefore.after((Date) value)) { VaadinUtility.validationNotification(getApplication(), i18NSource, getMessage("processdata.block.error.date.notbefore").replaceFirst("%s", dwe.getNotAfter())); field.setValue(notBefore); } } } }); } catch (ParseException e) { logException(getMessage("processdata.block.error.unparsable.date").replaceFirst("%s", dwe.getNotBefore()), e); } } if (nvl(dwe.getRequired(), false)) { field.setRequired(true); if (hasText(dwe.getCaption())) { field.setRequiredError(getMessage("processdata.block.field-required-error") + " " + dwe.getCaption()); } else { field.setRequiredError(getMessage("processdata.block.field-required-error")); } } return field; }
private DateField createDateField(final DateWidgetElement dwe) { SimpleDateFormat sdf; try { sdf = new SimpleDateFormat(dwe.getFormat()); } catch (Exception e) { logException(getMessage("processdata.block.error.unparsable.format").replaceFirst("%s", dwe.getFormat()), e); return null; } final PopupDateField field = new PopupDateField(); field.setDateFormat(dwe.getFormat()); field.setResolution(dwe.getShowMinutes() != null && dwe.getShowMinutes() ? DateField.RESOLUTION_MIN : DateField.RESOLUTION_DAY); if (hasText(dwe.getNotAfter())) { try { final Date notAfter = XmlConstants.DATE_CURRENT.equalsIgnoreCase(dwe.getNotAfter()) ? new Date() : sdf.parse(dwe.getNotAfter()); field.addListener(new ValueChangeListener() { @Override public void valueChange(ValueChangeEvent event) { Object value = event.getProperty().getValue(); if (value != null && value instanceof Date) { if (notAfter.before((Date) value)) { VaadinUtility.validationNotification(getApplication(), i18NSource, getMessage("processdata.block.error.date.notafter").replaceFirst("%s", dwe.getNotAfter())); field.setValue(notAfter); } } } }); } catch (ParseException e) { logException(getMessage("processdata.block.error.unparsable.date").replaceFirst("%s", dwe.getNotAfter()), e); } } if (hasText(dwe.getNotBefore())) { try { final Date notBefore = XmlConstants.DATE_CURRENT.equalsIgnoreCase(dwe.getNotBefore()) ? new Date() : sdf.parse(dwe.getNotBefore()); field.addListener(new ValueChangeListener() { @Override public void valueChange(ValueChangeEvent event) { Object value = event.getProperty().getValue(); if (value != null && value instanceof Date) { if (notBefore.after((Date) value)) { VaadinUtility.validationNotification(getApplication(), i18NSource, getMessage("processdata.block.error.date.notbefore").replaceFirst("%s", dwe.getNotBefore())); field.setValue(notBefore); } } } }); } catch (ParseException e) { logException(getMessage("processdata.block.error.unparsable.date").replaceFirst("%s", dwe.getNotBefore()), e); } } if (nvl(dwe.getRequired(), false)) { field.setRequired(true); if (hasText(dwe.getCaption())) { field.setRequiredError(getMessage("processdata.block.field-required-error") + " " + dwe.getCaption()); } else { field.setRequiredError(getMessage("processdata.block.field-required-error")); } } return field; }
public void update(com.jme3.system.Timer timer, Team currentTeam) { if (isCountdownStarted()) { if (timer.getTimeInSeconds() >= 5) { currentTeam.getCurrentPlayer().setCanShoot(true); map.shootTarget(); setTimerText(""); timer.reset(); setIsCountdownStarted(false); } else if (timer.getTimeInSeconds() >= 4 && timerCount == 0) { start(); } else if (timer.getTimeInSeconds() >= 3 && timerCount == 1) { count("1"); } else if (timer.getTimeInSeconds() >= 2 && timerCount == 2) { count("2"); } else if (timer.getTimeInSeconds() >= 1 && timerCount == 3) { count("3"); } } else { timer.reset(); } }
public void update(com.jme3.system.Timer timer, Team currentTeam) { if (isCountdownStarted()) { if (timer.getTimeInSeconds() >= 5) { currentTeam.getCurrentPlayer().setCanShoot(true); map.shootTarget(); setTimerText(""); timer.reset(); setIsCountdownStarted(false); } else if (timer.getTimeInSeconds() >= 4 && timerCount == 0) { start(); } else if (timer.getTimeInSeconds() >= 3 && timerCount == 1) { count("1"); } else if (timer.getTimeInSeconds() >= 2 && timerCount == 2) { count("2"); } else if (timer.getTimeInSeconds() >= 1 && timerCount == 3) { count("3"); } } else { timerCount = 3; timer.reset(); } }
public AxisService buildAxisService(SynapseConfiguration synCfg, AxisConfiguration axisCfg) { AxisService proxyService = null; InputStream wsdlInputStream = null; OMElement wsdlElement = null; if (wsdlKey != null) { Object keyObject = synCfg.getEntry(wsdlKey); if (keyObject instanceof OMElement) { wsdlElement = (OMElement) keyObject; } } else if (inLineWSDL != null) { wsdlElement = (OMElement) inLineWSDL; } else if (wsdlURI != null) { try { URL url = wsdlURI.toURL(); if (url != null) { URLConnection urlc = url.openConnection(); try { if (urlc != null) { XMLStreamReader parser = XMLInputFactory.newInstance(). createXMLStreamReader(urlc.getInputStream()); StAXOMBuilder builder = new StAXOMBuilder(parser); wsdlElement = builder.getDocumentElement(); wsdlElement.build(); } } catch (XMLStreamException e) { log.warn("Content at URL : " + url + " is non XML.."); } } } catch (MalformedURLException e) { handleException("Malformed URI for wsdl", e); } catch (IOException e) { handleException("Error reading from wsdl URI", e); } } if (wsdlElement != null) { OMNamespace wsdlNamespace = wsdlElement.getNamespace(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { wsdlElement.serialize(baos); wsdlInputStream = new ByteArrayInputStream(baos.toByteArray()); } catch (XMLStreamException e) { handleException("Error converting to a StreamSource", e); } if (wsdlInputStream != null) { try { if (wsdlNamespace != null) { WSDLToAxisServiceBuilder wsdlToAxisServiceBuilder = null; if (WSDL2Constants.WSDL_NAMESPACE. equals(wsdlNamespace.getNamespaceURI())) { wsdlToAxisServiceBuilder = new WSDL20ToAxisServiceBuilder(wsdlInputStream, null, null); } else if (org.apache.axis2.namespace.Constants.NS_URI_WSDL11. equals(wsdlNamespace.getNamespaceURI())) { wsdlToAxisServiceBuilder = new WSDL11ToAxisServiceBuilder(wsdlInputStream, null, null); } else { handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0"); } if (wsdlToAxisServiceBuilder == null) { throw new SynapseException( "Could not get the WSDL to Axis Service Builder"); } proxyService = wsdlToAxisServiceBuilder.populateService(); proxyService.setWsdlFound(true); } else { handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0"); } } catch (AxisFault af) { handleException("Error building service from WSDL", af); } catch (IOException ioe) { handleException("Error reading WSDL", ioe); } } } else { proxyService = new AxisService(); AxisOperation mediateOperation = new InOutAxisOperation(new QName("mediate")); proxyService.addOperation(mediateOperation); } if (proxyService == null) { throw new SynapseException("Could not create a proxy service"); } proxyService.setName(name); if (description != null) { proxyService.setServiceDescription(description); } if (transports == null || transports.size() == 0) { } else { proxyService.setExposedTransports(transports); } Iterator iter = parameters.keySet().iterator(); while (iter.hasNext()) { String name = (String) iter.next(); Object value = parameters.get(name); Parameter p = new Parameter(); p.setName(name); p.setValue(value); try { proxyService.addParameter(p); } catch (AxisFault af) { handleException("Error setting parameter : " + name + "" + "to proxy service as a Parameter", af); } } if (!serviceLevelPolicies.isEmpty()) { Policy svcEffectivePolicy = null; iter = serviceLevelPolicies.iterator(); while (iter.hasNext()) { String policyKey = (String) iter.next(); Object policyProp = synCfg.getEntry(policyKey); if (policyProp != null) { if (svcEffectivePolicy == null) { svcEffectivePolicy = PolicyEngine.getPolicy( Util.getStreamSource(policyProp).getInputStream()); } else { svcEffectivePolicy = (Policy) svcEffectivePolicy.merge( PolicyEngine.getPolicy( Util.getStreamSource(policyProp).getInputStream())); } } } PolicyInclude pi = proxyService.getPolicyInclude(); if (pi != null && svcEffectivePolicy != null) { pi.addPolicyElement(PolicyInclude.AXIS_SERVICE_POLICY, svcEffectivePolicy); } } ProxyServiceMessageReceiver msgRcvr = new ProxyServiceMessageReceiver(); msgRcvr.setName(name); iter = proxyService.getOperations(); while (iter.hasNext()) { AxisOperation op = (AxisOperation) iter.next(); op.setMessageReceiver(msgRcvr); } try { axisCfg.addService(proxyService); this.setRunning(true); } catch (AxisFault axisFault) { handleException("Unable to start the Proxy Service"); } if (wsRMEnabled) { try { proxyService.engageModule(axisCfg.getModule( Constants.SANDESHA2_MODULE_NAME), axisCfg); } catch (AxisFault axisFault) { handleException("Error loading WS RM module on proxy service : " + name, axisFault); } } if (wsSecEnabled) { try { proxyService.engageModule(axisCfg.getModule( Constants.RAMPART_MODULE_NAME), axisCfg); } catch (AxisFault axisFault) { handleException("Error loading WS Sec module on proxy service : " + name, axisFault); } } return proxyService; }
public AxisService buildAxisService(SynapseConfiguration synCfg, AxisConfiguration axisCfg) { AxisService proxyService = null; InputStream wsdlInputStream = null; OMElement wsdlElement = null; if (wsdlKey != null) { Object keyObject = synCfg.getEntry(wsdlKey); if (keyObject instanceof OMElement) { wsdlElement = (OMElement) keyObject; } } else if (inLineWSDL != null) { wsdlElement = (OMElement) inLineWSDL; } else if (wsdlURI != null) { try { URL url = wsdlURI.toURL(); if (url != null) { URLConnection urlc = url.openConnection(); try { if (urlc != null) { XMLStreamReader parser = XMLInputFactory.newInstance(). createXMLStreamReader(urlc.getInputStream()); StAXOMBuilder builder = new StAXOMBuilder(parser); wsdlElement = builder.getDocumentElement(); wsdlElement.build(); } } catch (XMLStreamException e) { log.warn("Content at URL : " + url + " is non XML.."); } } } catch (MalformedURLException e) { handleException("Malformed URI for wsdl", e); } catch (IOException e) { handleException("Error reading from wsdl URI", e); } } if (wsdlElement != null) { OMNamespace wsdlNamespace = wsdlElement.getNamespace(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { wsdlElement.serialize(baos); wsdlInputStream = new ByteArrayInputStream(baos.toByteArray()); } catch (XMLStreamException e) { handleException("Error converting to a StreamSource", e); } if (wsdlInputStream != null) { try { if (wsdlNamespace != null) { WSDLToAxisServiceBuilder wsdlToAxisServiceBuilder = null; if (WSDL2Constants.WSDL_NAMESPACE. equals(wsdlNamespace.getNamespaceURI())) { wsdlToAxisServiceBuilder = new WSDL20ToAxisServiceBuilder(wsdlInputStream, null, null); } else if (org.apache.axis2.namespace.Constants.NS_URI_WSDL11. equals(wsdlNamespace.getNamespaceURI())) { wsdlToAxisServiceBuilder = new WSDL11ToAxisServiceBuilder(wsdlInputStream, null, null); } else { handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0"); } if (wsdlToAxisServiceBuilder == null) { throw new SynapseException( "Could not get the WSDL to Axis Service Builder"); } proxyService = wsdlToAxisServiceBuilder.populateService(); proxyService.setWsdlFound(true); } else { handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0"); } } catch (AxisFault af) { handleException("Error building service from WSDL", af); } catch (IOException ioe) { handleException("Error reading WSDL", ioe); } } } else { proxyService = new AxisService(); AxisOperation mediateOperation = new InOutAxisOperation(new QName("mediate")); proxyService.addOperation(mediateOperation); } if (proxyService == null) { throw new SynapseException("Could not create a proxy service"); } proxyService.setName(name); if (description != null) { proxyService.setServiceDescription(description); } if (transports == null || transports.size() == 0) { } else { proxyService.setExposedTransports(transports); } Iterator iter = parameters.keySet().iterator(); while (iter.hasNext()) { String name = (String) iter.next(); Object value = parameters.get(name); Parameter p = new Parameter(); p.setName(name); p.setValue(value); try { proxyService.addParameter(p); } catch (AxisFault af) { handleException("Error setting parameter : " + name + "" + "to proxy service as a Parameter", af); } } if (!serviceLevelPolicies.isEmpty()) { Policy svcEffectivePolicy = null; iter = serviceLevelPolicies.iterator(); while (iter.hasNext()) { String policyKey = (String) iter.next(); Object policyProp = synCfg.getEntry(policyKey); if (policyProp != null) { if (svcEffectivePolicy == null) { svcEffectivePolicy = PolicyEngine.getPolicy( Util.getStreamSource(policyProp).getInputStream()); } else { svcEffectivePolicy = (Policy) svcEffectivePolicy.merge( PolicyEngine.getPolicy( Util.getStreamSource(policyProp).getInputStream())); } } } PolicyInclude pi = proxyService.getPolicyInclude(); if (pi != null && svcEffectivePolicy != null) { pi.addPolicyElement(PolicyInclude.AXIS_SERVICE_POLICY, svcEffectivePolicy); } } ProxyServiceMessageReceiver msgRcvr = new ProxyServiceMessageReceiver(); msgRcvr.setName(name); iter = proxyService.getOperations(); while (iter.hasNext()) { AxisOperation op = (AxisOperation) iter.next(); op.setMessageReceiver(msgRcvr); } try { axisCfg.addService(proxyService); this.setRunning(true); } catch (AxisFault axisFault) { try { if (axisCfg.getService(proxyService.getName()) != null) { axisCfg.removeService(proxyService.getName()); } } catch (AxisFault ignore) {} handleException("Error adding Proxy service to the Axis2 engine"); } if (wsRMEnabled) { try { proxyService.engageModule(axisCfg.getModule( Constants.SANDESHA2_MODULE_NAME), axisCfg); } catch (AxisFault axisFault) { handleException("Error loading WS RM module on proxy service : " + name, axisFault); } } if (wsSecEnabled) { try { proxyService.engageModule(axisCfg.getModule( Constants.RAMPART_MODULE_NAME), axisCfg); } catch (AxisFault axisFault) { handleException("Error loading WS Sec module on proxy service : " + name, axisFault); } } return proxyService; }
private SipRegistrationListener createRegistrationListener() { return new SipRegistrationListener() { public void onRegistrationDone(String profileUri, long expiryTime) { showRegistrationMessage(profileUri, getString( R.string.registration_status_done)); } public void onRegistering(String profileUri) { showRegistrationMessage(profileUri, getString( R.string.registration_status_registering)); } public void onRegistrationFailed(String profileUri, int errorCode, String message) { switch (errorCode) { case SipErrorCode.IN_PROGRESS: showRegistrationMessage(profileUri, getString( R.string.registration_status_still_trying)); break; case SipErrorCode.INVALID_CREDENTIALS: showRegistrationMessage(profileUri, getString( R.string.registration_status_invalid_credentials)); break; case SipErrorCode.SERVER_UNREACHABLE: showRegistrationMessage(profileUri, getString( R.string.registration_status_server_unreachable)); break; case SipErrorCode.DATA_CONNECTION_LOST: showRegistrationMessage(profileUri, getString( R.string.registration_status_no_data)); break; case SipErrorCode.CLIENT_ERROR: showRegistrationMessage(profileUri, getString( R.string.registration_status_not_running)); break; default: showRegistrationMessage(profileUri, getString( R.string.registration_status_failed_try_later, message)); } } }; }
private SipRegistrationListener createRegistrationListener() { return new SipRegistrationListener() { public void onRegistrationDone(String profileUri, long expiryTime) { showRegistrationMessage(profileUri, getString( R.string.registration_status_done)); } public void onRegistering(String profileUri) { showRegistrationMessage(profileUri, getString( R.string.registration_status_registering)); } public void onRegistrationFailed(String profileUri, int errorCode, String message) { switch (errorCode) { case SipErrorCode.IN_PROGRESS: showRegistrationMessage(profileUri, getString( R.string.registration_status_still_trying)); break; case SipErrorCode.INVALID_CREDENTIALS: showRegistrationMessage(profileUri, getString( R.string.registration_status_invalid_credentials)); break; case SipErrorCode.SERVER_UNREACHABLE: showRegistrationMessage(profileUri, getString( R.string.registration_status_server_unreachable)); break; case SipErrorCode.DATA_CONNECTION_LOST: if (SipManager.isSipWifiOnly(getApplicationContext())){ showRegistrationMessage(profileUri, getString( R.string.registration_status_no_wifi_data)); } else { showRegistrationMessage(profileUri, getString( R.string.registration_status_no_data)); } break; case SipErrorCode.CLIENT_ERROR: showRegistrationMessage(profileUri, getString( R.string.registration_status_not_running)); break; default: showRegistrationMessage(profileUri, getString( R.string.registration_status_failed_try_later, message)); } } }; }
public void onQueueFull(Mailbox service, int queueSize, long timeout, TimeUnit unit, Object message) { long lastExceptionTime = _lastExceptionTime.get(); long firstSequenceTime = _firstSequenceTime.get(); int repeatCount = _repeatCount.get(); long now = CurrentTime.getCurrentTime(); _lastExceptionTime.set(now); if (now - lastExceptionTime < _duplicateTimeout) { _repeatCount.incrementAndGet(); } else { _repeatCount.set(0); _firstSequenceTime.set(now); firstSequenceTime = now; } _lastExceptionTime.set(now); String msg; msg = L.l("Queue full in service {0}: queue-size={1}, timeout={2}ms, start={3}, now={4}, message={5}", service, queueSize, unit.toMillis(timeout), firstSequenceTime, now, message); if (repeatCount > 0) { msg += L.l(" repeats {0} times.", repeatCount); } if (_fatalTimeout < now - firstSequenceTime) { ShutdownSystem.shutdownActive(ExitCode.NETWORK, msg); } if (repeatCount % 100 == 0 || _repeatCount.get() == 0) { log.warning(msg); } RuntimeException exn; exn = new QueueFullException(msg); throw exn; }
public void onQueueFull(Mailbox service, int queueSize, long timeout, TimeUnit unit, Object message) { long lastExceptionTime = _lastExceptionTime.get(); long firstSequenceTime = _firstSequenceTime.get(); int repeatCount = _repeatCount.get(); long now = CurrentTime.getCurrentTime(); _lastExceptionTime.set(now); if (now - lastExceptionTime < _duplicateTimeout) { _repeatCount.incrementAndGet(); } else { _repeatCount.set(0); _firstSequenceTime.set(now); firstSequenceTime = now; } _lastExceptionTime.set(now); String msg; msg = L.l("Queue full in service {0}: queue-size={1}, timeout={2}ms, full-duration={3}ms, message={4}", service, queueSize, unit.toMillis(timeout), now - firstSequenceTime, message); if (repeatCount > 0) { msg += L.l(" repeats {0} times.", repeatCount); } if (_fatalTimeout < now - firstSequenceTime) { ShutdownSystem.shutdownActive(ExitCode.NETWORK, msg); } if (repeatCount % 100 == 0 || _repeatCount.get() == 0) { log.warning(msg); } RuntimeException exn; exn = new QueueFullException(msg); throw exn; }
public MetaData() { schema = new HashMap<String, String>(); schema.put("version", Manifest.SCHEMA_VERSION); schema.put("xmlns", XSI_ADLCP_SCHEMALOC); schema.put("xmlns:adlcp", XMLNS_IMSCP); schema.put("xmlns:xsi", XMLNS_XSI); schema.put("xsi:schemalocation", XSI_IMSCP_SCHEMALOC + " " + XSI_IMSMD_SCHEMALOC + " " + XSI_ADLCP_SCHEMALOC); }
public MetaData() { schema = new HashMap<String, String>(); schema.put("version", Manifest.SCHEMA_VERSION); schema.put("xmlns", XMLNS_IMSCP); schema.put("xmlns:adlcp", XMLNS_ADLCP); schema.put("xmlns:xsi", XMLNS_XSI); schema.put("xsi:schemalocation", XSI_IMSCP_SCHEMALOC + " " + XSI_IMSMD_SCHEMALOC + " " + XSI_ADLCP_SCHEMALOC); }
protected JPanel createButtonPanel() { JPanel buttonPanel = new JPanel(new GridLayout(1, 5)); MoveUpAction moveUpAction = new MoveUpAction(); adaptTo(moveUpAction, model); adaptTo(moveUpAction,selectionModel); buttonPanel.add(new SideButton(moveUpAction)); MoveDownAction moveDownAction = new MoveDownAction(); adaptTo(moveDownAction, model); adaptTo(moveDownAction,selectionModel); buttonPanel.add(new SideButton(moveDownAction)); ActivateLayerAction activateLayerAction = new ActivateLayerAction(); adaptTo(activateLayerAction, selectionModel); adaptToLayerChanges(activateLayerAction); buttonPanel.add(new SideButton(activateLayerAction, "activate")); ShowHideLayerAction showHideLayerAction = new ShowHideLayerAction(); adaptTo(showHideLayerAction, selectionModel); buttonPanel.add(new SideButton(showHideLayerAction, "showhide")); MergeAction mergeLayerAction = new MergeAction(); adaptTo(mergeLayerAction, model); adaptTo(mergeLayerAction,selectionModel); buttonPanel.add(new SideButton(mergeLayerAction)); DeleteLayerAction deleteLayerAction = new DeleteLayerAction(); layerList.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0),"deleteLayer" ); layerList.getActionMap().put("deleteLayer", deleteLayerAction); adaptTo(deleteLayerAction, selectionModel); buttonPanel.add(new SideButton(deleteLayerAction, "delete")); return buttonPanel; }
protected JPanel createButtonPanel() { JPanel buttonPanel = new JPanel(new GridLayout(1, 5)); MoveUpAction moveUpAction = new MoveUpAction(); adaptTo(moveUpAction, model); adaptTo(moveUpAction,selectionModel); buttonPanel.add(new SideButton(moveUpAction)); MoveDownAction moveDownAction = new MoveDownAction(); adaptTo(moveDownAction, model); adaptTo(moveDownAction,selectionModel); buttonPanel.add(new SideButton(moveDownAction)); ActivateLayerAction activateLayerAction = new ActivateLayerAction(); adaptTo(activateLayerAction, selectionModel); adaptToLayerChanges(activateLayerAction); buttonPanel.add(new SideButton(activateLayerAction, "activate")); ShowHideLayerAction showHideLayerAction = new ShowHideLayerAction(); adaptTo(showHideLayerAction, selectionModel); buttonPanel.add(new SideButton(showHideLayerAction, "showhide")); MergeAction mergeLayerAction = new MergeAction(); adaptTo(mergeLayerAction, model); adaptTo(mergeLayerAction,selectionModel); buttonPanel.add(new SideButton(mergeLayerAction)); DeleteLayerAction deleteLayerAction = new DeleteLayerAction(); adaptTo(deleteLayerAction, selectionModel); buttonPanel.add(new SideButton(deleteLayerAction, "delete")); return buttonPanel; }
public void actionPerformed(final ActionEvent ae) { dispatcher.exec(new Runnable() { public void run() { String command = ae.getActionCommand(); if (command.startsWith("Job")) { if (Utils.checkYN("Really cancel job?")) { project.getLoader().quitJob(command); repairGUI(); } return; } else if (command.equals("Move to top")) { if (null == active) return; canvas.setUpdateGraphics(true); layer.getParent().move(LayerSet.TOP, active); Display.repaint(layer.getParent(), active, 5); } else if (command.equals("Move up")) { if (null == active) return; canvas.setUpdateGraphics(true); layer.getParent().move(LayerSet.UP, active); Display.repaint(layer.getParent(), active, 5); } else if (command.equals("Move down")) { if (null == active) return; canvas.setUpdateGraphics(true); layer.getParent().move(LayerSet.DOWN, active); Display.repaint(layer.getParent(), active, 5); } else if (command.equals("Move to bottom")) { if (null == active) return; canvas.setUpdateGraphics(true); layer.getParent().move(LayerSet.BOTTOM, active); Display.repaint(layer.getParent(), active, 5); } else if (command.equals("Duplicate, link and send to next layer")) { duplicateLinkAndSendTo(active, 1, layer.getParent().next(layer)); } else if (command.equals("Duplicate, link and send to previous layer")) { duplicateLinkAndSendTo(active, 0, layer.getParent().previous(layer)); } else if (command.equals("Duplicate, link and send to...")) { GenericDialog gd = new GenericDialog("Send to"); gd.addMessage("Duplicate, link and send to..."); String[] sl = new String[layer.getParent().size()]; int next = 0; for (Iterator it = layer.getParent().getLayers().iterator(); it.hasNext(); ) { sl[next++] = project.findLayerThing(it.next()).toString(); } gd.addChoice("Layer: ", sl, sl[layer.getParent().indexOf(layer)]); gd.showDialog(); if (gd.wasCanceled()) return; Layer la = layer.getParent().getLayer(gd.getNextChoiceIndex()); if (layer == la) { Utils.showMessage("Can't duplicate, link and send to the same layer."); return; } duplicateLinkAndSendTo(active, 0, la); } else if (-1 != command.indexOf("z = ")) { Layer target_layer = layer.getParent().getLayer(Double.parseDouble(command.substring(command.lastIndexOf(' ') +1))); Utils.log2("layer: __" +command.substring(command.lastIndexOf(' ') +1) + "__"); if (null == target_layer) return; duplicateLinkAndSendTo(active, 0, target_layer); } else if (-1 != command.indexOf("z=")) { int iz = command.indexOf("z=")+2; Utils.log2("iz=" + iz + " other: " + command.indexOf(' ', iz+2)); int end = command.indexOf(' ', iz); if (-1 == end) end = command.length(); double lz = Double.parseDouble(command.substring(iz, end)); Layer target = layer.getParent().getLayer(lz); layer.getParent().move(selection.getAffected(), active.getLayer(), target); } else if (command.equals("Unlink")) { if (null == active || active instanceof Patch) return; active.unlink(); updateSelection(); } else if (command.equals("Unlink from images")) { if (null == active) return; try { for (Displayable displ: selection.getSelected()) { displ.unlinkAll(Patch.class); } updateSelection(); } catch (Exception e) { IJError.print(e); } } else if (command.equals("Unlink slices")) { YesNoCancelDialog yn = new YesNoCancelDialog(frame, "Attention", "Really unlink all slices from each other?\nThere is no undo."); if (!yn.yesPressed()) return; final ArrayList<Patch> pa = ((Patch)active).getStackPatches(); for (int i=pa.size()-1; i>0; i--) { pa.get(i).unlink(pa.get(i-1)); } } else if (command.equals("Send to next layer")) { Rectangle box = selection.getBox(); try { for (final Displayable displ : selection.getSelected()) { displ.unlinkAll(Patch.class); } updateSelection(); } catch (Exception e) { IJError.print(e); } selection.moveDown(); repaint(layer.getParent(), box); } else if (command.equals("Send to previous layer")) { Rectangle box = selection.getBox(); try { for (final Displayable displ : selection.getSelected()) { displ.unlinkAll(Patch.class); } updateSelection(); } catch (Exception e) { IJError.print(e); } selection.moveUp(); repaint(layer.getParent(), box); } else if (command.equals("Show centered")) { if (active == null) return; showCentered(active); } else if (command.equals("Delete...")) { selection.deleteAll(); } else if (command.equals("Color...")) { IJ.doCommand("Color Picker..."); } else if (command.equals("Revert")) { if (null == active || active.getClass() != Patch.class) return; Patch p = (Patch)active; if (!p.revert()) { if (null == p.getOriginalPath()) Utils.log("No editions to save for patch " + p.getTitle() + " #" + p.getId()); else Utils.log("Could not revert Patch " + p.getTitle() + " #" + p.getId()); } } else if (command.equals("Remove alpha mask")) { final ArrayList<Displayable> patches = selection.getSelected(Patch.class); if (patches.size() > 0) { Bureaucrat.createAndStart(new Worker.Task("Removing alpha mask" + (patches.size() > 1 ? "s" : "")) { public void exec() { final ArrayList<Future> jobs = new ArrayList<Future>(); for (final Displayable d : patches) { final Patch p = (Patch) d; p.setAlphaMask(null); Future job = p.getProject().getLoader().regenerateMipMaps(p); if (null != job) jobs.add(job); } for (final Future job : jobs) try { job.get(); } catch (Exception ie) {} }}, patches.get(0).getProject()); } } else if (command.equals("Undo")) { Bureaucrat.createAndStart(new Worker.Task("Undo") { public void exec() { layer.getParent().undoOneStep(); Display.repaint(layer.getParent()); }}, project); } else if (command.equals("Redo")) { Bureaucrat.createAndStart(new Worker.Task("Redo") { public void exec() { layer.getParent().redoOneStep(); Display.repaint(layer.getParent()); }}, project); } else if (command.equals("Apply transform")) { canvas.applyTransform(); } else if (command.equals("Apply transform propagating to last layer")) { if (mode.getClass() == AffineTransformMode.class || mode.getClass() == NonLinearTransformMode.class) { final LayerSet ls = getLayerSet(); final HashSet<Layer> subset = new HashSet<Layer>(ls.getLayers(ls.indexOf(Display.this.layer)+1, ls.size())); if (mode.getClass() == AffineTransformMode.class) ((AffineTransformMode)mode).applyAndPropagate(subset); else if (mode.getClass() == NonLinearTransformMode.class) ((NonLinearTransformMode)mode).apply(subset); setMode(new DefaultMode(Display.this)); } } else if (command.equals("Apply transform propagating to first layer")) { if (mode.getClass() == AffineTransformMode.class || mode.getClass() == NonLinearTransformMode.class) { final LayerSet ls = getLayerSet(); final HashSet<Layer> subset = new HashSet<Layer>(ls.getLayers(0, ls.indexOf(Display.this.layer) -1)); if (mode.getClass() == AffineTransformMode.class) ((AffineTransformMode)mode).applyAndPropagate(subset); else if (mode.getClass() == NonLinearTransformMode.class) ((NonLinearTransformMode)mode).apply(subset); setMode(new DefaultMode(Display.this)); } } else if (command.equals("Cancel transform")) { canvas.cancelTransform(); } else if (command.equals("Specify transform...")) { if (null == active) return; selection.specify(); } else if (command.equals("Hide all but images")) { ArrayList<Class> type = new ArrayList<Class>(); type.add(Patch.class); type.add(Stack.class); Collection<Displayable> col = layer.getParent().hideExcept(type, false); selection.removeAll(col); Display.updateCheckboxes(col, DisplayablePanel.VISIBILITY_STATE); Display.update(layer.getParent(), false); } else if (command.equals("Unhide all")) { Display.updateCheckboxes(layer.getParent().setAllVisible(false), DisplayablePanel.VISIBILITY_STATE); Display.update(layer.getParent(), false); } else if (command.startsWith("Hide all ")) { String type = command.substring(9, command.length() -1); Collection<Displayable> col = layer.getParent().setVisible(type, false, true); selection.removeAll(col); Display.updateCheckboxes(col, DisplayablePanel.VISIBILITY_STATE); } else if (command.startsWith("Unhide all ")) { String type = command.substring(11, command.length() -1); type = type.substring(0, 1).toUpperCase() + type.substring(1); updateCheckboxes(layer.getParent().setVisible(type, true, true), DisplayablePanel.VISIBILITY_STATE); } else if (command.equals("Hide deselected")) { hideDeselected(0 != (ActionEvent.ALT_MASK & ae.getModifiers())); } else if (command.equals("Hide deselected except images")) { hideDeselected(true); } else if (command.equals("Hide selected")) { selection.setVisible(false); Display.updateCheckboxes(selection.getSelected(), DisplayablePanel.VISIBILITY_STATE); } else if (command.equals("Resize canvas/LayerSet...")) { resizeCanvas(); } else if (command.equals("Autoresize canvas/LayerSet")) { layer.getParent().setMinimumDimensions(); } else if (command.equals("Import image")) { importImage(); } else if (command.equals("Import next image")) { importNextImage(); } else if (command.equals("Import stack...")) { Display.this.getLayerSet().addChangeTreesStep(); Rectangle sr = getCanvas().getSrcRect(); Bureaucrat burro = project.getLoader().importStack(layer, sr.x + sr.width/2, sr.y + sr.height/2, null, true, null, false); burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addChangeTreesStep(); }}); } else if (command.equals("Import stack with landmarks...")) { List<Project> pr = Project.getProjects(); if (1 == pr.size()) { Utils.logAll("Need another project open!"); return; } GenericDialog gd = new GenericDialog("Landmarks"); gd.addStringField("landmarks type:", "landmarks"); final String[] none = {"-- None --"}; final Hashtable<String,Project> mpr = new Hashtable<String,Project>(); for (Project p : pr) { if (p == project) continue; mpr.put(p.toString(), p); } final String[] project_titles = mpr.keySet().toArray(new String[0]); final Hashtable<String,ProjectThing> map_target = findLandmarkNodes(project, "landmarks"); String[] target_landmark_titles = map_target.isEmpty() ? none : map_target.keySet().toArray(new String[0]); gd.addChoice("Landmarks node in this project:", target_landmark_titles, target_landmark_titles[0]); gd.addMessage(""); gd.addChoice("Source project:", project_titles, project_titles[0]); final Hashtable<String,ProjectThing> map_source = findLandmarkNodes(mpr.get(project_titles[0]), "landmarks"); String[] source_landmark_titles = map_source.isEmpty() ? none : map_source.keySet().toArray(new String[0]); gd.addChoice("Landmarks node in source project:", source_landmark_titles, source_landmark_titles[0]); final List<Patch> stacks = Display.getPatchStacks(mpr.get(project_titles[0]).getRootLayerSet()); String[] stack_titles; if (stacks.isEmpty()) { if (1 == mpr.size()) { IJ.showMessage("Project " + project_titles[0] + " does not contain any Stack."); return; } stack_titles = none; } else { stack_titles = new String[stacks.size()]; int next = 0; for (Patch pa : stacks) stack_titles[next++] = pa.toString(); } gd.addChoice("Stacks:", stack_titles, stack_titles[0]); Vector vc = gd.getChoices(); final Choice choice_target_landmarks = (Choice) vc.get(0); final Choice choice_source_projects = (Choice) vc.get(1); final Choice choice_source_landmarks = (Choice) vc.get(2); final Choice choice_stacks = (Choice) vc.get(3); final TextField input = (TextField) gd.getStringFields().get(0); input.addTextListener(new TextListener() { public void textValueChanged(TextEvent te) { final String text = input.getText(); update(choice_target_landmarks, Display.this.project, text, map_target); update(choice_source_landmarks, mpr.get(choice_source_projects.getSelectedItem()), text, map_source); } private void update(Choice c, Project p, String type, Hashtable<String,ProjectThing> table) { table.clear(); table.putAll(findLandmarkNodes(p, type)); c.removeAll(); if (table.isEmpty()) c.add(none[0]); else for (String t : table.keySet()) c.add(t); } }); choice_source_projects.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { String item = (String) e.getItem(); Project p = mpr.get(choice_source_projects.getSelectedItem()); map_source.clear(); map_source.putAll(findLandmarkNodes(p, input.getText())); choice_target_landmarks.removeAll(); if (map_source.isEmpty()) choice_target_landmarks.add(none[0]); else for (String t : map_source.keySet()) choice_target_landmarks.add(t); stacks.clear(); choice_stacks.removeAll(); stacks.addAll(Display.getPatchStacks(mpr.get(project_titles[0]).getRootLayerSet())); if (stacks.isEmpty()) choice_stacks.add(none[0]); else for (Patch pa : stacks) choice_stacks.add(pa.toString()); } }); gd.showDialog(); if (gd.wasCanceled()) return; String type = gd.getNextString(); if (null == type || 0 == type.trim().length()) { Utils.log("Invalid landmarks node type!"); return; } ProjectThing target_landmarks_node = map_target.get(gd.getNextChoice()); Project source = mpr.get(gd.getNextChoice()); ProjectThing source_landmarks_node = map_source.get(gd.getNextChoice()); Patch stack_patch = stacks.get(gd.getNextChoiceIndex()); Display.this.getLayerSet().addLayerContentStep(layer); insertStack(target_landmarks_node, source, source_landmarks_node, stack_patch); Display.this.getLayerSet().addChangeTreesStep(); } else if (command.equals("Import grid...")) { Display.this.getLayerSet().addLayerContentStep(layer); Bureaucrat burro = project.getLoader().importGrid(layer); if (null != burro) burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addLayerContentStep(layer); }}); } else if (command.equals("Import sequence as grid...")) { Display.this.getLayerSet().addChangeTreesStep(); Bureaucrat burro = project.getLoader().importSequenceAsGrid(layer); if (null != burro) burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addChangeTreesStep(); }}); } else if (command.equals("Import from text file...")) { Display.this.getLayerSet().addChangeTreesStep(); Bureaucrat burro = project.getLoader().importImages(layer); if (null != burro) burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addChangeTreesStep(); }}); } else if (command.equals("Import labels as arealists...")) { Display.this.getLayerSet().addChangeTreesStep(); Bureaucrat burro = project.getLoader().importLabelsAsAreaLists(layer, null, Double.MAX_VALUE, 0, 0.4f, false); burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addChangeTreesStep(); }}); } else if (command.equals("Make flat image...")) { Rectangle srcRect = null; Roi roi = canvas.getFakeImagePlus().getRoi(); if (null != roi) { srcRect = roi.getBounds(); } else { srcRect = new Rectangle(0, 0, (int)Math.ceil(layer.getParent().getLayerWidth()), (int)Math.ceil(layer.getParent().getLayerHeight())); } double scale = 1.0; final String[] types = new String[]{"8-bit grayscale", "RGB Color"}; int the_type = ImagePlus.GRAY8; final GenericDialog gd = new GenericDialog("Choose", frame); gd.addSlider("Scale: ", 1, 100, 100); gd.addNumericField("Width: ", srcRect.width, 0); gd.addNumericField("height: ", srcRect.height, 0); Vector numfields = gd.getNumericFields(); UpdateDimensionField udf = new UpdateDimensionField(srcRect.width, srcRect.height, (TextField) numfields.get(1), (TextField) numfields.get(2), (TextField) numfields.get(0), (Scrollbar) gd.getSliders().get(0)); for (Object ob : numfields) ((TextField)ob).addTextListener(udf); gd.addChoice("Type: ", types, types[0]); if (layer.getParent().size() > 1) { Utils.addLayerRangeChoices(Display.this.layer, gd); gd.addCheckbox("Include non-empty layers only", true); } gd.addMessage("Background color:"); Utils.addRGBColorSliders(gd, Color.black); gd.addCheckbox("Best quality", false); gd.addMessage(""); gd.addCheckbox("Save to file", false); gd.addCheckbox("Save for web", false); gd.showDialog(); if (gd.wasCanceled()) return; scale = gd.getNextNumber() / 100; the_type = (0 == gd.getNextChoiceIndex() ? ImagePlus.GRAY8 : ImagePlus.COLOR_RGB); if (Double.isNaN(scale) || scale <= 0.0) { Utils.showMessage("Invalid scale."); return; } gd.getNextNumber(); gd.getNextNumber(); Layer[] layer_array = null; boolean non_empty_only = false; if (layer.getParent().size() > 1) { non_empty_only = gd.getNextBoolean(); int i_start = gd.getNextChoiceIndex(); int i_end = gd.getNextChoiceIndex(); ArrayList al = new ArrayList(); ArrayList al_zd = layer.getParent().getZDisplayables(); ZDisplayable[] zd = new ZDisplayable[al_zd.size()]; al_zd.toArray(zd); for (int i=i_start, j=0; i <= i_end; i++, j++) { Layer la = layer.getParent().getLayer(i); if (!la.isEmpty() || !non_empty_only) al.add(la); } if (0 == al.size()) { Utils.showMessage("All layers are empty!"); return; } layer_array = new Layer[al.size()]; al.toArray(layer_array); } else { layer_array = new Layer[]{Display.this.layer}; } final Color background = new Color((int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber()); final boolean quality = gd.getNextBoolean(); final boolean save_to_file = gd.getNextBoolean(); final boolean save_for_web = gd.getNextBoolean(); if (save_for_web) project.getLoader().makePrescaledTiles(layer_array, Patch.class, srcRect, scale, c_alphas, the_type); else project.getLoader().makeFlatImage(layer_array, srcRect, scale, c_alphas, the_type, save_to_file, quality, background); } else if (command.equals("Lock")) { selection.setLocked(true); Utils.revalidateComponent(tabs.getSelectedComponent()); } else if (command.equals("Unlock")) { selection.setLocked(false); Utils.revalidateComponent(tabs.getSelectedComponent()); } else if (command.equals("Properties...")) { active.adjustProperties(); updateSelection(); } else if (command.equals("Show current 2D position in 3D")) { Point p = canvas.consumeLastPopupPoint(); if (null == p) return; Display3D.addFatPoint("Current 2D Position", getLayerSet(), p.x, p.y, layer.getZ(), 10, Color.magenta); } else if (command.equals("Align stack slices")) { if (getActive() instanceof Patch) { final Patch slice = (Patch)getActive(); if (slice.isStack()) { final HashSet hs = slice.getLinkedGroup(new HashSet()); for (Iterator it = hs.iterator(); it.hasNext(); ) { if (it.next().getClass() != Patch.class) { Utils.showMessage("Images are linked to other objects, can't proceed to cross-correlate them."); return; } } final LayerSet ls = slice.getLayerSet(); final HashSet<Displayable> linked = slice.getLinkedGroup(null); ls.addTransformStepWithData(linked); Bureaucrat burro = AlignTask.registerStackSlices((Patch)getActive()); burro.addPostTask(new Runnable() { public void run() { ls.enlargeToFit(linked); ls.addTransformStepWithData(linked); }}); } else { Utils.log("Align stack slices: selected image is not part of a stack."); } } } else if (command.equals("Align layers with manual landmarks")) { setMode(new ManualAlignMode(Display.this)); } else if (command.equals("Align layers")) { final Layer la = layer; la.getParent().addTransformStep(la.getParent().getLayers()); Bureaucrat burro = AlignLayersTask.alignLayersTask( la ); burro.addPostTask(new Runnable() { public void run() { getLayerSet().enlargeToFit(getLayerSet().getDisplayables(Patch.class)); la.getParent().addTransformStep(la.getParent().getLayers()); }}); } else if (command.equals("Align multi-layer mosaic")) { final Layer la = layer; la.getParent().addTransformStep(); Bureaucrat burro = AlignTask.alignMultiLayerMosaicTask( la ); burro.addPostTask(new Runnable() { public void run() { getLayerSet().enlargeToFit(getLayerSet().getDisplayables(Patch.class)); la.getParent().addTransformStep(); }}); } else if (command.equals("Montage all images in this layer")) { final Layer la = layer; final List<Patch> patches = new ArrayList<Patch>( (List<Patch>) (List) la.getDisplayables(Patch.class)); if (patches.size() < 2) { Utils.showMessage("Montage needs 2 or more images selected"); return; } final Collection<Displayable> col = la.getParent().addTransformStepWithData(Arrays.asList(new Layer[]{la})); Bureaucrat burro = AlignTask.alignPatchesTask(patches, Arrays.asList(new Patch[]{patches.get(0)})); burro.addPostTask(new Runnable() { public void run() { getLayerSet().enlargeToFit(patches); la.getParent().addTransformStepWithData(col); }}); } else if (command.equals("Montage selected images (SIFT)")) { montage(0); } else if (command.equals("Montage selected images (phase correlation)")) { montage(1); } else if (command.equals("Montage multiple layers (phase correlation)")) { final GenericDialog gd = new GenericDialog("Choose range"); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.showDialog(); if (gd.wasCanceled()) return; final List<Layer> layers = getLayerSet().getLayers(gd.getNextChoiceIndex(), gd.getNextChoiceIndex()); final Collection<Displayable> col = getLayerSet().addTransformStepWithData(layers); Bureaucrat burro = StitchingTEM.montageWithPhaseCorrelation(layers); if (null == burro) return; burro.addPostTask(new Runnable() { public void run() { Collection<Displayable> ds = new ArrayList<Displayable>(); for (Layer la : layers) ds.addAll(la.getDisplayables(Patch.class)); getLayerSet().enlargeToFit(ds); getLayerSet().addTransformStepWithData(col); }}); } else if (command.equals("Montage multiple layers (SIFT)")) { final GenericDialog gd = new GenericDialog("Choose range"); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.showDialog(); if (gd.wasCanceled()) return; final List<Layer> layers = getLayerSet().getLayers(gd.getNextChoiceIndex(), gd.getNextChoiceIndex()); final Collection<Displayable> col = getLayerSet().addTransformStepWithData(layers); Bureaucrat burro = AlignTask.montageLayersTask(layers); burro.addPostTask(new Runnable() { public void run() { Collection<Displayable> ds = new ArrayList<Displayable>(); for (Layer la : layers) ds.addAll(la.getDisplayables(Patch.class)); getLayerSet().enlargeToFit(ds); getLayerSet().addTransformStepWithData(col); }}); } else if (command.equals("Properties ...")) { GenericDialog gd = new GenericDialog("Properties", Display.this.frame); gd.addSlider("layer_scroll_step: ", 1, layer.getParent().size(), Display.this.scroll_step); gd.addChoice("snapshots_mode", LayerSet.snapshot_modes, LayerSet.snapshot_modes[layer.getParent().getSnapshotsMode()]); gd.addCheckbox("prefer_snapshots_quality", layer.getParent().snapshotsQuality()); Loader lo = getProject().getLoader(); boolean using_mipmaps = lo.isMipMapsEnabled(); gd.addCheckbox("enable_mipmaps", using_mipmaps); gd.addCheckbox("enable_layer_pixels virtualization", layer.getParent().isPixelsVirtualizationEnabled()); double max = layer.getParent().getLayerWidth() < layer.getParent().getLayerHeight() ? layer.getParent().getLayerWidth() : layer.getParent().getLayerHeight(); gd.addSlider("max_dimension of virtualized layer pixels: ", 0, max, layer.getParent().getPixelsMaxDimension()); gd.addCheckbox("Show arrow heads in Treeline/AreaTree", layer.getParent().paint_arrows); gd.addCheckbox("Show edge confidence boxes in Treeline/AreaTree", layer.getParent().paint_edge_confidence_boxes); gd.addCheckbox("Show color cues", layer.getParent().color_cues); gd.addSlider("+/- layers to color cue", 0, 10, layer.getParent().n_layers_color_cue); gd.addCheckbox("Prepaint images", layer.getParent().prepaint); gd.showDialog(); if (gd.wasCanceled()) return; int sc = (int) gd.getNextNumber(); if (sc < 1) sc = 1; Display.this.scroll_step = sc; updateInDatabase("scroll_step"); layer.getParent().setSnapshotsMode(gd.getNextChoiceIndex()); layer.getParent().setSnapshotsQuality(gd.getNextBoolean()); boolean generate_mipmaps = gd.getNextBoolean(); if (using_mipmaps && generate_mipmaps) { } else { if (using_mipmaps) { lo.flushMipMaps(true); } else { lo.generateMipMaps(layer.getParent().getDisplayables(Patch.class)); } } layer.getParent().setPixelsVirtualizationEnabled(gd.getNextBoolean()); layer.getParent().setPixelsMaxDimension((int)gd.getNextNumber()); layer.getParent().paint_arrows = gd.getNextBoolean(); layer.getParent().paint_edge_confidence_boxes = gd.getNextBoolean(); layer.getParent().color_cues = gd.getNextBoolean(); layer.getParent().n_layers_color_cue = (int)gd.getNextNumber(); layer.getParent().prepaint = gd.getNextBoolean(); Display.repaint(layer.getParent()); } else if (command.equals("Adjust snapping parameters...")) { AlignTask.p_snap.setup("Snap"); } else if (command.equals("Adjust fast-marching parameters...")) { Segmentation.fmp.setup(); } else if (command.equals("Adjust arealist paint parameters...")) { AreaWrapper.PP.setup(); } else if (command.equals("Search...")) { new Search(); } else if (command.equals("Select all")) { selection.selectAll(); repaint(Display.this.layer, selection.getBox(), 0); } else if (command.equals("Select all visible")) { selection.selectAllVisible(); repaint(Display.this.layer, selection.getBox(), 0); } else if (command.equals("Select none")) { Rectangle box = selection.getBox(); selection.clear(); repaint(Display.this.layer, box, 0); } else if (command.equals("Restore selection")) { selection.restore(); } else if (command.equals("Select under ROI")) { Roi roi = canvas.getFakeImagePlus().getRoi(); if (null == roi) return; selection.selectAll(roi, true); } else if (command.equals("Merge")) { Bureaucrat burro = Bureaucrat.create(new Worker.Task("Merging AreaLists") { public void exec() { ArrayList al_sel = selection.getSelected(AreaList.class); al_sel.remove(Display.this.active); al_sel.add(0, Display.this.active); Set<DoStep> dataedits = new HashSet<DoStep>(); dataedits.add(new Displayable.DoEdit(Display.this.active).init(Display.this.active, new String[]{"data"})); getLayerSet().addChangeTreesStep(dataedits); AreaList ali = AreaList.merge(al_sel); if (null != ali) { for (int i=1; i<al_sel.size(); i++) { Object ob = al_sel.get(i); if (ob.getClass() == AreaList.class) { selection.remove((Displayable)ob); } } selection.updateTransform(ali); repaint(ali.getLayerSet(), ali, 0); } } }, Display.this.project); burro.addPostTask(new Runnable() { public void run() { Set<DoStep> dataedits = new HashSet<DoStep>(); dataedits.add(new Displayable.DoEdit(Display.this.active).init(Display.this.active, new String[]{"data"})); getLayerSet().addChangeTreesStep(dataedits); }}); burro.goHaveBreakfast(); } else if (command.equals("Reroot")) { if (!(active instanceof Tree)) return; Point p = canvas.consumeLastPopupPoint(); if (null == p) return; getLayerSet().addDataEditStep(active); ((Tree)active).reRoot(p.x, p.y, layer, canvas.getMagnification()); getLayerSet().addDataEditStep(active); Display.repaint(getLayerSet()); } else if (command.equals("Part subtree")) { if (!(active instanceof Tree)) return; Point p = canvas.consumeLastPopupPoint(); if (null == p) return; List<ZDisplayable> ts = ((Tree)active).splitNear(p.x, p.y, layer, canvas.getMagnification()); if (null == ts) return; Displayable elder = Display.this.active; for (ZDisplayable t : ts) { if (t == elder) continue; getLayerSet().add(t); project.getProjectTree().addSibling(elder, t); } selection.clear(); selection.selectAll(ts); selection.add(elder); getLayerSet().addChangeTreesStep(); Display.repaint(getLayerSet()); } else if (command.equals("Show tabular view")) { if (!(active instanceof Tree)) return; ((Tree)active).createMultiTableView(); } else if (command.equals("Mark")) { if (!(active instanceof Tree)) return; Point p = canvas.consumeLastPopupPoint(); if (null == p) return; if (((Tree)active).markNear(p.x, p.y, layer, canvas.getMagnification())) { Display.repaint(getLayerSet()); } } else if (command.equals("Clear marks (selected Trees)")) { for (Displayable d : selection.getSelected(Tree.class)) { ((Tree)d).unmark(); } Display.repaint(getLayerSet()); } else if (command.equals("Join")) { if (!(active instanceof Tree)) return; final List<Tree> tlines = (List<Tree>) (List) selection.getSelected(active.getClass()); if (((Tree)active).canJoin(tlines)) { Set<DoStep> dataedits = new HashSet<DoStep>(tlines.size()); for (final Tree tl : tlines) { dataedits.add(new Displayable.DoEdit(tl).init(tl, new String[]{"data"})); } getLayerSet().addChangeTreesStep(dataedits); ((Tree)active).join(tlines); for (final Tree tl : tlines) { if (tl == active) continue; tl.remove2(false); } Display.repaint(getLayerSet()); Set<DoStep> dataedits2 = new HashSet<DoStep>(1); dataedits2.add(new Displayable.DoEdit(active).init(active, new String[]{"data"})); getLayerSet().addChangeTreesStep(dataedits2); } } else if (command.equals("Previous branch point or start")) { if (!(active instanceof Tree)) return; Point p = canvas.consumeLastPopupPoint(); if (null == p) return; center(((Treeline)active).findPreviousBranchOrRootPoint(p.x, p.y, layer, canvas.getMagnification())); } else if (command.equals("Next branch point or end")) { if (!(active instanceof Tree)) return; Point p = canvas.consumeLastPopupPoint(); if (null == p) return; center(((Tree)active).findNextBranchOrEndPoint(p.x, p.y, layer, canvas.getMagnification())); } else if (command.equals("Root")) { if (!(active instanceof Tree)) return; Point p = canvas.consumeLastPopupPoint(); if (null == p) return; center(((Tree)active).createCoordinate(((Tree)active).getRoot())); } else if (command.equals("Last added point")) { if (!(active instanceof Tree)) return; center(((Treeline)active).getLastAdded()); } else if (command.equals("Last edited point")) { if (!(active instanceof Tree)) return; center(((Treeline)active).getLastEdited()); } else if (command.equals("Reverse point order")) { if (!(active instanceof Pipe)) return; getLayerSet().addDataEditStep(active); ((Pipe)active).reverse(); Display.repaint(Display.this.layer); getLayerSet().addDataEditStep(active); } else if (command.equals("View orthoslices")) { if (!(active instanceof Patch)) return; Display3D.showOrthoslices(((Patch)active)); } else if (command.equals("View volume")) { if (!(active instanceof Patch)) return; Display3D.showVolume(((Patch)active)); } else if (command.equals("Show in 3D")) { for (Iterator it = selection.getSelected(ZDisplayable.class).iterator(); it.hasNext(); ) { ZDisplayable zd = (ZDisplayable)it.next(); Display3D.show(zd.getProject().findProjectThing(zd)); } HashSet hs = new HashSet(); for (Iterator it = selection.getSelected(Profile.class).iterator(); it.hasNext(); ) { Displayable d = (Displayable)it.next(); ProjectThing profile_list = (ProjectThing)d.getProject().findProjectThing(d).getParent(); if (!hs.contains(profile_list)) { Display3D.show(profile_list); hs.add(profile_list); } } } else if (command.equals("Snap")) { if (!(active instanceof Patch)) return; Display.snap((Patch)active); } else if (command.equals("Blend")) { HashSet<Patch> patches = new HashSet<Patch>(); for (final Displayable d : selection.getSelected()) { if (d.getClass() == Patch.class) patches.add((Patch)d); } if (patches.size() > 1) { GenericDialog gd = new GenericDialog("Blending"); gd.addCheckbox("Respect current alpha mask", true); gd.showDialog(); if (gd.wasCanceled()) return; Blending.blend(patches, gd.getNextBoolean()); } else { IJ.log("Please select more than one overlapping image."); } } else if (command.equals("Montage")) { final Set<Displayable> affected = new HashSet<Displayable>(selection.getAffected()); final LayerSet ls = layer.getParent(); ls.addTransformStepWithData(affected); Bureaucrat burro = AlignTask.alignSelectionTask( selection ); burro.addPostTask(new Runnable() { public void run() { ls.enlargeToFit(affected); ls.addTransformStepWithData(affected); }}); } else if (command.equals("Lens correction")) { final Layer la = layer; la.getParent().addDataEditStep(new HashSet<Displayable>(la.getParent().getDisplayables())); Bureaucrat burro = DistortionCorrectionTask.correctDistortionFromSelection( selection ); burro.addPostTask(new Runnable() { public void run() { la.getParent().addDataEditStep(new HashSet<Displayable>(la.getParent().getDisplayables())); }}); } else if (command.equals("Link images...")) { GenericDialog gd = new GenericDialog("Options"); gd.addMessage("Linking images to images (within their own layer only):"); String[] options = {"all images to all images", "each image with any other overlapping image"}; gd.addChoice("Link: ", options, options[1]); String[] options2 = {"selected images only", "all images in this layer", "all images in all layers, within the layer only", "all images in all layers, within and across consecutive layers"}; gd.addChoice("Apply to: ", options2, options2[0]); gd.showDialog(); if (gd.wasCanceled()) return; Layer lay = layer; final HashSet<Displayable> ds = new HashSet<Displayable>(lay.getParent().getDisplayables()); lay.getParent().addDataEditStep(ds, new String[]{"data"}); boolean overlapping_only = 1 == gd.getNextChoiceIndex(); Collection<Displayable> coll = null; switch (gd.getNextChoiceIndex()) { case 0: coll = selection.getSelected(Patch.class); Patch.crosslink(coll, overlapping_only); break; case 1: coll = lay.getDisplayables(Patch.class); Patch.crosslink(coll, overlapping_only); break; case 2: coll = new ArrayList<Displayable>(); for (final Layer la : lay.getParent().getLayers()) { Collection<Displayable> acoll = la.getDisplayables(Patch.class); Patch.crosslink(acoll, overlapping_only); coll.addAll(acoll); } break; case 3: ArrayList<Layer> layers = lay.getParent().getLayers(); Collection<Displayable> lc1 = layers.get(0).getDisplayables(Patch.class); if (lay == layers.get(0)) coll = lc1; for (int i=1; i<layers.size(); i++) { Collection<Displayable> lc2 = layers.get(i).getDisplayables(Patch.class); if (null == coll && Display.this.layer == layers.get(i)) coll = lc2; Collection<Displayable> both = new ArrayList<Displayable>(); both.addAll(lc1); both.addAll(lc2); Patch.crosslink(both, overlapping_only); lc1 = lc2; } break; } if (null != coll) Display.updateCheckboxes(coll, DisplayablePanel.LINK_STATE, true); lay.getParent().addDataEditStep(ds); } else if (command.equals("Unlink all selected images")) { if (Utils.check("Really unlink selected images?")) { for (final Displayable d : selection.getSelected(Patch.class)) { d.unlink(); } } } else if (command.equals("Unlink all")) { if (Utils.check("Really unlink all objects from all layers?")) { Collection<Displayable> ds = layer.getParent().getDisplayables(); for (final Displayable d : ds) { d.unlink(); } Display.updateCheckboxes(ds, DisplayablePanel.LOCK_STATE); } } else if (command.equals("Calibration...")) { try { IJ.run(canvas.getFakeImagePlus(), "Properties...", ""); Display.updateTitle(getLayerSet()); } catch (RuntimeException re) { Utils.log2("Calibration dialog canceled."); } } else if (command.equals("Grid overlay...")) { if (null == gridoverlay) gridoverlay = new GridOverlay(); gridoverlay.setup(canvas.getFakeImagePlus().getRoi()); canvas.repaint(false); } else if (command.equals("Enhance contrast (selected images)...")) { final Layer la = layer; ArrayList<Displayable> selected = selection.getSelected(Patch.class); final HashSet<Displayable> ds = new HashSet<Displayable>(selected); la.getParent().addDataEditStep(ds); Displayable active = Display.this.getActive(); Patch ref = active.getClass() == Patch.class ? (Patch)active : null; Bureaucrat burro = getProject().getLoader().enhanceContrast(selected, ref); burro.addPostTask(new Runnable() { public void run() { la.getParent().addDataEditStep(ds); }}); } else if (command.equals("Enhance contrast layer-wise...")) { final GenericDialog gd = new GenericDialog("Choose range"); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.showDialog(); if (gd.wasCanceled()) return; java.util.List<Layer> layers = layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1); final HashSet<Displayable> ds = new HashSet<Displayable>(); for (final Layer l : layers) ds.addAll(l.getDisplayables(Patch.class)); getLayerSet().addDataEditStep(ds); Bureaucrat burro = project.getLoader().enhanceContrast(layers); burro.addPostTask(new Runnable() { public void run() { getLayerSet().addDataEditStep(ds); }}); } else if (command.equals("Set Min and Max layer-wise...")) { Displayable active = getActive(); double min = 0; double max = 0; if (null != active && active.getClass() == Patch.class) { min = ((Patch)active).getMin(); max = ((Patch)active).getMax(); } final GenericDialog gd = new GenericDialog("Min and Max"); gd.addMessage("Set min and max to all images in the layer range"); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.addNumericField("min: ", min, 2); gd.addNumericField("max: ", max, 2); gd.showDialog(); if (gd.wasCanceled()) return; min = gd.getNextNumber(); max = gd.getNextNumber(); ArrayList<Displayable> al = new ArrayList<Displayable>(); for (final Layer la : layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1)) { al.addAll(la.getDisplayables(Patch.class)); } final HashSet<Displayable> ds = new HashSet<Displayable>(al); getLayerSet().addDataEditStep(ds); Bureaucrat burro = project.getLoader().setMinAndMax(al, min, max); burro.addPostTask(new Runnable() { public void run() { getLayerSet().addDataEditStep(ds); }}); } else if (command.equals("Set Min and Max (selected images)...")) { Displayable active = getActive(); double min = 0; double max = 0; if (null != active && active.getClass() == Patch.class) { min = ((Patch)active).getMin(); max = ((Patch)active).getMax(); } final GenericDialog gd = new GenericDialog("Min and Max"); gd.addMessage("Set min and max to all selected images"); gd.addNumericField("min: ", min, 2); gd.addNumericField("max: ", max, 2); gd.showDialog(); if (gd.wasCanceled()) return; min = gd.getNextNumber(); max = gd.getNextNumber(); final HashSet<Displayable> ds = new HashSet<Displayable>(selection.getSelected(Patch.class)); getLayerSet().addDataEditStep(ds); Bureaucrat burro = project.getLoader().setMinAndMax(selection.getSelected(Patch.class), min, max); burro.addPostTask(new Runnable() { public void run() { getLayerSet().addDataEditStep(ds); }}); } else if (command.equals("Adjust min and max (selected images)...")) { final List<Displayable> list = selection.getSelected(Patch.class); if (list.isEmpty()) { Utils.log("No images selected!"); return; } Bureaucrat.createAndStart(new Worker.Task("Init contrast adjustment") { public void exec() { try { setMode(new ContrastAdjustmentMode(Display.this, list)); } catch (Exception e) { Utils.log("All images must be of the same type!"); } } }, list.get(0).getProject()); } else if (command.equals("Mask image borders (layer-wise)...")) { final GenericDialog gd = new GenericDialog("Mask borders"); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.addMessage("Borders:"); gd.addNumericField("left: ", 6, 2); gd.addNumericField("top: ", 6, 2); gd.addNumericField("right: ", 6, 2); gd.addNumericField("bottom: ", 6, 2); gd.showDialog(); if (gd.wasCanceled()) return; Collection<Layer> layers = layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1); final HashSet<Displayable> ds = new HashSet<Displayable>(); for (Layer l : layers) ds.addAll(l.getDisplayables(Patch.class)); getLayerSet().addDataEditStep(ds); Bureaucrat burro = project.getLoader().maskBordersLayerWise(layers, (int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber()); burro.addPostTask(new Runnable() { public void run() { getLayerSet().addDataEditStep(ds); }}); } else if (command.equals("Mask image borders (selected images)...")) { final GenericDialog gd = new GenericDialog("Mask borders"); gd.addMessage("Borders:"); gd.addNumericField("left: ", 6, 2); gd.addNumericField("top: ", 6, 2); gd.addNumericField("right: ", 6, 2); gd.addNumericField("bottom: ", 6, 2); gd.showDialog(); if (gd.wasCanceled()) return; Collection<Displayable> patches = selection.getSelected(Patch.class); final HashSet<Displayable> ds = new HashSet<Displayable>(patches); getLayerSet().addDataEditStep(ds); Bureaucrat burro = project.getLoader().maskBorders(patches, (int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber()); burro.addPostTask(new Runnable() { public void run() { getLayerSet().addDataEditStep(ds); }}); } else if (command.equals("Duplicate")) { final HashSet<Class> accepted = new HashSet<Class>(); accepted.add(Patch.class); accepted.add(DLabel.class); accepted.add(Stack.class); final ArrayList<Displayable> originals = new ArrayList<Displayable>(); final ArrayList<Displayable> selected = selection.getSelected(); for (final Displayable d : selected) { if (accepted.contains(d.getClass())) { originals.add(d); } } if (originals.size() > 0) { getLayerSet().addChangeTreesStep(); for (final Displayable d : originals) { if (d instanceof ZDisplayable) { d.getLayerSet().add((ZDisplayable)d.clone()); } else { d.getLayer().add(d.clone()); } } getLayerSet().addChangeTreesStep(); } else if (selected.size() > 0) { Utils.log("Can only duplicate images and text labels.\nDuplicate *other* objects in the Project Tree.\n"); } } else if (command.equals("Create subproject")) { Roi roi = canvas.getFakeImagePlus().getRoi(); if (null == roi) return; Layer first, last; if (1 == layer.getParent().size()) { first = last = layer; } else { GenericDialog gd = new GenericDialog("Choose layer range"); Utils.addLayerRangeChoices(layer, gd); gd.showDialog(); if (gd.wasCanceled()) return; first = layer.getParent().getLayer(gd.getNextChoiceIndex()); last = layer.getParent().getLayer(gd.getNextChoiceIndex()); Utils.log2("first, last: " + first + ", " + last); } Project sub = getProject().createSubproject(roi.getBounds(), first, last); final LayerSet subls = sub.getRootLayerSet(); Display.createDisplay(sub, subls.getLayer(0)); } else if (command.startsWith("Image stack under selected Arealist")) { if (null == active || active.getClass() != AreaList.class) return; GenericDialog gd = new GenericDialog("Stack options"); String[] types = {"8-bit", "16-bit", "32-bit", "RGB"}; gd.addChoice("type:", types, types[0]); gd.addSlider("Scale: ", 1, 100, 100); gd.showDialog(); if (gd.wasCanceled()) return; final int type; switch (gd.getNextChoiceIndex()) { case 0: type = ImagePlus.GRAY8; break; case 1: type = ImagePlus.GRAY16; break; case 2: type = ImagePlus.GRAY32; break; case 3: type = ImagePlus.COLOR_RGB; break; default: type = ImagePlus.GRAY8; break; } ImagePlus imp = ((AreaList)active).getStack(type, gd.getNextNumber()/100); if (null != imp) imp.show(); } else if (command.equals("Fly through selected Treeline/AreaTree")) { if (null == active || !(active instanceof Tree)) return; Bureaucrat.createAndStart(new Worker.Task("Creating fly through", true) { public void exec() { GenericDialog gd = new GenericDialog("Fly through"); gd.addNumericField("Width", 512, 0); gd.addNumericField("Height", 512, 0); String[] types = new String[]{"8-bit gray", "Color RGB"}; gd.addChoice("Image type", types, types[0]); gd.addSlider("scale", 0, 100, 100); gd.addCheckbox("save to file", false); gd.showDialog(); if (gd.wasCanceled()) return; int w = (int)gd.getNextNumber(); int h = (int)gd.getNextNumber(); int type = 0 == gd.getNextChoiceIndex() ? ImagePlus.GRAY8 : ImagePlus.COLOR_RGB; double scale = gd.getNextNumber(); if (w <=0 || h <=0) { Utils.log("Invalid width or height: " + w + ", " + h); return; } if (0 == scale || Double.isNaN(scale)) { Utils.log("Invalid scale: " + scale); return; } String dir = null; if (gd.getNextBoolean()) { DirectoryChooser dc = new DirectoryChooser("Target directory"); dir = dc.getDirectory(); if (null == dir) return; dir = Utils.fixDir(dir); } ImagePlus imp = ((Tree)active).flyThroughMarked(w, h, scale/100, type, dir); if (null == imp) { Utils.log("Mark a node first!"); return; } imp.show(); } }, project); } else if (command.startsWith("Arealists as labels")) { GenericDialog gd = new GenericDialog("Export labels"); gd.addSlider("Scale: ", 1, 100, 100); final String[] options = {"All area list", "Selected area lists"}; gd.addChoice("Export: ", options, options[0]); Utils.addLayerRangeChoices(layer, gd); gd.addCheckbox("Visible only", true); gd.showDialog(); if (gd.wasCanceled()) return; final float scale = (float)(gd.getNextNumber() / 100); java.util.List al = 0 == gd.getNextChoiceIndex() ? layer.getParent().getZDisplayables(AreaList.class) : selection.getSelected(AreaList.class); if (null == al) { Utils.log("No area lists found to export."); return; } al = (java.util.List<Displayable>) al; int first = gd.getNextChoiceIndex(); int last = gd.getNextChoiceIndex(); boolean visible_only = gd.getNextBoolean(); if (-1 != command.indexOf("(amira)")) { AreaList.exportAsLabels(al, canvas.getFakeImagePlus().getRoi(), scale, first, last, visible_only, true, true); } else if (-1 != command.indexOf("(tif)")) { AreaList.exportAsLabels(al, canvas.getFakeImagePlus().getRoi(), scale, first, last, visible_only, false, false); } } else if (command.equals("Project properties...")) { project.adjustProperties(); } else if (command.equals("Release memory...")) { Bureaucrat.createAndStart(new Worker("Releasing memory") { public void run() { startedWorking(); try { GenericDialog gd = new GenericDialog("Release Memory"); int max = (int)(IJ.maxMemory() / 1000000); gd.addSlider("Megabytes: ", 0, max, max/2); gd.showDialog(); if (!gd.wasCanceled()) { int n_mb = (int)gd.getNextNumber(); project.getLoader().releaseToFit((long)n_mb*1000000); } } catch (Throwable e) { IJError.print(e); } finally { finishedWorking(); } } }, project); } else if (command.equals("Flush image cache")) { Loader.releaseAllCaches(); } else if (command.equals("Regenerate all mipmaps")) { project.getLoader().regenerateMipMaps(getLayerSet().getDisplayables(Patch.class)); } else if (command.equals("Regenerate mipmaps (selected images)")) { project.getLoader().regenerateMipMaps(selection.getSelected(Patch.class)); } else if (command.equals("Tags...")) { File f = Utils.chooseFile(null, "tags", ".xml"); if (null == f) return; if (!Utils.saveToFile(f, getLayerSet().exportTags())) { Utils.logAll("ERROR when saving tags to file " + f.getAbsolutePath()); } } else if (command.equals("Tags ...")) { String[] ff = Utils.selectFile("Import tags"); if (null == ff) return; GenericDialog gd = new GenericDialog("Import tags"); String[] modes = new String[]{"Append to current tags", "Replace current tags"}; gd.addChoice("Import tags mode:", modes, modes[0]); gd.addMessage("Replacing current tags\nwill remove all tags\n from all nodes first!"); gd.showDialog(); if (gd.wasCanceled()) return; getLayerSet().importTags(new StringBuilder(ff[0]).append('/').append(ff[1]).toString(), 1 == gd.getNextChoiceIndex()); } else { Utils.log2("Display: don't know what to do with command " + command); } }});
public void actionPerformed(final ActionEvent ae) { dispatcher.exec(new Runnable() { public void run() { String command = ae.getActionCommand(); if (command.startsWith("Job")) { if (Utils.checkYN("Really cancel job?")) { project.getLoader().quitJob(command); repairGUI(); } return; } else if (command.equals("Move to top")) { if (null == active) return; canvas.setUpdateGraphics(true); layer.getParent().move(LayerSet.TOP, active); Display.repaint(layer.getParent(), active, 5); } else if (command.equals("Move up")) { if (null == active) return; canvas.setUpdateGraphics(true); layer.getParent().move(LayerSet.UP, active); Display.repaint(layer.getParent(), active, 5); } else if (command.equals("Move down")) { if (null == active) return; canvas.setUpdateGraphics(true); layer.getParent().move(LayerSet.DOWN, active); Display.repaint(layer.getParent(), active, 5); } else if (command.equals("Move to bottom")) { if (null == active) return; canvas.setUpdateGraphics(true); layer.getParent().move(LayerSet.BOTTOM, active); Display.repaint(layer.getParent(), active, 5); } else if (command.equals("Duplicate, link and send to next layer")) { duplicateLinkAndSendTo(active, 1, layer.getParent().next(layer)); } else if (command.equals("Duplicate, link and send to previous layer")) { duplicateLinkAndSendTo(active, 0, layer.getParent().previous(layer)); } else if (command.equals("Duplicate, link and send to...")) { GenericDialog gd = new GenericDialog("Send to"); gd.addMessage("Duplicate, link and send to..."); String[] sl = new String[layer.getParent().size()]; int next = 0; for (Iterator it = layer.getParent().getLayers().iterator(); it.hasNext(); ) { sl[next++] = project.findLayerThing(it.next()).toString(); } gd.addChoice("Layer: ", sl, sl[layer.getParent().indexOf(layer)]); gd.showDialog(); if (gd.wasCanceled()) return; Layer la = layer.getParent().getLayer(gd.getNextChoiceIndex()); if (layer == la) { Utils.showMessage("Can't duplicate, link and send to the same layer."); return; } duplicateLinkAndSendTo(active, 0, la); } else if (-1 != command.indexOf("z = ")) { Layer target_layer = layer.getParent().getLayer(Double.parseDouble(command.substring(command.lastIndexOf(' ') +1))); Utils.log2("layer: __" +command.substring(command.lastIndexOf(' ') +1) + "__"); if (null == target_layer) return; duplicateLinkAndSendTo(active, 0, target_layer); } else if (-1 != command.indexOf("z=")) { int iz = command.indexOf("z=")+2; Utils.log2("iz=" + iz + " other: " + command.indexOf(' ', iz+2)); int end = command.indexOf(' ', iz); if (-1 == end) end = command.length(); double lz = Double.parseDouble(command.substring(iz, end)); Layer target = layer.getParent().getLayer(lz); layer.getParent().move(selection.getAffected(), active.getLayer(), target); } else if (command.equals("Unlink")) { if (null == active || active instanceof Patch) return; active.unlink(); updateSelection(); } else if (command.equals("Unlink from images")) { if (null == active) return; try { for (Displayable displ: selection.getSelected()) { displ.unlinkAll(Patch.class); } updateSelection(); } catch (Exception e) { IJError.print(e); } } else if (command.equals("Unlink slices")) { YesNoCancelDialog yn = new YesNoCancelDialog(frame, "Attention", "Really unlink all slices from each other?\nThere is no undo."); if (!yn.yesPressed()) return; final ArrayList<Patch> pa = ((Patch)active).getStackPatches(); for (int i=pa.size()-1; i>0; i--) { pa.get(i).unlink(pa.get(i-1)); } } else if (command.equals("Send to next layer")) { Rectangle box = selection.getBox(); try { for (final Displayable displ : selection.getSelected()) { displ.unlinkAll(Patch.class); } updateSelection(); } catch (Exception e) { IJError.print(e); } selection.moveDown(); repaint(layer.getParent(), box); } else if (command.equals("Send to previous layer")) { Rectangle box = selection.getBox(); try { for (final Displayable displ : selection.getSelected()) { displ.unlinkAll(Patch.class); } updateSelection(); } catch (Exception e) { IJError.print(e); } selection.moveUp(); repaint(layer.getParent(), box); } else if (command.equals("Show centered")) { if (active == null) return; showCentered(active); } else if (command.equals("Delete...")) { selection.deleteAll(); } else if (command.equals("Color...")) { IJ.doCommand("Color Picker..."); } else if (command.equals("Revert")) { if (null == active || active.getClass() != Patch.class) return; Patch p = (Patch)active; if (!p.revert()) { if (null == p.getOriginalPath()) Utils.log("No editions to save for patch " + p.getTitle() + " #" + p.getId()); else Utils.log("Could not revert Patch " + p.getTitle() + " #" + p.getId()); } } else if (command.equals("Remove alpha mask")) { final ArrayList<Displayable> patches = selection.getSelected(Patch.class); if (patches.size() > 0) { Bureaucrat.createAndStart(new Worker.Task("Removing alpha mask" + (patches.size() > 1 ? "s" : "")) { public void exec() { final ArrayList<Future> jobs = new ArrayList<Future>(); for (final Displayable d : patches) { final Patch p = (Patch) d; p.setAlphaMask(null); Future job = p.getProject().getLoader().regenerateMipMaps(p); if (null != job) jobs.add(job); } for (final Future job : jobs) try { job.get(); } catch (Exception ie) {} }}, patches.get(0).getProject()); } } else if (command.equals("Undo")) { Bureaucrat.createAndStart(new Worker.Task("Undo") { public void exec() { layer.getParent().undoOneStep(); Display.repaint(layer.getParent()); }}, project); } else if (command.equals("Redo")) { Bureaucrat.createAndStart(new Worker.Task("Redo") { public void exec() { layer.getParent().redoOneStep(); Display.repaint(layer.getParent()); }}, project); } else if (command.equals("Apply transform")) { canvas.applyTransform(); } else if (command.equals("Apply transform propagating to last layer")) { if (mode.getClass() == AffineTransformMode.class || mode.getClass() == NonLinearTransformMode.class) { final LayerSet ls = getLayerSet(); final HashSet<Layer> subset = new HashSet<Layer>(ls.getLayers(ls.indexOf(Display.this.layer)+1, ls.size())); if (mode.getClass() == AffineTransformMode.class) ((AffineTransformMode)mode).applyAndPropagate(subset); else if (mode.getClass() == NonLinearTransformMode.class) ((NonLinearTransformMode)mode).apply(subset); setMode(new DefaultMode(Display.this)); } } else if (command.equals("Apply transform propagating to first layer")) { if (mode.getClass() == AffineTransformMode.class || mode.getClass() == NonLinearTransformMode.class) { final LayerSet ls = getLayerSet(); final HashSet<Layer> subset = new HashSet<Layer>(ls.getLayers(0, ls.indexOf(Display.this.layer) -1)); if (mode.getClass() == AffineTransformMode.class) ((AffineTransformMode)mode).applyAndPropagate(subset); else if (mode.getClass() == NonLinearTransformMode.class) ((NonLinearTransformMode)mode).apply(subset); setMode(new DefaultMode(Display.this)); } } else if (command.equals("Cancel transform")) { canvas.cancelTransform(); } else if (command.equals("Specify transform...")) { if (null == active) return; selection.specify(); } else if (command.equals("Hide all but images")) { ArrayList<Class> type = new ArrayList<Class>(); type.add(Patch.class); type.add(Stack.class); Collection<Displayable> col = layer.getParent().hideExcept(type, false); selection.removeAll(col); Display.updateCheckboxes(col, DisplayablePanel.VISIBILITY_STATE); Display.update(layer.getParent(), false); } else if (command.equals("Unhide all")) { Display.updateCheckboxes(layer.getParent().setAllVisible(false), DisplayablePanel.VISIBILITY_STATE); Display.update(layer.getParent(), false); } else if (command.startsWith("Hide all ")) { String type = command.substring(9, command.length() -1); Collection<Displayable> col = layer.getParent().setVisible(type, false, true); selection.removeAll(col); Display.updateCheckboxes(col, DisplayablePanel.VISIBILITY_STATE); } else if (command.startsWith("Unhide all ")) { String type = command.substring(11, command.length() -1); type = type.substring(0, 1).toUpperCase() + type.substring(1); updateCheckboxes(layer.getParent().setVisible(type, true, true), DisplayablePanel.VISIBILITY_STATE); } else if (command.equals("Hide deselected")) { hideDeselected(0 != (ActionEvent.ALT_MASK & ae.getModifiers())); } else if (command.equals("Hide deselected except images")) { hideDeselected(true); } else if (command.equals("Hide selected")) { selection.setVisible(false); Display.updateCheckboxes(selection.getSelected(), DisplayablePanel.VISIBILITY_STATE); } else if (command.equals("Resize canvas/LayerSet...")) { resizeCanvas(); } else if (command.equals("Autoresize canvas/LayerSet")) { layer.getParent().setMinimumDimensions(); } else if (command.equals("Import image")) { importImage(); } else if (command.equals("Import next image")) { importNextImage(); } else if (command.equals("Import stack...")) { Display.this.getLayerSet().addChangeTreesStep(); Rectangle sr = getCanvas().getSrcRect(); Bureaucrat burro = project.getLoader().importStack(layer, sr.x + sr.width/2, sr.y + sr.height/2, null, true, null, false); burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addChangeTreesStep(); }}); } else if (command.equals("Import stack with landmarks...")) { List<Project> pr = Project.getProjects(); if (1 == pr.size()) { Utils.logAll("Need another project open!"); return; } GenericDialog gd = new GenericDialog("Landmarks"); gd.addStringField("landmarks type:", "landmarks"); final String[] none = {"-- None --"}; final Hashtable<String,Project> mpr = new Hashtable<String,Project>(); for (Project p : pr) { if (p == project) continue; mpr.put(p.toString(), p); } final String[] project_titles = mpr.keySet().toArray(new String[0]); final Hashtable<String,ProjectThing> map_target = findLandmarkNodes(project, "landmarks"); String[] target_landmark_titles = map_target.isEmpty() ? none : map_target.keySet().toArray(new String[0]); gd.addChoice("Landmarks node in this project:", target_landmark_titles, target_landmark_titles[0]); gd.addMessage(""); gd.addChoice("Source project:", project_titles, project_titles[0]); final Hashtable<String,ProjectThing> map_source = findLandmarkNodes(mpr.get(project_titles[0]), "landmarks"); String[] source_landmark_titles = map_source.isEmpty() ? none : map_source.keySet().toArray(new String[0]); gd.addChoice("Landmarks node in source project:", source_landmark_titles, source_landmark_titles[0]); final List<Patch> stacks = Display.getPatchStacks(mpr.get(project_titles[0]).getRootLayerSet()); String[] stack_titles; if (stacks.isEmpty()) { if (1 == mpr.size()) { IJ.showMessage("Project " + project_titles[0] + " does not contain any Stack."); return; } stack_titles = none; } else { stack_titles = new String[stacks.size()]; int next = 0; for (Patch pa : stacks) stack_titles[next++] = pa.toString(); } gd.addChoice("Stacks:", stack_titles, stack_titles[0]); Vector vc = gd.getChoices(); final Choice choice_target_landmarks = (Choice) vc.get(0); final Choice choice_source_projects = (Choice) vc.get(1); final Choice choice_source_landmarks = (Choice) vc.get(2); final Choice choice_stacks = (Choice) vc.get(3); final TextField input = (TextField) gd.getStringFields().get(0); input.addTextListener(new TextListener() { public void textValueChanged(TextEvent te) { final String text = input.getText(); update(choice_target_landmarks, Display.this.project, text, map_target); update(choice_source_landmarks, mpr.get(choice_source_projects.getSelectedItem()), text, map_source); } private void update(Choice c, Project p, String type, Hashtable<String,ProjectThing> table) { table.clear(); table.putAll(findLandmarkNodes(p, type)); c.removeAll(); if (table.isEmpty()) c.add(none[0]); else for (String t : table.keySet()) c.add(t); } }); choice_source_projects.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { String item = (String) e.getItem(); Project p = mpr.get(choice_source_projects.getSelectedItem()); map_source.clear(); map_source.putAll(findLandmarkNodes(p, input.getText())); choice_target_landmarks.removeAll(); if (map_source.isEmpty()) choice_target_landmarks.add(none[0]); else for (String t : map_source.keySet()) choice_target_landmarks.add(t); stacks.clear(); choice_stacks.removeAll(); stacks.addAll(Display.getPatchStacks(mpr.get(project_titles[0]).getRootLayerSet())); if (stacks.isEmpty()) choice_stacks.add(none[0]); else for (Patch pa : stacks) choice_stacks.add(pa.toString()); } }); gd.showDialog(); if (gd.wasCanceled()) return; String type = gd.getNextString(); if (null == type || 0 == type.trim().length()) { Utils.log("Invalid landmarks node type!"); return; } ProjectThing target_landmarks_node = map_target.get(gd.getNextChoice()); Project source = mpr.get(gd.getNextChoice()); ProjectThing source_landmarks_node = map_source.get(gd.getNextChoice()); Patch stack_patch = stacks.get(gd.getNextChoiceIndex()); Display.this.getLayerSet().addLayerContentStep(layer); insertStack(target_landmarks_node, source, source_landmarks_node, stack_patch); Display.this.getLayerSet().addChangeTreesStep(); } else if (command.equals("Import grid...")) { Display.this.getLayerSet().addLayerContentStep(layer); Bureaucrat burro = project.getLoader().importGrid(layer); if (null != burro) burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addLayerContentStep(layer); }}); } else if (command.equals("Import sequence as grid...")) { Display.this.getLayerSet().addChangeTreesStep(); Bureaucrat burro = project.getLoader().importSequenceAsGrid(layer); if (null != burro) burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addChangeTreesStep(); }}); } else if (command.equals("Import from text file...")) { Display.this.getLayerSet().addChangeTreesStep(); Bureaucrat burro = project.getLoader().importImages(layer); if (null != burro) burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addChangeTreesStep(); }}); } else if (command.equals("Import labels as arealists...")) { Display.this.getLayerSet().addChangeTreesStep(); Bureaucrat burro = project.getLoader().importLabelsAsAreaLists(layer, null, Double.MAX_VALUE, 0, 0.4f, false); burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addChangeTreesStep(); }}); } else if (command.equals("Make flat image...")) { Rectangle srcRect = null; Roi roi = canvas.getFakeImagePlus().getRoi(); if (null != roi) { srcRect = roi.getBounds(); } else { srcRect = new Rectangle(0, 0, (int)Math.ceil(layer.getParent().getLayerWidth()), (int)Math.ceil(layer.getParent().getLayerHeight())); } double scale = 1.0; final String[] types = new String[]{"8-bit grayscale", "RGB Color"}; int the_type = ImagePlus.GRAY8; final GenericDialog gd = new GenericDialog("Choose", frame); gd.addSlider("Scale: ", 1, 100, 100); gd.addNumericField("Width: ", srcRect.width, 0); gd.addNumericField("height: ", srcRect.height, 0); Vector numfields = gd.getNumericFields(); UpdateDimensionField udf = new UpdateDimensionField(srcRect.width, srcRect.height, (TextField) numfields.get(1), (TextField) numfields.get(2), (TextField) numfields.get(0), (Scrollbar) gd.getSliders().get(0)); for (Object ob : numfields) ((TextField)ob).addTextListener(udf); gd.addChoice("Type: ", types, types[0]); if (layer.getParent().size() > 1) { Utils.addLayerRangeChoices(Display.this.layer, gd); gd.addCheckbox("Include non-empty layers only", true); } gd.addMessage("Background color:"); Utils.addRGBColorSliders(gd, Color.black); gd.addCheckbox("Best quality", false); gd.addMessage(""); gd.addCheckbox("Save to file", false); gd.addCheckbox("Save for web", false); gd.showDialog(); if (gd.wasCanceled()) return; scale = gd.getNextNumber() / 100; the_type = (0 == gd.getNextChoiceIndex() ? ImagePlus.GRAY8 : ImagePlus.COLOR_RGB); if (Double.isNaN(scale) || scale <= 0.0) { Utils.showMessage("Invalid scale."); return; } gd.getNextNumber(); gd.getNextNumber(); Layer[] layer_array = null; boolean non_empty_only = false; if (layer.getParent().size() > 1) { non_empty_only = gd.getNextBoolean(); int i_start = gd.getNextChoiceIndex(); int i_end = gd.getNextChoiceIndex(); ArrayList al = new ArrayList(); ArrayList al_zd = layer.getParent().getZDisplayables(); ZDisplayable[] zd = new ZDisplayable[al_zd.size()]; al_zd.toArray(zd); for (int i=i_start, j=0; i <= i_end; i++, j++) { Layer la = layer.getParent().getLayer(i); if (!la.isEmpty() || !non_empty_only) al.add(la); } if (0 == al.size()) { Utils.showMessage("All layers are empty!"); return; } layer_array = new Layer[al.size()]; al.toArray(layer_array); } else { layer_array = new Layer[]{Display.this.layer}; } final Color background = new Color((int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber()); final boolean quality = gd.getNextBoolean(); final boolean save_to_file = gd.getNextBoolean(); final boolean save_for_web = gd.getNextBoolean(); if (save_for_web) project.getLoader().makePrescaledTiles(layer_array, Patch.class, srcRect, scale, c_alphas, the_type); else project.getLoader().makeFlatImage(layer_array, srcRect, scale, c_alphas, the_type, save_to_file, quality, background); } else if (command.equals("Lock")) { selection.setLocked(true); Utils.revalidateComponent(tabs.getSelectedComponent()); } else if (command.equals("Unlock")) { selection.setLocked(false); Utils.revalidateComponent(tabs.getSelectedComponent()); } else if (command.equals("Properties...")) { active.adjustProperties(); updateSelection(); } else if (command.equals("Show current 2D position in 3D")) { Point p = canvas.consumeLastPopupPoint(); if (null == p) return; Display3D.addFatPoint("Current 2D Position", getLayerSet(), p.x, p.y, layer.getZ(), 10, Color.magenta); } else if (command.equals("Align stack slices")) { if (getActive() instanceof Patch) { final Patch slice = (Patch)getActive(); if (slice.isStack()) { final HashSet hs = slice.getLinkedGroup(new HashSet()); for (Iterator it = hs.iterator(); it.hasNext(); ) { if (it.next().getClass() != Patch.class) { Utils.showMessage("Images are linked to other objects, can't proceed to cross-correlate them."); return; } } final LayerSet ls = slice.getLayerSet(); final HashSet<Displayable> linked = slice.getLinkedGroup(null); ls.addTransformStepWithData(linked); Bureaucrat burro = AlignTask.registerStackSlices((Patch)getActive()); burro.addPostTask(new Runnable() { public void run() { ls.enlargeToFit(linked); ls.addTransformStepWithData(linked); }}); } else { Utils.log("Align stack slices: selected image is not part of a stack."); } } } else if (command.equals("Align layers with manual landmarks")) { setMode(new ManualAlignMode(Display.this)); } else if (command.equals("Align layers")) { final Layer la = layer; la.getParent().addTransformStep(la.getParent().getLayers()); Bureaucrat burro = AlignLayersTask.alignLayersTask( la ); burro.addPostTask(new Runnable() { public void run() { getLayerSet().enlargeToFit(getLayerSet().getDisplayables(Patch.class)); la.getParent().addTransformStep(la.getParent().getLayers()); }}); } else if (command.equals("Align multi-layer mosaic")) { final Layer la = layer; la.getParent().addTransformStep(); Bureaucrat burro = AlignTask.alignMultiLayerMosaicTask( la ); burro.addPostTask(new Runnable() { public void run() { getLayerSet().enlargeToFit(getLayerSet().getDisplayables(Patch.class)); la.getParent().addTransformStep(); }}); } else if (command.equals("Montage all images in this layer")) { final Layer la = layer; final List<Patch> patches = new ArrayList<Patch>( (List<Patch>) (List) la.getDisplayables(Patch.class)); if (patches.size() < 2) { Utils.showMessage("Montage needs 2 or more images selected"); return; } final Collection<Displayable> col = la.getParent().addTransformStepWithData(Arrays.asList(new Layer[]{la})); final ArrayList<Patch> fixed = new ArrayList<Patch>(); for (final Patch p : patches) { if (p.isLocked2()) fixed.add(p); } if (fixed.isEmpty()) fixed.add(patches.get(0)); Bureaucrat burro = AlignTask.alignPatchesTask(patches, fixed); burro.addPostTask(new Runnable() { public void run() { getLayerSet().enlargeToFit(patches); la.getParent().addTransformStepWithData(col); }}); } else if (command.equals("Montage selected images (SIFT)")) { montage(0); } else if (command.equals("Montage selected images (phase correlation)")) { montage(1); } else if (command.equals("Montage multiple layers (phase correlation)")) { final GenericDialog gd = new GenericDialog("Choose range"); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.showDialog(); if (gd.wasCanceled()) return; final List<Layer> layers = getLayerSet().getLayers(gd.getNextChoiceIndex(), gd.getNextChoiceIndex()); final Collection<Displayable> col = getLayerSet().addTransformStepWithData(layers); Bureaucrat burro = StitchingTEM.montageWithPhaseCorrelation(layers); if (null == burro) return; burro.addPostTask(new Runnable() { public void run() { Collection<Displayable> ds = new ArrayList<Displayable>(); for (Layer la : layers) ds.addAll(la.getDisplayables(Patch.class)); getLayerSet().enlargeToFit(ds); getLayerSet().addTransformStepWithData(col); }}); } else if (command.equals("Montage multiple layers (SIFT)")) { final GenericDialog gd = new GenericDialog("Choose range"); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.showDialog(); if (gd.wasCanceled()) return; final List<Layer> layers = getLayerSet().getLayers(gd.getNextChoiceIndex(), gd.getNextChoiceIndex()); final Collection<Displayable> col = getLayerSet().addTransformStepWithData(layers); Bureaucrat burro = AlignTask.montageLayersTask(layers); burro.addPostTask(new Runnable() { public void run() { Collection<Displayable> ds = new ArrayList<Displayable>(); for (Layer la : layers) ds.addAll(la.getDisplayables(Patch.class)); getLayerSet().enlargeToFit(ds); getLayerSet().addTransformStepWithData(col); }}); } else if (command.equals("Properties ...")) { GenericDialog gd = new GenericDialog("Properties", Display.this.frame); gd.addSlider("layer_scroll_step: ", 1, layer.getParent().size(), Display.this.scroll_step); gd.addChoice("snapshots_mode", LayerSet.snapshot_modes, LayerSet.snapshot_modes[layer.getParent().getSnapshotsMode()]); gd.addCheckbox("prefer_snapshots_quality", layer.getParent().snapshotsQuality()); Loader lo = getProject().getLoader(); boolean using_mipmaps = lo.isMipMapsEnabled(); gd.addCheckbox("enable_mipmaps", using_mipmaps); gd.addCheckbox("enable_layer_pixels virtualization", layer.getParent().isPixelsVirtualizationEnabled()); double max = layer.getParent().getLayerWidth() < layer.getParent().getLayerHeight() ? layer.getParent().getLayerWidth() : layer.getParent().getLayerHeight(); gd.addSlider("max_dimension of virtualized layer pixels: ", 0, max, layer.getParent().getPixelsMaxDimension()); gd.addCheckbox("Show arrow heads in Treeline/AreaTree", layer.getParent().paint_arrows); gd.addCheckbox("Show edge confidence boxes in Treeline/AreaTree", layer.getParent().paint_edge_confidence_boxes); gd.addCheckbox("Show color cues", layer.getParent().color_cues); gd.addSlider("+/- layers to color cue", 0, 10, layer.getParent().n_layers_color_cue); gd.addCheckbox("Prepaint images", layer.getParent().prepaint); gd.showDialog(); if (gd.wasCanceled()) return; int sc = (int) gd.getNextNumber(); if (sc < 1) sc = 1; Display.this.scroll_step = sc; updateInDatabase("scroll_step"); layer.getParent().setSnapshotsMode(gd.getNextChoiceIndex()); layer.getParent().setSnapshotsQuality(gd.getNextBoolean()); boolean generate_mipmaps = gd.getNextBoolean(); if (using_mipmaps && generate_mipmaps) { } else { if (using_mipmaps) { lo.flushMipMaps(true); } else { lo.generateMipMaps(layer.getParent().getDisplayables(Patch.class)); } } layer.getParent().setPixelsVirtualizationEnabled(gd.getNextBoolean()); layer.getParent().setPixelsMaxDimension((int)gd.getNextNumber()); layer.getParent().paint_arrows = gd.getNextBoolean(); layer.getParent().paint_edge_confidence_boxes = gd.getNextBoolean(); layer.getParent().color_cues = gd.getNextBoolean(); layer.getParent().n_layers_color_cue = (int)gd.getNextNumber(); layer.getParent().prepaint = gd.getNextBoolean(); Display.repaint(layer.getParent()); } else if (command.equals("Adjust snapping parameters...")) { AlignTask.p_snap.setup("Snap"); } else if (command.equals("Adjust fast-marching parameters...")) { Segmentation.fmp.setup(); } else if (command.equals("Adjust arealist paint parameters...")) { AreaWrapper.PP.setup(); } else if (command.equals("Search...")) { new Search(); } else if (command.equals("Select all")) { selection.selectAll(); repaint(Display.this.layer, selection.getBox(), 0); } else if (command.equals("Select all visible")) { selection.selectAllVisible(); repaint(Display.this.layer, selection.getBox(), 0); } else if (command.equals("Select none")) { Rectangle box = selection.getBox(); selection.clear(); repaint(Display.this.layer, box, 0); } else if (command.equals("Restore selection")) { selection.restore(); } else if (command.equals("Select under ROI")) { Roi roi = canvas.getFakeImagePlus().getRoi(); if (null == roi) return; selection.selectAll(roi, true); } else if (command.equals("Merge")) { Bureaucrat burro = Bureaucrat.create(new Worker.Task("Merging AreaLists") { public void exec() { ArrayList al_sel = selection.getSelected(AreaList.class); al_sel.remove(Display.this.active); al_sel.add(0, Display.this.active); Set<DoStep> dataedits = new HashSet<DoStep>(); dataedits.add(new Displayable.DoEdit(Display.this.active).init(Display.this.active, new String[]{"data"})); getLayerSet().addChangeTreesStep(dataedits); AreaList ali = AreaList.merge(al_sel); if (null != ali) { for (int i=1; i<al_sel.size(); i++) { Object ob = al_sel.get(i); if (ob.getClass() == AreaList.class) { selection.remove((Displayable)ob); } } selection.updateTransform(ali); repaint(ali.getLayerSet(), ali, 0); } } }, Display.this.project); burro.addPostTask(new Runnable() { public void run() { Set<DoStep> dataedits = new HashSet<DoStep>(); dataedits.add(new Displayable.DoEdit(Display.this.active).init(Display.this.active, new String[]{"data"})); getLayerSet().addChangeTreesStep(dataedits); }}); burro.goHaveBreakfast(); } else if (command.equals("Reroot")) { if (!(active instanceof Tree)) return; Point p = canvas.consumeLastPopupPoint(); if (null == p) return; getLayerSet().addDataEditStep(active); ((Tree)active).reRoot(p.x, p.y, layer, canvas.getMagnification()); getLayerSet().addDataEditStep(active); Display.repaint(getLayerSet()); } else if (command.equals("Part subtree")) { if (!(active instanceof Tree)) return; Point p = canvas.consumeLastPopupPoint(); if (null == p) return; List<ZDisplayable> ts = ((Tree)active).splitNear(p.x, p.y, layer, canvas.getMagnification()); if (null == ts) return; Displayable elder = Display.this.active; for (ZDisplayable t : ts) { if (t == elder) continue; getLayerSet().add(t); project.getProjectTree().addSibling(elder, t); } selection.clear(); selection.selectAll(ts); selection.add(elder); getLayerSet().addChangeTreesStep(); Display.repaint(getLayerSet()); } else if (command.equals("Show tabular view")) { if (!(active instanceof Tree)) return; ((Tree)active).createMultiTableView(); } else if (command.equals("Mark")) { if (!(active instanceof Tree)) return; Point p = canvas.consumeLastPopupPoint(); if (null == p) return; if (((Tree)active).markNear(p.x, p.y, layer, canvas.getMagnification())) { Display.repaint(getLayerSet()); } } else if (command.equals("Clear marks (selected Trees)")) { for (Displayable d : selection.getSelected(Tree.class)) { ((Tree)d).unmark(); } Display.repaint(getLayerSet()); } else if (command.equals("Join")) { if (!(active instanceof Tree)) return; final List<Tree> tlines = (List<Tree>) (List) selection.getSelected(active.getClass()); if (((Tree)active).canJoin(tlines)) { Set<DoStep> dataedits = new HashSet<DoStep>(tlines.size()); for (final Tree tl : tlines) { dataedits.add(new Displayable.DoEdit(tl).init(tl, new String[]{"data"})); } getLayerSet().addChangeTreesStep(dataedits); ((Tree)active).join(tlines); for (final Tree tl : tlines) { if (tl == active) continue; tl.remove2(false); } Display.repaint(getLayerSet()); Set<DoStep> dataedits2 = new HashSet<DoStep>(1); dataedits2.add(new Displayable.DoEdit(active).init(active, new String[]{"data"})); getLayerSet().addChangeTreesStep(dataedits2); } } else if (command.equals("Previous branch point or start")) { if (!(active instanceof Tree)) return; Point p = canvas.consumeLastPopupPoint(); if (null == p) return; center(((Treeline)active).findPreviousBranchOrRootPoint(p.x, p.y, layer, canvas.getMagnification())); } else if (command.equals("Next branch point or end")) { if (!(active instanceof Tree)) return; Point p = canvas.consumeLastPopupPoint(); if (null == p) return; center(((Tree)active).findNextBranchOrEndPoint(p.x, p.y, layer, canvas.getMagnification())); } else if (command.equals("Root")) { if (!(active instanceof Tree)) return; Point p = canvas.consumeLastPopupPoint(); if (null == p) return; center(((Tree)active).createCoordinate(((Tree)active).getRoot())); } else if (command.equals("Last added point")) { if (!(active instanceof Tree)) return; center(((Treeline)active).getLastAdded()); } else if (command.equals("Last edited point")) { if (!(active instanceof Tree)) return; center(((Treeline)active).getLastEdited()); } else if (command.equals("Reverse point order")) { if (!(active instanceof Pipe)) return; getLayerSet().addDataEditStep(active); ((Pipe)active).reverse(); Display.repaint(Display.this.layer); getLayerSet().addDataEditStep(active); } else if (command.equals("View orthoslices")) { if (!(active instanceof Patch)) return; Display3D.showOrthoslices(((Patch)active)); } else if (command.equals("View volume")) { if (!(active instanceof Patch)) return; Display3D.showVolume(((Patch)active)); } else if (command.equals("Show in 3D")) { for (Iterator it = selection.getSelected(ZDisplayable.class).iterator(); it.hasNext(); ) { ZDisplayable zd = (ZDisplayable)it.next(); Display3D.show(zd.getProject().findProjectThing(zd)); } HashSet hs = new HashSet(); for (Iterator it = selection.getSelected(Profile.class).iterator(); it.hasNext(); ) { Displayable d = (Displayable)it.next(); ProjectThing profile_list = (ProjectThing)d.getProject().findProjectThing(d).getParent(); if (!hs.contains(profile_list)) { Display3D.show(profile_list); hs.add(profile_list); } } } else if (command.equals("Snap")) { if (!(active instanceof Patch)) return; Display.snap((Patch)active); } else if (command.equals("Blend")) { HashSet<Patch> patches = new HashSet<Patch>(); for (final Displayable d : selection.getSelected()) { if (d.getClass() == Patch.class) patches.add((Patch)d); } if (patches.size() > 1) { GenericDialog gd = new GenericDialog("Blending"); gd.addCheckbox("Respect current alpha mask", true); gd.showDialog(); if (gd.wasCanceled()) return; Blending.blend(patches, gd.getNextBoolean()); } else { IJ.log("Please select more than one overlapping image."); } } else if (command.equals("Montage")) { final Set<Displayable> affected = new HashSet<Displayable>(selection.getAffected()); final LayerSet ls = layer.getParent(); ls.addTransformStepWithData(affected); Bureaucrat burro = AlignTask.alignSelectionTask( selection ); burro.addPostTask(new Runnable() { public void run() { ls.enlargeToFit(affected); ls.addTransformStepWithData(affected); }}); } else if (command.equals("Lens correction")) { final Layer la = layer; la.getParent().addDataEditStep(new HashSet<Displayable>(la.getParent().getDisplayables())); Bureaucrat burro = DistortionCorrectionTask.correctDistortionFromSelection( selection ); burro.addPostTask(new Runnable() { public void run() { la.getParent().addDataEditStep(new HashSet<Displayable>(la.getParent().getDisplayables())); }}); } else if (command.equals("Link images...")) { GenericDialog gd = new GenericDialog("Options"); gd.addMessage("Linking images to images (within their own layer only):"); String[] options = {"all images to all images", "each image with any other overlapping image"}; gd.addChoice("Link: ", options, options[1]); String[] options2 = {"selected images only", "all images in this layer", "all images in all layers, within the layer only", "all images in all layers, within and across consecutive layers"}; gd.addChoice("Apply to: ", options2, options2[0]); gd.showDialog(); if (gd.wasCanceled()) return; Layer lay = layer; final HashSet<Displayable> ds = new HashSet<Displayable>(lay.getParent().getDisplayables()); lay.getParent().addDataEditStep(ds, new String[]{"data"}); boolean overlapping_only = 1 == gd.getNextChoiceIndex(); Collection<Displayable> coll = null; switch (gd.getNextChoiceIndex()) { case 0: coll = selection.getSelected(Patch.class); Patch.crosslink(coll, overlapping_only); break; case 1: coll = lay.getDisplayables(Patch.class); Patch.crosslink(coll, overlapping_only); break; case 2: coll = new ArrayList<Displayable>(); for (final Layer la : lay.getParent().getLayers()) { Collection<Displayable> acoll = la.getDisplayables(Patch.class); Patch.crosslink(acoll, overlapping_only); coll.addAll(acoll); } break; case 3: ArrayList<Layer> layers = lay.getParent().getLayers(); Collection<Displayable> lc1 = layers.get(0).getDisplayables(Patch.class); if (lay == layers.get(0)) coll = lc1; for (int i=1; i<layers.size(); i++) { Collection<Displayable> lc2 = layers.get(i).getDisplayables(Patch.class); if (null == coll && Display.this.layer == layers.get(i)) coll = lc2; Collection<Displayable> both = new ArrayList<Displayable>(); both.addAll(lc1); both.addAll(lc2); Patch.crosslink(both, overlapping_only); lc1 = lc2; } break; } if (null != coll) Display.updateCheckboxes(coll, DisplayablePanel.LINK_STATE, true); lay.getParent().addDataEditStep(ds); } else if (command.equals("Unlink all selected images")) { if (Utils.check("Really unlink selected images?")) { for (final Displayable d : selection.getSelected(Patch.class)) { d.unlink(); } } } else if (command.equals("Unlink all")) { if (Utils.check("Really unlink all objects from all layers?")) { Collection<Displayable> ds = layer.getParent().getDisplayables(); for (final Displayable d : ds) { d.unlink(); } Display.updateCheckboxes(ds, DisplayablePanel.LOCK_STATE); } } else if (command.equals("Calibration...")) { try { IJ.run(canvas.getFakeImagePlus(), "Properties...", ""); Display.updateTitle(getLayerSet()); } catch (RuntimeException re) { Utils.log2("Calibration dialog canceled."); } } else if (command.equals("Grid overlay...")) { if (null == gridoverlay) gridoverlay = new GridOverlay(); gridoverlay.setup(canvas.getFakeImagePlus().getRoi()); canvas.repaint(false); } else if (command.equals("Enhance contrast (selected images)...")) { final Layer la = layer; ArrayList<Displayable> selected = selection.getSelected(Patch.class); final HashSet<Displayable> ds = new HashSet<Displayable>(selected); la.getParent().addDataEditStep(ds); Displayable active = Display.this.getActive(); Patch ref = active.getClass() == Patch.class ? (Patch)active : null; Bureaucrat burro = getProject().getLoader().enhanceContrast(selected, ref); burro.addPostTask(new Runnable() { public void run() { la.getParent().addDataEditStep(ds); }}); } else if (command.equals("Enhance contrast layer-wise...")) { final GenericDialog gd = new GenericDialog("Choose range"); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.showDialog(); if (gd.wasCanceled()) return; java.util.List<Layer> layers = layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1); final HashSet<Displayable> ds = new HashSet<Displayable>(); for (final Layer l : layers) ds.addAll(l.getDisplayables(Patch.class)); getLayerSet().addDataEditStep(ds); Bureaucrat burro = project.getLoader().enhanceContrast(layers); burro.addPostTask(new Runnable() { public void run() { getLayerSet().addDataEditStep(ds); }}); } else if (command.equals("Set Min and Max layer-wise...")) { Displayable active = getActive(); double min = 0; double max = 0; if (null != active && active.getClass() == Patch.class) { min = ((Patch)active).getMin(); max = ((Patch)active).getMax(); } final GenericDialog gd = new GenericDialog("Min and Max"); gd.addMessage("Set min and max to all images in the layer range"); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.addNumericField("min: ", min, 2); gd.addNumericField("max: ", max, 2); gd.showDialog(); if (gd.wasCanceled()) return; min = gd.getNextNumber(); max = gd.getNextNumber(); ArrayList<Displayable> al = new ArrayList<Displayable>(); for (final Layer la : layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1)) { al.addAll(la.getDisplayables(Patch.class)); } final HashSet<Displayable> ds = new HashSet<Displayable>(al); getLayerSet().addDataEditStep(ds); Bureaucrat burro = project.getLoader().setMinAndMax(al, min, max); burro.addPostTask(new Runnable() { public void run() { getLayerSet().addDataEditStep(ds); }}); } else if (command.equals("Set Min and Max (selected images)...")) { Displayable active = getActive(); double min = 0; double max = 0; if (null != active && active.getClass() == Patch.class) { min = ((Patch)active).getMin(); max = ((Patch)active).getMax(); } final GenericDialog gd = new GenericDialog("Min and Max"); gd.addMessage("Set min and max to all selected images"); gd.addNumericField("min: ", min, 2); gd.addNumericField("max: ", max, 2); gd.showDialog(); if (gd.wasCanceled()) return; min = gd.getNextNumber(); max = gd.getNextNumber(); final HashSet<Displayable> ds = new HashSet<Displayable>(selection.getSelected(Patch.class)); getLayerSet().addDataEditStep(ds); Bureaucrat burro = project.getLoader().setMinAndMax(selection.getSelected(Patch.class), min, max); burro.addPostTask(new Runnable() { public void run() { getLayerSet().addDataEditStep(ds); }}); } else if (command.equals("Adjust min and max (selected images)...")) { final List<Displayable> list = selection.getSelected(Patch.class); if (list.isEmpty()) { Utils.log("No images selected!"); return; } Bureaucrat.createAndStart(new Worker.Task("Init contrast adjustment") { public void exec() { try { setMode(new ContrastAdjustmentMode(Display.this, list)); } catch (Exception e) { Utils.log("All images must be of the same type!"); } } }, list.get(0).getProject()); } else if (command.equals("Mask image borders (layer-wise)...")) { final GenericDialog gd = new GenericDialog("Mask borders"); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.addMessage("Borders:"); gd.addNumericField("left: ", 6, 2); gd.addNumericField("top: ", 6, 2); gd.addNumericField("right: ", 6, 2); gd.addNumericField("bottom: ", 6, 2); gd.showDialog(); if (gd.wasCanceled()) return; Collection<Layer> layers = layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1); final HashSet<Displayable> ds = new HashSet<Displayable>(); for (Layer l : layers) ds.addAll(l.getDisplayables(Patch.class)); getLayerSet().addDataEditStep(ds); Bureaucrat burro = project.getLoader().maskBordersLayerWise(layers, (int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber()); burro.addPostTask(new Runnable() { public void run() { getLayerSet().addDataEditStep(ds); }}); } else if (command.equals("Mask image borders (selected images)...")) { final GenericDialog gd = new GenericDialog("Mask borders"); gd.addMessage("Borders:"); gd.addNumericField("left: ", 6, 2); gd.addNumericField("top: ", 6, 2); gd.addNumericField("right: ", 6, 2); gd.addNumericField("bottom: ", 6, 2); gd.showDialog(); if (gd.wasCanceled()) return; Collection<Displayable> patches = selection.getSelected(Patch.class); final HashSet<Displayable> ds = new HashSet<Displayable>(patches); getLayerSet().addDataEditStep(ds); Bureaucrat burro = project.getLoader().maskBorders(patches, (int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber()); burro.addPostTask(new Runnable() { public void run() { getLayerSet().addDataEditStep(ds); }}); } else if (command.equals("Duplicate")) { final HashSet<Class> accepted = new HashSet<Class>(); accepted.add(Patch.class); accepted.add(DLabel.class); accepted.add(Stack.class); final ArrayList<Displayable> originals = new ArrayList<Displayable>(); final ArrayList<Displayable> selected = selection.getSelected(); for (final Displayable d : selected) { if (accepted.contains(d.getClass())) { originals.add(d); } } if (originals.size() > 0) { getLayerSet().addChangeTreesStep(); for (final Displayable d : originals) { if (d instanceof ZDisplayable) { d.getLayerSet().add((ZDisplayable)d.clone()); } else { d.getLayer().add(d.clone()); } } getLayerSet().addChangeTreesStep(); } else if (selected.size() > 0) { Utils.log("Can only duplicate images and text labels.\nDuplicate *other* objects in the Project Tree.\n"); } } else if (command.equals("Create subproject")) { Roi roi = canvas.getFakeImagePlus().getRoi(); if (null == roi) return; Layer first, last; if (1 == layer.getParent().size()) { first = last = layer; } else { GenericDialog gd = new GenericDialog("Choose layer range"); Utils.addLayerRangeChoices(layer, gd); gd.showDialog(); if (gd.wasCanceled()) return; first = layer.getParent().getLayer(gd.getNextChoiceIndex()); last = layer.getParent().getLayer(gd.getNextChoiceIndex()); Utils.log2("first, last: " + first + ", " + last); } Project sub = getProject().createSubproject(roi.getBounds(), first, last); final LayerSet subls = sub.getRootLayerSet(); Display.createDisplay(sub, subls.getLayer(0)); } else if (command.startsWith("Image stack under selected Arealist")) { if (null == active || active.getClass() != AreaList.class) return; GenericDialog gd = new GenericDialog("Stack options"); String[] types = {"8-bit", "16-bit", "32-bit", "RGB"}; gd.addChoice("type:", types, types[0]); gd.addSlider("Scale: ", 1, 100, 100); gd.showDialog(); if (gd.wasCanceled()) return; final int type; switch (gd.getNextChoiceIndex()) { case 0: type = ImagePlus.GRAY8; break; case 1: type = ImagePlus.GRAY16; break; case 2: type = ImagePlus.GRAY32; break; case 3: type = ImagePlus.COLOR_RGB; break; default: type = ImagePlus.GRAY8; break; } ImagePlus imp = ((AreaList)active).getStack(type, gd.getNextNumber()/100); if (null != imp) imp.show(); } else if (command.equals("Fly through selected Treeline/AreaTree")) { if (null == active || !(active instanceof Tree)) return; Bureaucrat.createAndStart(new Worker.Task("Creating fly through", true) { public void exec() { GenericDialog gd = new GenericDialog("Fly through"); gd.addNumericField("Width", 512, 0); gd.addNumericField("Height", 512, 0); String[] types = new String[]{"8-bit gray", "Color RGB"}; gd.addChoice("Image type", types, types[0]); gd.addSlider("scale", 0, 100, 100); gd.addCheckbox("save to file", false); gd.showDialog(); if (gd.wasCanceled()) return; int w = (int)gd.getNextNumber(); int h = (int)gd.getNextNumber(); int type = 0 == gd.getNextChoiceIndex() ? ImagePlus.GRAY8 : ImagePlus.COLOR_RGB; double scale = gd.getNextNumber(); if (w <=0 || h <=0) { Utils.log("Invalid width or height: " + w + ", " + h); return; } if (0 == scale || Double.isNaN(scale)) { Utils.log("Invalid scale: " + scale); return; } String dir = null; if (gd.getNextBoolean()) { DirectoryChooser dc = new DirectoryChooser("Target directory"); dir = dc.getDirectory(); if (null == dir) return; dir = Utils.fixDir(dir); } ImagePlus imp = ((Tree)active).flyThroughMarked(w, h, scale/100, type, dir); if (null == imp) { Utils.log("Mark a node first!"); return; } imp.show(); } }, project); } else if (command.startsWith("Arealists as labels")) { GenericDialog gd = new GenericDialog("Export labels"); gd.addSlider("Scale: ", 1, 100, 100); final String[] options = {"All area list", "Selected area lists"}; gd.addChoice("Export: ", options, options[0]); Utils.addLayerRangeChoices(layer, gd); gd.addCheckbox("Visible only", true); gd.showDialog(); if (gd.wasCanceled()) return; final float scale = (float)(gd.getNextNumber() / 100); java.util.List al = 0 == gd.getNextChoiceIndex() ? layer.getParent().getZDisplayables(AreaList.class) : selection.getSelected(AreaList.class); if (null == al) { Utils.log("No area lists found to export."); return; } al = (java.util.List<Displayable>) al; int first = gd.getNextChoiceIndex(); int last = gd.getNextChoiceIndex(); boolean visible_only = gd.getNextBoolean(); if (-1 != command.indexOf("(amira)")) { AreaList.exportAsLabels(al, canvas.getFakeImagePlus().getRoi(), scale, first, last, visible_only, true, true); } else if (-1 != command.indexOf("(tif)")) { AreaList.exportAsLabels(al, canvas.getFakeImagePlus().getRoi(), scale, first, last, visible_only, false, false); } } else if (command.equals("Project properties...")) { project.adjustProperties(); } else if (command.equals("Release memory...")) { Bureaucrat.createAndStart(new Worker("Releasing memory") { public void run() { startedWorking(); try { GenericDialog gd = new GenericDialog("Release Memory"); int max = (int)(IJ.maxMemory() / 1000000); gd.addSlider("Megabytes: ", 0, max, max/2); gd.showDialog(); if (!gd.wasCanceled()) { int n_mb = (int)gd.getNextNumber(); project.getLoader().releaseToFit((long)n_mb*1000000); } } catch (Throwable e) { IJError.print(e); } finally { finishedWorking(); } } }, project); } else if (command.equals("Flush image cache")) { Loader.releaseAllCaches(); } else if (command.equals("Regenerate all mipmaps")) { project.getLoader().regenerateMipMaps(getLayerSet().getDisplayables(Patch.class)); } else if (command.equals("Regenerate mipmaps (selected images)")) { project.getLoader().regenerateMipMaps(selection.getSelected(Patch.class)); } else if (command.equals("Tags...")) { File f = Utils.chooseFile(null, "tags", ".xml"); if (null == f) return; if (!Utils.saveToFile(f, getLayerSet().exportTags())) { Utils.logAll("ERROR when saving tags to file " + f.getAbsolutePath()); } } else if (command.equals("Tags ...")) { String[] ff = Utils.selectFile("Import tags"); if (null == ff) return; GenericDialog gd = new GenericDialog("Import tags"); String[] modes = new String[]{"Append to current tags", "Replace current tags"}; gd.addChoice("Import tags mode:", modes, modes[0]); gd.addMessage("Replacing current tags\nwill remove all tags\n from all nodes first!"); gd.showDialog(); if (gd.wasCanceled()) return; getLayerSet().importTags(new StringBuilder(ff[0]).append('/').append(ff[1]).toString(), 1 == gd.getNextChoiceIndex()); } else { Utils.log2("Display: don't know what to do with command " + command); } }});
public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException { MyLog.v(TAG, "HttpServerPlugin exec action:" + action + ", args:" + args); if(action.equalsIgnoreCase("getServerRoot")){ if(localServer != null){ callbackContext.success(localServer.getServerRoot()); }else{ callbackContext.error("Error server is not started yet. Plesae start the server before lcalling this"); } return true; } if(action.equalsIgnoreCase("getIpAddress")){ callbackContext.success(NetworkUtils.getIPAddress(true)); return true; } if(action.equalsIgnoreCase("start")){ if(localServer != null){ callbackContext.error("A server is already running. Please stop current server before starting a new server."); return true; } if (args.length() < 2) { callbackContext.error("either documentRoot or params is not supplied"); } else { Runnable serverRunner = new Runnable(){ @Override public void run() { try{ String rootDir = args.getString(0); JSONObject params = args.getJSONObject(1); int port = params.getInt("port"); localServer = new MonacaLocalServer(cordova.getActivity(), rootDir, port); localServer.start(); JSONObject result = new JSONObject(); result.put("ip", NetworkUtils.getIPAddress(true)); result.put("port", port); callbackContext.success(result); }catch (JSONException e) { callbackContext.error(e.getMessage()); e.printStackTrace(); } catch (Exception e) { callbackContext.error("Cannot start server. error: " + e.getMessage()); e.printStackTrace(); } }}; Runnable fail = new Runnable(){ @Override public void run() { callbackContext.error("Cannot start server."); }}; if (((MonacaApplication)cordova.getActivity().getApplication()).enablesBootloader()) { LocalFileBootloader.setup(cordova.getActivity(), serverRunner, fail); } else { serverRunner.run(); } } return true; }else if(action.equalsIgnoreCase("stop")){ if(localServer != null){ localServer.stop(); localServer = null; callbackContext.success("stopped server"); } return true; }else{ return false; } }
public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException { MyLog.v(TAG, "HttpServerPlugin exec action:" + action + ", args:" + args); if(action.equalsIgnoreCase("getServerRoot")){ if(localServer != null){ callbackContext.success(localServer.getServerRoot()); }else{ callbackContext.error("Error server is not started yet. Plesae start the server before lcalling this"); } return true; } if(action.equalsIgnoreCase("getIpAddress")){ callbackContext.success(NetworkUtils.getIPAddress(true)); return true; } if(action.equalsIgnoreCase("start")){ if(localServer != null){ localServer.stop(); } if (args.length() < 2) { callbackContext.error("either documentRoot or params is not supplied"); } else { Runnable serverRunner = new Runnable(){ @Override public void run() { try{ String rootDir = args.getString(0); JSONObject params = args.getJSONObject(1); int port = params.getInt("port"); localServer = new MonacaLocalServer(cordova.getActivity(), rootDir, port); localServer.start(); JSONObject result = new JSONObject(); result.put("ip", NetworkUtils.getIPAddress(true)); result.put("port", port); callbackContext.success(result); }catch (JSONException e) { callbackContext.error(e.getMessage()); e.printStackTrace(); } catch (Exception e) { callbackContext.error("Cannot start server. error: " + e.getMessage()); e.printStackTrace(); } }}; Runnable fail = new Runnable(){ @Override public void run() { callbackContext.error("Cannot start server."); }}; if (((MonacaApplication)cordova.getActivity().getApplication()).enablesBootloader()) { LocalFileBootloader.setup(cordova.getActivity(), serverRunner, fail); } else { serverRunner.run(); } } return true; }else if(action.equalsIgnoreCase("stop")){ if(localServer != null){ localServer.stop(); localServer = null; callbackContext.success("stopped server"); } return true; }else{ return false; } }
public Object invoke(Object arg0, Method arg1, Object[] arg2) { ObjectMapper mapper = new ObjectMapper(); StringWriter writer = new StringWriter(); try { mapper.writeValue(writer, arg2); String send = sender.send(arg1.getName(), writer.toString()); if ("void".equals(arg1.getReturnType().getName())) { return mapper.readValue(send, TypeFactory.type(arg1.getGenericReturnType())); } else { return null; } } catch (JsonGenerationException e) { throw new JMSConnectorException(e.getMessage()); } catch (JsonMappingException e) { throw new JMSConnectorException(e.getMessage()); } catch (JsonParseException e) { throw new JMSConnectorException(e.getMessage()); } catch (IOException e) { throw new JMSConnectorException(e.getMessage()); } }
public Object invoke(Object arg0, Method arg1, Object[] arg2) { ObjectMapper mapper = new ObjectMapper(); StringWriter writer = new StringWriter(); try { mapper.writeValue(writer, arg2); String send = sender.send(arg1.getName(), writer.toString()); if (!"void".equals(arg1.getReturnType().getName())) { return mapper.readValue(send, TypeFactory.type(arg1.getGenericReturnType())); } else { return null; } } catch (JsonGenerationException e) { throw new JMSConnectorException(e.getMessage()); } catch (JsonMappingException e) { throw new JMSConnectorException(e.getMessage()); } catch (JsonParseException e) { throw new JMSConnectorException(e.getMessage()); } catch (IOException e) { throw new JMSConnectorException(e.getMessage()); } }
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String email = (String) req.getSession().getAttribute("email"); if(email == null){ req.setAttribute("msgClass", Constants.MSG_CSS_ERROR); req.setAttribute("message", Utility.getCONFG().getProperty(Constants.LOGIN_NEED_MESSAGE)); req.getRequestDispatcher("/messages.jsp").forward(req, resp); } else { User user = null; user = UserDAO.INSTANCE.getUserByEmail(email); Calendar from = Calendar.getInstance(); from.add(Calendar.DATE, -1); Calendar to = Calendar.getInstance(); to.add(Calendar.DATE, 15); DateFormat showDateFormat = new SimpleDateFormat("yyyy-MM-dd"); DateFormat showTimeFormat = new SimpleDateFormat("hh:mm a"); List<Sale> userSale = SaleDAO.INSTANCE.listSalesFromTOByUser(from.getTime(), to.getTime(), user.getUserId()); List<BookingDetails> bookings = new ArrayList<BookingDetails>(userSale.size()); for (Sale sale : userSale) { BookingDetails b = new BookingDetails(); b.setShowDate(showDateFormat.format(sale.getShowDate())); b.setShowTime(showTimeFormat.format(sale.getShowDate())); b.setTransactionDate(showDateFormat.format(sale.getTransactionDate())); b.setSeatNumbers(sale.getSeats()); b.setMovieName(MovieDetailDAO.INSTANCE.getMovieById(sale.getMovie()).getMovieName()); b.setSaleId(sale.getId()); bookings.add(b); } req.setAttribute("bookings", bookings); req.setAttribute("user", user); req.setAttribute("msgClass", Constants.MSG_CSS_INFO); req.setAttribute("message", Utility.getCONFG().getProperty(Constants.USER_PROFILE_UPDATE_INFO)); req.getRequestDispatcher("/profile.jsp").forward(req, resp); } }
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String email = (String) req.getSession().getAttribute("email"); if(email == null){ req.setAttribute("msgClass", Constants.MSG_CSS_ERROR); req.setAttribute("message", Utility.getCONFG().getProperty(Constants.LOGIN_NEED_MESSAGE)); req.getRequestDispatcher("/messages.jsp").forward(req, resp); } else { User user = null; user = UserDAO.INSTANCE.getUserByEmail(email); Calendar from = Calendar.getInstance(); from.add(Calendar.DATE, -1); Calendar to = Calendar.getInstance(); to.add(Calendar.DATE, 31); DateFormat showDateFormat = new SimpleDateFormat("yyyy-MM-dd"); DateFormat showTimeFormat = new SimpleDateFormat("hh:mm a"); List<Sale> userSale = SaleDAO.INSTANCE.listSalesFromTOByUser(from.getTime(), to.getTime(), user.getUserId()); List<BookingDetails> bookings = new ArrayList<BookingDetails>(userSale.size()); for (Sale sale : userSale) { BookingDetails b = new BookingDetails(); b.setShowDate(showDateFormat.format(sale.getShowDate())); b.setShowTime(showTimeFormat.format(sale.getShowDate())); b.setTransactionDate(showDateFormat.format(sale.getTransactionDate())); b.setSeatNumbers(sale.getSeats()); b.setMovieName(MovieDetailDAO.INSTANCE.getMovieById(sale.getMovie()).getMovieName()); b.setSaleId(sale.getId()); bookings.add(b); } req.setAttribute("bookings", bookings); req.setAttribute("user", user); req.setAttribute("msgClass", Constants.MSG_CSS_INFO); req.setAttribute("message", Utility.getCONFG().getProperty(Constants.USER_PROFILE_UPDATE_INFO)); req.getRequestDispatcher("/profile.jsp").forward(req, resp); } }
private void doExecute(String sql) throws SQLException { try { if (logger.isTraceEnabled()) logger.trace("CQL: "+ sql); resetResults(); CqlResult rSet = connection.execute(sql); String keyspace = connection.currentKeyspace; switch (rSet.getType()) { case ROWS: currentResultSet = new CassandraResultSet(this, rSet, keyspace); break; case INT: updateCount = rSet.getNum(); break; case VOID: updateCount = 0; break; } } catch (InvalidRequestException e) { throw new SQLSyntaxErrorException(e.getWhy()); } catch (UnavailableException e) { throw new SQLNonTransientConnectionException(NO_SERVER, e); } catch (TimedOutException e) { throw new SQLTransientConnectionException(e.getMessage()); } catch (SchemaDisagreementException e) { throw new SQLRecoverableException(SCHEMA_MISMATCH); } catch (TException e) { throw new SQLNonTransientConnectionException(e.getMessage()); } }
private void doExecute(String sql) throws SQLException { try { if (logger.isTraceEnabled()) logger.trace("CQL: "+ sql); resetResults(); CqlResult rSet = connection.execute(sql); String keyspace = connection.currentKeyspace; switch (rSet.getType()) { case ROWS: currentResultSet = new CassandraResultSet(this, rSet, keyspace); break; case INT: updateCount = rSet.getNum(); break; case VOID: updateCount = 0; break; } } catch (InvalidRequestException e) { throw new SQLSyntaxErrorException(e.getWhy()+"\n'"+sql+"'",e); } catch (UnavailableException e) { throw new SQLNonTransientConnectionException(NO_SERVER, e); } catch (TimedOutException e) { throw new SQLTransientConnectionException(e); } catch (SchemaDisagreementException e) { throw new SQLRecoverableException(SCHEMA_MISMATCH); } catch (TException e) { throw new SQLNonTransientConnectionException(e); } }
public ParseResultDto parse(final InputStream input) { initializeParser(); try { Iterator<Row> rowIterator = null; ByteArrayInputStream copiedInput = copyInputIntoByteInput(input); copiedInput.mark(0); try { rowIterator = new HSSFWorkbook(copiedInput).getSheetAt(0).iterator(); } catch (Exception e) { copiedInput.reset(); try { rowIterator = new XSSFWorkbook(copiedInput).getSheetAt(0).iterator(); } catch (Exception e2) { throw new MPesaXlsImporterException("Unknown file format. Supported file formats are: XLS (from Excel 2003 or older), XLSX"); } } int friendlyRowNum = 0; Row row = null; setPaymentType(); skipToTransactionData(rowIterator); if (!errorsList.isEmpty()) { return new ParseResultDto(errorsList, pmts); } while (rowIterator.hasNext()) { try { row = rowIterator.next(); friendlyRowNum = row.getRowNum() + 1; if (!isRowValid(row, friendlyRowNum, errorsList)) { continue; } String receipt = cellStringValue(row.getCell(RECEIPT)); Date transDate; try { transDate = getDate(row.getCell(TRANSACTION_DATE)); } catch (Exception e) { addError(row, "Date does not begin with expected format (YYYY-MM-DD)"); continue; } String phoneNumber = validatePhoneNumber(row); if (phoneNumber == null) { continue; } final LocalDate paymentDate = LocalDate.fromDateFields(transDate); String transactionPartyDetails = null; if(row.getCell(TRANSACTION_PARTY_DETAILS).getCellType() == Cell.CELL_TYPE_NUMERIC) { transactionPartyDetails = row.getCell(TRANSACTION_PARTY_DETAILS).getNumericCellValue() +""; if(transactionPartyDetails.endsWith(".0")){ transactionPartyDetails = transactionPartyDetails.replace(".0", ""); } else { throw new IllegalArgumentException("Unknown format of cell "+ TRANSACTION_PARTY_DETAILS); } } else if (row.getCell(TRANSACTION_PARTY_DETAILS).getCellType() == Cell.CELL_TYPE_STRING) { transactionPartyDetails = row.getCell(TRANSACTION_PARTY_DETAILS).getStringCellValue(); } String userDefinedProduct = getUserDefinedProduct(transactionPartyDetails); List<String> parameters; if (userDefinedProduct != null && !userDefinedProduct.isEmpty() && userDefinedProductValid(userDefinedProduct, phoneNumber)) { parameters = Arrays.asList(userDefinedProduct); } else { parameters = getConfiguredProducts(); } if (moreThanOneAccountMatchesProductCode(row, phoneNumber, parameters)) { continue; } List<String> loanPrds = new LinkedList<String>(); String lastInTheOrderProdSName = parameters.get(parameters.size() - 1); loanPrds.addAll(parameters.subList(0, parameters.size() - 1)); checkBlank(lastInTheOrderProdSName, "Savings product short name", row); BigDecimal paidInAmount = BigDecimal.ZERO; paidInAmount = BigDecimal.valueOf(row.getCell(PAID_IN).getNumericCellValue()); if (paidInAmount.scale() > configuredDigitsAfterDecimal()) { addError(row, String.format("Number of fraction digits in the \"Paid In\" column - %d - is greater than configured for the currency - %d", paidInAmount.scale(), configuredDigitsAfterDecimal())); continue; } boolean cancelTransactionFlag = false; List<AccountPaymentParametersDto> loanPaymentList = new ArrayList<AccountPaymentParametersDto>(); for (String loanPrd : loanPrds) { BigDecimal loanAccountPaymentAmount = BigDecimal.ZERO; BigDecimal loanAccountTotalDueAmount = BigDecimal.ZERO; final AccountReferenceDto loanAccountReference = getLoanAccount(phoneNumber, loanPrd); if(loanAccountReference == null){ continue; } loanAccountTotalDueAmount = getTotalPaymentDueAmount(loanAccountReference); if (paidInAmount.compareTo(BigDecimal.ZERO) > 0) { if (paidInAmount.compareTo(loanAccountTotalDueAmount) > 0) { loanAccountPaymentAmount = loanAccountTotalDueAmount; paidInAmount = paidInAmount.subtract(loanAccountTotalDueAmount); } else { loanAccountPaymentAmount = paidInAmount; paidInAmount = BigDecimal.ZERO; } } else { loanAccountPaymentAmount = BigDecimal.ZERO; } AccountPaymentParametersDto cumulativeLoanPayment = createPaymentParametersDto( loanAccountReference, loanAccountPaymentAmount, paymentDate); if (!isPaymentValid(cumulativeLoanPayment, row)) { cancelTransactionFlag = true; break; } loanPaymentList.add(new AccountPaymentParametersDto(getUserReferenceDto(), loanAccountReference, loanAccountPaymentAmount, paymentDate, getPaymentTypeDto(), "", new LocalDate(), receipt, customerWithPhoneNumber(phoneNumber))); } if (cancelTransactionFlag) { continue; } BigDecimal lastInOrderAmount; AccountReferenceDto lastInOrderAcc; lastInOrderAcc = getSavingsAccount(phoneNumber, lastInTheOrderProdSName); if(lastInOrderAcc == null) { lastInOrderAcc = getLoanAccount(phoneNumber, lastInTheOrderProdSName); if (lastInOrderAcc != null) { BigDecimal totalPaymentDueAmount = getTotalPaymentDueAmount(lastInOrderAcc); if(paidInAmount.compareTo(totalPaymentDueAmount) > 0) { addError(row, "Last account is a loan account but the total paid in amount is greater than the total due amount"); continue; } } } if(lastInOrderAcc == null) { addError(row, "No valid accounts found with this transaction"); continue; } if (paidInAmount.compareTo(BigDecimal.ZERO) > 0) { lastInOrderAmount = paidInAmount; paidInAmount = BigDecimal.ZERO; } else { lastInOrderAmount = BigDecimal.ZERO; } final AccountPaymentParametersDto cumulativePaymentlastAcc = createPaymentParametersDto(lastInOrderAcc, lastInOrderAmount, paymentDate); final AccountPaymentParametersDto lastInTheOrderAccPayment = new AccountPaymentParametersDto( getUserReferenceDto(), lastInOrderAcc, lastInOrderAmount, paymentDate, getPaymentTypeDto(), "", new LocalDate(), receipt, customerWithPhoneNumber(phoneNumber)); if (!isPaymentValid(cumulativePaymentlastAcc, row)) { continue; } successfullyParsedRows+=1; for (AccountPaymentParametersDto loanPayment : loanPaymentList) { pmts.add(loanPayment); } pmts.add(lastInTheOrderAccPayment); } catch (Exception e) { e.printStackTrace(); addError(row, e.getMessage()); continue; } } } catch (Exception e) { e.printStackTrace(); errorsList.add(e.getMessage() + ". Got error before reading rows"); } return parsingResult(); }
public ParseResultDto parse(final InputStream input) { initializeParser(); try { Iterator<Row> rowIterator = null; ByteArrayInputStream copiedInput = copyInputIntoByteInput(input); copiedInput.mark(0); try { rowIterator = new HSSFWorkbook(copiedInput).getSheetAt(0).iterator(); } catch (Exception e) { copiedInput.reset(); try { rowIterator = new XSSFWorkbook(copiedInput).getSheetAt(0).iterator(); } catch (Exception e2) { throw new MPesaXlsImporterException("Unknown file format. Supported file formats are: XLS (from Excel 2003 or older), XLSX"); } } int friendlyRowNum = 0; Row row = null; setPaymentType(); skipToTransactionData(rowIterator); if (!errorsList.isEmpty()) { return new ParseResultDto(errorsList, pmts); } while (rowIterator.hasNext()) { try { row = rowIterator.next(); friendlyRowNum = row.getRowNum() + 1; if (!isRowValid(row, friendlyRowNum, errorsList)) { continue; } String receipt = cellStringValue(row.getCell(RECEIPT)); Date transDate; try { transDate = getDate(row.getCell(TRANSACTION_DATE)); } catch (Exception e) { addError(row, "Date does not begin with expected format (YYYY-MM-DD)"); continue; } String phoneNumber = validatePhoneNumber(row); if (phoneNumber == null) { continue; } final LocalDate paymentDate = LocalDate.fromDateFields(transDate); String transactionPartyDetails = null; if(row.getCell(TRANSACTION_PARTY_DETAILS).getCellType() == Cell.CELL_TYPE_NUMERIC) { transactionPartyDetails = row.getCell(TRANSACTION_PARTY_DETAILS).getNumericCellValue() +""; if(transactionPartyDetails.endsWith(".0")){ transactionPartyDetails = transactionPartyDetails.replace(".0", ""); } else { throw new IllegalArgumentException("Unknown format of cell "+ TRANSACTION_PARTY_DETAILS); } } else if (row.getCell(TRANSACTION_PARTY_DETAILS).getCellType() == Cell.CELL_TYPE_STRING) { transactionPartyDetails = row.getCell(TRANSACTION_PARTY_DETAILS).getStringCellValue(); } String userDefinedProduct = getUserDefinedProduct(transactionPartyDetails); List<String> parameters; if (userDefinedProduct != null && !userDefinedProduct.isEmpty() && userDefinedProductValid(userDefinedProduct, phoneNumber)) { parameters = Arrays.asList(userDefinedProduct); } else { parameters = getConfiguredProducts(); } if (moreThanOneAccountMatchesProductCode(row, phoneNumber, parameters)) { continue; } List<String> loanPrds = new LinkedList<String>(); String lastInTheOrderProdSName = parameters.get(parameters.size() - 1); loanPrds.addAll(parameters.subList(0, parameters.size() - 1)); checkBlank(lastInTheOrderProdSName, "Savings product short name", row); BigDecimal paidInAmount = BigDecimal.ZERO; paidInAmount = BigDecimal.valueOf(row.getCell(PAID_IN).getNumericCellValue()); if (paidInAmount.scale() > configuredDigitsAfterDecimal()) { boolean nonZeroFractionalPart = false; try { paidInAmount.toBigIntegerExact(); } catch (ArithmeticException e) { nonZeroFractionalPart = true; } if (paidInAmount.scale() > 1 || nonZeroFractionalPart) { addError(row, String.format("Number of fraction digits in the \"Paid In\" column - %d - is greater than configured for the currency - %d", paidInAmount.scale(), configuredDigitsAfterDecimal())); continue; } } boolean cancelTransactionFlag = false; List<AccountPaymentParametersDto> loanPaymentList = new ArrayList<AccountPaymentParametersDto>(); for (String loanPrd : loanPrds) { BigDecimal loanAccountPaymentAmount = BigDecimal.ZERO; BigDecimal loanAccountTotalDueAmount = BigDecimal.ZERO; final AccountReferenceDto loanAccountReference = getLoanAccount(phoneNumber, loanPrd); if(loanAccountReference == null){ continue; } loanAccountTotalDueAmount = getTotalPaymentDueAmount(loanAccountReference); if (paidInAmount.compareTo(BigDecimal.ZERO) > 0) { if (paidInAmount.compareTo(loanAccountTotalDueAmount) > 0) { loanAccountPaymentAmount = loanAccountTotalDueAmount; paidInAmount = paidInAmount.subtract(loanAccountTotalDueAmount); } else { loanAccountPaymentAmount = paidInAmount; paidInAmount = BigDecimal.ZERO; } } else { loanAccountPaymentAmount = BigDecimal.ZERO; } AccountPaymentParametersDto cumulativeLoanPayment = createPaymentParametersDto( loanAccountReference, loanAccountPaymentAmount, paymentDate); if (!isPaymentValid(cumulativeLoanPayment, row)) { cancelTransactionFlag = true; break; } loanPaymentList.add(new AccountPaymentParametersDto(getUserReferenceDto(), loanAccountReference, loanAccountPaymentAmount, paymentDate, getPaymentTypeDto(), "", new LocalDate(), receipt, customerWithPhoneNumber(phoneNumber))); } if (cancelTransactionFlag) { continue; } BigDecimal lastInOrderAmount; AccountReferenceDto lastInOrderAcc; lastInOrderAcc = getSavingsAccount(phoneNumber, lastInTheOrderProdSName); if(lastInOrderAcc == null) { lastInOrderAcc = getLoanAccount(phoneNumber, lastInTheOrderProdSName); if (lastInOrderAcc != null) { BigDecimal totalPaymentDueAmount = getTotalPaymentDueAmount(lastInOrderAcc); if(paidInAmount.compareTo(totalPaymentDueAmount) > 0) { addError(row, "Last account is a loan account but the total paid in amount is greater than the total due amount"); continue; } } } if(lastInOrderAcc == null) { addError(row, "No valid accounts found with this transaction"); continue; } if (paidInAmount.compareTo(BigDecimal.ZERO) > 0) { lastInOrderAmount = paidInAmount; paidInAmount = BigDecimal.ZERO; } else { lastInOrderAmount = BigDecimal.ZERO; } final AccountPaymentParametersDto cumulativePaymentlastAcc = createPaymentParametersDto(lastInOrderAcc, lastInOrderAmount, paymentDate); final AccountPaymentParametersDto lastInTheOrderAccPayment = new AccountPaymentParametersDto( getUserReferenceDto(), lastInOrderAcc, lastInOrderAmount, paymentDate, getPaymentTypeDto(), "", new LocalDate(), receipt, customerWithPhoneNumber(phoneNumber)); if (!isPaymentValid(cumulativePaymentlastAcc, row)) { continue; } successfullyParsedRows+=1; for (AccountPaymentParametersDto loanPayment : loanPaymentList) { pmts.add(loanPayment); } pmts.add(lastInTheOrderAccPayment); } catch (Exception e) { e.printStackTrace(); addError(row, e.getMessage()); continue; } } } catch (Exception e) { e.printStackTrace(); errorsList.add(e.getMessage() + ". Got error before reading rows"); } return parsingResult(); }
public void testSize() throws FileNotFoundException { Main.main(new String[]{ Args.TEST_STYLE_ARG, "--route", Args.TEST_RESOURCE_OSM + "uk-test-1.osm.gz", Args.TEST_RESOURCE_MP + "test1.mp" }); FileSystem fs = ImgFS.openFs(Args.DEF_MAP_ID + ".img"); assertNotNull("file exists", fs); List<DirectoryEntry> entries = fs.list(); int count = 0; for (DirectoryEntry ent : entries) { String ext = ent.getExt(); int size = ent.getSize(); if (ext.equals("RGN")) { count++; assertThat("RGN size", size, new RangeMatcher(141999)); } else if (ext.equals("TRE")) { count++; assertEquals("TRE size", 1344, size); } else if (ext.equals("LBL")) { count++; assertEquals("LBL size", 27645, size); } else if (ext.equals("NET")) { count++; assertEquals("NET size", 73850, size); } else if (ext.equals("NOD")) { count++; assertEquals("NOD size", 195187, size); } } assertTrue("enough checks run", count == 5); fs = ImgFS.openFs(Args.DEF_MAP_FILENAME2); assertNotNull("file exists", fs); entries = fs.list(); count = 0; for (DirectoryEntry ent : entries) { String ext = ent.getExt(); int size = ent.getSize(); if (ext.equals("RGN")) { count++; assertThat("RGN size", size, new RangeMatcher(2934)); } else if (ext.equals("TRE")) { count++; assertEquals("TRE size", 594, size); } else if (ext.equals("LBL")) { count++; assertEquals("LBL size", 957, size); } else if (ext.equals("NET")) { count++; assertEquals("NET size", 1280, size); } else if (ext.equals("NOD")) { count++; assertEquals("NOD size", 3114, size); } } assertTrue("enough checks run", count == 5); }
public void testSize() throws FileNotFoundException { Main.main(new String[]{ Args.TEST_STYLE_ARG, "--route", Args.TEST_RESOURCE_OSM + "uk-test-1.osm.gz", Args.TEST_RESOURCE_MP + "test1.mp" }); FileSystem fs = ImgFS.openFs(Args.DEF_MAP_ID + ".img"); assertNotNull("file exists", fs); List<DirectoryEntry> entries = fs.list(); int count = 0; for (DirectoryEntry ent : entries) { String ext = ent.getExt(); int size = ent.getSize(); if (ext.equals("RGN")) { count++; assertThat("RGN size", size, new RangeMatcher(141999)); } else if (ext.equals("TRE")) { count++; assertEquals("TRE size", 1341, size); } else if (ext.equals("LBL")) { count++; assertEquals("LBL size", 27645, size); } else if (ext.equals("NET")) { count++; assertEquals("NET size", 73850, size); } else if (ext.equals("NOD")) { count++; assertEquals("NOD size", 195187, size); } } assertTrue("enough checks run", count == 5); fs = ImgFS.openFs(Args.DEF_MAP_FILENAME2); assertNotNull("file exists", fs); entries = fs.list(); count = 0; for (DirectoryEntry ent : entries) { String ext = ent.getExt(); int size = ent.getSize(); if (ext.equals("RGN")) { count++; assertThat("RGN size", size, new RangeMatcher(2934)); } else if (ext.equals("TRE")) { count++; assertEquals("TRE size", 594, size); } else if (ext.equals("LBL")) { count++; assertEquals("LBL size", 957, size); } else if (ext.equals("NET")) { count++; assertEquals("NET size", 1280, size); } else if (ext.equals("NOD")) { count++; assertEquals("NOD size", 3114, size); } } assertTrue("enough checks run", count == 5); }
public void setUp() throws Exception { context = new JUnit4Mockery() {{ setImposteriser(ClassImposteriser.INSTANCE); }}; brokerA = new BrokerService(); brokerA.setBrokerName("BrokerA"); configure(brokerA); brokerA.addConnector("tcp://localhost:0"); brokerA.start(); brokerA.waitUntilStarted(); proxy = new SocketProxy(brokerA.getTransportConnectors().get(0).getConnectUri()); managementContext = context.mock(ManagementContext.class); context.checking(new Expectations(){{ allowing (managementContext).getJmxDomainName(); will (returnValue("Test")); allowing (managementContext).start(); allowing (managementContext).isCreateConnector(); allowing (managementContext).stop(); allowing (managementContext).isConnectorStarted(); allowing (managementContext).registerMBean(with(any(Object.class)), with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=Broker")))); allowing (managementContext).registerMBean(with(any(Object.class)), with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkConnector,NetworkConnectorName=localhost")))); allowing (managementContext).registerMBean(with(any(Object.class)), with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.Connection")))); allowing (managementContext).registerMBean(with(any(Object.class)), with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=jobScheduler,jobSchedulerName=JMS")))); atLeast(maxReconnects - 1).of (managementContext).registerMBean(with(any(Object.class)), with(new NetworkBridgeObjectNameMatcher<ObjectName>( new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkBridge,NetworkConnectorName=localhost,Name=localhost/127.0.0.1_" + proxy.getUrl().getPort())))); will(new CustomAction("signal register network mbean") { public Object invoke(Invocation invocation) throws Throwable { LOG.info("Mbean Registered: " + invocation.getParameter(0)); mbeanRegistered.release(); return new ObjectInstance((ObjectName)invocation.getParameter(0), "dscription"); } }); atLeast(maxReconnects - 1).of (managementContext).unregisterMBean(with(new NetworkBridgeObjectNameMatcher<ObjectName>( new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkBridge,NetworkConnectorName=localhost,Name=localhost/127.0.0.1_" + proxy.getUrl().getPort())))); will(new CustomAction("signal unregister network mbean") { public Object invoke(Invocation invocation) throws Throwable { LOG.info("Mbean Unregistered: " + invocation.getParameter(0)); mbeanUnregistered.release(); return null; } }); allowing (managementContext).unregisterMBean(with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=Broker")))); allowing (managementContext).unregisterMBean(with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkConnector,NetworkConnectorName=localhost")))); allowing (managementContext).unregisterMBean(with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.Connection")))); }}); brokerB = new BrokerService(); brokerB.setManagementContext(managementContext); brokerB.setBrokerName("BrokerNC"); configure(brokerB); }
public void setUp() throws Exception { context = new JUnit4Mockery() {{ setImposteriser(ClassImposteriser.INSTANCE); }}; brokerA = new BrokerService(); brokerA.setBrokerName("BrokerA"); configure(brokerA); brokerA.addConnector("tcp://localhost:0"); brokerA.start(); brokerA.waitUntilStarted(); proxy = new SocketProxy(brokerA.getTransportConnectors().get(0).getConnectUri()); managementContext = context.mock(ManagementContext.class); context.checking(new Expectations(){{ allowing (managementContext).getJmxDomainName(); will (returnValue("Test")); allowing (managementContext).start(); allowing (managementContext).isCreateConnector(); allowing (managementContext).stop(); allowing (managementContext).isConnectorStarted(); allowing (managementContext).registerMBean(with(any(Object.class)), with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=Broker")))); allowing (managementContext).registerMBean(with(any(Object.class)), with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkConnector,NetworkConnectorName=localhost")))); allowing (managementContext).registerMBean(with(any(Object.class)), with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.Connection")))); allowing (managementContext).registerMBean(with(any(Object.class)), with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.NetworkBridge")))); allowing (managementContext).registerMBean(with(any(Object.class)), with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=jobScheduler,jobSchedulerName=JMS")))); atLeast(maxReconnects - 1).of (managementContext).registerMBean(with(any(Object.class)), with(new NetworkBridgeObjectNameMatcher<ObjectName>( new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkBridge,NetworkConnectorName=localhost,Name=localhost/127.0.0.1_" + proxy.getUrl().getPort())))); will(new CustomAction("signal register network mbean") { public Object invoke(Invocation invocation) throws Throwable { LOG.info("Mbean Registered: " + invocation.getParameter(0)); mbeanRegistered.release(); return new ObjectInstance((ObjectName)invocation.getParameter(0), "dscription"); } }); atLeast(maxReconnects - 1).of (managementContext).unregisterMBean(with(new NetworkBridgeObjectNameMatcher<ObjectName>( new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkBridge,NetworkConnectorName=localhost,Name=localhost/127.0.0.1_" + proxy.getUrl().getPort())))); will(new CustomAction("signal unregister network mbean") { public Object invoke(Invocation invocation) throws Throwable { LOG.info("Mbean Unregistered: " + invocation.getParameter(0)); mbeanUnregistered.release(); return null; } }); allowing (managementContext).unregisterMBean(with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=Broker")))); allowing (managementContext).unregisterMBean(with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkConnector,NetworkConnectorName=localhost")))); allowing (managementContext).unregisterMBean(with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.Connection")))); allowing (managementContext).unregisterMBean(with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.NetworkBridge")))); }}); brokerB = new BrokerService(); brokerB.setManagementContext(managementContext); brokerB.setBrokerName("BrokerNC"); configure(brokerB); }
private Result invoke(final Method method, final Object[] args, final MethodKind methodKind) throws Throwable { if (method.getParameterTypes().length == 0) { if (method.getName().equals("toString")) { return Result.cache(proxiedToString()); } else if (method.getName().equals("hashCode")) { return Result.cache(proxiedHashCode()); } } if (method.getParameterTypes().length == 1 && method.getParameterTypes()[0] == Object.class && method.getName().equals("equals")) { return Result.noCache(proxiedEquals(args[0])); } final Class<?> returnType = method.getReturnType(); final String name = getAttributeName(method, methodKind); if (returnType == String.class) { return Result.cache(modify(method.isAnnotationPresent(MapContent.class) ? configurationElement.getValue() : configurationElement.getAttribute(name))); } if (returnType.isPrimitive()) { return Result.cache(coerce(returnType, modify(configurationElement.getAttribute(name)))); } if (returnType == Bundle.class) { return Result.cache(ContributorFactoryOSGi.resolve(configurationElement.getContributor())); } if (returnType == Class.class) { String value = configurationElement.getAttribute(name); if (value == null) { return Result.CACHED_NULL; } Bundle bundle = ContributorFactoryOSGi.resolve(configurationElement.getContributor()); if (bundle == null) { return Result.CACHED_NULL; } int colon = value.indexOf(':'); if (colon != -1) { value = value.substring(0, colon); } return Result.cache(bundle.loadClass(value)); } if (returnType.isInterface() && returnType.isAnnotationPresent(ExtensionInterface.class)) { final IConfigurationElement[] cfgElements = configurationElement.getChildren(name); if (cfgElements.length == 0) { return Result.CACHED_NULL; } if (cfgElements.length == 1) { return Result.cache(Proxy.newProxyInstance(returnType.getClassLoader(), new Class[] { returnType }, new InterfaceBeanHandler(returnType, symbolReplace, cfgElements[0]))); } throw new IllegalStateException( "Got more than one configuration element but the interface expected exactly one, .i.e no array type has been specified for: " + method); } if (returnType.isArray() && returnType.getComponentType().isInterface()) { final IConfigurationElement[] cfgElements = configurationElement.getChildren(name); final Object[] result = (Object[]) Array.newInstance(returnType.getComponentType(), cfgElements.length); for (int i = 0; i < cfgElements.length; i++) { result[i] = Proxy.newProxyInstance(returnType.getComponentType().getClassLoader(), new Class[] { returnType.getComponentType() }, new InterfaceBeanHandler(returnType .getComponentType(), symbolReplace, cfgElements[i])); } return Result.cache(result); } if (method.getReturnType() == Void.class || (args != null && args.length > 0)) { throw new UnsupportedOperationException("Can not handle method '" + method + "' in '" + interfaceType.getName() + "'."); } if (configurationElement.getAttribute(name) == null) { return Result.CACHED_NULL; } if (method.isAnnotationPresent(CreateLazy.class)) { return Result.noCache(LazyExecutableExtension.newInstance(configurationElement, name)); } return Result.noCache(configurationElement.createExecutableExtension(name)); }
private Result invoke(final Method method, final Object[] args, final MethodKind methodKind) throws Throwable { if (method.getParameterTypes().length == 0) { if (method.getName().equals("toString")) { return Result.cache(proxiedToString()); } else if (method.getName().equals("hashCode")) { return Result.cache(proxiedHashCode()); } } if (method.getParameterTypes().length == 1 && method.getParameterTypes()[0] == Object.class && method.getName().equals("equals")) { return Result.noCache(proxiedEquals(args[0])); } final Class<?> returnType = method.getReturnType(); final String name = getAttributeName(method, methodKind); if (returnType == String.class) { return Result.noCache(modify(method.isAnnotationPresent(MapContent.class) ? configurationElement.getValue() : configurationElement.getAttribute(name))); } if (returnType.isPrimitive()) { return Result.noCache(coerce(returnType, modify(configurationElement.getAttribute(name)))); } if (returnType == Bundle.class) { return Result.cache(ContributorFactoryOSGi.resolve(configurationElement.getContributor())); } if (returnType == Class.class) { String value = configurationElement.getAttribute(name); if (value == null) { return Result.CACHED_NULL; } Bundle bundle = ContributorFactoryOSGi.resolve(configurationElement.getContributor()); if (bundle == null) { return Result.CACHED_NULL; } int colon = value.indexOf(':'); if (colon != -1) { value = value.substring(0, colon); } return Result.cache(bundle.loadClass(value)); } if (returnType.isInterface() && returnType.isAnnotationPresent(ExtensionInterface.class)) { final IConfigurationElement[] cfgElements = configurationElement.getChildren(name); if (cfgElements.length == 0) { return Result.CACHED_NULL; } if (cfgElements.length == 1) { return Result.cache(Proxy.newProxyInstance(returnType.getClassLoader(), new Class[] { returnType }, new InterfaceBeanHandler(returnType, symbolReplace, cfgElements[0]))); } throw new IllegalStateException( "Got more than one configuration element but the interface expected exactly one, .i.e no array type has been specified for: " + method); } if (returnType.isArray() && returnType.getComponentType().isInterface()) { final IConfigurationElement[] cfgElements = configurationElement.getChildren(name); final Object[] result = (Object[]) Array.newInstance(returnType.getComponentType(), cfgElements.length); for (int i = 0; i < cfgElements.length; i++) { result[i] = Proxy.newProxyInstance(returnType.getComponentType().getClassLoader(), new Class[] { returnType.getComponentType() }, new InterfaceBeanHandler(returnType .getComponentType(), symbolReplace, cfgElements[i])); } return Result.cache(result); } if (method.getReturnType() == Void.class || (args != null && args.length > 0)) { throw new UnsupportedOperationException("Can not handle method '" + method + "' in '" + interfaceType.getName() + "'."); } if (configurationElement.getAttribute(name) == null) { return Result.CACHED_NULL; } if (method.isAnnotationPresent(CreateLazy.class)) { return Result.noCache(LazyExecutableExtension.newInstance(configurationElement, name)); } return Result.noCache(configurationElement.createExecutableExtension(name)); }
public void afterTaskAddedEvent(@Observes(notifyObserver = Reception.IF_EXISTS) @AfterTaskAddedEvent Task task) { Map<String, Object> taskInputParameters = getTaskInputParameters(task); Map<String, Object> taskOutputParameters = getTaskOutputParameters(task, taskInputParameters); PeopleAssignments peopleAssignments = new PeopleAssignmentsImpl(); List<OrganizationalEntity> potentialOwners = new ArrayList<OrganizationalEntity>(); String to = (String) taskInputParameters.get("to"); JahiaUser jahiaUser = null; if (StringUtils.isNotEmpty(to)) { jahiaUser = ServicesRegistry.getInstance().getJahiaUserManagerService().lookupUserByKey(to); potentialOwners.add(new UserImpl((jahiaUser).getUserKey())); } List<OrganizationalEntity> administrators = new ArrayList<OrganizationalEntity>(); administrators.add(new GroupImpl(ServicesRegistry.getInstance().getJahiaGroupManagerService().getAdministratorGroup(null).getGroupKey())); peopleAssignments.getBusinessAdministrators().addAll(administrators); peopleAssignments.getPotentialOwners().addAll(potentialOwners); if (jahiaUser != null) { List<JahiaPrincipal> jahiaPrincipals = new ArrayList<JahiaPrincipal>(); jahiaPrincipals.add(jahiaUser); try { createTask(task, taskInputParameters, taskOutputParameters, jahiaPrincipals); ((SynchronizedTaskService) taskService).addContent(task.getId(), taskOutputParameters); } catch (RepositoryException e) { e.printStackTrace(); } } }
public void afterTaskAddedEvent(@Observes(notifyObserver = Reception.IF_EXISTS) @AfterTaskAddedEvent Task task) { Map<String, Object> taskInputParameters = getTaskInputParameters(task); Map<String, Object> taskOutputParameters = getTaskOutputParameters(task, taskInputParameters); PeopleAssignments peopleAssignments = new PeopleAssignmentsImpl(); List<OrganizationalEntity> potentialOwners = new ArrayList<OrganizationalEntity>(); String to = (String) taskInputParameters.get("to"); JahiaUser jahiaUser = null; if (StringUtils.isNotEmpty(to)) { jahiaUser = ServicesRegistry.getInstance().getJahiaUserManagerService().lookupUserByKey(to); potentialOwners.add(new UserImpl((jahiaUser).getUserKey())); } List<OrganizationalEntity> administrators = new ArrayList<OrganizationalEntity>(); administrators.add(new GroupImpl(ServicesRegistry.getInstance().getJahiaGroupManagerService().getAdministratorGroup(null).getGroupKey())); if (jahiaUser != null) { List<JahiaPrincipal> jahiaPrincipals = new ArrayList<JahiaPrincipal>(); jahiaPrincipals.add(jahiaUser); try { createTask(task, taskInputParameters, taskOutputParameters, jahiaPrincipals); ((SynchronizedTaskService) taskService).addContent(task.getId(), taskOutputParameters); } catch (RepositoryException e) { e.printStackTrace(); } } }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Amarino.connect(this, DEVICE_ADDRESS); Display1 = (TextView) findViewById(R.id.textView2); Display2 = (TextView) findViewById(R.id.textView3); Display3 = (TextView) findViewById(R.id.textView4); Display4 = (TextView) findViewById(R.id.textView5); Display5 = (TextView) findViewById(R.id.textView6); Display6 = (TextView) findViewById(R.id.textView7); Display7 = (TextView) findViewById(R.id.textView8); Display8 = (TextView) findViewById(R.id.textView9); Display9 = (TextView) findViewById(R.id.textView10); Display1.setText(new String(Maze[0])); Display2.setText(new String(Maze[1])); Display3.setText(new String(Maze[2])); Display4.setText(new String(Maze[3])); Display5.setText(new String(Maze[4])); Display6.setText(new String(Maze[5])); Display7.setText(new String(Maze[6])); Display8.setText(new String(Maze[7])); Display9.setText(new String(Maze[8])); Display10 = (TextView) findViewById(R.id.textView12); Display11 = (TextView) findViewById(R.id.textView13); Display12 = (TextView) findViewById(R.id.textView14); Display13 = (TextView) findViewById(R.id.textView15); Display14 = (TextView) findViewById(R.id.textView16); Display15 = (TextView) findViewById(R.id.textView17); Display16 = (TextView) findViewById(R.id.textView18); Display17 = (TextView) findViewById(R.id.textView19); Display18 = (TextView) findViewById(R.id.textView20); button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { if(solve(Start.getX(), Start.getY())){ findpath(); Display10.setText(new String(Maze[0])); Display11.setText(new String(Maze[1])); Display12.setText(new String(Maze[2])); Display13.setText(new String(Maze[3])); Display14.setText(new String(Maze[4])); Display15.setText(new String(Maze[5])); Display16.setText(new String(Maze[6])); Display17.setText(new String(Maze[7])); Display18.setText(new String(Maze[8])); button.setVisibility(View.INVISIBLE); button2.setVisibility(0); } } }); button2 = (Button) findViewById(R.id.button2); button2.setVisibility(View.INVISIBLE); button2.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { for(String x: instructions){ if(x.equals("Forward")){ forward(); } else if (x.equals("Left")){ left(); } else if(x.equals("Right")){ right(); } } } }); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Amarino.connect(this, DEVICE_ADDRESS); Display1 = (TextView) findViewById(R.id.textView2); Display2 = (TextView) findViewById(R.id.textView3); Display3 = (TextView) findViewById(R.id.textView4); Display4 = (TextView) findViewById(R.id.textView5); Display5 = (TextView) findViewById(R.id.textView6); Display6 = (TextView) findViewById(R.id.textView7); Display7 = (TextView) findViewById(R.id.textView8); Display8 = (TextView) findViewById(R.id.textView9); Display9 = (TextView) findViewById(R.id.textView10); Display1.setText(new String(Maze[0])); Display2.setText(new String(Maze[1])); Display3.setText(new String(Maze[2])); Display4.setText(new String(Maze[3])); Display5.setText(new String(Maze[4])); Display6.setText(new String(Maze[5])); Display7.setText(new String(Maze[6])); Display8.setText(new String(Maze[7])); Display9.setText(new String(Maze[8])); Display10 = (TextView) findViewById(R.id.textView12); Display11 = (TextView) findViewById(R.id.textView13); Display12 = (TextView) findViewById(R.id.textView14); Display13 = (TextView) findViewById(R.id.textView15); Display14 = (TextView) findViewById(R.id.textView16); Display15 = (TextView) findViewById(R.id.textView17); Display16 = (TextView) findViewById(R.id.textView18); Display17 = (TextView) findViewById(R.id.textView19); Display18 = (TextView) findViewById(R.id.textView20); button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { if(solve(Start.getX(), Start.getY())){ findpath(); Display10.setText(new String(Maze[0])); Display11.setText(new String(Maze[1])); Display12.setText(new String(Maze[2])); Display13.setText(new String(Maze[3])); Display14.setText(new String(Maze[4])); Display15.setText(new String(Maze[5])); Display16.setText(new String(Maze[6])); Display17.setText(new String(Maze[7])); Display18.setText(new String(Maze[8])); button.setVisibility(View.INVISIBLE); button2.setVisibility(0); } } }); button2 = (Button) findViewById(R.id.button2); button2.setVisibility(View.INVISIBLE); button2.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { for(String x: instructions){ if(x.equals("Forward")){ forward(); } else if (x.equals("Left")){ left(); forward(); } else if(x.equals("Right")){ right(); forward(); } } } }); }
public void javaToNative(Object object, TransferData transferData) { if (!checkMyType(object) || !isSupportedType(transferData)) { DND.error(DND.ERROR_INVALID_DATA); } try { byte[] buffer = Base64.encodeBytes(((DragAndDropContainer) object).getXML().getBytes()).getBytes(); super.javaToNative(buffer, transferData); } catch (Exception e) { LogWriter.getInstance().logError(toString(), "Unexpected error trying to put a string onto the XML Transfer type: " + e.toString()); LogWriter.getInstance().logError(toString(), Const.getStackTracker(e)); return; } }
public void javaToNative(Object object, TransferData transferData) { if (!checkMyType(object) ) { DND.error(DND.ERROR_INVALID_DATA); } try { byte[] buffer = Base64.encodeBytes(((DragAndDropContainer) object).getXML().getBytes()).getBytes(); super.javaToNative(buffer, transferData); } catch (Exception e) { LogWriter.getInstance().logError(toString(), "Unexpected error trying to put a string onto the XML Transfer type: " + e.toString()); LogWriter.getInstance().logError(toString(), Const.getStackTracker(e)); return; } }
public static void check(String[] argss){ ArrayList<String> args = new ArrayList<String>(); for(String s : argss) args.add(s); if(args.contains("randommu")){ Constants._murand = true; if(args.indexOf("randommu") < args.size() - 2){ Constants.randMuStart = Double.parseDouble(args.get(1)); Constants.randMuEnd = Double.parseDouble(args.get(2)); } } if(args.contains("mu")){ Constants.muCheck = true; if(args.indexOf("mu") < args.size() - 1){ Constants.muIncUp = Double.parseDouble(args.get(args.indexOf("mu") + 1 )); } } if(args.contains("constantep")){ Constants.ConstantEp = true; if(args.indexOf("constantep") < args.size() - 1){ Main.monitor.constants._epsilon = Double.parseDouble(args.get(args.indexOf("constantep") + 1 )); } } if(args.contains("repulse")){ Constants.Repulsive = true; if(args.indexOf("repulse") < args.size() - 1){ Constants.repuslivePer = Integer.parseInt(args.get(args.indexOf("repulsive") + 1 )); } } if(args.contains("nodes")){ Constants.resetVals(Integer.parseInt(args.get(args.indexOf("nodes") + 1)), Integer.parseInt(args.get(args.indexOf("nodes") + 2))); } }
public static void check(String[] argss){ ArrayList<String> args = new ArrayList<String>(); for(String s : argss) args.add(s); if(args.contains("randommu")){ Constants._murand = true; if(args.indexOf("randommu") < args.size() - 2){ Constants.randMuStart = Double.parseDouble(args.get(1)); Constants.randMuEnd = Double.parseDouble(args.get(2)); } } if(args.contains("mu")){ Constants.muCheck = true; if(args.indexOf("mu") < args.size() - 1){ Constants.muIncUp = Double.parseDouble(args.get(args.indexOf("mu")+1)); } } if(args.contains("constantep")){ Constants.ConstantEp = true; if(args.indexOf("constantep") < args.size() - 1){ Main.monitor.constants._epsilon = Double.parseDouble(args.get(args.indexOf("constantep") + 1 )); } } if(args.contains("repulse")){ Constants.Repulsive = true; if(args.indexOf("repulse") < args.size() - 1){ Constants.repuslivePer = Integer.parseInt(args.get(args.indexOf("repulse") + 1 )); } } if(args.contains("nodes")){ Constants.resetVals(Integer.parseInt(args.get(args.indexOf("nodes") + 1)), Integer.parseInt(args.get(args.indexOf("nodes") + 2))); } }
public boolean rebalance(RoutingAllocation allocation) { logger.trace("rebalance"); boolean changed = false; if (allocation.nodes().getSize() == 0) { return false; } NodesStatsResponse stats = nodeFsStats(); RoutingNode[] sortedNodesLeastToHigh = sortedNodesByShardCountLeastToHigh(allocation, stats); int lowIndex = 0; int highIndex = sortedNodesLeastToHigh.length - 1; boolean relocationPerformed; do { relocationPerformed = false; while (lowIndex != highIndex) { RoutingNode lowRoutingNode = sortedNodesLeastToHigh[lowIndex]; RoutingNode highRoutingNode = sortedNodesLeastToHigh[highIndex]; int averageNumOfShards = allocation.routingNodes().requiredAverageNumberOfShardsPerNode(); if (highRoutingNode.numberOfOwningShards() <= averageNumOfShards) { highIndex--; continue; } if (lowRoutingNode.shards().size() >= averageNumOfShards) { lowIndex++; continue; } boolean relocated = false; List<MutableShardRouting> startedShards = highRoutingNode.shardsWithState(STARTED); for (MutableShardRouting startedShard : startedShards) { if (!allocation.deciders().canRebalance(startedShard, allocation)) { continue; } if (allocation.deciders().canAllocate(startedShard, lowRoutingNode, allocation).allocate() && this.enoughDiskForShard(startedShard, lowRoutingNode, stats)) { changed = true; lowRoutingNode.add(new MutableShardRouting(startedShard.index(), startedShard.id(), lowRoutingNode.nodeId(), startedShard.currentNodeId(), startedShard.primary(), INITIALIZING, startedShard.version() + 1)); startedShard.relocate(lowRoutingNode.nodeId()); relocated = true; relocationPerformed = true; break; } } if (!relocated) { highIndex--; } } } while (relocationPerformed); if (changed || allocation.nodes().size() == 1) { return changed; } logger.info("Initiating shard swap check."); RoutingNode[] nodesSmallestToLargest = sortedNodesByFreeSpaceLeastToHigh(allocation, stats); for (RoutingNode node : nodesSmallestToLargest) { logger.info("Node: " + node.nodeId() + " -> " + averageAvailableBytes(stats.getNodesMap().get(node.nodeId()).fs())); } RoutingNode largestNode = nodesSmallestToLargest[nodesSmallestToLargest.length - 1]; RoutingNode smallestNode = nodesSmallestToLargest[0]; double largestNodeSize = 100 - averagePercentageFree(stats.getNodesMap().get(largestNode.nodeId()).fs()); double smallestNodeSize = 100 - averagePercentageFree(stats.getNodesMap().get(smallestNode.nodeId()).fs()); double sizeDifference = largestNodeSize - smallestNodeSize; logger.info("Checking size disparity: (" + sizeDifference + " >= " + this.minimumSwapDifferencePercentage + ")"); if (sizeDifference >= this.minimumAvailablePercentage) { logger.info("Size disparity found, checking for swappable shards."); HashMap<ShardId, Long> shardSizes = nodeShardStats(); List<MutableShardRouting> largestNodeShards = sortedStartedShardsOnNodeLargestToSmallest(largestNode, shardSizes); List<MutableShardRouting> smallestNodeShards = sortedStartedShardsOnNodeLargestToSmallest(smallestNode, shardSizes); Collections.reverse(smallestNodeShards); MutableShardRouting largestShardAvailableForRelocation = null; MutableShardRouting smallestShardAvailableForRelocation = null; for (MutableShardRouting shard : largestNodeShards) { if (allocation.deciders().canAllocate(shard, smallestNode, allocation).allocate()) { largestShardAvailableForRelocation = shard; break; } } for (MutableShardRouting shard : smallestNodeShards) { if (allocation.deciders().canAllocate(shard, largestNode, allocation).allocate()) { smallestShardAvailableForRelocation = shard; break; } } if (largestShardAvailableForRelocation == null && smallestShardAvailableForRelocation == null) { return changed; } logger.info("Swapping " + smallestShardAvailableForRelocation.shardId() + " and " + largestShardAvailableForRelocation); this.move(smallestShardAvailableForRelocation, largestNode, allocation); this.move(largestShardAvailableForRelocation, smallestNode, allocation); changed = true; } return changed; }
public boolean rebalance(RoutingAllocation allocation) { logger.trace("rebalance"); boolean changed = false; if (allocation.nodes().getSize() == 0) { return false; } NodesStatsResponse stats = nodeFsStats(); RoutingNode[] sortedNodesLeastToHigh = sortedNodesByShardCountLeastToHigh(allocation, stats); int lowIndex = 0; int highIndex = sortedNodesLeastToHigh.length - 1; boolean relocationPerformed; do { relocationPerformed = false; while (lowIndex != highIndex) { RoutingNode lowRoutingNode = sortedNodesLeastToHigh[lowIndex]; RoutingNode highRoutingNode = sortedNodesLeastToHigh[highIndex]; int averageNumOfShards = allocation.routingNodes().requiredAverageNumberOfShardsPerNode(); if (highRoutingNode.numberOfOwningShards() <= averageNumOfShards) { highIndex--; continue; } if (lowRoutingNode.shards().size() >= averageNumOfShards) { lowIndex++; continue; } boolean relocated = false; List<MutableShardRouting> startedShards = highRoutingNode.shardsWithState(STARTED); for (MutableShardRouting startedShard : startedShards) { if (!allocation.deciders().canRebalance(startedShard, allocation)) { continue; } if (allocation.deciders().canAllocate(startedShard, lowRoutingNode, allocation).allocate() && this.enoughDiskForShard(startedShard, lowRoutingNode, stats)) { changed = true; lowRoutingNode.add(new MutableShardRouting(startedShard.index(), startedShard.id(), lowRoutingNode.nodeId(), startedShard.currentNodeId(), startedShard.primary(), INITIALIZING, startedShard.version() + 1)); startedShard.relocate(lowRoutingNode.nodeId()); relocated = true; relocationPerformed = true; break; } } if (!relocated) { highIndex--; } } } while (relocationPerformed); if (changed || allocation.nodes().size() == 1) { return changed; } logger.info("Initiating shard swap check."); RoutingNode[] nodesSmallestToLargest = sortedNodesByFreeSpaceLeastToHigh(allocation, stats); RoutingNode largestNode = nodesSmallestToLargest[nodesSmallestToLargest.length - 1]; RoutingNode smallestNode = nodesSmallestToLargest[0]; double largestNodeSize = 100 - averagePercentageFree(stats.getNodesMap().get(largestNode.nodeId()).fs()); double smallestNodeSize = 100 - averagePercentageFree(stats.getNodesMap().get(smallestNode.nodeId()).fs()); double sizeDifference = largestNodeSize - smallestNodeSize; logger.info("Checking size disparity: " + largestNode.nodeId() + " -> " + smallestNode.nodeId() + " (" + sizeDifference + " >= " + this.minimumSwapDifferencePercentage + ")"); if (sizeDifference >= this.minimumAvailablePercentage) { logger.info("Size disparity found, checking for swappable shards."); HashMap<ShardId, Long> shardSizes = nodeShardStats(); List<MutableShardRouting> largestNodeShards = sortedStartedShardsOnNodeLargestToSmallest(largestNode, shardSizes); List<MutableShardRouting> smallestNodeShards = sortedStartedShardsOnNodeLargestToSmallest(smallestNode, shardSizes); Collections.reverse(smallestNodeShards); MutableShardRouting largestShardAvailableForRelocation = null; MutableShardRouting smallestShardAvailableForRelocation = null; for (MutableShardRouting shard : largestNodeShards) { if (allocation.deciders().canAllocate(shard, smallestNode, allocation).allocate()) { largestShardAvailableForRelocation = shard; break; } } for (MutableShardRouting shard : smallestNodeShards) { if (allocation.deciders().canAllocate(shard, largestNode, allocation).allocate()) { smallestShardAvailableForRelocation = shard; break; } } if (largestShardAvailableForRelocation == null && smallestShardAvailableForRelocation == null) { return changed; } logger.info("Swapping " + smallestShardAvailableForRelocation.shardId() + " and " + largestShardAvailableForRelocation); this.move(smallestShardAvailableForRelocation, largestNode, allocation); this.move(largestShardAvailableForRelocation, smallestNode, allocation); changed = true; } return changed; }
public static DescriptorExtensionList<WorkspaceUpdater,WorkspaceUpdaterDescriptor> all() { return Hudson.getInstance().getDescriptorList(WorkspaceUpdater.class); }
public static DescriptorExtensionList<WorkspaceUpdater,WorkspaceUpdaterDescriptor> all() { return (DescriptorExtensionList)Hudson.getInstance().getDescriptorList(WorkspaceUpdater.class); }
public Object[] sync(Connection con) { mCol.save(); HttpResponse ret = mServer.meta(); if (ret == null) { return null; } int returntype = ret.getStatusLine().getStatusCode(); if (returntype == 403){ return new Object[] {"badAuth"}; } else if (returntype != 200) { return new Object[] {"error", returntype, ret.getStatusLine().getReasonPhrase()}; } long rts; long lts; try { mCol.getDb().getDatabase().beginTransaction(); try { JSONArray ra = new JSONArray(mServer.stream2String(ret.getEntity().getContent())); mRMod = ra.getLong(0); mRScm = ra.getLong(1); mMaxUsn = ra.getInt(2); rts = ra.getLong(3); mMediaUsn = ra.getInt(4); Log.i(AnkiDroidApp.TAG, "Sync: getting meta data"); JSONArray la = meta(); mLMod = la.getLong(0); mLScm = la.getLong(1); mMinUsn = la.getInt(2); lts = la.getLong(3); long diff = Math.abs(rts - lts); if (diff > 300) { return new Object[]{"clockOff", diff}; } if (mLMod == mRMod) { Log.i(AnkiDroidApp.TAG, "Sync: no changes - returning"); return new Object[]{"noChanges"}; } else if (mLScm != mRScm) { Log.i(AnkiDroidApp.TAG, "Sync: full sync necessary - returning"); return new Object[]{"fullSync"}; } mLNewer = mLMod > mRMod; con.publishProgress(R.string.sync_deletions_message); Log.i(AnkiDroidApp.TAG, "Sync: collection removed data"); JSONObject lrem = removed(); JSONObject o = new JSONObject(); o.put("minUsn", mMinUsn); o.put("lnewer", mLNewer); o.put("graves", lrem); Log.i(AnkiDroidApp.TAG, "Sync: sending and receiving removed data"); JSONObject rrem = mServer.start(o); if (rrem == null) { Log.i(AnkiDroidApp.TAG, "Sync: error - returning"); return null; } if (rrem.has("errorType")) { Log.i(AnkiDroidApp.TAG, "Sync: error - returning"); return new Object[]{"error", rrem.get("errorType"), rrem.get("errorReason")}; } Log.i(AnkiDroidApp.TAG, "Sync: applying removed data"); remove(rrem); con.publishProgress(R.string.sync_small_objects_message); Log.i(AnkiDroidApp.TAG, "Sync: collection small changes"); JSONObject lchg = changes(); JSONObject sch = new JSONObject(); sch.put("changes", lchg); Log.i(AnkiDroidApp.TAG, "Sync: sending and receiving small changes"); JSONObject rchg = mServer.applyChanges(sch); if (rchg == null) { Log.i(AnkiDroidApp.TAG, "Sync: error - returning"); return null; } if (rchg.has("errorType")) { Log.i(AnkiDroidApp.TAG, "Sync: error - returning"); return new Object[]{"error", rchg.get("errorType"), rchg.get("errorReason")}; } Log.i(AnkiDroidApp.TAG, "Sync: mergin small changes"); mergeChanges(lchg, rchg); con.publishProgress(R.string.sync_download_chunk); while (true) { Log.i(AnkiDroidApp.TAG, "Sync: downloading chunked data"); JSONObject chunk = mServer.chunk(); if (chunk == null) { Log.i(AnkiDroidApp.TAG, "Sync: error - returning"); return null; } if (chunk.has("errorType")) { Log.i(AnkiDroidApp.TAG, "Sync: error - returning"); return new Object[]{"error", chunk.get("errorType"), chunk.get("errorReason")}; } Log.i(AnkiDroidApp.TAG, "Sync: applying chunked data"); applyChunk(chunk); if (chunk.getBoolean("done")) { break; } } con.publishProgress(R.string.sync_upload_chunk); while (true) { Log.i(AnkiDroidApp.TAG, "Sync: collecting chunked data"); JSONObject chunk = chunk(); JSONObject sech = new JSONObject(); sech.put("chunk", chunk); Log.i(AnkiDroidApp.TAG, "Sync: sending chunked data"); mServer.applyChunk(sech); if (chunk.getBoolean("done")) { break; } } JSONArray c = sanityCheck(); if (c == null) { return new Object[]{"error", 200, "sanity check error on local"}; } JSONArray s = mServer.sanityCheck(); if (s.getString(0).equals("error")) { return new Object[]{"error", 200, "sanity check error on server"}; } boolean error = false; for (int i = 0; i < s.getJSONArray(0).length(); i++) { if (c.getJSONArray(0).getLong(i) != s.getJSONArray(0).getLong(i)) { error = true; } } for (int i = 1; i < s.length(); i++) { if (c.getLong(i) != s.getLong(i)) { error = true; } } if (error) { return new Object[]{"error", 200, "sanity check failed:\nlocal: " + c.toString() + "\nremote: " + s.toString()}; } con.publishProgress(R.string.sync_finish_message); Log.i(AnkiDroidApp.TAG, "Sync: sending finish command"); long mod = mServer.finish(); if (mod == 0) { return new Object[]{"finishError"}; } Log.i(AnkiDroidApp.TAG, "Sync: finishing"); finish(mod); mCol.getDb().getDatabase().setTransactionSuccessful(); } finally { mCol.getDb().getDatabase().setTransactionSuccessful(); } } catch (JSONException e) { throw new RuntimeException(e); } catch (IllegalStateException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } return new Object[]{"success"}; }
public Object[] sync(Connection con) { mCol.save(); HttpResponse ret = mServer.meta(); if (ret == null) { return null; } int returntype = ret.getStatusLine().getStatusCode(); if (returntype == 403){ return new Object[] {"badAuth"}; } else if (returntype != 200) { return new Object[] {"error", returntype, ret.getStatusLine().getReasonPhrase()}; } long rts; long lts; try { mCol.getDb().getDatabase().beginTransaction(); try { JSONArray ra = new JSONArray(mServer.stream2String(ret.getEntity().getContent())); mRMod = ra.getLong(0); mRScm = ra.getLong(1); mMaxUsn = ra.getInt(2); rts = ra.getLong(3); mMediaUsn = ra.getInt(4); Log.i(AnkiDroidApp.TAG, "Sync: getting meta data"); JSONArray la = meta(); mLMod = la.getLong(0); mLScm = la.getLong(1); mMinUsn = la.getInt(2); lts = la.getLong(3); long diff = Math.abs(rts - lts); if (diff > 300) { return new Object[]{"clockOff", diff}; } if (mLMod == mRMod) { Log.i(AnkiDroidApp.TAG, "Sync: no changes - returning"); return new Object[]{"noChanges"}; } else if (mLScm != mRScm) { Log.i(AnkiDroidApp.TAG, "Sync: full sync necessary - returning"); return new Object[]{"fullSync"}; } mLNewer = mLMod > mRMod; con.publishProgress(R.string.sync_deletions_message); Log.i(AnkiDroidApp.TAG, "Sync: collection removed data"); JSONObject lrem = removed(); JSONObject o = new JSONObject(); o.put("minUsn", mMinUsn); o.put("lnewer", mLNewer); o.put("graves", lrem); Log.i(AnkiDroidApp.TAG, "Sync: sending and receiving removed data"); JSONObject rrem = mServer.start(o); if (rrem == null) { Log.i(AnkiDroidApp.TAG, "Sync: error - returning"); return null; } if (rrem.has("errorType")) { Log.i(AnkiDroidApp.TAG, "Sync: error - returning"); return new Object[]{"error", rrem.get("errorType"), rrem.get("errorReason")}; } Log.i(AnkiDroidApp.TAG, "Sync: applying removed data"); remove(rrem); con.publishProgress(R.string.sync_small_objects_message); Log.i(AnkiDroidApp.TAG, "Sync: collection small changes"); JSONObject lchg = changes(); JSONObject sch = new JSONObject(); sch.put("changes", lchg); Log.i(AnkiDroidApp.TAG, "Sync: sending and receiving small changes"); JSONObject rchg = mServer.applyChanges(sch); if (rchg == null) { Log.i(AnkiDroidApp.TAG, "Sync: error - returning"); return null; } if (rchg.has("errorType")) { Log.i(AnkiDroidApp.TAG, "Sync: error - returning"); return new Object[]{"error", rchg.get("errorType"), rchg.get("errorReason")}; } Log.i(AnkiDroidApp.TAG, "Sync: mergin small changes"); mergeChanges(lchg, rchg); con.publishProgress(R.string.sync_download_chunk); while (true) { Log.i(AnkiDroidApp.TAG, "Sync: downloading chunked data"); JSONObject chunk = mServer.chunk(); if (chunk == null) { Log.i(AnkiDroidApp.TAG, "Sync: error - returning"); return null; } if (chunk.has("errorType")) { Log.i(AnkiDroidApp.TAG, "Sync: error - returning"); return new Object[]{"error", chunk.get("errorType"), chunk.get("errorReason")}; } Log.i(AnkiDroidApp.TAG, "Sync: applying chunked data"); applyChunk(chunk); if (chunk.getBoolean("done")) { break; } } con.publishProgress(R.string.sync_upload_chunk); while (true) { Log.i(AnkiDroidApp.TAG, "Sync: collecting chunked data"); JSONObject chunk = chunk(); JSONObject sech = new JSONObject(); sech.put("chunk", chunk); Log.i(AnkiDroidApp.TAG, "Sync: sending chunked data"); mServer.applyChunk(sech); if (chunk.getBoolean("done")) { break; } } JSONArray c = sanityCheck(); if (c == null) { return new Object[]{"error", 200, "sanity check error on local"}; } JSONArray s = mServer.sanityCheck(); if (s.getString(0).equals("error")) { return new Object[]{"error", 200, "sanity check error on server"}; } boolean error = false; for (int i = 0; i < s.getJSONArray(0).length(); i++) { if (c.getJSONArray(0).getLong(i) != s.getJSONArray(0).getLong(i)) { error = true; } } for (int i = 1; i < s.length(); i++) { if (c.getLong(i) != s.getLong(i)) { error = true; } } if (error) { return new Object[]{"error", 200, "sanity check failed:\nlocal: " + c.toString() + "\nremote: " + s.toString()}; } con.publishProgress(R.string.sync_finish_message); Log.i(AnkiDroidApp.TAG, "Sync: sending finish command"); long mod = mServer.finish(); if (mod == 0) { return new Object[]{"finishError"}; } Log.i(AnkiDroidApp.TAG, "Sync: finishing"); finish(mod); mCol.getDb().getDatabase().setTransactionSuccessful(); } finally { mCol.getDb().getDatabase().endTransaction(); } } catch (JSONException e) { throw new RuntimeException(e); } catch (IllegalStateException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } return new Object[]{"success"}; }
public void testGetDisplayName() { Assert.assertEquals("Adobe Portable Document Format", ContentType.PDF.getDisplayName()); Assert.assertEquals("Open eBook Publication Structure", ContentType.valueOf( "application/oebps-package+xml").getDisplayName()); Assert.assertEquals(".pdf", ContentType.PDF.getExtension()); Assert.assertEquals(".wpd", ContentType.valueOf("application/wordperfect").getExtension()); Assert.assertArrayEquals(new String[]{ ".wpd", ".wp", ".wp5", ".wp6" }, ContentType.valueOf("application/wordperfect").getExtensions()); }
public void testGetDisplayName() { Assert.assertEquals("Adobe Portable Document Format", ContentType.PDF.getDisplayName()); Assert.assertEquals("Open eBook Publication Structure", ContentType.valueOf( "application/oebps-package+xml").getDisplayName()); Assert.assertEquals("pdf", ContentType.PDF.getExtension()); Assert.assertEquals("wpd", ContentType.valueOf("application/wordperfect").getExtension()); Assert.assertArrayEquals(new String[]{ "wpd", "wp", "wp5", "wp6" }, ContentType.valueOf("application/wordperfect").getExtensions()); }
protected Filter performBuild() throws Exception { Assert.state(!securityFilterChainBuilders.isEmpty(), "At least one SecurityFilterBuilder needs to be specified. Invoke FilterChainProxyBuilder.securityFilterChains"); int chainSize = ignoredRequests.size() + securityFilterChainBuilders.size(); List<SecurityFilterChain> securityFilterChains = new ArrayList<SecurityFilterChain>(chainSize); for(RequestMatcher ignoredRequest : ignoredRequests) { securityFilterChains.add(new DefaultSecurityFilterChain(ignoredRequest)); } for(SecurityBuilder<? extends SecurityFilterChain> securityFilterChainBuilder : securityFilterChainBuilders) { securityFilterChains.add(securityFilterChainBuilder.build()); } FilterChainProxy filterChainProxy = new FilterChainProxy(securityFilterChains); if(httpFirewall != null) { filterChainProxy.setFirewall(httpFirewall); } filterChainProxy.afterPropertiesSet(); Filter result = filterChainProxy; if(debugEnabled) { logger.warn("\n\n" + "********************************************************************\n" + "********** Security debugging is enabled. *************\n" + "********** This may include sensitive information. *************\n" + "********** Do not use in a production system! *************\n" + "********************************************************************\n\n"); result = new DebugFilter(filterChainProxy); } postBuildAction.run(); return result; }
protected Filter performBuild() throws Exception { Assert.state(!securityFilterChainBuilders.isEmpty(), "At least one SecurityBuilder<? extends SecurityFilterChain> needs to be specified. Typically this done by adding a @Configuration that extends WebSecurityConfigurerAdapter. More advanced users can invoke " + WebSecurity.class.getSimpleName() + ".addSecurityFilterChainBuilder directly"); int chainSize = ignoredRequests.size() + securityFilterChainBuilders.size(); List<SecurityFilterChain> securityFilterChains = new ArrayList<SecurityFilterChain>(chainSize); for(RequestMatcher ignoredRequest : ignoredRequests) { securityFilterChains.add(new DefaultSecurityFilterChain(ignoredRequest)); } for(SecurityBuilder<? extends SecurityFilterChain> securityFilterChainBuilder : securityFilterChainBuilders) { securityFilterChains.add(securityFilterChainBuilder.build()); } FilterChainProxy filterChainProxy = new FilterChainProxy(securityFilterChains); if(httpFirewall != null) { filterChainProxy.setFirewall(httpFirewall); } filterChainProxy.afterPropertiesSet(); Filter result = filterChainProxy; if(debugEnabled) { logger.warn("\n\n" + "********************************************************************\n" + "********** Security debugging is enabled. *************\n" + "********** This may include sensitive information. *************\n" + "********** Do not use in a production system! *************\n" + "********************************************************************\n\n"); result = new DebugFilter(filterChainProxy); } postBuildAction.run(); return result; }
public static void main(String[] av) { Date now = new Date(); long t = now.getTime(); t -= 700*24*60*60*1000; Date then = new Date(t); System.out.println("Seven hundred days ago was " + then); }
public static void main(String[] av) { Date now = new Date(); long t = now.getTime(); t -= 700L*24*60*60*1000; Date then = new Date(t); System.out.println("Seven hundred days ago was " + then); }
private void readTRDCACFile(Stimuli sd, URL fileURL, List<PALine> paList, Analysis.AnalysisType analysisType) throws IOException { if (openBinaryInput(fileURL)) return; eofReached = false; resetBinaryTRACDCReader(); Analysis an = new Analysis(sd, analysisType); startProgressDialog("HSpice " + analysisType.toString() + " analysis", fileURL.getFile()); System.out.println("Reading HSpice " + analysisType.toString() + " analysis " + fileURL.getFile()) ; int nodcnt = getHSpiceInt(); int numnoi = getHSpiceInt(); int cndcnt = getHSpiceInt(); StringBuffer line = new StringBuffer(); for(int j=0; j<4; j++) line.append((char)getByteFromFile()); int multiplier = TextUtils.atoi(line.toString(), 0, 10); nodcnt += multiplier * 10000; int numSignals = numnoi + nodcnt - 1; if (numSignals <= 0) { System.out.println("Error reading " + fileURL.getFile()); return; } int version = getHSpiceInt(); if (version != 9007 && version != 9601) System.out.println("Warning: may not be able to read HSpice files of type " + version); for(int j=0; j<76; j++) { int k = getByteFromFile(); if (!isTRACDCBinary && k == '\n') j--; } for(int j=0; j<16; j++) getByteFromFile(); for(int j=0; j<72; j++) { int k = getByteFromFile(); if (!isTRACDCBinary && k == '\n') j--; } int sweepcnt = getHSpiceInt(); if (cndcnt == 0) sweepcnt = 0; for(int j=0; j<76; j++) { int k = getByteFromFile(); if (!isTRACDCBinary && k == '\n') j--; } String [] signalNames = new String[numSignals]; int [] signalTypes = new int[numSignals]; for(int k=0; k<=numSignals; k++) { line = new StringBuffer(); for(int j=0; j<8; j++) { int l = getByteFromFile(); line.append((char)l); if (!isTRACDCBinary && l == '\n') j--; } if (k == 0) continue; int l = k - nodcnt; if (k < nodcnt) l = k + numnoi - 1; signalTypes[l] = TextUtils.atoi(line.toString(), 0, 10); } boolean paMissingWarned = false; for(int k=0; k<=numSignals; k++) { int j = 0; line = new StringBuffer(); for(;;) { int l = getByteFromFile(); if (l == '\n') continue; if (l == ' ') break; line.append((char)l); j++; if (version == 9007 && j >= 16) break; } int l = (j+16) / 16 * 16 - 1; if (version == 9007) { l = (j+15) / 16 * 16 - 1; } for(; j<l; j++) { int i = getByteFromFile(); if (!isTRACDCBinary && i == '\n') { j--; continue; } } if (k == 0) continue; int startPos = 0; int openPos = line.indexOf("("); if (openPos >= 0) startPos = openPos+1; for(j=startPos; j<line.length(); j++) { if (line.charAt(j) == ':') break; if (!TextUtils.isDigit(line.charAt(j))) break; } if (j < line.length() && line.charAt(j) == ':') { l = TextUtils.atoi(line.toString().substring(startPos), 0, 10); PALine foundPALine = null; if (paList == null) { if (!paMissingWarned) System.out.println("ERROR: there should be a ." + paExtension + " file with extra signal names"); paMissingWarned = true; } else { for(PALine paLine : paList) { if (paLine.number == l) { foundPALine = paLine; break; } } } if (foundPALine != null) { StringBuffer newSB = new StringBuffer(); newSB.append(line.substring(0, startPos)); newSB.append(foundPALine.string); newSB.append(line.substring(j+1)); line = newSB; } } else { if (line.indexOf(".") >= 0) { String fixedLine = removeLeadingX(line.toString()); line = new StringBuffer(); line.append(fixedLine); } } openPos = line.indexOf("("); if (openPos >= 0) { int lastDot = line.lastIndexOf("."); if (lastDot >= 0) { StringBuffer newSB = new StringBuffer(); newSB.append(line.substring(openPos+1, lastDot+1)); newSB.append(line.substring(0, openPos+1)); newSB.append(line.substring(lastDot+1)); line = newSB; } } if (k < nodcnt) l = k + numnoi - 1; else l = k - nodcnt; signalNames[l] = line.toString(); } if (cndcnt != 0) { int j = 0; line = new StringBuffer(); for(;;) { int l = getByteFromFile(); if (l == '\n') continue; if (l == ' ') break; line.append((char)l); j++; if (j >= 16) break; } int l = (j+15) / 16 * 16 - 1; for(; j<l; j++) { int i = getByteFromFile(); if (!isTRACDCBinary && i == '\n') { j--; continue; } } } line = new StringBuffer(); if (!isTRACDCBinary) { for(int j=0; ; j++) { int l = getByteFromFile(); if (l == '\n') break; if (j < 4) line.append(l); } } else { for(int j=0; j<4; j++) line.append((char)getByteFromFile()); } if (!line.toString().equals("$&%#")) { System.out.println("HSpice header improperly terminated (got "+line.toString()+")"); closeInput(); stopProgressDialog(); return; } resetBinaryTRACDCReader(); HSpiceAnalogSignal [] allSignals = new HSpiceAnalogSignal[numSignals]; for(int k=0; k<numSignals; k++) { HSpiceAnalogSignal as = new HSpiceAnalogSignal(an); allSignals[k] = as; int lastDotPos = signalNames[k].lastIndexOf('.'); if (lastDotPos >= 0) { as.setSignalContext(signalNames[k].substring(0, lastDotPos)); as.setSignalName(signalNames[k].substring(lastDotPos+1)); } else { as.setSignalName(signalNames[k]); } } List<List<float[]>> theSweeps = new ArrayList<List<float[]>>(); int sweepCounter = sweepcnt; for(;;) { if (sweepcnt > 0) { float sweepValue = getHSpiceFloat(); if (eofReached) break; an.addSweep(new Double(sweepValue)); } List<float[]> allTheData = new ArrayList<float[]>(); for(;;) { float [] oneSetOfData = new float[numSignals+1]; float time = getHSpiceFloat(); if (eofReached) break; oneSetOfData[0] = time; for(int k=0; k<numSignals; k++) { float value = getHSpiceFloat(); if (eofReached) break; oneSetOfData[(k+numnoi)%numSignals+1] = value; } if (eofReached) break; allTheData.add(oneSetOfData); } int numEvents = allTheData.size(); an.addCommonTime(numEvents); theSweeps.add(allTheData); sweepCounter--; if (sweepCounter <= 0) break; eofReached = false; } closeInput(); for(int sigNum=0; sigNum<numSignals; sigNum++) { HSpiceAnalogSignal as = allSignals[sigNum]; as.sigData = new float[theSweeps.size()][]; for(int sweepNum=0; sweepNum<theSweeps.size(); sweepNum++) { List<float[]> allTheData = theSweeps.get(sweepNum); as.sigData[sweepNum] = new float[allTheData.size()]; for (int eventNum = 0; eventNum < allTheData.size(); eventNum++) { float [] oneSetOfData = allTheData.get(eventNum); as.sigData[sweepNum][eventNum] = oneSetOfData[sigNum+1]; if (sigNum == 0) an.setCommonTime(eventNum, sweepNum, oneSetOfData[0]); } } } an.setBoundsDirty(); stopProgressDialog(); }
private void readTRDCACFile(Stimuli sd, URL fileURL, List<PALine> paList, Analysis.AnalysisType analysisType) throws IOException { if (openBinaryInput(fileURL)) return; eofReached = false; resetBinaryTRACDCReader(); Analysis an = new Analysis(sd, analysisType); startProgressDialog("HSpice " + analysisType.toString() + " analysis", fileURL.getFile()); System.out.print("\nReading HSpice " + analysisType.toString() + " analysis '" + fileURL.getFile() + "'") ; int nodcnt = getHSpiceInt(); int numnoi = getHSpiceInt(); int cndcnt = getHSpiceInt(); StringBuffer line = new StringBuffer(); for(int j=0; j<4; j++) line.append((char)getByteFromFile()); int multiplier = TextUtils.atoi(line.toString(), 0, 10); nodcnt += multiplier * 10000; int numSignals = numnoi + nodcnt - 1; if (numSignals <= 0) { System.out.println(".... Error reading " + fileURL.getFile()); closeInput(); stopProgressDialog(); return; } int version = getHSpiceInt(); if (version != 9007 && version != 9601) System.out.println("Warning: may not be able to read HSpice files of type " + version); for(int j=0; j<76; j++) { int k = getByteFromFile(); if (!isTRACDCBinary && k == '\n') j--; } for(int j=0; j<16; j++) getByteFromFile(); for(int j=0; j<72; j++) { int k = getByteFromFile(); if (!isTRACDCBinary && k == '\n') j--; } int sweepcnt = getHSpiceInt(); if (cndcnt == 0) sweepcnt = 0; for(int j=0; j<76; j++) { int k = getByteFromFile(); if (!isTRACDCBinary && k == '\n') j--; } String [] signalNames = new String[numSignals]; int [] signalTypes = new int[numSignals]; for(int k=0; k<=numSignals; k++) { line = new StringBuffer(); for(int j=0; j<8; j++) { int l = getByteFromFile(); line.append((char)l); if (!isTRACDCBinary && l == '\n') j--; } if (k == 0) continue; int l = k - nodcnt; if (k < nodcnt) l = k + numnoi - 1; signalTypes[l] = TextUtils.atoi(line.toString(), 0, 10); } boolean paMissingWarned = false; for(int k=0; k<=numSignals; k++) { int j = 0; line = new StringBuffer(); for(;;) { int l = getByteFromFile(); if (l == '\n') continue; if (l == ' ') break; line.append((char)l); j++; if (version == 9007 && j >= 16) break; } int l = (j+16) / 16 * 16 - 1; if (version == 9007) { l = (j+15) / 16 * 16 - 1; } for(; j<l; j++) { int i = getByteFromFile(); if (!isTRACDCBinary && i == '\n') { j--; continue; } } if (k == 0) continue; int startPos = 0; int openPos = line.indexOf("("); if (openPos >= 0) startPos = openPos+1; for(j=startPos; j<line.length(); j++) { if (line.charAt(j) == ':') break; if (!TextUtils.isDigit(line.charAt(j))) break; } if (j < line.length() && line.charAt(j) == ':') { l = TextUtils.atoi(line.toString().substring(startPos), 0, 10); PALine foundPALine = null; if (paList == null) { if (!paMissingWarned) System.out.println("ERROR: there should be a ." + paExtension + " file with extra signal names"); paMissingWarned = true; } else { for(PALine paLine : paList) { if (paLine.number == l) { foundPALine = paLine; break; } } } if (foundPALine != null) { StringBuffer newSB = new StringBuffer(); newSB.append(line.substring(0, startPos)); newSB.append(foundPALine.string); newSB.append(line.substring(j+1)); line = newSB; } } else { if (line.indexOf(".") >= 0) { String fixedLine = removeLeadingX(line.toString()); line = new StringBuffer(); line.append(fixedLine); } } openPos = line.indexOf("("); if (openPos >= 0) { int lastDot = line.lastIndexOf("."); if (lastDot >= 0) { StringBuffer newSB = new StringBuffer(); newSB.append(line.substring(openPos+1, lastDot+1)); newSB.append(line.substring(0, openPos+1)); newSB.append(line.substring(lastDot+1)); line = newSB; } } if (k < nodcnt) l = k + numnoi - 1; else l = k - nodcnt; signalNames[l] = line.toString(); } if (cndcnt != 0) { int j = 0; line = new StringBuffer(); for(;;) { int l = getByteFromFile(); if (l == '\n') continue; if (l == ' ') break; line.append((char)l); j++; if (j >= 16) break; } int l = (j+15) / 16 * 16 - 1; for(; j<l; j++) { int i = getByteFromFile(); if (!isTRACDCBinary && i == '\n') { j--; continue; } } } line = new StringBuffer(); if (!isTRACDCBinary) { for(int j=0; ; j++) { int l = getByteFromFile(); if (l == '\n') break; if (j < 4) line.append(l); } } else { for(int j=0; j<4; j++) line.append((char)getByteFromFile()); } if (!line.toString().equals("$&%#")) { System.out.println("..... HSpice header improperly terminated (got "+line.toString()+")"); closeInput(); stopProgressDialog(); return; } resetBinaryTRACDCReader(); HSpiceAnalogSignal [] allSignals = new HSpiceAnalogSignal[numSignals]; for(int k=0; k<numSignals; k++) { HSpiceAnalogSignal as = new HSpiceAnalogSignal(an); allSignals[k] = as; int lastDotPos = signalNames[k].lastIndexOf('.'); if (lastDotPos >= 0) { as.setSignalContext(signalNames[k].substring(0, lastDotPos)); as.setSignalName(signalNames[k].substring(lastDotPos+1)); } else { as.setSignalName(signalNames[k]); } } List<List<float[]>> theSweeps = new ArrayList<List<float[]>>(); int sweepCounter = sweepcnt; for(;;) { if (sweepcnt > 0) { float sweepValue = getHSpiceFloat(); if (eofReached) break; an.addSweep(new Double(sweepValue)); } List<float[]> allTheData = new ArrayList<float[]>(); for(;;) { float [] oneSetOfData = new float[numSignals+1]; float time = getHSpiceFloat(); if (eofReached) break; oneSetOfData[0] = time; for(int k=0; k<numSignals; k++) { float value = getHSpiceFloat(); if (eofReached) break; oneSetOfData[(k+numnoi)%numSignals+1] = value; } if (eofReached) break; allTheData.add(oneSetOfData); } int numEvents = allTheData.size(); an.addCommonTime(numEvents); theSweeps.add(allTheData); sweepCounter--; if (sweepCounter <= 0) break; eofReached = false; } closeInput(); for(int sigNum=0; sigNum<numSignals; sigNum++) { HSpiceAnalogSignal as = allSignals[sigNum]; as.sigData = new float[theSweeps.size()][]; for(int sweepNum=0; sweepNum<theSweeps.size(); sweepNum++) { List<float[]> allTheData = theSweeps.get(sweepNum); as.sigData[sweepNum] = new float[allTheData.size()]; for (int eventNum = 0; eventNum < allTheData.size(); eventNum++) { float [] oneSetOfData = allTheData.get(eventNum); as.sigData[sweepNum][eventNum] = oneSetOfData[sigNum+1]; if (sigNum == 0) an.setCommonTime(eventNum, sweepNum, oneSetOfData[0]); } } } an.setBoundsDirty(); stopProgressDialog(); System.out.print("... Done"); }
private static void refreshModules() { REGISTERED_MODULES.clear(); for (java.util.Map.Entry<Bundle, List<String>> entry : new LinkedHashSet<java.util.Map.Entry<Bundle, List<String>>>( EXTENDING_BUNDLES.entrySet())) { for (String path : entry.getValue()) { String actualPath = path; if (actualPath.charAt(0) != '/') { actualPath = '/' + actualPath; } if (actualPath.charAt(actualPath.length() - 1) == '/') { actualPath = actualPath.substring(0, actualPath.length() - 1); } if (actualPath.startsWith("/src") || actualPath.startsWith("/bin")) { actualPath = actualPath.substring(actualPath.indexOf('/', 2)); } final String filePattern = "*." + IAcceleoConstants.EMTL_FILE_EXTENSION; Enumeration<URL> emtlFiles = entry.getKey().findEntries("/", filePattern, true); if (emtlFiles == null) { AcceleoEnginePlugin.log(AcceleoEngineMessages.getString( "AcceleoDynamicTemplatesEclipseUtil.MissingDynamicTemplates", entry.getKey() .getSymbolicName(), path), false); return; } try { while (emtlFiles.hasMoreElements()) { final URL next = emtlFiles.nextElement(); String emtlPath = next.getPath(); emtlPath.substring(0, emtlPath.lastIndexOf('/')); if (emtlPath.endsWith(actualPath)) { final File moduleFile = new File(FileLocator.toFileURL(next).getFile()); if (moduleFile.exists() && moduleFile.canRead()) { REGISTERED_MODULES.add(moduleFile); } } } } catch (IOException e) { AcceleoEnginePlugin.log(e, false); } } } }
private static void refreshModules() { REGISTERED_MODULES.clear(); for (java.util.Map.Entry<Bundle, List<String>> entry : new LinkedHashSet<java.util.Map.Entry<Bundle, List<String>>>( EXTENDING_BUNDLES.entrySet())) { for (String path : entry.getValue()) { String actualPath = path; if (actualPath.charAt(0) != '/') { actualPath = '/' + actualPath; } if (actualPath.charAt(actualPath.length() - 1) == '/') { actualPath = actualPath.substring(0, actualPath.length() - 1); } if (actualPath.startsWith("/src") || actualPath.startsWith("/bin")) { int firstFragmentEnd = actualPath.indexOf('/', 2); if (firstFragmentEnd > 0) { actualPath = actualPath.substring(firstFragmentEnd); } else { actualPath = "/"; } } final String filePattern = "*." + IAcceleoConstants.EMTL_FILE_EXTENSION; Enumeration<URL> emtlFiles = entry.getKey().findEntries("/", filePattern, true); if (emtlFiles == null) { AcceleoEnginePlugin.log(AcceleoEngineMessages.getString( "AcceleoDynamicTemplatesEclipseUtil.MissingDynamicTemplates", entry.getKey() .getSymbolicName(), path), false); return; } try { while (emtlFiles.hasMoreElements()) { final URL next = emtlFiles.nextElement(); String emtlPath = next.getPath(); emtlPath.substring(0, emtlPath.lastIndexOf('/')); if (emtlPath.endsWith(actualPath)) { final File moduleFile = new File(FileLocator.toFileURL(next).getFile()); if (moduleFile.exists() && moduleFile.canRead()) { REGISTERED_MODULES.add(moduleFile); } } } } catch (IOException e) { AcceleoEnginePlugin.log(e, false); } } } }
public static byte[] build_fixed_int(int size, long value) { byte[] packet = new byte[size]; if (size == 8) { packet[0] = (byte) ((value >> 0) & 0xFF); packet[1] = (byte) ((value >> 8) & 0xFF); packet[2] = (byte) ((value >> 16) & 0xFF); packet[3] = (byte) ((value >> 24) & 0xFF); packet[4] = (byte) ((value >> 32) & 0xFF); packet[5] = (byte) ((value >> 40) & 0xFF); packet[6] = (byte) ((value >> 48) & 0xFF); packet[7] = (byte) ((value >> 56) & 0xFF); } else if (size == 4) { packet[0] = (byte) ((value >> 0) & 0xFF); packet[1] = (byte) ((value >> 8) & 0xFF); packet[2] = (byte) ((value >> 16) & 0xFF); packet[3] = (byte) ((value >> 24) & 0xFF); } else if (size == 3) { packet[0] = (byte) ((value >> 0) & 0xFF); packet[1] = (byte) ((value >> 8) & 0xFF); packet[2] = (byte) ((value >> 16) & 0xFF); } else if (size == 2) { packet[0] = (byte) ((value >> 0) & 0xFF); packet[1] = (byte) ((value >> 8) & 0xFF); } else if (size == 1) { packet[0] = (byte) ((value >> 0) & 0xFF); } else { Logger.getLogger("MySQL.Proto").fatal("Encoding int["+size+"] "+value+" failed!"); return null; } return packet; }
public static byte[] build_fixed_int(int size, long value) { byte[] packet = new byte[size]; if (size == 8) { packet[0] = (byte) ((value >> 0) & 0xFF); packet[1] = (byte) ((value >> 8) & 0xFF); packet[2] = (byte) ((value >> 16) & 0xFF); packet[3] = (byte) ((value >> 24) & 0xFF); packet[4] = (byte) ((value >> 32) & 0xFF); packet[5] = (byte) ((value >> 40) & 0xFF); packet[6] = (byte) ((value >> 48) & 0xFF); packet[7] = (byte) ((value >> 56) & 0xFF); } else if (size == 6) { packet[0] = (byte) ((value >> 0) & 0xFF); packet[1] = (byte) ((value >> 8) & 0xFF); packet[2] = (byte) ((value >> 16) & 0xFF); packet[3] = (byte) ((value >> 24) & 0xFF); packet[4] = (byte) ((value >> 32) & 0xFF); packet[5] = (byte) ((value >> 40) & 0xFF); } else if (size == 4) { packet[0] = (byte) ((value >> 0) & 0xFF); packet[1] = (byte) ((value >> 8) & 0xFF); packet[2] = (byte) ((value >> 16) & 0xFF); packet[3] = (byte) ((value >> 24) & 0xFF); } else if (size == 3) { packet[0] = (byte) ((value >> 0) & 0xFF); packet[1] = (byte) ((value >> 8) & 0xFF); packet[2] = (byte) ((value >> 16) & 0xFF); } else if (size == 2) { packet[0] = (byte) ((value >> 0) & 0xFF); packet[1] = (byte) ((value >> 8) & 0xFF); } else if (size == 1) { packet[0] = (byte) ((value >> 0) & 0xFF); } else { Logger.getLogger("MySQL.Proto").fatal("Encoding int["+size+"] "+value+" failed!"); return null; } return packet; }
public void complete(CompleteOperation completeOperation) { String line = completeOperation.getBuffer(); ShellContext shellContext = shell.newShellContext(); final ShellCommand cmd = shell.findCommand(shellContext, line); if (cmd == null) { Collection<ShellCommand> commands = shell.findMatchingCommands(shellContext, line); for (ShellCommand command : commands) { completeOperation.addCompletionCandidate(command.getName()); } } else { try { ParameterInt param = cmd.getParameter(); ParsedCompleteObject completeObject = cmd.parseCompleteObject(line); if (completeObject.doDisplayOptions()) { if (completeObject.getName() != null && !completeObject.getName().isEmpty()) { List<String> possibleOptions = param.findPossibleLongNamesWitdDash(completeObject.getName()); completeOperation.addCompletionCandidates(possibleOptions); } else { List<String> optionNames = param.getOptionLongNamesWithDash(); removeExistingOptions(line, optionNames); completeOperation.addCompletionCandidates(optionNames); } } else { final InputComponent<?, Object> input; if (completeObject.isOption()) { input = cmd.getInputs().get(completeObject.getName()); } else if (completeObject.isArgument()) { input = cmd.getInputs().get(ARGUMENTS_INPUT_NAME); } else { input = null; } if (input != null) { CompletionStrategy completionObj = CompletionStrategyFactory.getCompletionFor(input); completionObj.complete(completeOperation, input, shellContext, completeObject.getValue(), shell.getConverterFactory()); } } if (completeOperation.getCompletionCandidates().size() == 1) { completeOperation.setOffset(completeOperation.getCursor() - completeObject.getOffset()); } } catch (Exception e) { logger.warning(e.getMessage()); return; } } }
public void complete(CompleteOperation completeOperation) { String line = completeOperation.getBuffer(); ShellContext shellContext = shell.newShellContext(); final ShellCommand cmd = shell.findCommand(shellContext, line); if (cmd == null) { Collection<ShellCommand> commands = shell.findMatchingCommands(shellContext, line); for (ShellCommand command : commands) { completeOperation.addCompletionCandidate(command.getName()); } } else { try { ParameterInt param = cmd.getParameter(); ParsedCompleteObject completeObject = cmd.parseCompleteObject(line); if (completeObject.doDisplayOptions()) { if (completeObject.getName() != null && !completeObject.getName().isEmpty()) { List<String> possibleOptions = param.findPossibleLongNamesWitdDash(completeObject.getName()); completeOperation.addCompletionCandidates(possibleOptions); } else { List<String> optionNames = param.getOptionLongNamesWithDash(); removeExistingOptions(line, optionNames); completeOperation.addCompletionCandidates(optionNames); } if (completeOperation.getCompletionCandidates().size() == 1) { completeOperation.setOffset(completeOperation.getCursor() - completeObject.getOffset()); } } else { final InputComponent<?, Object> input; if (completeObject.isOption()) { input = cmd.getInputs().get(completeObject.getName()); } else if (completeObject.isArgument()) { input = cmd.getInputs().get(ARGUMENTS_INPUT_NAME); } else { input = null; } if (input != null) { CompletionStrategy completionObj = CompletionStrategyFactory.getCompletionFor(input); completionObj.complete(completeOperation, input, shellContext, completeObject.getValue(), shell.getConverterFactory()); } } } catch (Exception e) { logger.warning(e.getMessage()); return; } } }
protected Integer doInBackground(String... strings) { try { HttpPost post = new HttpPost("http://connactiv.com/test/index.php"); post.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); DefaultHttpClient client = new DefaultHttpClient(post.getParams()); client.setCookieStore(cs); List<NameValuePair> postParams = new ArrayList<NameValuePair>(3); postParams.add(new BasicNameValuePair("login", "1")); postParams.add(new BasicNameValuePair("username", strings[0])); postParams.add(new BasicNameValuePair("pass", strings[1])); post.setEntity( new UrlEncodedFormEntity(postParams) ); BasicResponseHandler brh = new BasicResponseHandler(); HttpResponse response = client.execute( post, httpCtx ); final String resp = brh.handleResponse( response ); runOnUiThread( new Runnable() { public void run() { pb.setVisibility(View.INVISIBLE); if( resp.startsWith("1") ) Toast.makeText(ctx, "Incorrect password.", Toast.LENGTH_SHORT).show(); else if ( resp.startsWith("2") ) Toast.makeText(ctx, "User does not exist.", Toast.LENGTH_SHORT).show(); else if ( resp.startsWith("3") ) Toast.makeText(ctx, "All fields are required.", Toast.LENGTH_SHORT).show(); else if (resp.startsWith("0")) { CookieSyncManager.getInstance().sync(); List<Cookie> cookieList = cs.getCookies(); Log.i(TAG, "===== Cookie List ====="); for( Cookie c : cookieList ) Log.i(TAG, c.getName() ); Toast.makeText(ctx, "Welcome to ConnActiv, " +email.getText().toString().split("@")[0] +"!", Toast.LENGTH_SHORT).show(); finish(); } } }); } catch (Exception e) { Log.i(TAG, "ERROR: " +e.toString()); } return 0; }
protected Integer doInBackground(String... strings) { try { HttpPost post = new HttpPost("http://connactiv.nfshost.com/test/index.php"); post.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); DefaultHttpClient client = new DefaultHttpClient(post.getParams()); client.setCookieStore(cs); List<NameValuePair> postParams = new ArrayList<NameValuePair>(3); postParams.add(new BasicNameValuePair("login", "1")); postParams.add(new BasicNameValuePair("username", strings[0])); postParams.add(new BasicNameValuePair("pass", strings[1])); post.setEntity( new UrlEncodedFormEntity(postParams) ); BasicResponseHandler brh = new BasicResponseHandler(); HttpResponse response = client.execute( post, httpCtx ); final String resp = brh.handleResponse( response ); runOnUiThread( new Runnable() { public void run() { pb.setVisibility(View.INVISIBLE); if( resp.contains("Incorrect password")) Toast.makeText(ctx, "Incorrect password.", Toast.LENGTH_SHORT).show(); else if ( resp.startsWith("Sorry, that user does not exist in our database.") ) Toast.makeText(ctx, "User does not exist.", Toast.LENGTH_SHORT).show(); else if ( resp.startsWith("Oops.") ) Toast.makeText(ctx, "All fields are required.", Toast.LENGTH_SHORT).show(); else { CookieSyncManager.getInstance().sync(); List<Cookie> cookieList = cs.getCookies(); Log.i(TAG, resp); Log.i(TAG, "===== Cookie List ====="); Toast.makeText(ctx, "Welcome to ConnActiv, " +email.getText().toString().split("@")[0] +"!", Toast.LENGTH_SHORT).show(); } } }); } catch (Exception e) { Log.i(TAG, "ERROR: " +e.toString()); } return 0; }
public ResponseEntity<String> handle(@PathVariable("testbedId") int testbedId, @PathVariable("capabilityName") String capabilityName, @PathVariable("rdfEncoding") String rdfEncoding, HttpServletRequest request) throws IOException, FeedException, NodeNotFoundException, TestbedNotFoundException, InvalidTestbedIdException { final long start = System.currentTimeMillis(); initialize(SecurityContextHolder.getContext().getAuthentication().getPrincipal()); final Testbed testbed = testbedManager.getByID(testbedId); if (testbed == null) { throw new TestbedNotFoundException("Cannot find testbed [" + testbedId + "]."); } final Capability capability = capabilityManager.getByID(capabilityName); StringBuilder rdfDescription = new StringBuilder(""); rdfDescription.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") .append("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n") .append(" xmlns:ns0=\"http://www.w3.org/2000/01/rdf-schema#\"\n") .append(" xmlns:ns1=\"http://purl.oclc.org/NET/ssnx/ssn#\"\n") .append(" xmlns:ns2=\"http://spitfire-project.eu/cc/spitfireCC_n3.owl#\"\n") .append(" xmlns:ns3=\"http://www.loa-cnr.it/ontologies/DUL.owl#\"\n") .append(" xmlns:owl=\"http://www.w3.org/2002/07/owl#Class#\"\n") .append(" xmlns:ns4=\"http://purl.org/dc/terms/\">\n").append("\n"); rdfDescription.append("<rdf:Description rdf:about=\"" + request.getRequestURL() + "\">\n") .append("\t<owl:sameAs rdf:resource=\"" + capability.getSemanticUrl() + "\"/>\n") .append("</rdf:Description>\n"); rdfDescription.append("\n") .append("</rdf:RDF>"); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.add("Content-Type", "application/rdf+xml; charset=UTF-8"); return new ResponseEntity<String>(rdfDescription.toString(), responseHeaders, HttpStatus.OK); }
public ResponseEntity<String> handle(@PathVariable("testbedId") int testbedId, @PathVariable("capabilityName") String capabilityName, @PathVariable("rdfEncoding") String rdfEncoding, HttpServletRequest request) throws IOException, FeedException, NodeNotFoundException, TestbedNotFoundException, InvalidTestbedIdException { final long start = System.currentTimeMillis(); initialize(SecurityContextHolder.getContext().getAuthentication().getPrincipal()); final Testbed testbed = testbedManager.getByID(testbedId); if (testbed == null) { throw new TestbedNotFoundException("Cannot find testbed [" + testbedId + "]."); } final Capability capability = capabilityManager.getByID(capabilityName); StringBuilder rdfDescription = new StringBuilder(""); rdfDescription.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") .append("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n") .append(" xmlns:ns0=\"http://www.w3.org/2000/01/rdf-schema#\"\n") .append(" xmlns:ns1=\"http://purl.oclc.org/NET/ssnx/ssn#\"\n") .append(" xmlns:ns2=\"http://spitfire-project.eu/cc/spitfireCC_n3.owl#\"\n") .append(" xmlns:ns3=\"http://www.loa-cnr.it/ontologies/DUL.owl#\"\n") .append(" xmlns:owl=\"http://www.w3.org/2002/07/owl#\"\n") .append(" xmlns:ns4=\"http://purl.org/dc/terms/\">\n").append("\n"); rdfDescription.append("<rdf:Description rdf:about=\"" + request.getRequestURL() + "\">\n") .append("\t<owl:sameAs rdf:resource=\"" + capability.getSemanticUrl() + "\"/>\n") .append("</rdf:Description>\n"); rdfDescription.append("\n") .append("</rdf:RDF>"); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.add("Content-Type", "application/rdf+xml; charset=UTF-8"); return new ResponseEntity<String>(rdfDescription.toString(), responseHeaders, HttpStatus.OK); }
public void traverse(Element altElement, XSElementDecl element, XSDocumentInfo schemaDoc, SchemaGrammar grammar) { Object[] attrValues = fAttrChecker.checkAttributes(altElement, false, schemaDoc); QName typeAtt = (QName) attrValues[XSAttributeChecker.ATTIDX_TYPE]; String test = (String) attrValues[XSAttributeChecker.ATTIDX_XPATH]; String xpathNS = (String) attrValues[XSAttributeChecker.ATTIDX_XPATHDEFAULTNS]; Element childNode = DOMUtil.getFirstChildElement(altElement); XSAnnotationImpl annotation = null; if (childNode != null && DOMUtil.getLocalName(childNode).equals(SchemaSymbols.ELT_ANNOTATION)) { annotation = traverseAnnotationDecl(childNode, attrValues, false, schemaDoc); childNode = DOMUtil.getNextSiblingElement(childNode); } else { String text = DOMUtil.getSyntheticAnnotation(altElement); if (text != null) { annotation = traverseSyntheticAnnotation(altElement, text, attrValues, false, schemaDoc); } } XSObjectList annotations = null; if (annotation != null) { annotations = new XSObjectListImpl(); ((XSObjectListImpl)annotations).addXSObject(annotation); } else { annotations = XSObjectListImpl.EMPTY_LIST; } XSTypeDefinition alternativeType = null; boolean hasAnonType = false; if (typeAtt != null) { alternativeType = (XSTypeDefinition)fSchemaHandler.getGlobalDecl(schemaDoc, XSDHandler.TYPEDECL_TYPE, typeAtt, altElement); } if (childNode != null) { String childName = DOMUtil.getLocalName(childNode); XSTypeDefinition typeDef = null; if (childName.equals(SchemaSymbols.ELT_COMPLEXTYPE)) { typeDef = fSchemaHandler.fComplexTypeTraverser.traverseLocal(childNode, schemaDoc, grammar, element); hasAnonType = true; childNode = DOMUtil.getNextSiblingElement(childNode); } else if (childName.equals(SchemaSymbols.ELT_SIMPLETYPE)) { typeDef = fSchemaHandler.fSimpleTypeTraverser.traverseLocal(childNode, schemaDoc, grammar, element); hasAnonType = true; childNode = DOMUtil.getNextSiblingElement(childNode); } if (alternativeType == null) { alternativeType = typeDef; } if (hasAnonType && (typeAtt != null)) { reportSchemaError("src-type-alternative.3.12.13.1", null, altElement); } } if (typeAtt == null && !hasAnonType) { reportSchemaError("src-type-alternative.3.12.13.2", null, altElement); } if (alternativeType == null) { alternativeType = element.fType; } else if (alternativeType != fErrorType){ short block = element.fBlock; if (element.fType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { block |= ((XSComplexTypeDecl) element.fType).getProhibitedSubstitutions(); } if (!fSchemaHandler.fXSConstraints.checkTypeDerivationOk(alternativeType, element.fType, block)) { reportSchemaError( "e-props-correct.7", new Object[] { element.getName(), alternativeType.getName(), element.fType.getName()}, altElement); } alternativeType = element.fType; } if (childNode != null) { reportSchemaError("s4s-elt-must-match.1", new Object[]{"type alternative", "(annotation?, (simpleType | complexType)?)", DOMUtil.getLocalName(childNode)}, childNode); }
public void traverse(Element altElement, XSElementDecl element, XSDocumentInfo schemaDoc, SchemaGrammar grammar) { Object[] attrValues = fAttrChecker.checkAttributes(altElement, false, schemaDoc); QName typeAtt = (QName) attrValues[XSAttributeChecker.ATTIDX_TYPE]; String test = (String) attrValues[XSAttributeChecker.ATTIDX_XPATH]; String xpathNS = (String) attrValues[XSAttributeChecker.ATTIDX_XPATHDEFAULTNS]; Element childNode = DOMUtil.getFirstChildElement(altElement); XSAnnotationImpl annotation = null; if (childNode != null && DOMUtil.getLocalName(childNode).equals(SchemaSymbols.ELT_ANNOTATION)) { annotation = traverseAnnotationDecl(childNode, attrValues, false, schemaDoc); childNode = DOMUtil.getNextSiblingElement(childNode); } else { String text = DOMUtil.getSyntheticAnnotation(altElement); if (text != null) { annotation = traverseSyntheticAnnotation(altElement, text, attrValues, false, schemaDoc); } } XSObjectList annotations = null; if (annotation != null) { annotations = new XSObjectListImpl(); ((XSObjectListImpl)annotations).addXSObject(annotation); } else { annotations = XSObjectListImpl.EMPTY_LIST; } XSTypeDefinition alternativeType = null; boolean hasAnonType = false; if (typeAtt != null) { alternativeType = (XSTypeDefinition)fSchemaHandler.getGlobalDecl(schemaDoc, XSDHandler.TYPEDECL_TYPE, typeAtt, altElement); } if (childNode != null) { String childName = DOMUtil.getLocalName(childNode); XSTypeDefinition typeDef = null; if (childName.equals(SchemaSymbols.ELT_COMPLEXTYPE)) { typeDef = fSchemaHandler.fComplexTypeTraverser.traverseLocal(childNode, schemaDoc, grammar, element); hasAnonType = true; childNode = DOMUtil.getNextSiblingElement(childNode); } else if (childName.equals(SchemaSymbols.ELT_SIMPLETYPE)) { typeDef = fSchemaHandler.fSimpleTypeTraverser.traverseLocal(childNode, schemaDoc, grammar, element); hasAnonType = true; childNode = DOMUtil.getNextSiblingElement(childNode); } if (alternativeType == null) { alternativeType = typeDef; } if (hasAnonType && (typeAtt != null)) { reportSchemaError("src-type-alternative.3.12.13.1", null, altElement); } } if (typeAtt == null && !hasAnonType) { reportSchemaError("src-type-alternative.3.12.13.2", null, altElement); } if (alternativeType == null) { alternativeType = element.fType; } else if (alternativeType != fErrorType){ short block = element.fBlock; if (element.fType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { block |= ((XSComplexTypeDecl) element.fType).getProhibitedSubstitutions(); } if (!fSchemaHandler.fXSConstraints.checkTypeDerivationOk(alternativeType, element.fType, block)) { reportSchemaError( "e-props-correct.7", new Object[] { element.getName(), alternativeType.getName(), element.fType.getName()}, altElement); alternativeType = element.fType; } } if (childNode != null) { reportSchemaError("s4s-elt-must-match.1", new Object[]{"type alternative", "(annotation?, (simpleType | complexType)?)", DOMUtil.getLocalName(childNode)}, childNode); }
public URL transformStringToURL(String string) throws MalformedURLException { return new URL(string); }
public URL transformStringToURL(String string) throws MalformedURLException { try { return new URL(string); } catch (MalformedURLException e) { throw new MalformedURLException(e.getMessage() + " " + string); } }
public static String formatDate(String inputDate){ String monthNumber; String monthLetter = ""; String day = ""; String[] monthDayYear = inputDate.split(" "); for (int i=0;i<2;i++){ if (Character.isLetter(monthDayYear[i].charAt(0))){ monthLetter = monthDayYear[i]; }else{ day = monthDayYear[i]; } } if (monthLetter.equals("January")) monthNumber = "01"; else if (monthLetter.equals("February")) monthNumber = "02"; else if (monthLetter.equals("March")) monthNumber = "03"; else if (monthLetter.equals("April")) monthNumber = "04"; else if (monthLetter.equals("May")) monthNumber = "05"; else if (monthLetter.equals("June")) monthNumber = "06"; else if (monthLetter.equals("July")) monthNumber = "07"; else if (monthLetter.equals("August")) monthNumber = "08"; else if (monthLetter.equals("September")) monthNumber = "09"; else if (monthLetter.equals("October")) monthNumber = "10"; else if (monthLetter.equals("November")) monthNumber = "11"; else if (monthLetter.equals("December")) monthNumber = "12"; else monthNumber = "00"; String total = day+"/"+monthNumber+"/"+monthDayYear[2]; return total.trim(); }
public static String formatDate(String inputDate){ String monthNumber; String monthLetter = ""; String day = ""; String[] monthDayYear = inputDate.split(" "); for (int i=0;i<2;i++){ if (Character.isLetter(monthDayYear[i].charAt(0))){ monthLetter = monthDayYear[i]; }else{ if (monthDayYear[i].length() == 1){ day = "0"+monthDayYear[i]; }else{ day = monthDayYear[i]; } } } if (monthLetter.equals("January")) monthNumber = "01"; else if (monthLetter.equals("February")) monthNumber = "02"; else if (monthLetter.equals("March")) monthNumber = "03"; else if (monthLetter.equals("April")) monthNumber = "04"; else if (monthLetter.equals("May")) monthNumber = "05"; else if (monthLetter.equals("June")) monthNumber = "06"; else if (monthLetter.equals("July")) monthNumber = "07"; else if (monthLetter.equals("August")) monthNumber = "08"; else if (monthLetter.equals("September")) monthNumber = "09"; else if (monthLetter.equals("October")) monthNumber = "10"; else if (monthLetter.equals("November")) monthNumber = "11"; else if (monthLetter.equals("December")) monthNumber = "12"; else monthNumber = "00"; String total = day+"/"+monthNumber+"/"+monthDayYear[2]; return total.trim(); }
public void addError( String messagePattern, Object... arguments ) { StackTraceElement[] stackTrace = new Exception().getStackTrace(); StackTraceElement element = null; int stackIndex = stackTrace.length - 1; while ( element == null && stackIndex > 0 ) { Class<?> moduleClass; try { moduleClass = Class.forName( stackTrace[stackIndex].getClassName(), false, this.classLoader ); } catch ( ClassNotFoundException e ) { try { moduleClass = Class.forName( stackTrace[stackIndex].getClassName(), false, this.getClass().getClassLoader() ); } catch ( ClassNotFoundException e1 ) { moduleClass = null; } } if ( moduleClass != null ) { if ( RulesModule.class.isAssignableFrom( moduleClass ) ) { element = stackTrace[stackIndex]; } } stackIndex--; } if ( element != null ) { messagePattern = format( "%s (%s:%s)", messagePattern, element.getFileName(), element.getLineNumber() ); } addError( new ErrorMessage( messagePattern, arguments ) ); }
public void addError( String messagePattern, Object... arguments ) { StackTraceElement[] stackTrace = new Exception().getStackTrace(); StackTraceElement element = null; int stackIndex = stackTrace.length - 1; while ( element == null && stackIndex > 0 ) { Class<?> moduleClass; try { moduleClass = Class.forName( stackTrace[stackIndex].getClassName(), false, this.classLoader ); } catch ( ClassNotFoundException e ) { try { moduleClass = Class.forName( stackTrace[stackIndex].getClassName(), false, this.getClass().getClassLoader() ); } catch ( ClassNotFoundException e1 ) { moduleClass = null; } } if ( moduleClass != null && RulesModule.class.isAssignableFrom( moduleClass ) ) { element = stackTrace[stackIndex]; } stackIndex--; } if ( element != null ) { messagePattern = format( "%s (%s:%s)", messagePattern, element.getFileName(), element.getLineNumber() ); } addError( new ErrorMessage( messagePattern, arguments ) ); }
public View getView(int position, View convertView, ViewGroup parent) { DreamInfo dreamInfo = getItem(position); logd("getView(%s)", dreamInfo.caption); final View row = convertView != null ? convertView : createDreamInfoRow(parent); row.setTag(dreamInfo); ((ImageView) row.findViewById(android.R.id.icon)).setImageDrawable(dreamInfo.icon); ((TextView) row.findViewById(android.R.id.title)).setText(dreamInfo.caption); RadioButton radioButton = (RadioButton) row.findViewById(android.R.id.button1); radioButton.setChecked(dreamInfo.isActive); radioButton.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { row.onTouchEvent(event); return false; }}); boolean showSettings = dreamInfo.settingsComponentName != null; View settingsDivider = row.findViewById(R.id.divider); settingsDivider.setVisibility(showSettings ? View.VISIBLE : View.INVISIBLE); ImageView settingsButton = (ImageView) row.findViewById(android.R.id.button2); settingsButton.setVisibility(showSettings ? View.VISIBLE : View.INVISIBLE); settingsButton.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { mBackend.launchSettings((DreamInfo) row.getTag()); }}); return row; }
public View getView(int position, View convertView, ViewGroup parent) { DreamInfo dreamInfo = getItem(position); logd("getView(%s)", dreamInfo.caption); final View row = convertView != null ? convertView : createDreamInfoRow(parent); row.setTag(dreamInfo); ((ImageView) row.findViewById(android.R.id.icon)).setImageDrawable(dreamInfo.icon); ((TextView) row.findViewById(android.R.id.title)).setText(dreamInfo.caption); RadioButton radioButton = (RadioButton) row.findViewById(android.R.id.button1); radioButton.setChecked(dreamInfo.isActive); radioButton.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { row.onTouchEvent(event); return false; }}); boolean showSettings = dreamInfo.settingsComponentName != null; View settingsDivider = row.findViewById(R.id.divider); settingsDivider.setVisibility(showSettings ? View.VISIBLE : View.INVISIBLE); ImageView settingsButton = (ImageView) row.findViewById(android.R.id.button2); settingsButton.setVisibility(showSettings ? View.VISIBLE : View.INVISIBLE); settingsButton.setAlpha(dreamInfo.isActive ? 1f : 0.7f); settingsButton.setEnabled(dreamInfo.isActive); settingsButton.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { mBackend.launchSettings((DreamInfo) row.getTag()); }}); return row; }
public ActivityPage(PageParameters params) { super(params); setupPage("", ""); int daysBack = WicketUtils.getDaysBack(params); if (daysBack < 1) { daysBack = GitBlit.getInteger(Keys.web.activityDuration, 7); } String objectId = WicketUtils.getObject(params); List<RepositoryModel> models = getRepositories(params); List<Activity> recentActivity = ActivityUtils.getRecentActivity(models, daysBack, objectId, getTimeZone()); String headerPattern; if (daysBack == 1) { if (recentActivity.size() == 0) { headerPattern = getString("gb.todaysActivityNone"); } else { headerPattern = getString("gb.todaysActivityStats"); } } else { if (recentActivity.size() == 0) { headerPattern = getString("gb.recentActivityNone"); } else { headerPattern = getString("gb.recentActivityStats"); } } if (recentActivity.size() == 0) { add(new Label("subheader", MessageFormat.format(headerPattern, daysBack))); add(new Label("activityPanel")); } else { int totalCommits = 0; Set<String> uniqueAuthors = new HashSet<String>(); for (Activity activity : recentActivity) { totalCommits += activity.getCommitCount(); uniqueAuthors.addAll(activity.getAuthorMetrics().keySet()); } int totalAuthors = uniqueAuthors.size(); add(new Label("subheader", MessageFormat.format(headerPattern, daysBack, totalCommits, totalAuthors))); if (GitBlit.getBoolean(Keys.web.generateActivityGraph, true)) { GoogleCharts charts = createCharts(recentActivity); add(new HeaderContributor(charts)); add(new Fragment("chartsPanel", "chartsFragment", this)); } else { add(new Label("chartsPanel").setVisible(false)); } add(new ActivityPanel("activityPanel", recentActivity)); } }
public ActivityPage(PageParameters params) { super(params); setupPage("", ""); int daysBack = WicketUtils.getDaysBack(params); if (daysBack < 1) { daysBack = GitBlit.getInteger(Keys.web.activityDuration, 7); } String objectId = WicketUtils.getObject(params); List<RepositoryModel> models = getRepositories(params); List<Activity> recentActivity = ActivityUtils.getRecentActivity(models, daysBack, objectId, getTimeZone()); String headerPattern; if (daysBack == 1) { if (recentActivity.size() == 0) { headerPattern = getString("gb.todaysActivityNone"); } else { headerPattern = getString("gb.todaysActivityStats"); } } else { if (recentActivity.size() == 0) { headerPattern = getString("gb.recentActivityNone"); } else { headerPattern = getString("gb.recentActivityStats"); } } if (recentActivity.size() == 0) { add(new Label("subheader", MessageFormat.format(headerPattern, daysBack))); add(new Label("chartsPanel").setVisible(false)); add(new Label("activityPanel")); } else { int totalCommits = 0; Set<String> uniqueAuthors = new HashSet<String>(); for (Activity activity : recentActivity) { totalCommits += activity.getCommitCount(); uniqueAuthors.addAll(activity.getAuthorMetrics().keySet()); } int totalAuthors = uniqueAuthors.size(); add(new Label("subheader", MessageFormat.format(headerPattern, daysBack, totalCommits, totalAuthors))); if (GitBlit.getBoolean(Keys.web.generateActivityGraph, true)) { GoogleCharts charts = createCharts(recentActivity); add(new HeaderContributor(charts)); add(new Fragment("chartsPanel", "chartsFragment", this)); } else { add(new Label("chartsPanel").setVisible(false)); } add(new ActivityPanel("activityPanel", recentActivity)); } }
private void showStatus() { if (mDevice.isSuperuserAppInstalled) mSuperuserRow.setAvailable(true); else mSuperuserRow.setAvailable(false, "market://details?id=com.noshufou.android.su"); mRootedRow.setAvailable(mDevice.isRooted); mRootGrantedRow.setAvailable(Utils.canGainSu(this)); if (mDevice.mFileSystem == FileSystem.EXTFS) mFsSupportedRow.setAvailable(true); else mFsSupportedRow.setAvailable(false); mSuProtectedRow.setAvailable(mDevice.isSuProtected); mUnrootButton.setVisibility(View.GONE); if (mDevice.isRooted && !mDevice.isSuProtected) { if (mDevice.mFileSystem == FileSystem.EXTFS) mBackupButton.setText(R.string.protect_root); else mBackupButton.setText(R.string.backup_root); mRestoreButton.setVisibility(View.GONE); mDeleteBackupButton.setVisibility(View.GONE); } else if (mDevice.isRooted && mDevice.isSuProtected) { mBackupButton.setVisibility(View.GONE); mRestoreButton.setVisibility(View.GONE); mDeleteBackupButton.setVisibility(View.VISIBLE); mUnrootButton.setVisibility(View.VISIBLE); } else if (!mDevice.isRooted && mDevice.isSuProtected) { mBackupButton.setVisibility(View.GONE); mRestoreButton.setVisibility(View.VISIBLE); mDeleteBackupButton.setVisibility(View.GONE); } }
private void showStatus() { if (mDevice.isSuperuserAppInstalled) mSuperuserRow.setAvailable(true); else mSuperuserRow.setAvailable(false, "market://details?id=com.noshufou.android.su"); mRootedRow.setAvailable(mDevice.isRooted); mRootGrantedRow.setAvailable(Utils.canGainSu(this)); if (mDevice.mFileSystem == FileSystem.EXTFS) mFsSupportedRow.setAvailable(true); else mFsSupportedRow.setAvailable(false); mSuProtectedRow.setAvailable(mDevice.isSuProtected); mUnrootButton.setVisibility(View.GONE); if (mDevice.isRooted && !mDevice.isSuProtected) { if (mDevice.mFileSystem == FileSystem.EXTFS) mBackupButton.setText(R.string.protect_root); else mBackupButton.setText(R.string.backup_root); mRestoreButton.setVisibility(View.GONE); mDeleteBackupButton.setVisibility(View.GONE); } else if (mDevice.isRooted && mDevice.isSuProtected) { mBackupButton.setVisibility(View.GONE); mRestoreButton.setVisibility(View.GONE); mDeleteBackupButton.setVisibility(View.VISIBLE); mUnrootButton.setVisibility(View.VISIBLE); } else if (!mDevice.isRooted && mDevice.isSuProtected) { mBackupButton.setVisibility(View.GONE); mRestoreButton.setVisibility(View.VISIBLE); mDeleteBackupButton.setVisibility(View.GONE); } else { mBackupButton.setVisibility(View.GONE); mRestoreButton.setVisibility(View.GONE); mDeleteBackupButton.setVisibility(View.GONE); } }
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { Object taskObj = req.getAttribute("task"); Object nameObj = req.getAttribute("name"); String task; String name; if (taskObj == null) { name = req.getParameter("name"); task = req.getParameter("task"); } else { name = nameObj.toString(); task = taskObj.toString(); } if(!userExists(name)) { String splitName[] = name.split(" "); resp.sendRedirect("/newUser.jsp?name=" + name.substring(0, name.indexOf(" ")) + "+" + name.substring(name.indexOf(" "), name.length()).trim() + "&task=" + task); } else if(task.equals("volunteer")) { resp.sendRedirect("/volunteer.jsp?pageNumber=1&resultIndex=1"); } else if(task.equals("initiate")) { resp.sendRedirect("/add.jsp"); } else if(task.equals("manage")) { resp.sendRedirect("/manProj.jsp?pageNumber=1&resultIndex=1"); } else if(task.equals("dashboard")) { resp.sendRedirect("/underConstruction.jsp"); } else if(task.equals("preferences")) { resp.sendRedirect("/prefs.jsp?name=" + name.substring(0, name.indexOf(" ")) + "+" + name.substring(name.indexOf(" "), name.length()).trim() + "&email=" + getEmail(name) + "&phone=" + getPhone(name) + "&reminder=" + getReminder(name)); } }
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { Object taskObj = req.getAttribute("task"); Object nameObj = req.getAttribute("name"); String task; String name; if (taskObj == null) { name = req.getParameter("name"); task = req.getParameter("task"); } else { name = nameObj.toString(); task = taskObj.toString(); } if(!userExists(name)) { String splitName[] = name.split(" "); String redirect = "/newUser.jsp?name="; for( int i = 0; i < splitName.length; i++ ) { if( i > 0 ) redirect += "+"; redirect += splitName[i]; } redirect += "&task=" + task; resp.sendRedirect( redirect ); } else if(task.equals("volunteer")) { resp.sendRedirect("/volunteer.jsp?pageNumber=1&resultIndex=1"); } else if(task.equals("initiate")) { resp.sendRedirect("/add.jsp"); } else if(task.equals("manage")) { resp.sendRedirect("/manProj.jsp?pageNumber=1&resultIndex=1"); } else if(task.equals("dashboard")) { resp.sendRedirect("/underConstruction.jsp"); } else if(task.equals("preferences")) { resp.sendRedirect("/prefs.jsp?name=" + name.substring(0, name.indexOf(" ")) + "+" + name.substring(name.indexOf(" "), name.length()).trim() + "&email=" + getEmail(name) + "&phone=" + getPhone(name) + "&reminder=" + getReminder(name)); } }
public AbsPropagator Propagator( int kind, Rsrcc_src_dstc_dst simple, Rsrcc_src_fld_dstc_dst load, Rsrcc_src_dstc_dst_fld store, Robjc_obj_varc_var alloc, Qvarc_var_objc_obj propout, AbsPAG pag ) { switch( kind ) { case PaddleOptions.propagator_worklist: return new PropWorklist(simple, load, store, alloc, propout, pag); case PaddleOptions.propagator_iter: return new PropIter(simple, load, store, alloc, propout, pag); case PaddleOptions.propagator_alias: return new PropAlias(simple, load, store, alloc, propout, pag); case PaddleOptions.propagator_auto: case PaddleOptions.propagator_bdd: return new PropBDD(simple, load, store, alloc, propout, pag); case PaddleOptions.propagator_incbdd: return new PropBDDInc(simple, load, store, alloc, propout, pag); default: throw new RuntimeException( "Unimplemented propagator specified "+kind ); } }
public AbsPropagator Propagator( int kind, Rsrcc_src_dstc_dst simple, Rsrcc_src_fld_dstc_dst load, Rsrcc_src_dstc_dst_fld store, Robjc_obj_varc_var alloc, Qvarc_var_objc_obj propout, AbsPAG pag ) { switch( kind ) { case PaddleOptions.propagator_worklist: return new PropWorklist(simple, load, store, alloc, propout, pag); case PaddleOptions.propagator_iter: return new PropIter(simple, load, store, alloc, propout, pag); case PaddleOptions.propagator_alias: return new PropAlias(simple, load, store, alloc, propout, pag); case PaddleOptions.propagator_bdd: return new PropBDD(simple, load, store, alloc, propout, pag); case PaddleOptions.propagator_auto: case PaddleOptions.propagator_incbdd: return new PropBDDInc(simple, load, store, alloc, propout, pag); default: throw new RuntimeException( "Unimplemented propagator specified "+kind ); } }
public void loadPart(){ mView.loadTexture("data/gui/blank.png", RegionID.BLANK, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_CHAT_OFF, 192, 192, 96, 96, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_CHAT_ON, 192, 288, 96, 96, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_MENU_OFF, 288, 192, 96, 96, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_MENU_ON, 288, 288, 96, 96, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_CHANNEL_MAIN_OFF, 0, 0, 96, 96, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_CHANNEL_MAIN_ON, 0, 96, 96, 96, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_CHANNEL_LOCATION_OFF, 96, 0, 96, 96, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_CHANNEL_LOCATION_ON, 96, 96, 96, 96, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_CHANNEL_PLANET_OFF, 192, 0, 96, 96, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_CHANNEL_PLANET_ON, 192, 96, 96, 96, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_CHANNEL_DOMAIN_OFF, 288, 0, 96, 96, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_CHANNEL_DOMAIN_ON, 288, 96, 96, 96, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_CHANNEL_PRIVATE_OFF, 0, 192, 96, 96, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_CHANNEL_PRIVATE_ON, 0, 288, 96, 96, false); mView.loadTexture("data/gui/ui_back.png", RegionID.BTN_UI_BACK_OFF, 0, 0, 450, 100, false); mView.loadTexture("data/gui/ui_back.png", RegionID.BTN_UI_BACK_ON, 0, 100, 450, 100, false); mView.loadTexture("data/gui/ui_exit.png", RegionID.BTN_UI_EXIT_OFF, 0, 0, 450, 100, false); mView.loadTexture("data/gui/ui_exit.png", RegionID.BTN_UI_EXIT_ON, 0, 100, 450, 100, false); mView.loadTexture("data/gui/chat_field.png", RegionID.FIELD_CHAT, false); mView.loadTexture("data/gui/chat_edit.png", RegionID.EDIT_CHAT, false); mView.loadTexture("data/gui/btn_send.png", RegionID.BTN_UI_SEND_OFF, 0, 0, 128, 64, false); mView.loadTexture("data/gui/btn_send.png", RegionID.BTN_UI_SEND_ON, 0, 64, 128, 64, false); float halfWidth = mView.getHUDCamera().getWidth() * 0.5f; float halfHeight = mView.getHUDCamera().getHeight() * 0.5f; panelBlank = new PressedButton(RegionID.BLANK, RegionID.BLANK, 0.0f, 0.0f); btnDisconnect = new PressedButton(RegionID.BTN_UI_EXIT_OFF, RegionID.BTN_UI_EXIT_ON, halfWidth * 0.0f, -halfHeight * 0.137f, new TouchAction() { @Override public void execute(boolean touch) { Controllers.netController.disconnect(); } }); btnCancel = new PressedButton(RegionID.BTN_UI_BACK_OFF, RegionID.BTN_UI_BACK_ON, halfWidth * 0.0f, halfHeight * 0.137f, new TouchAction() { @Override public void execute(boolean touch) { setVisible(panel); lController.getRadar().visible = true; Parts.getInfoPanel().setVisible(true); RaniaGame.mController.addProcessor(lController.getPlayerController()); } }); btnMenu = new PressedButton(RegionID.BTN_UI_MENU_OFF, RegionID.BTN_UI_MENU_ON, halfWidth * 0.9396f, -halfHeight * 0.8926f, new TouchAction() { @Override public void execute(boolean touch) { setVisible(menu); lController.getRadar().visible = false; Parts.getInfoPanel().setVisible(false); RaniaGame.mController.removeProcessor(lController.getPlayerController()); } }); btnChat = new PressedButton(RegionID.BTN_UI_CHAT_OFF, RegionID.BTN_UI_CHAT_ON, halfWidth * 0.9396f, -halfHeight * 0.6963f, new TouchAction() { @Override public void execute(boolean touch) { chatVisible = !chatVisible; chat.setVisible(chatVisible); Parts.getInfoPanel().setVisible(!chatVisible); lController.getRadar().visible = !chatVisible; if (chatVisible) RaniaGame.mController.removeProcessor(lController.getPlayerController()); else RaniaGame.mController.addProcessor(lController.getPlayerController()); editUser.setFocus(); } }); fieldChat = new ChatList(RegionID.FIELD_CHAT, -halfWidth + mView.getTextureRegion(RegionID.FIELD_CHAT).getRegionWidth() * 0.5f, halfHeight - mView.getTextureRegion(RegionID.FIELD_CHAT).getRegionHeight() * 0.5f, new MultilineText("", Font.getFont("data/fonts/Arial.ttf", 20), new Color(1, 1, 1, 1), -mView.getTextureRegion(RegionID.FIELD_CHAT).getRegionWidth() * 0.5f + 20.0f, mView.getTextureRegion(RegionID.FIELD_CHAT).getRegionHeight() * 0.5f - 10.0f, Text.Align.LEFT, Text.Align.TOP), mView.getTextureRegion(RegionID.FIELD_CHAT).getRegionWidth() * 0.95f, mView.getTextureRegion(RegionID.FIELD_CHAT).getRegionHeight() * 0.95f); editUser = new Edit(RegionID.EDIT_CHAT, RegionID.EDIT_CHAT, -halfWidth + mView.getTextureRegion(RegionID.EDIT_CHAT).getRegionWidth() * 0.5f, -halfHeight + mView.getTextureRegion(RegionID.EDIT_CHAT).getRegionHeight() * 0.5f, new Text("", Font.getFont("data/fonts/Arial.ttf", 20), new Color(1, 1, 1, 1), -mView.getTextureRegion(RegionID.EDIT_CHAT).getRegionWidth() * 0.5f + 20.0f, 0, Text.Align.LEFT, Text.Align.CENTER), 255, new EditAction() { @Override public void execute(Edit edit) { Controllers.netController.sendChatMessage(edit.getText(), fieldChat.getCurrentChannel()); edit.setText(""); edit.setFocus(); } }); btnSend = new PressedButton(RegionID.BTN_UI_SEND_OFF, RegionID.BTN_UI_SEND_ON, -halfWidth + mView.getTextureRegion(RegionID.EDIT_CHAT).getRegionWidth() + mView.getTextureRegion(RegionID.BTN_UI_SEND_OFF).getRegionWidth() * 0.5f, editUser.position.y, new TouchAction() { @Override public void execute(boolean touch) { editUser.keyUp(Input.Keys.ENTER); } }); grpButtons = new RadioGroup(); btnMain = new RadioButton(RegionID.BTN_UI_CHANNEL_MAIN_OFF, RegionID.BTN_UI_CHANNEL_MAIN_ON, halfWidth * 0.9396f, halfHeight - mView.getTextureRegion(RegionID.BTN_UI_CHANNEL_MAIN_OFF).getRegionHeight() * 0.75f, new TouchAction() { @Override public void execute(boolean touch) { fieldChat.setCurrentChannel(ChatList.mainChannel); } }); btnMain.setCheck(true); grpButtons.addButton(btnMain); btnLocation = new RadioButton(RegionID.BTN_UI_CHANNEL_LOCATION_OFF, RegionID.BTN_UI_CHANNEL_LOCATION_ON, halfWidth * 0.9396f, halfHeight - mView.getTextureRegion(RegionID.BTN_UI_CHANNEL_MAIN_OFF).getRegionHeight() * 2.0f , new TouchAction() { @Override public void execute(boolean touch) { fieldChat.setCurrentChannel(ChatList.locationChannel); } }); grpButtons.addButton(btnLocation); btnPlanet = new RadioButton(RegionID.BTN_UI_CHANNEL_PLANET_OFF, RegionID.BTN_UI_CHANNEL_PLANET_ON, halfWidth * 0.9396f, halfHeight - mView.getTextureRegion(RegionID.BTN_UI_CHANNEL_MAIN_OFF).getRegionHeight() * 3.25f , new TouchAction() { @Override public void execute(boolean touch) { fieldChat.setCurrentChannel(ChatList.planetChannel); } }); grpButtons.addButton(btnPlanet); btnDomain = new RadioButton(RegionID.BTN_UI_CHANNEL_DOMAIN_OFF, RegionID.BTN_UI_CHANNEL_DOMAIN_ON, halfWidth * 0.9396f, halfHeight - mView.getTextureRegion(RegionID.BTN_UI_CHANNEL_MAIN_OFF).getRegionHeight() * 4.5f , new TouchAction() { @Override public void execute(boolean touch) { fieldChat.setCurrentChannel(ChatList.domainChannel); } }); grpButtons.addButton(btnDomain); btnPrivate = new RadioButton(RegionID.BTN_UI_CHANNEL_PRIVATE_OFF, RegionID.BTN_UI_CHANNEL_PRIVATE_ON, halfWidth * 0.9396f, halfHeight - mView.getTextureRegion(RegionID.BTN_UI_CHANNEL_MAIN_OFF).getRegionHeight() * 5.75f , new TouchAction() { @Override public void execute(boolean touch) { fieldChat.setCurrentChannel(ChatList.privateChannel); } }); grpButtons.addButton(btnPrivate); menu.addElement(panelBlank); menu.addElement(btnDisconnect); menu.addElement(btnCancel); addElement(menu); panel.addElement(btnMenu); panel.addElement(btnChat); addElement(panel); chat.addElement(fieldChat); chat.addElement(editUser); chat.addElement(btnSend); chat.addElement(btnMain); chat.addElement(btnLocation); chat.addElement(btnPlanet); chat.addElement(btnDomain); chat.addElement(btnPrivate); addElement(chat); }
public void loadPart(){ mView.loadTexture("data/gui/blank.png", RegionID.BLANK, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_CHAT_OFF, 192, 192, 96, 96, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_CHAT_ON, 192, 288, 96, 96, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_MENU_OFF, 288, 192, 96, 96, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_MENU_ON, 288, 288, 96, 96, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_CHANNEL_MAIN_OFF, 0, 0, 96, 96, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_CHANNEL_MAIN_ON, 0, 96, 96, 96, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_CHANNEL_LOCATION_OFF, 96, 0, 96, 96, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_CHANNEL_LOCATION_ON, 96, 96, 96, 96, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_CHANNEL_PLANET_OFF, 192, 0, 96, 96, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_CHANNEL_PLANET_ON, 192, 96, 96, 96, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_CHANNEL_DOMAIN_OFF, 288, 0, 96, 96, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_CHANNEL_DOMAIN_ON, 288, 96, 96, 96, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_CHANNEL_PRIVATE_OFF, 0, 192, 96, 96, false); mView.loadTexture("data/gui/icon_collect.png", RegionID.BTN_UI_CHANNEL_PRIVATE_ON, 0, 288, 96, 96, false); mView.loadTexture("data/gui/ui_back.png", RegionID.BTN_UI_BACK_OFF, 0, 0, 450, 100, false); mView.loadTexture("data/gui/ui_back.png", RegionID.BTN_UI_BACK_ON, 0, 100, 450, 100, false); mView.loadTexture("data/gui/ui_exit.png", RegionID.BTN_UI_EXIT_OFF, 0, 0, 450, 100, false); mView.loadTexture("data/gui/ui_exit.png", RegionID.BTN_UI_EXIT_ON, 0, 100, 450, 100, false); mView.loadTexture("data/gui/chat_field.png", RegionID.FIELD_CHAT, false); mView.loadTexture("data/gui/chat_edit.png", RegionID.EDIT_CHAT, false); mView.loadTexture("data/gui/btn_send.png", RegionID.BTN_UI_SEND_OFF, 0, 0, 128, 64, false); mView.loadTexture("data/gui/btn_send.png", RegionID.BTN_UI_SEND_ON, 0, 64, 128, 64, false); float halfWidth = mView.getHUDCamera().getWidth() * 0.5f; float halfHeight = mView.getHUDCamera().getHeight() * 0.5f; panelBlank = new PressedButton(RegionID.BLANK, RegionID.BLANK, 0.0f, 0.0f); btnDisconnect = new PressedButton(RegionID.BTN_UI_EXIT_OFF, RegionID.BTN_UI_EXIT_ON, halfWidth * 0.0f, -halfHeight * 0.137f, new TouchAction() { @Override public void execute(boolean touch) { Controllers.netController.disconnect(); } }); btnCancel = new PressedButton(RegionID.BTN_UI_BACK_OFF, RegionID.BTN_UI_BACK_ON, halfWidth * 0.0f, halfHeight * 0.137f, new TouchAction() { @Override public void execute(boolean touch) { setVisible(panel); lController.getRadar().visible = true; Parts.getInfoPanel().setVisible(true); Parts.getSkillsPanel().setVisible(true); RaniaGame.mController.addProcessor(lController.getPlayerController()); } }); btnMenu = new PressedButton(RegionID.BTN_UI_MENU_OFF, RegionID.BTN_UI_MENU_ON, halfWidth * 0.9396f, -halfHeight * 0.8926f, new TouchAction() { @Override public void execute(boolean touch) { setVisible(menu); lController.getRadar().visible = false; Parts.getInfoPanel().setVisible(false); Parts.getSkillsPanel().setVisible(false); RaniaGame.mController.removeProcessor(lController.getPlayerController()); } }); btnChat = new PressedButton(RegionID.BTN_UI_CHAT_OFF, RegionID.BTN_UI_CHAT_ON, halfWidth * 0.9396f, -halfHeight * 0.6963f, new TouchAction() { @Override public void execute(boolean touch) { chatVisible = !chatVisible; chat.setVisible(chatVisible); Parts.getInfoPanel().setVisible(!chatVisible); Parts.getSkillsPanel().setVisible(!chatVisible); lController.getRadar().visible = !chatVisible; if (chatVisible) RaniaGame.mController.removeProcessor(lController.getPlayerController()); else RaniaGame.mController.addProcessor(lController.getPlayerController()); editUser.setFocus(); } }); fieldChat = new ChatList(RegionID.FIELD_CHAT, -halfWidth + mView.getTextureRegion(RegionID.FIELD_CHAT).getRegionWidth() * 0.5f, halfHeight - mView.getTextureRegion(RegionID.FIELD_CHAT).getRegionHeight() * 0.5f, new MultilineText("", Font.getFont("data/fonts/Arial.ttf", 20), new Color(1, 1, 1, 1), -mView.getTextureRegion(RegionID.FIELD_CHAT).getRegionWidth() * 0.5f + 20.0f, mView.getTextureRegion(RegionID.FIELD_CHAT).getRegionHeight() * 0.5f - 10.0f, Text.Align.LEFT, Text.Align.TOP), mView.getTextureRegion(RegionID.FIELD_CHAT).getRegionWidth() * 0.95f, mView.getTextureRegion(RegionID.FIELD_CHAT).getRegionHeight() * 0.95f); editUser = new Edit(RegionID.EDIT_CHAT, RegionID.EDIT_CHAT, -halfWidth + mView.getTextureRegion(RegionID.EDIT_CHAT).getRegionWidth() * 0.5f, -halfHeight + mView.getTextureRegion(RegionID.EDIT_CHAT).getRegionHeight() * 0.5f, new Text("", Font.getFont("data/fonts/Arial.ttf", 20), new Color(1, 1, 1, 1), -mView.getTextureRegion(RegionID.EDIT_CHAT).getRegionWidth() * 0.5f + 20.0f, 0, Text.Align.LEFT, Text.Align.CENTER), 255, new EditAction() { @Override public void execute(Edit edit) { Controllers.netController.sendChatMessage(edit.getText(), fieldChat.getCurrentChannel()); edit.setText(""); edit.setFocus(); } }); btnSend = new PressedButton(RegionID.BTN_UI_SEND_OFF, RegionID.BTN_UI_SEND_ON, -halfWidth + mView.getTextureRegion(RegionID.EDIT_CHAT).getRegionWidth() + mView.getTextureRegion(RegionID.BTN_UI_SEND_OFF).getRegionWidth() * 0.5f, editUser.position.y, new TouchAction() { @Override public void execute(boolean touch) { editUser.keyUp(Input.Keys.ENTER); } }); grpButtons = new RadioGroup(); btnMain = new RadioButton(RegionID.BTN_UI_CHANNEL_MAIN_OFF, RegionID.BTN_UI_CHANNEL_MAIN_ON, halfWidth * 0.9396f, halfHeight - mView.getTextureRegion(RegionID.BTN_UI_CHANNEL_MAIN_OFF).getRegionHeight() * 0.75f, new TouchAction() { @Override public void execute(boolean touch) { fieldChat.setCurrentChannel(ChatList.mainChannel); } }); btnMain.setCheck(true); grpButtons.addButton(btnMain); btnLocation = new RadioButton(RegionID.BTN_UI_CHANNEL_LOCATION_OFF, RegionID.BTN_UI_CHANNEL_LOCATION_ON, halfWidth * 0.9396f, halfHeight - mView.getTextureRegion(RegionID.BTN_UI_CHANNEL_MAIN_OFF).getRegionHeight() * 2.0f , new TouchAction() { @Override public void execute(boolean touch) { fieldChat.setCurrentChannel(ChatList.locationChannel); } }); grpButtons.addButton(btnLocation); btnPlanet = new RadioButton(RegionID.BTN_UI_CHANNEL_PLANET_OFF, RegionID.BTN_UI_CHANNEL_PLANET_ON, halfWidth * 0.9396f, halfHeight - mView.getTextureRegion(RegionID.BTN_UI_CHANNEL_MAIN_OFF).getRegionHeight() * 3.25f , new TouchAction() { @Override public void execute(boolean touch) { fieldChat.setCurrentChannel(ChatList.planetChannel); } }); grpButtons.addButton(btnPlanet); btnDomain = new RadioButton(RegionID.BTN_UI_CHANNEL_DOMAIN_OFF, RegionID.BTN_UI_CHANNEL_DOMAIN_ON, halfWidth * 0.9396f, halfHeight - mView.getTextureRegion(RegionID.BTN_UI_CHANNEL_MAIN_OFF).getRegionHeight() * 4.5f , new TouchAction() { @Override public void execute(boolean touch) { fieldChat.setCurrentChannel(ChatList.domainChannel); } }); grpButtons.addButton(btnDomain); btnPrivate = new RadioButton(RegionID.BTN_UI_CHANNEL_PRIVATE_OFF, RegionID.BTN_UI_CHANNEL_PRIVATE_ON, halfWidth * 0.9396f, halfHeight - mView.getTextureRegion(RegionID.BTN_UI_CHANNEL_MAIN_OFF).getRegionHeight() * 5.75f , new TouchAction() { @Override public void execute(boolean touch) { fieldChat.setCurrentChannel(ChatList.privateChannel); } }); grpButtons.addButton(btnPrivate); menu.addElement(panelBlank); menu.addElement(btnDisconnect); menu.addElement(btnCancel); addElement(menu); panel.addElement(btnMenu); panel.addElement(btnChat); addElement(panel); chat.addElement(fieldChat); chat.addElement(editUser); chat.addElement(btnSend); chat.addElement(btnMain); chat.addElement(btnLocation); chat.addElement(btnPlanet); chat.addElement(btnDomain); chat.addElement(btnPrivate); addElement(chat); }
protected AbstractTower(Point p, Rectangle2D pathBounds, String name, int fireRate, double range, double bulletSpeed, double damage, int width, int turretWidth, boolean hasOverlay) { centre = new Point(p); this.pathBounds = pathBounds; topLeft = new Point(0, 0); this.name = name; this.fireRate = fireRate; this.range = range; rangeUpgrade = range * (upgradeIncreaseFactor - 1); twiceRange = (int)(range * 2); this.bulletSpeed = bulletSpeed; bulletSpeedUpgrade = bulletSpeed * (upgradeIncreaseFactor - 1); this.damage = damage; this.width = width; halfWidth = width / 2; this.turretWidth = turretWidth; bounds = new Circle(centre, halfWidth); setTopLeft(); setBounds(); String className = getClass().getSimpleName(); className = className.substring(0, className.length() - 5); String nameLowerCase = makeFirstCharacterLowerCase(className); baseImage = loadImage(towerButtonImages, width, "towers", nameLowerCase + ".png"); imageRotates = (hasOverlay && turretWidth != 0); if(hasOverlay) { rotatingImage = loadImage(rotatingImages, width, "towers", "overlays", className + "Overlay.png"); } else { rotatingImage = null; } currentImage = drawCurrentImage(rotatingImage); buttonImage = loadImage(towerButtonImages, 0, "buttons", "towers", className + "Tower.png"); }
protected AbstractTower(Point p, Rectangle2D pathBounds, String name, int fireRate, double range, double bulletSpeed, double damage, int width, int turretWidth, boolean hasOverlay) { centre = new Point(p); this.pathBounds = pathBounds; topLeft = new Point(0, 0); this.name = name; this.fireRate = fireRate; this.range = range; rangeUpgrade = range * (upgradeIncreaseFactor - 1); twiceRange = (int)(range * 2); this.bulletSpeed = bulletSpeed; bulletSpeedUpgrade = bulletSpeed * (upgradeIncreaseFactor - 1); this.damage = damage; this.width = width; halfWidth = width / 2; this.turretWidth = turretWidth; bounds = new Circle(centre, halfWidth); setTopLeft(); setBounds(); String className = getClass().getSimpleName(); className = className.substring(0, className.length() - 5); String nameLowerCase = makeFirstCharacterLowerCase(className); baseImage = loadImage(towerImages, width, "towers", nameLowerCase + ".png"); imageRotates = (hasOverlay && turretWidth != 0); if(hasOverlay) { rotatingImage = loadImage(rotatingImages, width, "towers", "overlays", className + "Overlay.png"); } else { rotatingImage = null; } currentImage = drawCurrentImage(rotatingImage); buttonImage = loadImage(towerButtonImages, 0, "buttons", "towers", className + "Tower.png"); }
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { switch (args.length) { case 0: throw new NotEnoughArgumentsException(); case 1: final User player = getPlayer(server, args, 0); if (!player.isTeleportEnabled()) { throw new Exception(_("teleportDisabled", player.getDisplayName())); } if (user.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + player.getWorld().getName())) { throw new Exception(_("noPerm", "essentials.worlds." + player.getWorld().getName())); } user.sendMessage(_("teleporting")); final Trade charge = new Trade(this.getName(), ess); charge.isAffordableFor(user); user.getTeleport().teleport(player, charge, TeleportCause.COMMAND); throw new NoChargeException(); case 4: if (!user.isAuthorized("essentials.tp.others")) { throw new Exception(_("noPerm", "essentials.tp.others")); } user.sendMessage(_("teleporting")); final User target2 = getPlayer(server, args, 0); final double x = args[1].startsWith("~") ? target2.getLocation().getX() + Integer.parseInt(args[1].substring(1)) : Integer.parseInt(args[1]); final double y = args[2].startsWith("~") ? target2.getLocation().getY() + Integer.parseInt(args[2].substring(1)) : Integer.parseInt(args[2]); final double z = args[3].startsWith("~") ? target2.getLocation().getZ() + Integer.parseInt(args[3].substring(1)) : Integer.parseInt(args[3]); if (x > 30000000 || y > 30000000 || z > 30000000 || x < -30000000 || y < -30000000 || z < -30000000) { throw new NotEnoughArgumentsException("Value of coordinates cannot be over 30000000"); } final Location location = new Location(target2.getWorld(), x, y, z); if (!target2.isTeleportEnabled()) { throw new Exception(_("teleportDisabled", target2.getDisplayName())); } target2.getTeleport().now(location, false, TeleportCause.COMMAND); target2.sendMessage(_("teleporting")); case 2: default: if (!user.isAuthorized("essentials.tp.others")) { throw new Exception(_("noPerm", "essentials.tp.others")); } user.sendMessage(_("teleporting")); final User target = getPlayer(server, args, 0); final User toPlayer = getPlayer(server, args, 1); if (!target.isTeleportEnabled()) { throw new Exception(_("teleportDisabled", target.getDisplayName())); } if (!toPlayer.isTeleportEnabled()) { throw new Exception(_("teleportDisabled", toPlayer.getDisplayName())); } if (target.getWorld() != toPlayer.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + toPlayer.getWorld().getName())) { throw new Exception(_("noPerm", "essentials.worlds." + toPlayer.getWorld().getName())); } target.getTeleport().now(toPlayer, false, TeleportCause.COMMAND); target.sendMessage(_("teleportAtoB", user.getDisplayName(), toPlayer.getDisplayName())); break; } }
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { switch (args.length) { case 0: throw new NotEnoughArgumentsException(); case 1: final User player = getPlayer(server, args, 0); if (!player.isTeleportEnabled()) { throw new Exception(_("teleportDisabled", player.getDisplayName())); } if (user.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + player.getWorld().getName())) { throw new Exception(_("noPerm", "essentials.worlds." + player.getWorld().getName())); } user.sendMessage(_("teleporting")); final Trade charge = new Trade(this.getName(), ess); charge.isAffordableFor(user); user.getTeleport().teleport(player, charge, TeleportCause.COMMAND); throw new NoChargeException(); case 4: if (!user.isAuthorized("essentials.tp.others")) { throw new Exception(_("noPerm", "essentials.tp.others")); } final User target2 = getPlayer(server, args, 0); final double x = args[1].startsWith("~") ? target2.getLocation().getX() + Integer.parseInt(args[1].substring(1)) : Integer.parseInt(args[1]); final double y = args[2].startsWith("~") ? target2.getLocation().getY() + Integer.parseInt(args[2].substring(1)) : Integer.parseInt(args[2]); final double z = args[3].startsWith("~") ? target2.getLocation().getZ() + Integer.parseInt(args[3].substring(1)) : Integer.parseInt(args[3]); if (x > 30000000 || y > 30000000 || z > 30000000 || x < -30000000 || y < -30000000 || z < -30000000) { throw new NotEnoughArgumentsException("Value of coordinates cannot be over 30000000"); } final Location location = new Location(target2.getWorld(), x, y, z); if (!target2.isTeleportEnabled()) { throw new Exception(_("teleportDisabled", target2.getDisplayName())); } target2.getTeleport().now(location, false, TeleportCause.COMMAND); user.sendMessage(_("teleporting")); target2.sendMessage(_("teleporting")); case 2: default: if (!user.isAuthorized("essentials.tp.others")) { throw new Exception(_("noPerm", "essentials.tp.others")); } final User target = getPlayer(server, args, 0); final User toPlayer = getPlayer(server, args, 1); if (!target.isTeleportEnabled()) { throw new Exception(_("teleportDisabled", target.getDisplayName())); } if (!toPlayer.isTeleportEnabled()) { throw new Exception(_("teleportDisabled", toPlayer.getDisplayName())); } if (target.getWorld() != toPlayer.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + toPlayer.getWorld().getName())) { throw new Exception(_("noPerm", "essentials.worlds." + toPlayer.getWorld().getName())); } target.getTeleport().now(toPlayer, false, TeleportCause.COMMAND); user.sendMessage(_("teleporting")); target.sendMessage(_("teleportAtoB", user.getDisplayName(), toPlayer.getDisplayName())); break; } }
private Components() { shooter = new ShooterComponents(SHOOTER_LEFT_JAGUAR_PORT, SHOOTER_RIGHT_JAGUAR_PORT, SHOOTER_ROTATOR_JAGUAR_PORT, BALL_LOAD_PISTON_SPIKE); drive = new DrivingComponents(LEFT_JAGUAR_PORT, RIGHT_JAGUAR_PORT, SUPER_SHIFTERS_SPIKE); collector = new CollectorComponents(BALL_COLL_ROTATE_SPIKE, BALL_COLL_LIFT_JAGUAR, CONV_MOVE_SPIKE); cameraServoVertical = new Servo(CAMERA_SERVO_VERTICAL); sonar = new SonarComponents(SONAR, FIRFilter.autoWeightedFilter(20)); gyro = new Gyro(GYRO); compressor = new Compressor(COMPRESSOR_PRESSURE_SENSOR,COMPRESSOR_SPIKE); compressor.start(); textOutput = DriverStationLCD.getInstance(); cypress = new CypressComponents(); timer = new Timer(); }
private Components() { shooter = new ShooterComponents(SHOOTER_LEFT_JAGUAR_PORT, SHOOTER_RIGHT_JAGUAR_PORT, SHOOTER_ROTATOR_JAGUAR_PORT, BALL_LOAD_PISTON_SPIKE); drive = new DrivingComponents(LEFT_JAGUAR_PORT, RIGHT_JAGUAR_PORT, SUPER_SHIFTERS_SPIKE); collector = new CollectorComponents(BALL_COLL_LIFT_JAGUAR, BALL_COLL_ROTATE_SPIKE, CONV_MOVE_SPIKE); cameraServoVertical = new Servo(CAMERA_SERVO_VERTICAL); sonar = new SonarComponents(SONAR, FIRFilter.autoWeightedFilter(20)); gyro = new Gyro(GYRO); compressor = new Compressor(COMPRESSOR_PRESSURE_SENSOR,COMPRESSOR_SPIKE); compressor.start(); textOutput = DriverStationLCD.getInstance(); cypress = new CypressComponents(); timer = new Timer(); }
public Response getIframeReport(@QueryParam(REST_QUERY_CUSTOMERID) String customerId, @QueryParam(REST_QUERY_USERID) String userId, @QueryParam(REST_QUERY_APPDIR_NAME) String appDirName, @QueryParam(REST_QUERY_VALIDATE_AGAINST) String validateAgainst, @QueryParam(REST_QUERY_MODULE_NAME) String module, @Context HttpServletRequest request) { ResponseInfo<PossibleValues> responseData = new ResponseInfo<PossibleValues>(); StringBuilder sb = new StringBuilder(); try { if (StringUtils.isNotEmpty(module)) { appDirName = appDirName + File.separator + module; } ApplicationInfo appInfo = FrameworkServiceUtil.getApplicationInfo(appDirName); PomProcessor processor = FrameworkServiceUtil.getPomProcessor(appDirName); String validateReportUrl = processor.getProperty(Constants.POM_PROP_KEY_VALIDATE_REPORT); FrameworkConfiguration frameworkConfig = PhrescoFrameworkFactory.getFrameworkConfig(); ServiceManager serviceManager = CONTEXT_MANAGER_MAP.get(userId); Customer customer = serviceManager.getCustomer(customerId); Properties sysProps = System.getProperties(); String phrescoFileServerNumber = sysProps.getProperty(PHRESCO_FILE_SERVER_PORT_NO); if (StringUtils.isNotEmpty(validateReportUrl)) { StringBuilder codeValidatePath = new StringBuilder(FrameworkServiceUtil.getApplicationHome(appDirName)); codeValidatePath.append(validateReportUrl); codeValidatePath.append(validateAgainst); codeValidatePath.append(File.separatorChar); codeValidatePath.append(INDEX_HTML); File indexPath = new File(codeValidatePath.toString()); if (indexPath.isFile() && StringUtils.isNotEmpty(phrescoFileServerNumber)) { sb.append(HTTP_PROTOCOL); sb.append(PROTOCOL_POSTFIX); InetAddress thisIp = InetAddress.getLocalHost(); sb.append(thisIp.getHostAddress()); sb.append(FrameworkConstants.COLON); sb.append(phrescoFileServerNumber); sb.append(FrameworkConstants.FORWARD_SLASH); sb.append(appDirName); sb.append(validateReportUrl); sb.append(validateAgainst); sb.append(FrameworkConstants.FORWARD_SLASH); sb.append(INDEX_HTML); ResponseInfo<String> finalOutput = responseDataEvaluation(responseData, null, sb.toString(), RESPONSE_STATUS_SUCCESS, PHR500003); return Response.ok(finalOutput).header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER).build(); } else { ResponseInfo<PossibleValues> finalOutput = responseDataEvaluation(responseData, null, null, RESPONSE_STATUS_SUCCESS, PHR500005); return Response.status(Status.OK).entity(finalOutput).header( ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER).build(); } } String serverUrl = ""; FrameworkUtil frameworkUtil = new FrameworkUtil(request); serverUrl = frameworkUtil.getSonarHomeURL(); StringBuilder reportPath = new StringBuilder(FrameworkServiceUtil.getApplicationHome(appDirName)); if (StringUtils.isNotEmpty(validateAgainst) && FUNCTIONALTEST.equals(validateAgainst)) { reportPath.append(frameworkUtil.getFunctionalTestDir(appInfo)); } reportPath.append(File.separatorChar); reportPath.append(POM_XML); File file = new File(reportPath.toString()); processor = new PomProcessor(file); String groupId = processor.getModel().getGroupId(); String artifactId = processor.getModel().getArtifactId(); sb.append(serverUrl); sb.append(frameworkConfig.getSonarReportPath()); sb.append(groupId); sb.append(FrameworkConstants.COLON); sb.append(artifactId); if (StringUtils.isNotEmpty(validateAgainst) && !REQ_SRC.equals(validateAgainst)) { sb.append(FrameworkConstants.COLON); sb.append(validateAgainst); } int responseCode = 0; URL sonarURL = new URL(sb.toString()); String protocol = sonarURL.getProtocol(); HttpURLConnection connection = null; if (protocol.equals(HTTP_PROTOCOL)) { connection = (HttpURLConnection) sonarURL.openConnection(); responseCode = connection.getResponseCode(); } else if (protocol.equals("https")) { responseCode = FrameworkUtil.getHttpsResponse(sb.toString()); } if (responseCode != 200) { ResponseInfo<PossibleValues> finalOutput = responseDataEvaluation(responseData, null, null, RESPONSE_STATUS_FAILURE, PHR510003); return Response.status(Status.OK).entity(finalOutput).header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER).build(); } Map<String, String> theme = customer.getFrameworkTheme(); if (MapUtils.isNotEmpty(theme)) { sb.append("?"); sb.append(CUST_BASE_COLOR + theme.get("customerBaseColor")); sb.append("&" + CSS_PHRESCO_STYLE); } else { sb.append("?"); sb.append(CSS_PHRESCO_STYLE); } } catch (PhrescoException e) { ResponseInfo<PossibleValues> finalOutput = responseDataEvaluation(responseData, e, null, RESPONSE_STATUS_ERROR, PHR510009); return Response.status(Status.OK).entity(finalOutput).header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER) .build(); } catch (PhrescoPomException e) { ResponseInfo<PossibleValues> finalOutput = responseDataEvaluation(responseData, e, null, RESPONSE_STATUS_ERROR, PHR510006); return Response.status(Status.OK).entity(finalOutput).header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER) .build(); } catch (UnknownHostException e) { ResponseInfo<PossibleValues> finalOutput = responseDataEvaluation(responseData, e, null, RESPONSE_STATUS_ERROR, PHR510007); return Response.status(Status.OK).entity(finalOutput).header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER) .build(); } catch (IOException e) { ResponseInfo<PossibleValues> finalOutput = responseDataEvaluation(responseData, e, null, RESPONSE_STATUS_ERROR, PHR510008); return Response.status(Status.OK).entity(finalOutput).header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER) .build(); } ResponseInfo<String> finalOutput = responseDataEvaluation(responseData, null, sb.toString(), RESPONSE_STATUS_SUCCESS, PHR500003); return Response.ok(finalOutput).header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER).build(); }
public Response getIframeReport(@QueryParam(REST_QUERY_CUSTOMERID) String customerId, @QueryParam(REST_QUERY_USERID) String userId, @QueryParam(REST_QUERY_APPDIR_NAME) String appDirName, @QueryParam(REST_QUERY_VALIDATE_AGAINST) String validateAgainst, @QueryParam(REST_QUERY_MODULE_NAME) String module, @Context HttpServletRequest request) { ResponseInfo<PossibleValues> responseData = new ResponseInfo<PossibleValues>(); StringBuilder sb = new StringBuilder(); try { if (StringUtils.isNotEmpty(module)) { appDirName = appDirName + File.separator + module; } ApplicationInfo appInfo = FrameworkServiceUtil.getApplicationInfo(appDirName); PomProcessor processor = FrameworkServiceUtil.getPomProcessor(appDirName); String validateReportUrl = processor.getProperty(Constants.POM_PROP_KEY_VALIDATE_REPORT); FrameworkConfiguration frameworkConfig = PhrescoFrameworkFactory.getFrameworkConfig(); ServiceManager serviceManager = CONTEXT_MANAGER_MAP.get(userId); Customer customer = serviceManager.getCustomer(customerId); Properties sysProps = System.getProperties(); String phrescoFileServerNumber = sysProps.getProperty(PHRESCO_FILE_SERVER_PORT_NO); if (StringUtils.isNotEmpty(validateReportUrl)) { StringBuilder codeValidatePath = new StringBuilder(FrameworkServiceUtil.getApplicationHome(appDirName)); codeValidatePath.append(validateReportUrl); codeValidatePath.append(validateAgainst); codeValidatePath.append(File.separatorChar); codeValidatePath.append(INDEX_HTML); File indexPath = new File(codeValidatePath.toString()); if (indexPath.isFile() && StringUtils.isNotEmpty(phrescoFileServerNumber)) { sb.append(HTTP_PROTOCOL); sb.append(PROTOCOL_POSTFIX); InetAddress thisIp = InetAddress.getLocalHost(); sb.append(thisIp.getHostAddress()); sb.append(FrameworkConstants.COLON); sb.append(phrescoFileServerNumber); sb.append(FrameworkConstants.FORWARD_SLASH); sb.append(appDirName); sb.append(validateReportUrl); sb.append(validateAgainst); sb.append(FrameworkConstants.FORWARD_SLASH); sb.append(INDEX_HTML); ResponseInfo<String> finalOutput = responseDataEvaluation(responseData, null, sb.toString(), RESPONSE_STATUS_SUCCESS, PHR500003); return Response.ok(finalOutput).header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER).build(); } else { ResponseInfo<PossibleValues> finalOutput = responseDataEvaluation(responseData, null, null, RESPONSE_STATUS_SUCCESS, PHR500005); return Response.status(Status.OK).entity(finalOutput).header( ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER).build(); } } String serverUrl = ""; FrameworkUtil frameworkUtil = new FrameworkUtil(request); serverUrl = frameworkUtil.getSonarHomeURL(); StringBuilder reportPath = new StringBuilder(FrameworkServiceUtil.getApplicationHome(appDirName)); if (StringUtils.isNotEmpty(validateAgainst) && FUNCTIONALTEST.equals(validateAgainst)) { reportPath.append(frameworkUtil.getFunctionalTestDir(appDirName)); } reportPath.append(File.separatorChar); reportPath.append(POM_XML); File file = new File(reportPath.toString()); processor = new PomProcessor(file); String groupId = processor.getModel().getGroupId(); String artifactId = processor.getModel().getArtifactId(); sb.append(serverUrl); sb.append(frameworkConfig.getSonarReportPath()); sb.append(groupId); sb.append(FrameworkConstants.COLON); sb.append(artifactId); if (StringUtils.isNotEmpty(validateAgainst) && !REQ_SRC.equals(validateAgainst)) { sb.append(FrameworkConstants.COLON); sb.append(validateAgainst); } int responseCode = 0; URL sonarURL = new URL(sb.toString()); String protocol = sonarURL.getProtocol(); HttpURLConnection connection = null; if (protocol.equals(HTTP_PROTOCOL)) { connection = (HttpURLConnection) sonarURL.openConnection(); responseCode = connection.getResponseCode(); } else if (protocol.equals("https")) { responseCode = FrameworkUtil.getHttpsResponse(sb.toString()); } if (responseCode != 200) { ResponseInfo<PossibleValues> finalOutput = responseDataEvaluation(responseData, null, null, RESPONSE_STATUS_FAILURE, PHR510003); return Response.status(Status.OK).entity(finalOutput).header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER).build(); } Map<String, String> theme = customer.getFrameworkTheme(); if (MapUtils.isNotEmpty(theme)) { sb.append("?"); sb.append(CUST_BASE_COLOR + theme.get("customerBaseColor")); sb.append("&" + CSS_PHRESCO_STYLE); } else { sb.append("?"); sb.append(CSS_PHRESCO_STYLE); } } catch (PhrescoException e) { ResponseInfo<PossibleValues> finalOutput = responseDataEvaluation(responseData, e, null, RESPONSE_STATUS_ERROR, PHR510009); return Response.status(Status.OK).entity(finalOutput).header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER) .build(); } catch (PhrescoPomException e) { ResponseInfo<PossibleValues> finalOutput = responseDataEvaluation(responseData, e, null, RESPONSE_STATUS_ERROR, PHR510006); return Response.status(Status.OK).entity(finalOutput).header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER) .build(); } catch (UnknownHostException e) { ResponseInfo<PossibleValues> finalOutput = responseDataEvaluation(responseData, e, null, RESPONSE_STATUS_ERROR, PHR510007); return Response.status(Status.OK).entity(finalOutput).header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER) .build(); } catch (IOException e) { ResponseInfo<PossibleValues> finalOutput = responseDataEvaluation(responseData, e, null, RESPONSE_STATUS_ERROR, PHR510008); return Response.status(Status.OK).entity(finalOutput).header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER) .build(); } ResponseInfo<String> finalOutput = responseDataEvaluation(responseData, null, sb.toString(), RESPONSE_STATUS_SUCCESS, PHR500003); return Response.ok(finalOutput).header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER).build(); }
public void process(String model) { MTransactionView stsV = MTransactionView.getView(); try{ conn = DBconnector.getConnection(); Statement stmt = conn.createStatement(); if(DEBUG == true){ System.out.println("SELECT * FROM MONEY_TRANS WHERE TUSERNAME = '" + c.getUsername() + "'" ); } rs = stmt.executeQuery("SELECT * FROM MONEY_TRANS WHERE TUSERNAME = '" + c.getUsername() + "'" ); mtV.getRow().clear(); while( rs.next() ){ if(DEBUG == true){ System.out.println("Getting Row"); } Vector<String> newRow = new Vector<String>(); String date = rs.getString("TDATE"); int id = rs.getInt("M_TRANS_ID"); int type = rs.getInt("TTYPE"); float amt = rs.getFloat("AMOUNT"); float balance = rs.getFloat("BALANCE"); newRow.add(Integer.toString(id)); newRow.add(date); if( type == 2 ){ newRow.add("Withdraw"); } else if ( type == 1 ){ newRow.add("Deposit"); } newRow.add(Float.toString(amt)); newRow.add(Float.toString(balance)); mtV.getRow().add(newRow); } mtV.updateView(); }catch (SQLException e){ System.out.println("Exception in MTransactionController"); } stsV.setVisible(true); }
public void process(String model) { MTransactionView stsV = MTransactionView.getView(); try{ conn = DBconnector.getConnection(); Statement stmt = conn.createStatement(); if(DEBUG == true){ System.out.println("SELECT * FROM MONEY_TRANS WHERE TUSERNAME = '" + c.getUsername() + "'" ); } rs = stmt.executeQuery("SELECT * FROM MONEY_TRANS WHERE TUSERNAME = '" + c.getUsername() + "'" ); mtV.getRow().clear(); while( rs.next() ){ if(DEBUG == true){ System.out.println("Getting Row"); } Vector<String> newRow = new Vector<String>(); String date = rs.getString("TDATE"); int id = rs.getInt("M_TRANS_ID"); int type = rs.getInt("TTYPE"); float amt = rs.getFloat("AMOUNT"); float balance = rs.getFloat("BALANCE"); newRow.add(Integer.toString(id)); newRow.add(date); if( type == 2 ){ newRow.add("Withdraw"); } else if ( type == 1 ){ newRow.add("Deposit"); } else if(type == 3) newRow.add("Interest"); newRow.add(Float.toString(amt)); newRow.add(Float.toString(balance)); mtV.getRow().add(newRow); } mtV.updateView(); }catch (SQLException e){ System.out.println("Exception in MTransactionController"); } stsV.setVisible(true); }
protected FunctionWizard createWizard() { FunctionWizard result; List<FunctionWizardDescriptor<?>> factories = FunctionWizardExtension.getInstance().getFactories(new FactoryFilter<FunctionWizardFactory, FunctionWizardDescriptor<?>>() { @Override public boolean acceptFactory(FunctionWizardDescriptor<?> factory) { return factory.getFunctionId().equals(function.getId()); } @Override public boolean acceptCollection( ExtensionObjectFactoryCollection<FunctionWizardFactory, FunctionWizardDescriptor<?>> collection) { return true; } }); if (!factories.isEmpty()) { FunctionWizardDescriptor<?> fwd = factories.get(0); result = fwd.createNewWizard(null); } if (function instanceof TypeFunction) { result = new GenericTypeFunctionWizard(null, function.getId()); } else { result = new GenericPropertyFunctionWizard(null, function.getId()); } result.init(); return result; }
protected FunctionWizard createWizard() { FunctionWizard result = null; List<FunctionWizardDescriptor<?>> factories = FunctionWizardExtension.getInstance().getFactories(new FactoryFilter<FunctionWizardFactory, FunctionWizardDescriptor<?>>() { @Override public boolean acceptFactory(FunctionWizardDescriptor<?> factory) { return factory.getFunctionId().equals(function.getId()); } @Override public boolean acceptCollection( ExtensionObjectFactoryCollection<FunctionWizardFactory, FunctionWizardDescriptor<?>> collection) { return true; } }); if (!factories.isEmpty()) { FunctionWizardDescriptor<?> fwd = factories.get(0); result = fwd.createNewWizard(null); } if (result == null) { if (function instanceof TypeFunction) { result = new GenericTypeFunctionWizard(null, function.getId()); } else { result = new GenericPropertyFunctionWizard(null, function.getId()); } } result.init(); return result; }
public String execute(String instruction) { switch (getCommand(instruction)) { case READ_COMMAND: try { String filePath = instruction.substring(CODE.length() + 6); return ";if (navigator.file.read_success != null) { navigator.file.read_success("+escapeString(filePath)+"); };"; } catch (Exception e) { return ";if (navigator.file.read_error != null) { navigator.file.read_error('Exception: " + e.getMessage().replace('\'', '`') + "'); };"; } } return null; }
public String execute(String instruction) { switch (getCommand(instruction)) { case READ_COMMAND: try { String filePath = instruction.substring(CODE.length() + 6); return ";if (navigator.file.read_success != null) { navigator.file.read_success('"+escapeString(filePath)+"'); };"; } catch (Exception e) { return ";if (navigator.file.read_error != null) { navigator.file.read_error('Exception: " + e.getMessage().replace('\'', '`') + "'); };"; } } return null; }
private void apply() { if (oldUserData == null) { lblStatus.setText("Please wait for user data to be fetched"); return; } disableControls(); final String realname; final String email; if (oldUserData.realname.equals(txtRealname.getText())) realname = null; else realname = txtRealname.getText(); if (oldUserData.email.equals(txtEmail.getText())) email = null; else email = txtEmail.getText(); Runnable helper = new Runnable() { boolean refreshRealname = realname != null; boolean refreshEmail = email != null; @Override public void run() { if (realname == null && email == null) { lblStatus.setText("Nothing to do here"); return; } if (realname != null && email != null) lblStatus.setText("Setting new parameters ... "); else if (realname == null) lblStatus.setText("Updating email ... "); else lblStatus.setText("Updating realname ... "); if (realname != null) IUser.Util.getInstance().setRealName(realname, new AsyncCallback<Void>() { @Override public void onSuccess(Void result) { lblStatus.setText("Realname set successfully." + (refreshEmail ? " Waiting for email to finish ..." : "")); refreshRealname = false; checkDone(); } @Override public void onFailure(Throwable caught) { lblStatus.setText("Error setting new real name"); } }); if (email != null) { IUser.Util.getInstance().setEmail(email, new AsyncCallback<Void>() { @Override public void onSuccess(Void result) { lblStatus.setText("Email set successfully." + (refreshRealname ? " Waiting for realname to finish ..." : "")); refreshEmail = false; checkDone(); } @Override public void onFailure(Throwable caught) { lblStatus.setText("Error setting new email"); } }); } } private void checkDone() { if (refreshEmail) return; if (refreshRealname) return; lblStatus.setText("Done"); close(); } }; helper.run(); }
private void apply() { if (oldUserData == null) { lblStatus.setText("Please wait for user data to be fetched"); return; } disableControls(); final String realname; final String email; if (oldUserData.realname.equals(txtRealname.getText())) realname = null; else realname = txtRealname.getText(); if (oldUserData.email.equals(txtEmail.getText())) email = null; else email = txtEmail.getText(); Runnable helper = new Runnable() { boolean refreshRealname = realname != null; boolean refreshEmail = email != null; @Override public void run() { if (realname == null && email == null) { lblStatus.setText("Nothing to do here"); return; } if (realname != null && email != null) lblStatus.setText("Setting new parameters ... "); else if (realname == null) lblStatus.setText("Updating email ... "); else lblStatus.setText("Updating realname ... "); if (realname != null) IUser.Util.getInstance().setRealName(realname, new AsyncCallback<Void>() { @Override public void onSuccess(Void result) { lblStatus.setText("Realname set successfully." + (refreshEmail ? " Waiting for email to finish ..." : "")); refreshRealname = false; checkDone(); } @Override public void onFailure(Throwable caught) { lblStatus.setText("Error setting new real name"); enableControls(); } }); if (email != null) { IUser.Util.getInstance().setEmail(email, new AsyncCallback<Void>() { @Override public void onSuccess(Void result) { lblStatus.setText("Email set successfully." + (refreshRealname ? " Waiting for realname to finish ..." : "")); refreshEmail = false; checkDone(); } @Override public void onFailure(Throwable caught) { lblStatus.setText("Error setting new email"); enableControls(); } }); } } private void checkDone() { if (refreshEmail) return; if (refreshRealname) return; lblStatus.setText("Done"); close(); } }; helper.run(); }
protected InitScript renderInitScript(FacesContext context, DropDownComponent dropDown) throws IOException { Spinner spinner = (Spinner) dropDown; if (spinner.getStep().doubleValue() <= 0) { throw new FacesException("The 'step' attribute of <o:spinner> with id " + spinner.getClientId(context) + " should be greater then 0, but was " + spinner.getStep()); } String buttonStyle = (String) dropDown.getAttributes().get("buttonStyle"); String buttonClass = (String) dropDown.getAttributes().get("buttonClass"); String buttonStyleClass = Styles.getCSSClass(context, dropDown, buttonStyle, DEFAULT_BUTTON_CLASS, buttonClass); String rolloverButtonStyle = (String) dropDown.getAttributes().get("rolloverButtonStyle"); String rolloverButtonClass = (String) dropDown.getAttributes().get("rolloverButtonClass"); String buttonRolloverStyleClass = Styles.getCSSClass(context, dropDown, rolloverButtonStyle, StyleGroup.rolloverStyleGroup(), rolloverButtonClass, DEFAULT_BUTTON_ROLLOVER_CLASS); String pressedButtonStyle = (String) dropDown.getAttributes().get("pressedButtonStyle"); String pressedButtonClass = (String) dropDown.getAttributes().get("pressedButtonClass"); String buttonPressedStyleClass = Styles.getCSSClass(context, dropDown, pressedButtonStyle, StyleGroup.rolloverStyleGroup(2), pressedButtonClass, DEFAULT_BUTTON_PRESSED_CLASS); if (dropDown.isDisabled()) { buttonRolloverStyleClass = ""; String disabledButtonStyle = (String) dropDown.getAttributes().get("disabledButtonStyle"); String disabledButtonClass = (String) dropDown.getAttributes().get("disabledButtonClass"); String disabledButtonStyleClass = Styles.getCSSClass(context, dropDown, disabledButtonStyle, StyleGroup.disabledStyleGroup(), disabledButtonClass, DEFAULT_DISABLED_BUTTON_CLASS); if (Rendering.isNullOrEmpty(disabledButtonStyle) && Rendering.isNullOrEmpty(disabledButtonClass)) { buttonStyleClass = Styles.mergeClassNames(disabledButtonStyleClass, buttonStyleClass); } else { buttonStyleClass = Styles.mergeClassNames(disabledButtonStyleClass, Styles.getCSSClass(context, dropDown, null, StyleGroup.regularStyleGroup(), null, DEFAULT_BUTTON_CLASS)); } } JSONObject options; try { options = createFormatOptions(context, spinner); } catch (JSONException e) { throw new FacesException(e); } ScriptBuilder sb = new ScriptBuilder().initScript(context, spinner, "O$.Spinner._init", spinner.getMinValue(), spinner.getMaxValue(), spinner.getStep(), spinner.isCycled(), buttonStyleClass, buttonRolloverStyleClass, buttonPressedStyleClass, spinner.isDisabled(), spinner.getOnchange(), options); return new InitScript(sb, new String[]{ Resources.utilJsURL(context), getDropdownJsURL(context), Resources.internalURL(context, "input/spinner.js"), Resources.internalURL(context, "util/dojo.js") }); }
protected InitScript renderInitScript(FacesContext context, DropDownComponent dropDown) throws IOException { Spinner spinner = (Spinner) dropDown; if (spinner.getStep().doubleValue() <= 0) { throw new FacesException("The 'step' attribute of <o:spinner> with id " + spinner.getClientId(context) + " should be greater then 0, but was " + spinner.getStep()); } String buttonStyle = (String) dropDown.getAttributes().get("buttonStyle"); String buttonClass = (String) dropDown.getAttributes().get("buttonClass"); String buttonStyleClass = Styles.getCSSClass(context, dropDown, buttonStyle, DEFAULT_BUTTON_CLASS, buttonClass); String rolloverButtonStyle = (String) dropDown.getAttributes().get("rolloverButtonStyle"); String rolloverButtonClass = (String) dropDown.getAttributes().get("rolloverButtonClass"); String buttonRolloverStyleClass = Styles.getCSSClass(context, dropDown, rolloverButtonStyle, StyleGroup.rolloverStyleGroup(), rolloverButtonClass, DEFAULT_BUTTON_ROLLOVER_CLASS); String pressedButtonStyle = (String) dropDown.getAttributes().get("pressedButtonStyle"); String pressedButtonClass = (String) dropDown.getAttributes().get("pressedButtonClass"); String buttonPressedStyleClass = Styles.getCSSClass(context, dropDown, pressedButtonStyle, StyleGroup.rolloverStyleGroup(2), pressedButtonClass, DEFAULT_BUTTON_PRESSED_CLASS); if (dropDown.isDisabled()) { buttonRolloverStyleClass = ""; String disabledButtonStyle = (String) dropDown.getAttributes().get("disabledButtonStyle"); String disabledButtonClass = (String) dropDown.getAttributes().get("disabledButtonClass"); String disabledButtonStyleClass = Styles.getCSSClass(context, dropDown, disabledButtonStyle, StyleGroup.disabledStyleGroup(), disabledButtonClass, DEFAULT_DISABLED_BUTTON_CLASS); if (Rendering.isNullOrEmpty(disabledButtonStyle) && Rendering.isNullOrEmpty(disabledButtonClass)) { buttonStyleClass = Styles.mergeClassNames(disabledButtonStyleClass, buttonStyleClass); } else { buttonStyleClass = Styles.mergeClassNames(disabledButtonStyleClass, Styles.getCSSClass(context, dropDown, null, StyleGroup.regularStyleGroup(), null, DEFAULT_BUTTON_CLASS)); } } JSONObject options; try { options = createFormatOptions(context, spinner); } catch (JSONException e) { throw new FacesException(e); } ScriptBuilder sb = new ScriptBuilder().initScript(context, spinner, "O$.Spinner._init", spinner.getMinValue(), spinner.getMaxValue(), spinner.getStep(), spinner.isCycled(), buttonStyleClass, buttonRolloverStyleClass, buttonPressedStyleClass, spinner.isDisabled(), spinner.isRequired(), spinner.getOnchange(), options); return new InitScript(sb, new String[]{ Resources.utilJsURL(context), getDropdownJsURL(context), Resources.internalURL(context, "input/spinner.js"), Resources.internalURL(context, "util/dojo.js") }); }
public DERObject getDERObject() { try { return new DERObjectIdentifier(stream.toByteArray()); } catch (IOException e) { throw new IllegalStateException("IOException converting stream to byte array: " + e.getMessage()); } }
public DERObject getDERObject() { try { return new DEROctetString(stream.toByteArray()); } catch (IOException e) { throw new IllegalStateException("IOException converting stream to byte array: " + e.getMessage()); } }
public List<PairWritable3> filter(RuleWritable source, ArrayWritable listTargetAndProb, int countIndex) { ArrayWritable listTargetAndProbSorted = sortByCount(listTargetAndProb, countIndex); List<PairWritable3> res = new ArrayList<PairWritable3>(); SidePattern sourcePattern = SidePattern.getSourcePattern(source); if (!sourcePattern.isPhrase() && !sourcePatternConstraints.containsKey(sourcePattern)) { return res; } int numberTranslations = 0; int numberTranslationsMonotone = 0; int numberTranslationsInvert = 0; double previousNumberOfOccurrences = -1; double previousNumberOfOccurrences2NTmonotone = -1; double previousNumberOfOccurrences2NTinvert = -1; boolean tie = false; boolean twoNTmonotoneTie = false; boolean twoNTinvertTie = false; for (int i = 0; i < listTargetAndProbSorted.get().length; i++) { PairWritable3 targetAndProb = (PairWritable3) listTargetAndProbSorted.get()[i]; double source2targetProbability = ((DoubleWritable) targetAndProb.second.get()[0]).get(); double target2sourceProbability = ((DoubleWritable) targetAndProb.second.get()[1]).get(); double numberOfOccurrences = ((DoubleWritable) targetAndProb.second.get()[2]).get(); if (numberOfOccurrences == previousNumberOfOccurrences) { tie = true; } else { tie = false; } previousNumberOfOccurrences = numberOfOccurrences; RulePattern rulePattern = RulePattern.getPattern(source, targetAndProb.first); if (sourcePattern.hasMoreThan1NT()) { if (rulePattern.isSwappingNT()) { if (numberOfOccurrences == previousNumberOfOccurrences2NTinvert) { twoNTinvertTie = true; } else { twoNTinvertTie = false; } previousNumberOfOccurrences2NTinvert = numberOfOccurrences; } else { if (numberOfOccurrences == previousNumberOfOccurrences2NTmonotone) { twoNTmonotoneTie = true; } else { twoNTmonotoneTie = false; } previousNumberOfOccurrences2NTmonotone = numberOfOccurrences; } } if (!sourcePattern.isPhrase() && !allowedPatterns.contains(rulePattern) && (skipPatterns == null || !skipPatterns .contains(rulePattern))) { continue; } if (sourcePattern.isPhrase()) { if (source2targetProbability <= minSource2TargetPhrase) { break; } if (target2sourceProbability <= minTarget2SourcePhrase) { continue; } } else { if (source2targetProbability <= minSource2TargetRule) { break; } if (target2sourceProbability <= minTarget2SourceRule) { continue; } if (sourcePatternConstraints.get(sourcePattern).containsKey( "nocc")) { if (numberOfOccurrences < sourcePatternConstraints .get(sourcePattern).get("nocc")) { break; } } if (sourcePattern.hasMoreThan1NT()) { if (sourcePatternConstraints.get(sourcePattern).get( "ntrans") <= numberTranslationsMonotone && sourcePatternConstraints.get(sourcePattern).get( "ntrans") <= numberTranslationsInvert && (!keepTiedRules || (keepTiedRules && !twoNTmonotoneTie && !twoNTinvertTie))) { break; } } else if (sourcePatternConstraints.get(sourcePattern).get( "ntrans") <= numberTranslations && (!keepTiedRules || (keepTiedRules && !tie))) { break; } } if (sourcePattern.isPhrase()) { res.add(new PairWritable3(new RuleWritable(source, targetAndProb.first), targetAndProb.second)); } else if (sourcePattern.hasMoreThan1NT()) { if (skipPatterns == null || !skipPatterns.contains(rulePattern)) { if (rulePattern.isSwappingNT()) { if (sourcePatternConstraints.get(sourcePattern).get( "ntrans") > numberTranslationsInvert || (keepTiedRules && twoNTinvertTie)) { res.add(new PairWritable3(new RuleWritable(source, targetAndProb.first), targetAndProb.second)); } } else { if (sourcePatternConstraints.get(sourcePattern).get( "ntrans") > numberTranslationsMonotone || (keepTiedRules && twoNTmonotoneTie)) { res.add(new PairWritable3(new RuleWritable(source, targetAndProb.first), targetAndProb.second)); } } } } else if (skipPatterns == null || !skipPatterns.contains(rulePattern)) { res.add(new PairWritable3(new RuleWritable(source, targetAndProb.first), targetAndProb.second)); } if (sourcePattern.hasMoreThan1NT()) { if (rulePattern.isSwappingNT()) { numberTranslationsInvert++; } else { numberTranslationsMonotone++; } } numberTranslations++; } return res; }
public List<PairWritable3> filter(RuleWritable source, ArrayWritable listTargetAndProb, int countIndex) { ArrayWritable listTargetAndProbSorted = sortByCount(listTargetAndProb, countIndex); List<PairWritable3> res = new ArrayList<PairWritable3>(); SidePattern sourcePattern = SidePattern.getSourcePattern(source); if (!sourcePattern.isPhrase() && !sourcePatternConstraints.containsKey(sourcePattern)) { return res; } int numberTranslations = 0; int numberTranslationsMonotone = 0; int numberTranslationsInvert = 0; double previousNumberOfOccurrences = -1; double previousNumberOfOccurrences2NTmonotone = -1; double previousNumberOfOccurrences2NTinvert = -1; boolean tie = false; boolean twoNTmonotoneTie = false; boolean twoNTinvertTie = false; for (int i = 0; i < listTargetAndProbSorted.get().length; i++) { PairWritable3 targetAndProb = (PairWritable3) listTargetAndProbSorted.get()[i]; double source2targetProbability = ((DoubleWritable) targetAndProb.second.get()[countIndex - 2]) .get(); double target2sourceProbability = ((DoubleWritable) targetAndProb.second.get()[countIndex - 1]) .get(); double numberOfOccurrences = ((DoubleWritable) targetAndProb.second.get()[countIndex]) .get(); if (numberOfOccurrences == previousNumberOfOccurrences) { tie = true; } else { tie = false; } previousNumberOfOccurrences = numberOfOccurrences; RulePattern rulePattern = RulePattern.getPattern(source, targetAndProb.first); if (sourcePattern.hasMoreThan1NT()) { if (rulePattern.isSwappingNT()) { if (numberOfOccurrences == previousNumberOfOccurrences2NTinvert) { twoNTinvertTie = true; } else { twoNTinvertTie = false; } previousNumberOfOccurrences2NTinvert = numberOfOccurrences; } else { if (numberOfOccurrences == previousNumberOfOccurrences2NTmonotone) { twoNTmonotoneTie = true; } else { twoNTmonotoneTie = false; } previousNumberOfOccurrences2NTmonotone = numberOfOccurrences; } } if (!sourcePattern.isPhrase() && !allowedPatterns.contains(rulePattern) && (skipPatterns == null || !skipPatterns .contains(rulePattern))) { continue; } if (sourcePattern.isPhrase()) { if (source2targetProbability <= minSource2TargetPhrase) { break; } if (target2sourceProbability <= minTarget2SourcePhrase) { continue; } } else { if (source2targetProbability <= minSource2TargetRule) { break; } if (target2sourceProbability <= minTarget2SourceRule) { continue; } if (sourcePatternConstraints.get(sourcePattern).containsKey( "nocc")) { if (numberOfOccurrences < sourcePatternConstraints .get(sourcePattern).get("nocc")) { break; } } if (sourcePattern.hasMoreThan1NT()) { if (sourcePatternConstraints.get(sourcePattern).get( "ntrans") <= numberTranslationsMonotone && sourcePatternConstraints.get(sourcePattern).get( "ntrans") <= numberTranslationsInvert && (!keepTiedRules || (keepTiedRules && !twoNTmonotoneTie && !twoNTinvertTie))) { break; } } else if (sourcePatternConstraints.get(sourcePattern).get( "ntrans") <= numberTranslations && (!keepTiedRules || (keepTiedRules && !tie))) { break; } } if (sourcePattern.isPhrase()) { res.add(new PairWritable3(new RuleWritable(source, targetAndProb.first), targetAndProb.second)); } else if (sourcePattern.hasMoreThan1NT()) { if (skipPatterns == null || !skipPatterns.contains(rulePattern)) { if (rulePattern.isSwappingNT()) { if (sourcePatternConstraints.get(sourcePattern).get( "ntrans") > numberTranslationsInvert || (keepTiedRules && twoNTinvertTie)) { res.add(new PairWritable3(new RuleWritable(source, targetAndProb.first), targetAndProb.second)); } } else { if (sourcePatternConstraints.get(sourcePattern).get( "ntrans") > numberTranslationsMonotone || (keepTiedRules && twoNTmonotoneTie)) { res.add(new PairWritable3(new RuleWritable(source, targetAndProb.first), targetAndProb.second)); } } } } else if (skipPatterns == null || !skipPatterns.contains(rulePattern)) { res.add(new PairWritable3(new RuleWritable(source, targetAndProb.first), targetAndProb.second)); } if (sourcePattern.hasMoreThan1NT()) { if (rulePattern.isSwappingNT()) { numberTranslationsInvert++; } else { numberTranslationsMonotone++; } } numberTranslations++; } return res; }
protected void handleStartElement(QName element, XMLAttributes attributes, Augmentations augs, boolean isEmpty) throws XNIException { fNamespaceSupport.pushContext(); int length = attributes.getLength(); for (int i = 0; i < length; i++) { String localpart = attributes.getLocalName(i); String prefix = attributes.getPrefix(i); if (prefix == fXmlnsSymbol || localpart == fXmlnsSymbol) { prefix = localpart != fXmlnsSymbol ? localpart : fEmptySymbol; String uri = attributes.getValue(i); uri = fSymbolTable.addSymbol(uri); if (uri == fEmptySymbol && localpart != fXmlnsSymbol) { fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN, "EmptyPrefixedAttName", new Object[]{attributes.getQName(i)}, XMLErrorReporter.SEVERITY_FATAL_ERROR); continue; } fNamespaceSupport.declarePrefix(prefix, uri.length() != 0 ? uri : null); if (fDocumentHandler != null) { fDocumentHandler.startPrefixMapping(prefix, uri, augs); } } } String prefix = element.prefix != null ? element.prefix : fEmptySymbol; element.uri = fNamespaceSupport.getURI(prefix); if (element.prefix == null && element.uri != null) { element.prefix = fEmptySymbol; } if (element.prefix != null && element.uri == null) { fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN, "ElementPrefixUnbound", new Object[]{element.prefix, element.rawname}, XMLErrorReporter.SEVERITY_FATAL_ERROR); } for (int i = 0; i < length; i++) { attributes.getName(i, fAttributeQName); String aprefix = fAttributeQName.prefix != null ? fAttributeQName.prefix : fEmptySymbol; String arawname = fAttributeQName.rawname; if (aprefix == fXmlSymbol) { fAttributeQName.uri = fNamespaceSupport.getURI(fXmlSymbol); attributes.setName(i, fAttributeQName); } else if (arawname != fXmlnsSymbol && !arawname.startsWith("xmlns:")) { if (aprefix != fEmptySymbol) { fAttributeQName.uri = fNamespaceSupport.getURI(aprefix); if (fAttributeQName.uri == null) { fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN, "AttributePrefixUnbound", new Object[]{aprefix, arawname}, XMLErrorReporter.SEVERITY_FATAL_ERROR); } attributes.setName(i, fAttributeQName); } } } int attrCount = attributes.getLength(); for (int i = 0; i < attrCount - 1; i++) { String alocalpart = attributes.getLocalName(i); String auri = attributes.getURI(i); for (int j = i + 1; j < attrCount; j++) { String blocalpart = attributes.getLocalName(j); String buri = attributes.getURI(j); if (alocalpart == blocalpart && auri == buri) { fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN, "AttributeNSNotUnique", new Object[]{element.rawname,alocalpart, auri}, XMLErrorReporter.SEVERITY_FATAL_ERROR); } } } if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) { if (isEmpty) { fDocumentHandler.emptyElement(element, attributes, augs); } else { fDocumentHandler.startElement(element, attributes, augs); } } }
protected void handleStartElement(QName element, XMLAttributes attributes, Augmentations augs, boolean isEmpty) throws XNIException { fNamespaceSupport.pushContext(); int length = attributes.getLength(); for (int i = 0; i < length; i++) { String localpart = attributes.getLocalName(i); String prefix = attributes.getPrefix(i); if (prefix == fXmlnsSymbol || localpart == fXmlnsSymbol) { prefix = localpart != fXmlnsSymbol ? localpart : fEmptySymbol; String uri = attributes.getValue(i); uri = fSymbolTable.addSymbol(uri); if (uri == fEmptySymbol && localpart != fXmlnsSymbol) { fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN, "EmptyPrefixedAttName", new Object[]{attributes.getQName(i)}, XMLErrorReporter.SEVERITY_FATAL_ERROR); continue; } fNamespaceSupport.declarePrefix(prefix, uri.length() != 0 ? uri : null); if (fDocumentHandler != null) { fDocumentHandler.startPrefixMapping(prefix, uri, augs); } } } String prefix = element.prefix != null ? element.prefix : fEmptySymbol; element.uri = fNamespaceSupport.getURI(prefix); if (element.prefix == null && element.uri != null) { element.prefix = fEmptySymbol; } if (element.prefix != null && element.uri == null) { fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN, "ElementPrefixUnbound", new Object[]{element.prefix, element.rawname}, XMLErrorReporter.SEVERITY_FATAL_ERROR); } for (int i = 0; i < length; i++) { attributes.getName(i, fAttributeQName); String aprefix = fAttributeQName.prefix != null ? fAttributeQName.prefix : fEmptySymbol; String arawname = fAttributeQName.rawname; if (aprefix == fXmlSymbol) { fAttributeQName.uri = fNamespaceSupport.getURI(fXmlSymbol); attributes.setName(i, fAttributeQName); } else if (arawname != fXmlnsSymbol && !arawname.startsWith("xmlns:")) { if (aprefix != fEmptySymbol) { fAttributeQName.uri = fNamespaceSupport.getURI(aprefix); if (fAttributeQName.uri == null) { fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN, "AttributePrefixUnbound", new Object[]{aprefix, arawname}, XMLErrorReporter.SEVERITY_FATAL_ERROR); } attributes.setName(i, fAttributeQName); } } } int attrCount = attributes.getLength(); for (int i = 0; i < attrCount - 1; i++) { String alocalpart = attributes.getLocalName(i); String auri = attributes.getURI(i); String arawName = attributes.getQName(i); for (int j = i + 1; j < attrCount; j++) { String blocalpart = attributes.getLocalName(j); String buri = attributes.getURI(j); String brawName = attributes.getQName(j); if (alocalpart == blocalpart && auri == buri) { if ((arawName == brawName) || (!arawName.startsWith("xmlns") && !brawName.startsWith("xmlns"))) { fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN, "AttributeNSNotUnique", new Object[]{element.rawname,alocalpart, auri}, XMLErrorReporter.SEVERITY_FATAL_ERROR); } } } } if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) { if (isEmpty) { fDocumentHandler.emptyElement(element, attributes, augs); } else { fDocumentHandler.startElement(element, attributes, augs); } } }
public static void loadSoundManager() { POLYPHONY_COUNT = Integer.parseInt(HexKeyboard.mPrefs.getString("polyphonyCount", "8")); if (mSoundPool != null) mSoundPool.release(); mSoundPool = null; System.gc(); mSoundPool = new SoundPool(POLYPHONY_COUNT, AudioManager.STREAM_MUSIC, 0); mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() { @Override public void onLoadComplete(SoundPool mSoundPool, int sampleId, int status) { mBoard.invalidate(); if (currLoadingInstrument.sound_load_queue.hasNext()) { ArrayList tuple = currLoadingInstrument.sound_load_queue.next(); if (!currLoadingInstrument.mExternal) { currLoadingInstrument.addSound((Integer)tuple.get(0), (Integer)tuple.get(1), (Integer)tuple.get(2)); } else { currLoadingInstrument.addSound((Integer)tuple.get(0), (Integer)tuple.get(1), (String)tuple.get(2)); } } else if (currLoadingInstrument.notes_load_queue.hasNext()) { currLoadingInstrument.currListOfTuples = currLoadingInstrument.notes_load_queue.next(); currLoadingInstrument.sound_load_queue = currLoadingInstrument.currListOfTuples.iterator(); onLoadComplete(mSoundPool, sampleId, status); } else if (instrument_load_queue.hasNext()) { currLoadingInstrument = instrument_load_queue.next(); currLoadingInstrument.notes_load_queue = currLoadingInstrument.sounds_to_load.values().iterator(); onLoadComplete(mSoundPool, sampleId, status); } else { Toast.makeText(HexKeyboard.mContext, R.string.finished_loading, Toast.LENGTH_SHORT).show(); } } }); }
public static void loadSoundManager() { POLYPHONY_COUNT = Integer.parseInt(HexKeyboard.mPrefs.getString("polyphonyCount", "8")); if (mSoundPool != null) mSoundPool.release(); mSoundPool = null; System.gc(); mSoundPool = new SoundPool(POLYPHONY_COUNT, AudioManager.STREAM_MUSIC, 0); mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() { @Override public void onLoadComplete(SoundPool mSoundPool, int sampleId, int status) { mBoard.invalidate(); if (currLoadingInstrument.sound_load_queue != null && currLoadingInstrument.sound_load_queue.hasNext()) { ArrayList tuple = currLoadingInstrument.sound_load_queue.next(); if (!currLoadingInstrument.mExternal) { currLoadingInstrument.addSound((Integer)tuple.get(0), (Integer)tuple.get(1), (Integer)tuple.get(2)); } else { currLoadingInstrument.addSound((Integer)tuple.get(0), (Integer)tuple.get(1), (String)tuple.get(2)); } } else if (currLoadingInstrument.notes_load_queue != null && currLoadingInstrument.notes_load_queue.hasNext()) { currLoadingInstrument.currListOfTuples = currLoadingInstrument.notes_load_queue.next(); currLoadingInstrument.sound_load_queue = currLoadingInstrument.currListOfTuples.iterator(); onLoadComplete(mSoundPool, sampleId, status); } else if (instrument_load_queue.hasNext()) { currLoadingInstrument = instrument_load_queue.next(); currLoadingInstrument.notes_load_queue = currLoadingInstrument.sounds_to_load.values().iterator(); onLoadComplete(mSoundPool, sampleId, status); } else { Toast.makeText(HexKeyboard.mContext, R.string.finished_loading, Toast.LENGTH_SHORT).show(); } } }); }
private void initExpectedResults() { addExpectedResult("testAggregateSymbol1", VERSION_7_7_2, "COUNT('abc')"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testAggregateSymbol1", version83, "abc('abc')"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testAggregateSymbol1", version84, "abc('abc')"); } addExpectedResult("testAggregateSymbol2", VERSION_7_7_2, "COUNT(DISTINCT 'abc')"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testAggregateSymbol2", version83, "abc(DISTINCT 'abc')"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testAggregateSymbol2", version84, "abc(DISTINCT 'abc')"); } addExpectedResult("testAggregateSymbol3", VERSION_7_7_2, "COUNT(*)"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testAggregateSymbol3", version83, "abc(*)"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testAggregateSymbol3", version84, "abc(*)"); } addExpectedResult("testAggregateSymbol4", VERSION_7_7_2, "AVG('abc')"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testAggregateSymbol4", version83, "abc('abc')"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testAggregateSymbol4", version84, "abc('abc')"); } addExpectedResult("testAggregateSymbol5", VERSION_7_7_2, "SUM('abc')"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testAggregateSymbol5", version83, "abc('abc')"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testAggregateSymbol5", version84, "abc('abc')"); } addExpectedResult("testAggregateSymbol6", VERSION_7_7_2, "MIN('abc')"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testAggregateSymbol6", version83, "abc('abc')"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testAggregateSymbol6", version84, "abc('abc')"); } addExpectedResult("testAggregateSymbol7", VERSION_7_7_2, "MAX('abc')"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testAggregateSymbol7", version83, "abc('abc')"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testAggregateSymbol7", version84, "abc('abc')"); } addExpectedResult("testRaiseStatement", VERSION_7_7_2, "ERROR 'My Error';"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testRaiseStatement", version83, "RAISE 'My Error';"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testRaiseStatement", version84, "RAISE 'My Error';"); } addExpectedResult("testRaiseStatementWithExpression", VERSION_7_7_2, "ERROR a;"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testRaiseStatementWithExpression", version83, "RAISE a;"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testRaiseStatementWithExpression", version84, "RAISE a;"); } addExpectedResult("testBlock1", VERSION_7_7_2, "BEGIN\n\tDELETE FROM g;\n\ta = 1;\n\tERROR 'My Error';\nEND"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testBlock1", version83, "BEGIN\n\tDELETE FROM g;\n\ta = 1;\n\tRAISE 'My Error';\nEND"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testBlock1", version84, "BEGIN\n\tDELETE FROM g;\n\ta = 1;\n\tRAISE 'My Error';\nEND"); } addExpectedResult("testCreateUpdateProcedure1", VERSION_7_7_2, "CREATE PROCEDURE\nBEGIN\n\tDELETE FROM g;\n\ta = 1;\n\tERROR 'My Error';\nEND"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testCreateUpdateProcedure1", version83, "CREATE VIRTUAL PROCEDURE\nBEGIN\n\tDELETE FROM g;\n\ta = 1;\n\tRAISE 'My Error';\nEND"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testCreateUpdateProcedure1", version84, "CREATE VIRTUAL PROCEDURE\nBEGIN\n\tDELETE FROM g;\n\ta = 1;\n\tRAISE 'My Error';\nEND"); } addExpectedResult("testCreateUpdateProcedure2", VERSION_7_7_2, "CREATE PROCEDURE\nBEGIN\n\tDELETE FROM g;\n\ta = 1;\n\tERROR 'My Error';\nEND"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testCreateUpdateProcedure2", version83, "CREATE VIRTUAL PROCEDURE\nBEGIN\n\tDELETE FROM g;\n\ta = 1;\n\tRAISE 'My Error';\nEND"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testCreateUpdateProcedure2", version84, "CREATE VIRTUAL PROCEDURE\nBEGIN\n\tDELETE FROM g;\n\ta = 1;\n\tRAISE 'My Error';\nEND"); } addExpectedResult("testCreateUpdateProcedure3", VERSION_7_7_2, "CREATE PROCEDURE\nBEGIN\n\tDELETE FROM g;\n\ta = 1;\n\tERROR 'My Error';\nEND"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testCreateUpdateProcedure3", version83, "CREATE VIRTUAL PROCEDURE\nBEGIN\n\tDELETE FROM g;\n\ta = 1;\n\tRAISE 'My Error';\nEND"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testCreateUpdateProcedure3", version84, "CREATE VIRTUAL PROCEDURE\nBEGIN\n\tDELETE FROM g;\n\ta = 1;\n\tRAISE 'My Error';\nEND"); } addExpectedResult("testTrimAliasSymbol", VERSION_7_7_2, "SELECT\n\t\ttrim(' ' FROM X) AS ID\n\tFROM\n\t\tY"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testTrimAliasSymbol", version83, "SELECT\n\t\ttrim(' ' FROM X) AS ID\n\tFROM\n\t\tY"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testTrimAliasSymbol", version84, "SELECT\n\t\ttrim(' ' FROM X) AS ID\n\tFROM\n\t\tY"); } addExpectedResult("testConstantAliasSymbol", VERSION_7_7_2, "SELECT\n\t\t'123' AS ID\n\tFROM\n\t\tX"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testConstantAliasSymbol", version83, "SELECT\n\t\t'123' AS ID\n\tFROM\n\t\tX"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testConstantAliasSymbol", version84, "SELECT\n\t\t'123' AS ID\n\tFROM\n\t\tX"); } addExpectedResult("testConcatWithNull", VERSION_7_7_2, "SELECT\n\t\tconcat('abcd', null) AS ProductName\n\tFROM\n\t\tPRODUCTDATA"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testConcatWithNull", version83, "SELECT\n\t\tconcat('abcd', null) AS ProductName\n\tFROM\n\t\tPRODUCTDATA"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testConcatWithNull", version84, "SELECT\n\t\tconcat('abcd', null) AS ProductName\n\tFROM\n\t\tPRODUCTDATA"); } }
private void initExpectedResults() { addExpectedResult("testAggregateSymbol1", VERSION_7_7_2, "COUNT('abc')"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testAggregateSymbol1", version83, "abc('abc')"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testAggregateSymbol1", version84, "abc('abc')"); } addExpectedResult("testAggregateSymbol2", VERSION_7_7_2, "COUNT(DISTINCT 'abc')"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testAggregateSymbol2", version83, "abc(DISTINCT 'abc')"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testAggregateSymbol2", version84, "abc(DISTINCT 'abc')"); } addExpectedResult("testAggregateSymbol3", VERSION_7_7_2, "COUNT(*)"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testAggregateSymbol3", version83, "abc(*)"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testAggregateSymbol3", version84, "abc(*)"); } addExpectedResult("testAggregateSymbol4", VERSION_7_7_2, "AVG('abc')"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testAggregateSymbol4", version83, "abc('abc')"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testAggregateSymbol4", version84, "abc('abc')"); } addExpectedResult("testAggregateSymbol5", VERSION_7_7_2, "SUM('abc')"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testAggregateSymbol5", version83, "abc('abc')"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testAggregateSymbol5", version84, "abc('abc')"); } addExpectedResult("testAggregateSymbol6", VERSION_7_7_2, "MIN('abc')"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testAggregateSymbol6", version83, "abc('abc')"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testAggregateSymbol6", version84, "abc('abc')"); } addExpectedResult("testAggregateSymbol7", VERSION_7_7_2, "MAX('abc')"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testAggregateSymbol7", version83, "abc('abc')"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testAggregateSymbol7", version84, "abc('abc')"); } addExpectedResult("testRaiseStatement", VERSION_7_7_2, "ERROR 'My Error';"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testRaiseStatement", version83, "RAISE 'My Error';"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testRaiseStatement", version84, "RAISE 'My Error';"); } addExpectedResult("testRaiseStatementWithExpression", VERSION_7_7_2, "ERROR a;"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testRaiseStatementWithExpression", version83, "RAISE a;"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testRaiseStatementWithExpression", version84, "RAISE a;"); } addExpectedResult("testBlock1", VERSION_7_7_2, "BEGIN\n\tDELETE FROM g;\n\ta = 1;\n\tERROR 'My Error';\nEND"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testBlock1", version83, "BEGIN\n\tDELETE FROM g;\n\ta = 1;\n\tRAISE 'My Error';\nEND"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testBlock1", version84, "BEGIN\n\tDELETE FROM g;\n\ta = 1;\n\tRAISE 'My Error';\nEND"); } addExpectedResult("testCreateUpdateProcedure1", VERSION_7_7_2, "CREATE PROCEDURE\nBEGIN\n\tDELETE FROM g;\n\ta = 1;\n\tERROR 'My Error';\nEND"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testCreateUpdateProcedure1", version83, "CREATE VIRTUAL PROCEDURE\nBEGIN\n\tDELETE FROM g;\n\ta = 1;\n\tRAISE 'My Error';\nEND"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testCreateUpdateProcedure1", version84, "BEGIN\n\tDELETE FROM g;\n\ta = 1;\n\tRAISE 'My Error';\nEND"); } addExpectedResult("testCreateUpdateProcedure2", VERSION_7_7_2, "CREATE PROCEDURE\nBEGIN\n\tDELETE FROM g;\n\ta = 1;\n\tERROR 'My Error';\nEND"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testCreateUpdateProcedure2", version83, "CREATE VIRTUAL PROCEDURE\nBEGIN\n\tDELETE FROM g;\n\ta = 1;\n\tRAISE 'My Error';\nEND"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testCreateUpdateProcedure2", version84, "BEGIN\n\tDELETE FROM g;\n\ta = 1;\n\tRAISE 'My Error';\nEND"); } addExpectedResult("testCreateUpdateProcedure3", VERSION_7_7_2, "CREATE PROCEDURE\nBEGIN\n\tDELETE FROM g;\n\ta = 1;\n\tERROR 'My Error';\nEND"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testCreateUpdateProcedure3", version83, "CREATE VIRTUAL PROCEDURE\nBEGIN\n\tDELETE FROM g;\n\ta = 1;\n\tRAISE 'My Error';\nEND"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testCreateUpdateProcedure3", version84, "BEGIN\n\tDELETE FROM g;\n\ta = 1;\n\tRAISE 'My Error';\nEND"); } addExpectedResult("testTrimAliasSymbol", VERSION_7_7_2, "SELECT\n\t\ttrim(' ' FROM X) AS ID\n\tFROM\n\t\tY"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testTrimAliasSymbol", version83, "SELECT\n\t\ttrim(' ' FROM X) AS ID\n\tFROM\n\t\tY"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testTrimAliasSymbol", version84, "SELECT\n\t\ttrim(' ' FROM X) AS ID\n\tFROM\n\t\tY"); } addExpectedResult("testConstantAliasSymbol", VERSION_7_7_2, "SELECT\n\t\t'123' AS ID\n\tFROM\n\t\tX"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testConstantAliasSymbol", version83, "SELECT\n\t\t'123' AS ID\n\tFROM\n\t\tX"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testConstantAliasSymbol", version84, "SELECT\n\t\t'123' AS ID\n\tFROM\n\t\tX"); } addExpectedResult("testConcatWithNull", VERSION_7_7_2, "SELECT\n\t\tconcat('abcd', null) AS ProductName\n\tFROM\n\t\tPRODUCTDATA"); for (ITeiidServerVersion version83 : VERSIONS_8_3) { addExpectedResult("testConcatWithNull", version83, "SELECT\n\t\tconcat('abcd', null) AS ProductName\n\tFROM\n\t\tPRODUCTDATA"); } for (ITeiidServerVersion version84 : VERSIONS_8_4) { addExpectedResult("testConcatWithNull", version84, "SELECT\n\t\tconcat('abcd', null) AS ProductName\n\tFROM\n\t\tPRODUCTDATA"); } }
public SteamPacket getReply() throws IOException, TimeoutException, SteamCondenserException { int bytesRead; SteamPacket packet; bytesRead = this.receivePacket(1400); if(this.packetIsSplit()) { boolean isCompressed = false; byte[] splitData; int packetCount, packetNumber, requestId; int packetChecksum = 0; short splitSize; Vector<byte[]> splitPackets = new Vector<byte[]>(); do { requestId = Integer.reverseBytes(this.buffer.getInt()); isCompressed = ((requestId & 0x8000) != 0); packetCount = this.buffer.get(); packetNumber = this.buffer.get() + 1; if(isCompressed) { splitSize = Short.reverseBytes(this.buffer.getShort()); packetChecksum = Integer.reverseBytes(this.buffer.getInt()); } else { splitSize = Short.reverseBytes(this.buffer.getShort()); } splitData = new byte[splitSize]; this.buffer.get(splitData); splitPackets.setSize(packetCount); splitPackets.set(packetNumber - 1, splitData); bytesRead = this.receivePacket(); Logger.getLogger("global").info("Received packet #" + packetNumber + " of " + packetCount + " for request ID " + requestId + "."); } while(bytesRead > 0 && Integer.reverseBytes(this.buffer.getInt()) == -2); if(isCompressed) { packet = SteamPacketFactory.reassemblePacket(splitPackets, true, splitSize, packetChecksum); } else { packet = SteamPacketFactory.reassemblePacket(splitPackets); } } else { packet = this.getPacketFromData(); } this.buffer.flip(); Logger.getLogger("global").info("Received packet of type \"" + packet.getClass().getSimpleName() + "\""); return packet; }
public SteamPacket getReply() throws IOException, TimeoutException, SteamCondenserException { int bytesRead; SteamPacket packet; bytesRead = this.receivePacket(1400); if(this.packetIsSplit()) { boolean isCompressed = false; byte[] splitData; int packetCount, packetNumber, requestId; int packetChecksum = 0; short splitSize; Vector<byte[]> splitPackets = new Vector<byte[]>(); do { requestId = Integer.reverseBytes(this.buffer.getInt()); isCompressed = ((requestId & 0x8000000) != 0); packetCount = this.buffer.get(); packetNumber = this.buffer.get() + 1; if(isCompressed) { splitSize = Short.reverseBytes(this.buffer.getShort()); packetChecksum = Integer.reverseBytes(this.buffer.getInt()); } else { splitSize = Short.reverseBytes(this.buffer.getShort()); } splitData = new byte[splitSize]; this.buffer.get(splitData); splitPackets.setSize(packetCount); splitPackets.set(packetNumber - 1, splitData); bytesRead = this.receivePacket(); Logger.getLogger("global").info("Received packet #" + packetNumber + " of " + packetCount + " for request ID " + requestId + "."); } while(bytesRead > 0 && Integer.reverseBytes(this.buffer.getInt()) == -2); if(isCompressed) { packet = SteamPacketFactory.reassemblePacket(splitPackets, true, splitSize, packetChecksum); } else { packet = SteamPacketFactory.reassemblePacket(splitPackets); } } else { packet = this.getPacketFromData(); } this.buffer.flip(); Logger.getLogger("global").info("Received packet of type \"" + packet.getClass().getSimpleName() + "\""); return packet; }
public void onItemHeldChange(PlayerItemHeldEvent event) { if (!event.getPlayer().isSneaking()) return; ItemStack itemStack = event.getPlayer().getInventory().getItem(event.getPreviousSlot()); if (itemStack == null || !itemStack.getType().equals(Material.WRITTEN_BOOK)) return; MinestarBook book = MinestarBook.loadBook(itemStack); if (book.getAuthor().equalsIgnoreCase(MailBox.MAIL_BOX_HEAD)) { MailBox mailBox = VinciCodeCore.messageManger.getMailBox(event.getPlayer().getName()); if (mailBox == null) { PlayerUtils.sendError(event.getPlayer(), VinciCodeCore.NAME, "Du hast keine Nachrichten!"); this.swapItems(event.getPlayer().getInventory(), event.getNewSlot(), event.getPreviousSlot()); return; } boolean forward = (event.getNewSlot() == 0 && event.getPreviousSlot() == 8) || (event.getNewSlot() > event.getPreviousSlot() && event.getPreviousSlot() != 0); if (forward) { if (mailBox.hasNext()) { Message message = mailBox.next(); book.setPages(BookHelper.format(message)); String text = "Nachricht "; if (message.isRead()) { text += "" + ChatColor.GOLD + (mailBox.getIndex() + 1) + ChatColor.GRAY; } else { text += "" + ChatColor.RED + (mailBox.getIndex() + 1) + ChatColor.GRAY; } text += " von " + mailBox.getMessageCount(); PlayerUtils.sendInfo(event.getPlayer(), VinciCodeCore.NAME, text); } else { PlayerUtils.sendError(event.getPlayer(), VinciCodeCore.NAME, "Keine weiteren Nachrichten."); } } else { if (mailBox.hasPrev()) { Message message = mailBox.prev(); book.setPages(BookHelper.format(message)); String text = "Nachricht "; if (message.isRead()) { text += "" + ChatColor.GOLD + (mailBox.getIndex() - 1) + ChatColor.GRAY; } else { text += "" + ChatColor.RED + (mailBox.getIndex() - 1) + ChatColor.GRAY; } text += " von " + mailBox.getMessageCount(); PlayerUtils.sendInfo(event.getPlayer(), VinciCodeCore.NAME, text); } else { PlayerUtils.sendError(event.getPlayer(), VinciCodeCore.NAME, "Keine vorherigen Nachrichten."); } } this.swapItems(event.getPlayer().getInventory(), event.getNewSlot(), event.getPreviousSlot());; } }
public void onItemHeldChange(PlayerItemHeldEvent event) { if (!event.getPlayer().isSneaking()) return; ItemStack itemStack = event.getPlayer().getInventory().getItem(event.getPreviousSlot()); if (itemStack == null || !itemStack.getType().equals(Material.WRITTEN_BOOK)) return; MinestarBook book = MinestarBook.loadBook(itemStack); if (book.getAuthor().equalsIgnoreCase(MailBox.MAIL_BOX_HEAD)) { MailBox mailBox = VinciCodeCore.messageManger.getMailBox(event.getPlayer().getName()); if (mailBox == null) { PlayerUtils.sendError(event.getPlayer(), VinciCodeCore.NAME, "Du hast keine Nachrichten!"); this.swapItems(event.getPlayer().getInventory(), event.getNewSlot(), event.getPreviousSlot()); return; } boolean forward = (event.getNewSlot() == 0 && event.getPreviousSlot() == 8) || (event.getNewSlot() > event.getPreviousSlot() && !(event.getPreviousSlot() == 0 && event.getNewSlot() == 8)); if (forward) { if (mailBox.hasNext()) { Message message = mailBox.next(); book.setPages(BookHelper.format(message)); String text = "Nachricht "; if (message.isRead()) { text += "" + ChatColor.GOLD + (mailBox.getIndex() + 1) + ChatColor.GRAY; } else { text += "" + ChatColor.RED + (mailBox.getIndex() + 1) + ChatColor.GRAY; } text += " von " + mailBox.getMessageCount(); PlayerUtils.sendInfo(event.getPlayer(), VinciCodeCore.NAME, text); } else { PlayerUtils.sendError(event.getPlayer(), VinciCodeCore.NAME, "Keine weiteren Nachrichten."); } } else { if (mailBox.hasPrev()) { Message message = mailBox.prev(); book.setPages(BookHelper.format(message)); String text = "Nachricht "; if (message.isRead()) { text += "" + ChatColor.GOLD + (mailBox.getIndex() + 1) + ChatColor.GRAY; } else { text += "" + ChatColor.RED + (mailBox.getIndex() + 1) + ChatColor.GRAY; } text += " von " + mailBox.getMessageCount(); PlayerUtils.sendInfo(event.getPlayer(), VinciCodeCore.NAME, text); } else { PlayerUtils.sendError(event.getPlayer(), VinciCodeCore.NAME, "Keine vorherigen Nachrichten."); } } this.swapItems(event.getPlayer().getInventory(), event.getNewSlot(), event.getPreviousSlot());; } }
public void testCacheItems003() throws Throwable { IFile index_file = PROJECT.getFile(".dltk.index"); index_file.create(new ByteArrayInputStream(new byte[0]), true, new NullProgressMonitor()); ArchiveCacheIndexBuilder builder = new ArchiveCacheIndexBuilder( new FileOutputStream(new File(index_file.getLocation() .toOSString()))); IFile file1 = PROJECT.getFile("file1.te"); file1.create(new ByteArrayInputStream(new byte[0]), true, new NullProgressMonitor()); IFile file2 = PROJECT.getFile("file2.te"); file2.create(new ByteArrayInputStream(new byte[0]), true, new NullProgressMonitor()); builder.addEntry("file1.te", file1.getLocalTimeStamp(), "ast", new ByteArrayInputStream("testValue1".getBytes())); builder.addEntry("file1.te", file1.getLocalTimeStamp(), "ast2", new ByteArrayInputStream("testValue2".getBytes())); builder.addEntry("file2.te", file2.getLocalTimeStamp(), "ast3", new ByteArrayInputStream("testValue3".getBytes())); builder.addEntry("file2.te", file2.getLocalTimeStamp(), "ast4", new ByteArrayInputStream("testValue4".getBytes())); builder.done(); IContentCache cache = ModelManager.getModelManager().getCoreCache(); IEnvironment env = EnvironmentManager.getLocalEnvironment(); IFileHandle handle1 = env.getFile(file1.getLocation()); IFileHandle handle2 = env.getFile(file2.getLocation()); String ast1 = cache.getCacheEntryAttributeString(handle1, "ast"); String ast2 = cache.getCacheEntryAttributeString(handle1, "ast2"); String ast3 = cache.getCacheEntryAttributeString(handle2, "ast3"); String ast4 = cache.getCacheEntryAttributeString(handle2, "ast4"); TestCase.assertEquals("testValue1", ast1); TestCase.assertEquals("testValue2", ast2); TestCase.assertEquals("testValue3", ast3); TestCase.assertEquals("testValue4", ast4); }
public void testCacheItems003() throws Throwable { IFile index_file = PROJECT.getFile(".dltk.index"); index_file.create(new ByteArrayInputStream(new byte[0]), true, new NullProgressMonitor()); ArchiveCacheIndexBuilder builder = new ArchiveCacheIndexBuilder( new FileOutputStream(new File(index_file.getLocation() .toOSString())), 0); IFile file1 = PROJECT.getFile("file1.te"); file1.create(new ByteArrayInputStream(new byte[0]), true, new NullProgressMonitor()); IFile file2 = PROJECT.getFile("file2.te"); file2.create(new ByteArrayInputStream(new byte[0]), true, new NullProgressMonitor()); builder.addEntry("file1.te", file1.getLocalTimeStamp(), "ast", new ByteArrayInputStream("testValue1".getBytes())); builder.addEntry("file1.te", file1.getLocalTimeStamp(), "ast2", new ByteArrayInputStream("testValue2".getBytes())); builder.addEntry("file2.te", file2.getLocalTimeStamp(), "ast3", new ByteArrayInputStream("testValue3".getBytes())); builder.addEntry("file2.te", file2.getLocalTimeStamp(), "ast4", new ByteArrayInputStream("testValue4".getBytes())); builder.done(); IContentCache cache = ModelManager.getModelManager().getCoreCache(); IEnvironment env = EnvironmentManager.getLocalEnvironment(); IFileHandle handle1 = env.getFile(file1.getLocation()); IFileHandle handle2 = env.getFile(file2.getLocation()); String ast1 = cache.getCacheEntryAttributeString(handle1, "ast"); String ast2 = cache.getCacheEntryAttributeString(handle1, "ast2"); String ast3 = cache.getCacheEntryAttributeString(handle2, "ast3"); String ast4 = cache.getCacheEntryAttributeString(handle2, "ast4"); TestCase.assertEquals("testValue1", ast1); TestCase.assertEquals("testValue2", ast2); TestCase.assertEquals("testValue3", ast3); TestCase.assertEquals("testValue4", ast4); }
private void save(int playListIndex, String fileName) { if (fileName==null || fileName.equals("")) throw new IllegalArgumentException("No filename specified"); if (playListIndex<0 || playListIndex>2) throw new IllegalArgumentException( "Bad PlayList index "+playListIndex); File f = new File(fileName); if (f.exists()) { String prompt = app.getResourceFormatted( "query.Confirm.FileExists.prompt",fileName); if (!viewer.confirmDialog(prompt)) return; } switch (playListIndex) { case 0: viewer.saveMainPlayList(fileName); break; case 1: viewer.savePrintablePlayList(fileName); break; default: PlayList playList = getActivePlayList(); try { PrintWriter pw = new PrintWriter(f); playList.save(pw,f.getParentFile()); pw.flush(); pw.close(); } catch (IOException ex) { throw new RuntimeException("failed to save PlayList",ex); } break; } }
private void save(int playListIndex, String fileName) { if (fileName==null || fileName.equals("")) throw new IllegalArgumentException("No filename specified"); if (playListIndex<0 || playListIndex>=(customListNames.size()+2)) throw new IllegalArgumentException( "Bad PlayList index "+playListIndex); File f = new File(fileName); if (f.exists()) { String prompt = app.getResourceFormatted( "query.Confirm.FileExists.prompt",fileName); if (!viewer.confirmDialog(prompt)) return; } switch (playListIndex) { case 0: viewer.saveMainPlayList(fileName); break; case 1: viewer.savePrintablePlayList(fileName); break; default: PlayList playList = getActivePlayList(); try { PrintWriter pw = new PrintWriter(f); playList.save(pw,f.getParentFile()); pw.flush(); pw.close(); } catch (IOException ex) { throw new RuntimeException("failed to save PlayList",ex); } break; } }
public void onMove(double dx, double dy, double dz) { final Entity handle = entity.getHandle(Entity.class); if (handle.Z) { handle.boundingBox.d(dx, dy, dz); handle.locX = (handle.boundingBox.a + handle.boundingBox.d) / 2.0D; handle.locY = (handle.boundingBox.b + (double) handle.height) - (double) handle.Y; handle.locZ = (handle.boundingBox.c + handle.boundingBox.f) / 2.0D; } else { handle.Y *= 0.4f; final double oldLocX = handle.locX; final double oldLocY = handle.locY; final double oldLocZ = handle.locZ; if (EntityRef.justLanded.get(handle)) { EntityRef.justLanded.set(handle, false); dx *= 0.25; dy *= 0.05; dz *= 0.25; handle.motX = 0.0; handle.motY = 0.0; handle.motZ = 0.0; } final double oldDx = dx; final double oldDy = dy; final double oldDz = dz; AxisAlignedBB axisalignedbb = handle.boundingBox.clone(); List<AxisAlignedBB> list = EntityControllerCollisionHelper.getCollisions(this, handle.boundingBox.a(dx, dy, dz)); for (AxisAlignedBB aabb : list) { dy = aabb.b(handle.boundingBox, dy); } handle.boundingBox.d(0.0, dy, 0.0); if (!handle.L && oldDy != dy) { dz = 0.0D; dy = 0.0D; dx = 0.0D; } boolean isOnGround = handle.onGround || oldDy != dy && oldDy < 0.0; for (AxisAlignedBB aabb : list) { dx = aabb.a(handle.boundingBox, dx); } handle.boundingBox.d(dx, 0.0, 0.0); if (!handle.L && oldDx != dx) { dz = 0.0; dy = 0.0; dx = 0.0; } for (AxisAlignedBB aabb : list) { dz = aabb.c(handle.boundingBox, dz); } handle.boundingBox.d(0.0, 0.0, dz); if (!handle.L && oldDz != dz) { dz = 0.0; dy = 0.0; dx = 0.0; } double moveDx; double moveDy; double moveDz; if (handle.Y > 0.0f && handle.Y < 0.05f && isOnGround && (oldDx != dx || oldDz != dz)) { moveDx = dx; moveDy = dy; moveDz = dz; dx = oldDx; dy = (double) handle.Y; dz = oldDz; AxisAlignedBB axisalignedbb1 = handle.boundingBox.clone(); handle.boundingBox.c(axisalignedbb); list = EntityControllerCollisionHelper.getCollisions(this, handle.boundingBox.a(oldDx, dy, oldDz)); for (AxisAlignedBB aabb : list) { dy = aabb.b(handle.boundingBox, dy); } handle.boundingBox.d(0.0, dy, 0.0); if (!handle.L && oldDy != dy) { dz = 0.0; dy = 0.0; dx = 0.0; } for (AxisAlignedBB aabb : list) { dx = aabb.a(handle.boundingBox, dx); } handle.boundingBox.d(dx, 0.0, 0.0D); if (!handle.L && oldDx != dx) { dz = 0.0; dy = 0.0; dx = 0.0; } for (AxisAlignedBB aabb : list) { dz = aabb.c(handle.boundingBox, dz); } handle.boundingBox.d(0.0, 0.0, dz); if (!handle.L && oldDz != dz) { dz = 0.0; dy = 0.0; dx = 0.0; } if (!handle.L && oldDy != dy) { dz = 0.0; dy = 0.0; dx = 0.0; } else { dy = (double) -handle.Y; for (int k = 0; k < list.size(); k++) { dy = list.get(k).b(handle.boundingBox, dy); } handle.boundingBox.d(0.0, dy, 0.0); } if (MathUtil.lengthSquared(moveDx, moveDz) >= MathUtil.lengthSquared(dx, dz)) { dx = moveDx; dy = moveDy; dz = moveDz; handle.boundingBox.c(axisalignedbb1); } else { double subY = handle.boundingBox.b - (int) handle.boundingBox.b; if (subY > 0.0) { handle.Y += subY + 0.01; } } } handle.locX = (handle.boundingBox.a + handle.boundingBox.d) / 2D; handle.locY = (handle.boundingBox.b + (double) handle.height) - (double) handle.Y; handle.locZ = (handle.boundingBox.c + handle.boundingBox.f) / 2D; entity.setMovementImpaired(oldDx != dx || oldDz != dz); handle.H = oldDy != dy; handle.onGround = oldDy != dy && oldDy < 0.0D; handle.I = entity.isMovementImpaired() || handle.H; EntityRef.updateFalling(handle, dy, handle.onGround); if (oldDy != dy) { handle.motY = 0.0; } if (oldDx != dx && Math.abs(handle.motX) > Math.abs(handle.motZ)) { handle.motX = 0.0; } if (oldDz != dz && Math.abs(handle.motZ) > Math.abs(handle.motX)) { handle.motZ = 0.0; } moveDx = handle.locX - oldLocX; moveDy = handle.locY - oldLocY; moveDz = handle.locZ - oldLocZ; if (entity instanceof Vehicle && entity.isMovementImpaired()) { Vehicle vehicle = (Vehicle) entity.getEntity(); org.bukkit.block.Block block = entity.getWorld().getBlockAt(MathUtil.floor(handle.locX), MathUtil.floor(handle.locY - (double) handle.height), MathUtil.floor(handle.locZ)); if (oldDx > dx) { block = block.getRelative(BlockFace.EAST); } else if (oldDx < dx) { block = block.getRelative(BlockFace.WEST); } else if (oldDz > dz) { block = block.getRelative(BlockFace.SOUTH); } else if (oldDz < dz) { block = block.getRelative(BlockFace.NORTH); } VehicleBlockCollisionEvent event = new VehicleBlockCollisionEvent(vehicle, block); entity.getServer().getPluginManager().callEvent(event); } if (EntityRef.hasMovementSound(handle) && handle.vehicle == null) { int bX = MathUtil.floor(handle.locX); int bY = MathUtil.floor(handle.locY - 0.2D - (double) handle.height); int bZ = MathUtil.floor(handle.locZ); int typeId = handle.world.getTypeId(bX, bY, bZ); if (typeId == 0 && handle.world.getTypeId(bX, bY - 1, bZ) == Material.FENCE.getId()) { typeId = Material.FENCE.getId(); } if (typeId != Material.LADDER.getId()) { moveDy = 0.0; } handle.R += Math.sqrt(moveDx * moveDx + moveDz * moveDz) * 0.6; handle.S += Math.sqrt(moveDx * moveDx + moveDy * moveDy + moveDz * moveDz) * 0.6; if (handle.S > EntityRef.stepCounter.get(entity.getHandle()) && typeId > 0) { EntityRef.stepCounter.set(entity.getHandle(), (int) handle.S + 1); if (handle.H()) { float f = (float) Math.sqrt(handle.motX * handle.motX * 0.2 + handle.motY * handle.motY + handle.motZ * handle.motZ * 0.2) * 0.35F; if (f > 1.0F) { f = 1.0F; } entity.makeRandomSound(Sound.SWIM, f, 1.0f); } entity.makeStepSound(bX, bY, bZ, typeId); Block.byId[bZ].b(handle.world, bX, bY, bZ, handle); } } EntityRef.updateBlockCollision(handle); boolean flag2 = handle.G(); if (handle.world.e(handle.boundingBox.shrink(0.001D, 0.001D, 0.001D))) { onBurnDamage(1); if (!flag2) { handle.fireTicks++; if (handle.fireTicks <= 0) { EntityCombustEvent event = new EntityCombustEvent(entity.getEntity(), 8); entity.getServer().getPluginManager().callEvent(event); if (!event.isCancelled()) { handle.setOnFire(event.getDuration()); } } else { handle.setOnFire(8); } } } else if (handle.fireTicks <= 0) { handle.fireTicks = -handle.maxFireTicks; } if (flag2 && handle.fireTicks > 0) { entity.makeRandomSound(Sound.FIZZ, 0.7f, 1.6f); handle.fireTicks = -handle.maxFireTicks; } } }
public void onMove(double dx, double dy, double dz) { final Entity handle = entity.getHandle(Entity.class); if (handle.Z) { handle.boundingBox.d(dx, dy, dz); handle.locX = (handle.boundingBox.a + handle.boundingBox.d) / 2.0D; handle.locY = (handle.boundingBox.b + (double) handle.height) - (double) handle.Y; handle.locZ = (handle.boundingBox.c + handle.boundingBox.f) / 2.0D; } else { handle.Y *= 0.4f; final double oldLocX = handle.locX; final double oldLocY = handle.locY; final double oldLocZ = handle.locZ; if (EntityRef.justLanded.get(handle)) { EntityRef.justLanded.set(handle, false); dx *= 0.25; dy *= 0.05; dz *= 0.25; handle.motX = 0.0; handle.motY = 0.0; handle.motZ = 0.0; } final double oldDx = dx; final double oldDy = dy; final double oldDz = dz; AxisAlignedBB axisalignedbb = handle.boundingBox.clone(); List<AxisAlignedBB> list = EntityControllerCollisionHelper.getCollisions(this, handle.boundingBox.a(dx, dy, dz)); for (AxisAlignedBB aabb : list) { dy = aabb.b(handle.boundingBox, dy); } handle.boundingBox.d(0.0, dy, 0.0); if (!handle.L && oldDy != dy) { dz = 0.0D; dy = 0.0D; dx = 0.0D; } boolean isOnGround = handle.onGround || oldDy != dy && oldDy < 0.0; for (AxisAlignedBB aabb : list) { dx = aabb.a(handle.boundingBox, dx); } handle.boundingBox.d(dx, 0.0, 0.0); if (!handle.L && oldDx != dx) { dz = 0.0; dy = 0.0; dx = 0.0; } for (AxisAlignedBB aabb : list) { dz = aabb.c(handle.boundingBox, dz); } handle.boundingBox.d(0.0, 0.0, dz); if (!handle.L && oldDz != dz) { dz = 0.0; dy = 0.0; dx = 0.0; } double moveDx; double moveDy; double moveDz; if (handle.Y > 0.0f && handle.Y < 0.05f && isOnGround && (oldDx != dx || oldDz != dz)) { moveDx = dx; moveDy = dy; moveDz = dz; dx = oldDx; dy = (double) handle.Y; dz = oldDz; AxisAlignedBB axisalignedbb1 = handle.boundingBox.clone(); handle.boundingBox.c(axisalignedbb); list = EntityControllerCollisionHelper.getCollisions(this, handle.boundingBox.a(oldDx, dy, oldDz)); for (AxisAlignedBB aabb : list) { dy = aabb.b(handle.boundingBox, dy); } handle.boundingBox.d(0.0, dy, 0.0); if (!handle.L && oldDy != dy) { dz = 0.0; dy = 0.0; dx = 0.0; } for (AxisAlignedBB aabb : list) { dx = aabb.a(handle.boundingBox, dx); } handle.boundingBox.d(dx, 0.0, 0.0D); if (!handle.L && oldDx != dx) { dz = 0.0; dy = 0.0; dx = 0.0; } for (AxisAlignedBB aabb : list) { dz = aabb.c(handle.boundingBox, dz); } handle.boundingBox.d(0.0, 0.0, dz); if (!handle.L && oldDz != dz) { dz = 0.0; dy = 0.0; dx = 0.0; } if (!handle.L && oldDy != dy) { dz = 0.0; dy = 0.0; dx = 0.0; } else { dy = (double) -handle.Y; for (int k = 0; k < list.size(); k++) { dy = list.get(k).b(handle.boundingBox, dy); } handle.boundingBox.d(0.0, dy, 0.0); } if (MathUtil.lengthSquared(moveDx, moveDz) >= MathUtil.lengthSquared(dx, dz)) { dx = moveDx; dy = moveDy; dz = moveDz; handle.boundingBox.c(axisalignedbb1); } else { double subY = handle.boundingBox.b - (int) handle.boundingBox.b; if (subY > 0.0) { handle.Y += subY + 0.01; } } } handle.locX = (handle.boundingBox.a + handle.boundingBox.d) / 2D; handle.locY = (handle.boundingBox.b + (double) handle.height) - (double) handle.Y; handle.locZ = (handle.boundingBox.c + handle.boundingBox.f) / 2D; entity.setMovementImpaired(oldDx != dx || oldDz != dz); handle.H = oldDy != dy; handle.onGround = oldDy != dy && oldDy < 0.0D; handle.I = entity.isMovementImpaired() || handle.H; EntityRef.updateFalling(handle, dy, handle.onGround); if (oldDy != dy) { handle.motY = 0.0; } if (oldDx != dx && Math.abs(handle.motX) > Math.abs(handle.motZ)) { handle.motX = 0.0; } if (oldDz != dz && Math.abs(handle.motZ) > Math.abs(handle.motX)) { handle.motZ = 0.0; } moveDx = handle.locX - oldLocX; moveDy = handle.locY - oldLocY; moveDz = handle.locZ - oldLocZ; if (entity.getEntity() instanceof Vehicle && entity.isMovementImpaired()) { Vehicle vehicle = (Vehicle) entity.getEntity(); org.bukkit.block.Block block = entity.getWorld().getBlockAt(MathUtil.floor(handle.locX), MathUtil.floor(handle.locY - (double) handle.height), MathUtil.floor(handle.locZ)); if (oldDx > dx) { block = block.getRelative(BlockFace.EAST); } else if (oldDx < dx) { block = block.getRelative(BlockFace.WEST); } else if (oldDz > dz) { block = block.getRelative(BlockFace.SOUTH); } else if (oldDz < dz) { block = block.getRelative(BlockFace.NORTH); } VehicleBlockCollisionEvent event = new VehicleBlockCollisionEvent(vehicle, block); entity.getServer().getPluginManager().callEvent(event); } if (EntityRef.hasMovementSound(handle) && handle.vehicle == null) { int bX = MathUtil.floor(handle.locX); int bY = MathUtil.floor(handle.locY - 0.2D - (double) handle.height); int bZ = MathUtil.floor(handle.locZ); int typeId = handle.world.getTypeId(bX, bY, bZ); if (typeId == 0 && handle.world.getTypeId(bX, bY - 1, bZ) == Material.FENCE.getId()) { typeId = Material.FENCE.getId(); } if (typeId != Material.LADDER.getId()) { moveDy = 0.0; } handle.R += Math.sqrt(moveDx * moveDx + moveDz * moveDz) * 0.6; handle.S += Math.sqrt(moveDx * moveDx + moveDy * moveDy + moveDz * moveDz) * 0.6; if (handle.S > EntityRef.stepCounter.get(entity.getHandle()) && typeId > 0) { EntityRef.stepCounter.set(entity.getHandle(), (int) handle.S + 1); if (handle.H()) { float f = (float) Math.sqrt(handle.motX * handle.motX * 0.2 + handle.motY * handle.motY + handle.motZ * handle.motZ * 0.2) * 0.35F; if (f > 1.0F) { f = 1.0F; } entity.makeRandomSound(Sound.SWIM, f, 1.0f); } entity.makeStepSound(bX, bY, bZ, typeId); Block.byId[bZ].b(handle.world, bX, bY, bZ, handle); } } EntityRef.updateBlockCollision(handle); boolean flag2 = handle.G(); if (handle.world.e(handle.boundingBox.shrink(0.001D, 0.001D, 0.001D))) { onBurnDamage(1); if (!flag2) { handle.fireTicks++; if (handle.fireTicks <= 0) { EntityCombustEvent event = new EntityCombustEvent(entity.getEntity(), 8); entity.getServer().getPluginManager().callEvent(event); if (!event.isCancelled()) { handle.setOnFire(event.getDuration()); } } else { handle.setOnFire(8); } } } else if (handle.fireTicks <= 0) { handle.fireTicks = -handle.maxFireTicks; } if (flag2 && handle.fireTicks > 0) { entity.makeRandomSound(Sound.FIZZ, 0.7f, 1.6f); handle.fireTicks = -handle.maxFireTicks; } } }
Augmentations handleStartElement(QName element, XMLAttributes attributes, Augmentations augs) { if (DEBUG) { System.out.println("==>handleStartElement: " + element); } if (fElementDepth == -1 && fValidationManager.isGrammarFound()) { if (fSchemaType == null) { fSchemaDynamicValidation = true; } else { } } if (!fUseGrammarPoolOnly) { String sLocation = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_SCHEMALOCATION); String nsLocation = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); storeLocations(sLocation, nsLocation); } if (fSkipValidationDepth >= 0) { fElementDepth++; if (fAugPSVI) augs = getEmptyAugs(augs); if (fSchemaVersion == Constants.SCHEMA_VERSION_1_1) { assertionValidatorStartElementDelegate(element, attributes, augs); } return augs; } Object decl = null; if (fCurrentCM != null) { decl = fCurrentCM.oneTransition(element, fCurrCMState, fSubGroupHandler, this); if (fCurrCMState[0] == XSCMValidator.FIRST_ERROR) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; Vector next; if (ctype.fParticle != null && (next = fCurrentCM.whatCanGoHere(fCurrCMState)).size() > 0) { String expected = expectedStr(next); final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState); String elemExpandedQname = (element.uri != null) ? "{"+'"'+element.uri+'"'+":"+element.localpart+"}" : element.localpart; if (occurenceInfo != null) { final int minOccurs = occurenceInfo[0]; final int maxOccurs = occurenceInfo[1]; final int count = occurenceInfo[2]; if (count < minOccurs) { final int required = minOccurs - count; if (required > 1) { reportSchemaError("cvc-complex-type.2.4.h", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs), Integer.toString(required) }); } else { reportSchemaError("cvc-complex-type.2.4.g", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs) }); } } else if (count >= maxOccurs && maxOccurs != SchemaSymbols.OCCURRENCE_UNBOUNDED) { reportSchemaError("cvc-complex-type.2.4.e", new Object[] { element.rawname, expected, Integer.toString(maxOccurs) }); } else { reportSchemaError("cvc-complex-type.2.4.a", new Object[] { elemExpandedQname, expected }); } } else { reportSchemaError("cvc-complex-type.2.4.a", new Object[] { elemExpandedQname, expected }); } } else { final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState); if (occurenceInfo != null) { final int maxOccurs = occurenceInfo[1]; final int count = occurenceInfo[2]; if (count >= maxOccurs && maxOccurs != SchemaSymbols.OCCURRENCE_UNBOUNDED) { reportSchemaError("cvc-complex-type.2.4.f", new Object[] { fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(maxOccurs) }); } else { reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname }); } } else { reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname }); } } } } if (fElementDepth != -1) { ensureStackCapacity(); fSubElementStack[fElementDepth] = true; fSubElement = false; fElemDeclStack[fElementDepth] = fCurrentElemDecl; fNilStack[fElementDepth] = fNil; fNotationStack[fElementDepth] = fNotation; fTypeStack[fElementDepth] = fCurrentType; fStrictAssessStack[fElementDepth] = fStrictAssess; fCMStack[fElementDepth] = fCurrentCM; fCMStateStack[fElementDepth] = fCurrCMState; fSawTextStack[fElementDepth] = fSawText; fStringContent[fElementDepth] = fSawCharacters; } fElementDepth++; fCurrentElemDecl = null; XSWildcardDecl wildcard = null; fCurrentType = null; fStrictAssess = true; fNil = false; fNotation = null; fBuffer.setLength(0); fSawText = false; fSawCharacters = false; if (decl != null) { if (decl instanceof XSElementDecl) { fCurrentElemDecl = (XSElementDecl) decl; } else if (decl instanceof XSOpenContentDecl) { wildcard = (XSWildcardDecl) ((XSOpenContentDecl)decl).getWildcard(); } else { wildcard = (XSWildcardDecl) decl; } } if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_SKIP) { fSkipValidationDepth = fElementDepth; if (fAugPSVI) augs = getEmptyAugs(augs); if (fSchemaVersion == Constants.SCHEMA_VERSION_1_1) { assertionValidatorStartElementDelegate(element, attributes, augs); } return augs; } if (fElementDepth == 0) { if (fRootElementDeclaration != null) { fCurrentElemDecl = fRootElementDeclaration; checkElementMatchesRootElementDecl(fCurrentElemDecl, element); } else if (fRootElementDeclQName != null) { processRootElementDeclQName(fRootElementDeclQName, element); } else if (fRootTypeDefinition != null) { fCurrentType = fRootTypeDefinition; } else if (fRootTypeQName != null) { processRootTypeQName(fRootTypeQName); } } if (fCurrentType == null) { if (fCurrentElemDecl == null) { SchemaGrammar sGrammar = findSchemaGrammar( XSDDescription.CONTEXT_ELEMENT, element.uri, null, element, attributes); if (sGrammar != null) { fCurrentElemDecl = sGrammar.getGlobalElementDecl(element.localpart); } } if (fCurrentElemDecl != null) { fCurrentType = fCurrentElemDecl.fType; } } if (fTypeAlternativesChecking && fCurrentElemDecl != null) { fTypeAlternative = fTypeAlternativeValidator.getTypeAlternative(fCurrentElemDecl, element, attributes, fInheritableAttrList); if (fTypeAlternative != null) { fCurrentType = fTypeAlternative.getTypeDefinition(); } } if (fElementDepth == fIgnoreXSITypeDepth && fCurrentElemDecl == null) { fIgnoreXSITypeDepth++; } String xsiType = null; if (fElementDepth >= fIgnoreXSITypeDepth) { xsiType = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_TYPE); } final boolean isSchema11 = (fSchemaVersion == Constants.SCHEMA_VERSION_1_1); boolean needToPushErrorContext = false; if (fCurrentType == null && xsiType == null) { if (fElementDepth == 0) { if (fDynamicValidation || fSchemaDynamicValidation) { if (fDocumentSource != null) { fDocumentSource.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) fDocumentHandler.setDocumentSource(fDocumentSource); fElementDepth = -2; return augs; } fSkipValidationDepth = fElementDepth; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } fXSIErrorReporter.fErrorReporter.reportError( XSMessageFormatter.SCHEMA_DOMAIN, "cvc-elt.1.a", new Object[] { element.rawname }, XMLErrorReporter.SEVERITY_ERROR); } else if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_STRICT) { reportSchemaError("cvc-complex-type.2.4.c", new Object[] { element.rawname }); } fCurrentType = SchemaGrammar.getXSAnyType(fSchemaVersion); fStrictAssess = false; fNFullValidationDepth = fElementDepth; fAppendBuffer = false; if (isSchema11) { needToPushErrorContext = true; } else { fXSIErrorReporter.pushContext(); } } else { if (isSchema11) { needToPushErrorContext = true; } else { fXSIErrorReporter.pushContext(); } if (xsiType != null) { XSTypeDefinition oldType = fCurrentType; if (isSchema11) { if (fXSITypeErrors.size() > 0) { fXSITypeErrors.clear(); } fCurrentType = getAndCheckXsiType(element, xsiType, attributes, fXSITypeErrors); } else { fCurrentType = getAndCheckXsiType(element, xsiType, attributes); } if (fCurrentType == null) { if (oldType == null) fCurrentType = SchemaGrammar.getXSAnyType(fSchemaVersion); else fCurrentType = oldType; } } fNNoneValidationDepth = fElementDepth; if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() == XSConstants.VC_FIXED) { fAppendBuffer = true; } else if (fCurrentType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE) { fAppendBuffer = true; } else { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; fAppendBuffer = (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE); } } if (isSchema11) { if (wildcard != null && fCurrentCM != null) { XSElementDecl elemDecl = fCurrentCM.findMatchingElemDecl(element, fSubGroupHandler); if (elemDecl != null) { final XSTypeDefinition elemType = elemDecl.getTypeDefinition(); if (fCurrentType != elemType) { short block = elemDecl.fBlock; if (elemType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { block |= ((XSComplexTypeDecl) elemType).fBlock; } if (!fXSConstraints.checkTypeDerivationOk(fCurrentType, elemType, block)) { reportSchemaError( "cvc-elt.4.cos-element-consistent.4.a", new Object[] { element.rawname, fCurrentType, elemType.getName()}); } } } } if (needToPushErrorContext) { fXSIErrorReporter.pushContext(); final int errorSize = fXSITypeErrors.size(); if (errorSize > 0) { for (int i=0; i<errorSize; ++i) { reportSchemaError((String)fXSITypeErrors.get(i), (Object[])fXSITypeErrors.get(++i)); } fXSITypeErrors.clear(); } } } if (fCurrentElemDecl != null && fCurrentElemDecl.getAbstract()) reportSchemaError("cvc-elt.2", new Object[] { element.rawname }); if (fElementDepth == 0) { fValidationRoot = element.rawname; } if (fNormalizeData) { fFirstChunk = true; fTrailing = false; fUnionType = false; fWhiteSpace = -1; } if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; if (ctype.getAbstract()) { reportSchemaError("cvc-type.2", new Object[] { element.rawname }); } if (fNormalizeData) { if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { if (ctype.fXSSimpleType.getVariety() == XSSimpleType.VARIETY_UNION) { fUnionType = true; } else { try { fWhiteSpace = ctype.fXSSimpleType.getWhitespace(); } catch (DatatypeException e) { } } } } } else if (fNormalizeData) { XSSimpleType dv = (XSSimpleType) fCurrentType; if (dv.getVariety() == XSSimpleType.VARIETY_UNION) { fUnionType = true; } else { try { fWhiteSpace = dv.getWhitespace(); } catch (DatatypeException e) { } } } fCurrentCM = null; if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { fCurrentCM = ((XSComplexTypeDecl) fCurrentType).getContentModel(fCMBuilder); } fCurrCMState = null; if (fCurrentCM != null) fCurrCMState = fCurrentCM.startContentModel(); String xsiNil = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NIL); if (xsiNil != null && fCurrentElemDecl != null) fNil = getXsiNil(element, xsiNil); XSAttributeGroupDecl attrGrp = null; if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; attrGrp = ctype.getAttrGrp(); } if (fIDCChecking) { fValueStoreCache.startElement(); fMatcherStack.pushContext(); if (fCurrentElemDecl != null && fCurrentElemDecl.fIDCPos > 0) { fIdConstraint = true; fValueStoreCache.initValueStoresFor(fCurrentElemDecl, this); } } if (fSchemaVersion == Constants.SCHEMA_VERSION_1_1) { fIDContext.pushContext(); } processAttributes(element, attributes, attrGrp); if (attrGrp != null) { addDefaultAttributes(element, attributes, attrGrp); } if (fSchemaVersion == Constants.SCHEMA_VERSION_1_1) { fIDContext.setCurrentScopeToParent(); } int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); matcher.startElement( element, attributes); } if (fAugPSVI) { augs = getEmptyAugs(augs); fCurrentPSVI.fValidationContext = fValidationRoot; fCurrentPSVI.fDeclaration = fCurrentElemDecl; fCurrentPSVI.fTypeDecl = fCurrentType; fCurrentPSVI.fNotation = fNotation; fCurrentPSVI.fNil = fNil; if (fSchemaVersion == Constants.SCHEMA_VERSION_1_1) { fCurrentPSVI.fTypeAlternative = fTypeAlternative; fInhrAttrCountStack.push(fInheritableAttrList.size()); fCurrentPSVI.fInheritedAttributes = getInheritedAttributesForPSVI(); fCurrentPSVI.fFailedAssertions = fFailedAssertions; } } if (fSchemaVersion == Constants.SCHEMA_VERSION_1_1) { saveInheritableAttributes(fCurrentElemDecl, attributes); assertionValidatorStartElementDelegate(element, attributes, augs); } return augs; }
Augmentations handleStartElement(QName element, XMLAttributes attributes, Augmentations augs) { if (DEBUG) { System.out.println("==>handleStartElement: " + element); } if (fElementDepth == -1 && fValidationManager.isGrammarFound()) { if (fSchemaType == null) { fSchemaDynamicValidation = true; } else { } } if (!fUseGrammarPoolOnly) { String sLocation = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_SCHEMALOCATION); String nsLocation = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); storeLocations(sLocation, nsLocation); } if (fSkipValidationDepth >= 0) { fElementDepth++; if (fAugPSVI) augs = getEmptyAugs(augs); if (fSchemaVersion == Constants.SCHEMA_VERSION_1_1) { assertionValidatorStartElementDelegate(element, attributes, augs); } return augs; } Object decl = null; if (fCurrentCM != null) { decl = fCurrentCM.oneTransition(element, fCurrCMState, fSubGroupHandler, this); if (fCurrCMState[0] == XSCMValidator.FIRST_ERROR) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; Vector next; if (ctype.fParticle != null && (next = fCurrentCM.whatCanGoHere(fCurrCMState)).size() > 0) { String expected = expectedStr(next); final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState); String elemExpandedQname = (element.uri != null) ? "{"+'"'+element.uri+'"'+":"+element.localpart+"}" : element.localpart; if (occurenceInfo != null) { final int minOccurs = occurenceInfo[0]; final int maxOccurs = occurenceInfo[1]; final int count = occurenceInfo[2]; if (count < minOccurs) { final int required = minOccurs - count; if (required > 1) { reportSchemaError("cvc-complex-type.2.4.h", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs), Integer.toString(required) }); } else { reportSchemaError("cvc-complex-type.2.4.g", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs) }); } } else if (count >= maxOccurs && maxOccurs != SchemaSymbols.OCCURRENCE_UNBOUNDED) { reportSchemaError("cvc-complex-type.2.4.e", new Object[] { element.rawname, expected, Integer.toString(maxOccurs) }); } else { reportSchemaError("cvc-complex-type.2.4.a", new Object[] { elemExpandedQname, expected }); } } else { reportSchemaError("cvc-complex-type.2.4.a", new Object[] { elemExpandedQname, expected }); } } else { final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState); if (occurenceInfo != null) { final int maxOccurs = occurenceInfo[1]; final int count = occurenceInfo[2]; if (count >= maxOccurs && maxOccurs != SchemaSymbols.OCCURRENCE_UNBOUNDED) { reportSchemaError("cvc-complex-type.2.4.f", new Object[] { fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(maxOccurs) }); } else { reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname }); } } else { reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname }); } } } } if (fElementDepth != -1) { ensureStackCapacity(); fSubElementStack[fElementDepth] = true; fSubElement = false; fElemDeclStack[fElementDepth] = fCurrentElemDecl; fNilStack[fElementDepth] = fNil; fNotationStack[fElementDepth] = fNotation; fTypeStack[fElementDepth] = fCurrentType; fStrictAssessStack[fElementDepth] = fStrictAssess; fCMStack[fElementDepth] = fCurrentCM; fCMStateStack[fElementDepth] = fCurrCMState; fSawTextStack[fElementDepth] = fSawText; fStringContent[fElementDepth] = fSawCharacters; } fElementDepth++; fCurrentElemDecl = null; XSWildcardDecl wildcard = null; fCurrentType = null; fStrictAssess = true; fNil = false; fNotation = null; fBuffer.setLength(0); fSawText = false; fSawCharacters = false; if (decl != null) { if (decl instanceof XSElementDecl) { fCurrentElemDecl = (XSElementDecl) decl; } else if (decl instanceof XSOpenContentDecl) { wildcard = (XSWildcardDecl) ((XSOpenContentDecl)decl).getWildcard(); } else { wildcard = (XSWildcardDecl) decl; } } if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_SKIP) { fSkipValidationDepth = fElementDepth; if (fAugPSVI) augs = getEmptyAugs(augs); if (fSchemaVersion == Constants.SCHEMA_VERSION_1_1) { assertionValidatorStartElementDelegate(element, attributes, augs); } return augs; } if (fElementDepth == 0) { if (fRootElementDeclaration != null) { fCurrentElemDecl = fRootElementDeclaration; checkElementMatchesRootElementDecl(fCurrentElemDecl, element); } else if (fRootElementDeclQName != null) { processRootElementDeclQName(fRootElementDeclQName, element); } else if (fRootTypeDefinition != null) { fCurrentType = fRootTypeDefinition; } else if (fRootTypeQName != null) { processRootTypeQName(fRootTypeQName); } } if (fCurrentType == null) { if (fCurrentElemDecl == null) { SchemaGrammar sGrammar = findSchemaGrammar( XSDDescription.CONTEXT_ELEMENT, element.uri, null, element, attributes); if (sGrammar != null) { fCurrentElemDecl = sGrammar.getGlobalElementDecl(element.localpart); } } if (fCurrentElemDecl != null) { fCurrentType = fCurrentElemDecl.fType; } } if (fTypeAlternativesChecking && fCurrentElemDecl != null) { fTypeAlternative = fTypeAlternativeValidator.getTypeAlternative(fCurrentElemDecl, element, attributes, fInheritableAttrList); if (fTypeAlternative != null) { fCurrentType = fTypeAlternative.getTypeDefinition(); } } if (fElementDepth == fIgnoreXSITypeDepth && fCurrentElemDecl == null) { fIgnoreXSITypeDepth++; } String xsiType = null; if (fElementDepth >= fIgnoreXSITypeDepth) { xsiType = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_TYPE); } final boolean isSchema11 = (fSchemaVersion == Constants.SCHEMA_VERSION_1_1); boolean needToPushErrorContext = false; if (fCurrentType == null && xsiType == null) { if (fElementDepth == 0) { if (fDynamicValidation || fSchemaDynamicValidation) { if (fDocumentSource != null) { fDocumentSource.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) fDocumentHandler.setDocumentSource(fDocumentSource); fElementDepth = -2; return augs; } fSkipValidationDepth = fElementDepth; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } fXSIErrorReporter.fErrorReporter.reportError( XSMessageFormatter.SCHEMA_DOMAIN, "cvc-elt.1.a", new Object[] { element.rawname }, XMLErrorReporter.SEVERITY_ERROR); } else if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_STRICT) { reportSchemaError("cvc-complex-type.2.4.c", new Object[] { element.rawname }); } fCurrentType = SchemaGrammar.getXSAnyType(fSchemaVersion); fStrictAssess = false; fNFullValidationDepth = fElementDepth; fAppendBuffer = false; if (isSchema11) { needToPushErrorContext = true; } else { fXSIErrorReporter.pushContext(); } } else { if (isSchema11) { needToPushErrorContext = true; } else { fXSIErrorReporter.pushContext(); } if (xsiType != null) { XSTypeDefinition oldType = fCurrentType; if (isSchema11) { if (fXSITypeErrors.size() > 0) { fXSITypeErrors.clear(); } fCurrentType = getAndCheckXsiType(element, xsiType, attributes, fXSITypeErrors); } else { fCurrentType = getAndCheckXsiType(element, xsiType, attributes); } if (fCurrentType == null) { if (oldType == null) fCurrentType = SchemaGrammar.getXSAnyType(fSchemaVersion); else fCurrentType = oldType; } } fNNoneValidationDepth = fElementDepth; if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() == XSConstants.VC_FIXED) { fAppendBuffer = true; } else if (fCurrentType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE) { fAppendBuffer = true; } else { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; fAppendBuffer = (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE); } } if (isSchema11) { if (wildcard != null && fCurrentCM != null) { XSElementDecl elemDecl = fCurrentCM.findMatchingElemDecl(element, fSubGroupHandler); if (elemDecl != null) { final XSTypeDefinition elemType = elemDecl.getTypeDefinition(); if (fCurrentType != elemType) { short block = elemDecl.fBlock; if (elemType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { block |= ((XSComplexTypeDecl) elemType).fBlock; } if (!fXSConstraints.checkTypeDerivationOk(fCurrentType, elemType, block)) { reportSchemaError( "cos-element-consistent.4.a", new Object[] { element.rawname, fCurrentType, elemType.getName()}); } } } } if (needToPushErrorContext) { fXSIErrorReporter.pushContext(); final int errorSize = fXSITypeErrors.size(); if (errorSize > 0) { for (int i=0; i<errorSize; ++i) { reportSchemaError((String)fXSITypeErrors.get(i), (Object[])fXSITypeErrors.get(++i)); } fXSITypeErrors.clear(); } } } if (fCurrentElemDecl != null && fCurrentElemDecl.getAbstract()) reportSchemaError("cvc-elt.2", new Object[] { element.rawname }); if (fElementDepth == 0) { fValidationRoot = element.rawname; } if (fNormalizeData) { fFirstChunk = true; fTrailing = false; fUnionType = false; fWhiteSpace = -1; } if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; if (ctype.getAbstract()) { reportSchemaError("cvc-type.2", new Object[] { element.rawname }); } if (fNormalizeData) { if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { if (ctype.fXSSimpleType.getVariety() == XSSimpleType.VARIETY_UNION) { fUnionType = true; } else { try { fWhiteSpace = ctype.fXSSimpleType.getWhitespace(); } catch (DatatypeException e) { } } } } } else if (fNormalizeData) { XSSimpleType dv = (XSSimpleType) fCurrentType; if (dv.getVariety() == XSSimpleType.VARIETY_UNION) { fUnionType = true; } else { try { fWhiteSpace = dv.getWhitespace(); } catch (DatatypeException e) { } } } fCurrentCM = null; if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { fCurrentCM = ((XSComplexTypeDecl) fCurrentType).getContentModel(fCMBuilder); } fCurrCMState = null; if (fCurrentCM != null) fCurrCMState = fCurrentCM.startContentModel(); String xsiNil = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NIL); if (xsiNil != null && fCurrentElemDecl != null) fNil = getXsiNil(element, xsiNil); XSAttributeGroupDecl attrGrp = null; if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; attrGrp = ctype.getAttrGrp(); } if (fIDCChecking) { fValueStoreCache.startElement(); fMatcherStack.pushContext(); if (fCurrentElemDecl != null && fCurrentElemDecl.fIDCPos > 0) { fIdConstraint = true; fValueStoreCache.initValueStoresFor(fCurrentElemDecl, this); } } if (fSchemaVersion == Constants.SCHEMA_VERSION_1_1) { fIDContext.pushContext(); } processAttributes(element, attributes, attrGrp); if (attrGrp != null) { addDefaultAttributes(element, attributes, attrGrp); } if (fSchemaVersion == Constants.SCHEMA_VERSION_1_1) { fIDContext.setCurrentScopeToParent(); } int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); matcher.startElement( element, attributes); } if (fAugPSVI) { augs = getEmptyAugs(augs); fCurrentPSVI.fValidationContext = fValidationRoot; fCurrentPSVI.fDeclaration = fCurrentElemDecl; fCurrentPSVI.fTypeDecl = fCurrentType; fCurrentPSVI.fNotation = fNotation; fCurrentPSVI.fNil = fNil; if (fSchemaVersion == Constants.SCHEMA_VERSION_1_1) { fCurrentPSVI.fTypeAlternative = fTypeAlternative; fInhrAttrCountStack.push(fInheritableAttrList.size()); fCurrentPSVI.fInheritedAttributes = getInheritedAttributesForPSVI(); fCurrentPSVI.fFailedAssertions = fFailedAssertions; } } if (fSchemaVersion == Constants.SCHEMA_VERSION_1_1) { saveInheritableAttributes(fCurrentElemDecl, attributes); assertionValidatorStartElementDelegate(element, attributes, augs); } return augs; }
public static String render(IMessage message) { StringBuffer sb = new StringBuffer(); String text = message.getMessage(); if (text.equals(AbortException.NO_MESSAGE_TEXT)) { text = null; } boolean toString = (LangUtil.isEmpty(text)); if (toString) { text = message.toString(); } ISourceLocation loc = message.getSourceLocation(); String context = null; if (null != loc) { File file = loc.getSourceFile(); if (null != file) { String name = file.getName(); if (!toString || (-1 == text.indexOf(name))) { sb.append(FileUtil.getBestPath(file)); if (loc.getLine() > 0) { sb.append(":" + loc.getLine()); } int col = loc.getColumn(); if (0 < col) { sb.append(":" + col); } sb.append(" "); } } context = loc.getContext(); } if (message.getKind() == IMessage.ERROR) { sb.append("error "); } else if (message.getKind() == IMessage.WARNING) { sb.append("warning "); } sb.append(text); if (null != context) { sb.append(LangUtil.EOL); sb.append(context); } String details = message.getDetails(); if (details != null) { sb.append(LangUtil.EOL); sb.append('\t'); sb.append(details); } Throwable thrown = message.getThrown(); if (null != thrown) { sb.append(LangUtil.EOL); sb.append(Main.renderExceptionForUser(thrown)); } if (message.getExtraSourceLocations().isEmpty()) { return sb.toString(); } else { return MessageUtil.addExtraSourceLocations(message, sb.toString()); } }
public static String render(IMessage message) { StringBuffer sb = new StringBuffer(); String text = message.getMessage(); if (text.equals(AbortException.NO_MESSAGE_TEXT)) { text = null; } boolean toString = (LangUtil.isEmpty(text)); if (toString) { text = message.toString(); } ISourceLocation loc = message.getSourceLocation(); String context = null; if (null != loc) { File file = loc.getSourceFile(); if (null != file) { String name = file.getName(); if (!toString || (-1 == text.indexOf(name))) { sb.append(FileUtil.getBestPath(file)); if (loc.getLine() > 0) { sb.append(":" + loc.getLine()); } int col = loc.getColumn(); if (0 < col) { sb.append(":" + col); } sb.append(" "); } } context = loc.getContext(); } if (message.getKind() == IMessage.ERROR) { sb.append("[error] "); } else if (message.getKind() == IMessage.WARNING) { sb.append("[warning] "); } sb.append(text); if (null != context) { sb.append(LangUtil.EOL); sb.append(context); } String details = message.getDetails(); if (details != null) { sb.append(LangUtil.EOL); sb.append('\t'); sb.append(details); } Throwable thrown = message.getThrown(); if (null != thrown) { sb.append(LangUtil.EOL); sb.append(Main.renderExceptionForUser(thrown)); } if (message.getExtraSourceLocations().isEmpty()) { return sb.toString(); } else { return MessageUtil.addExtraSourceLocations(message, sb.toString()); } }
public static void main (final String[] args) { if (args.length < 4) { System.out.println("Usage: run.sh $AWS_ACCESS_KEY_ID $AWS_ACCESS_KEY bucketName filePath"); return; } final AmazonS3 s3 = new AmazonS3Impl(args[0], args[1]); try { s3.createBucket(args[2]); } catch (final IOException e) { System.out.println("Could not create bucket. Already exists?"); e.printStackTrace(); } final String fileString = args[3]; final File file = new File(fileString); if (!file.isFile()) { System.out.println("File not found: "+fileString); return; } try { s3.putPublicFile(args[3], file); } catch (IOException e) { System.out.println("Could not upload file. Error was: "); e.printStackTrace(); } }
public static void main (final String[] args) { if (args.length < 4) { System.out.println("Usage: run.sh $AWS_ACCESS_KEY_ID $AWS_ACCESS_KEY bucketName filePath"); return; } final AmazonS3 s3 = new AmazonS3Impl(args[0], args[1]); final String bucketName = args[2]; try { s3.createBucket(bucketName); } catch (final IOException e) { System.out.println("Could not create bucket. Already exists?"); e.printStackTrace(); } final String fileString = args[3]; final File file = new File(fileString); if (!file.isFile()) { System.out.println("File not found: "+fileString); return; } try { s3.putPublicFile(bucketName, file); } catch (IOException e) { System.out.println("Could not upload file. Error was: "); e.printStackTrace(); } }
private void setHtmlClass() { this.htmlClass = getConditionsClass() + " "; if (jsRegexp != null) this.htmlClass += "validate-regex"; else if (widget == null) return; else if (widget.equals("select")) this.htmlClass += "validate-no-first"; else if (widget.equals("radio")) this.htmlClass += "validate-one-required"; else this.htmlClass += "validate-" + widget; }
private void setHtmlClass() { this.htmlClass = getConditionsClass() + " "; if (jsRegexp != null) this.htmlClass += "validate-regex"; else if (widget == null) return; else if (widget.equals("select")) this.htmlClass += "validate-not-first"; else if (widget.equals("radio")) this.htmlClass += "validate-one-required"; else this.htmlClass += "validate-" + widget; }
public String input() throws ContinuumException, ContinuumStoreException { try { if ( executor == null ) { if ( projectId != 0 ) { executor = getContinuum().getProject( projectId ).getExecutorId(); } else { List projects = getContinuum().getProjectGroupWithProjects( projectGroupId ).getProjects(); if ( projects.size() > 0 ) { Project project = (Project) projects.get( 0 ); executor = project.getExecutorId(); } } } if ( buildDefinitionId != 0 ) { if ( projectId != 0 ) { checkModifyProjectBuildDefinitionAuthorization( getProjectGroupName() ); } else { checkModifyGroupBuildDefinitionAuthorization( getProjectGroupName() ); } BuildDefinition buildDefinition = getContinuum().getBuildDefinition( buildDefinitionId ); goals = buildDefinition.getGoals(); arguments = buildDefinition.getArguments(); buildFile = buildDefinition.getBuildFile(); buildFresh = buildDefinition.isBuildFresh(); scheduleId = buildDefinition.getSchedule().getId(); defaultBuildDefinition = buildDefinition.isDefaultForProject(); Profile profile = buildDefinition.getProfile(); if ( profile != null ) { profileId = profile.getId(); } description = buildDefinition.getDescription(); buildDefinitionType = buildDefinition.getType(); alwaysBuild = buildDefinition.isAlwaysBuild(); } else { String preDefinedBuildFile = ""; if ( projectId != 0 ) { checkAddProjectBuildDefinitionAuthorization( getProjectGroupName() ); BuildDefinition bd = getContinuum().getDefaultBuildDefinition( projectId ); preDefinedBuildFile = bd.getBuildFile(); } else { checkAddGroupBuildDefinitionAuthorization( getProjectGroupName() ); List bds = getContinuum().getBuildDefinitionsForProjectGroup( projectGroupId ); if ( bds != null && !bds.isEmpty() ) { preDefinedBuildFile = ( (BuildDefinition) bds.get( 0 ) ).getBuildFile(); } } if ( StringUtils.isEmpty( preDefinedBuildFile ) ) { if ( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR.equals( executor ) ) { buildFile = getContinuum().getConfiguration().getDefaultMavenTwoBuildDefinition().getBuildFile(); buildDefinitionType = ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR; } else if ( ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR.equals( executor ) ) { buildFile = getContinuum().getConfiguration().getDefaultMavenOneBuildDefinition().getBuildFile(); buildDefinitionType = ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR; } else if ( ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR.equals( executor ) ) { buildFile = getContinuum().getConfiguration().getDefaultAntBuildDefinition().getBuildFile(); buildDefinitionType = ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR; } else { buildDefinitionType = ContinuumBuildExecutorConstants.SHELL_BUILD_EXECUTOR; } } else { buildFile = preDefinedBuildFile; } } if ( StringUtils.isEmpty( buildDefinitionType ) ) { if ( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR.equals( executor ) ) { buildDefinitionType = ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR; } else if ( ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR.equals( executor ) ) { buildDefinitionType = ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR; } else if ( ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR.equals( executor ) ) { buildDefinitionType = ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR; } else { buildDefinitionType = ContinuumBuildExecutorConstants.SHELL_BUILD_EXECUTOR; } } } catch ( AuthorizationRequiredException authzE ) { return REQUIRES_AUTHORIZATION; } return SUCCESS; }
public String input() throws ContinuumException, ContinuumStoreException { try { if ( executor == null ) { if ( projectId != 0 ) { executor = getContinuum().getProject( projectId ).getExecutorId(); } else { List projects = getContinuum().getProjectGroupWithProjects( projectGroupId ).getProjects(); if ( projects.size() > 0 ) { Project project = (Project) projects.get( 0 ); executor = project.getExecutorId(); } } } if ( buildDefinitionId != 0 ) { if ( projectId != 0 ) { checkModifyProjectBuildDefinitionAuthorization( getProjectGroupName() ); } else { checkModifyGroupBuildDefinitionAuthorization( getProjectGroupName() ); } BuildDefinition buildDefinition = getContinuum().getBuildDefinition( buildDefinitionId ); goals = buildDefinition.getGoals(); arguments = buildDefinition.getArguments(); buildFile = buildDefinition.getBuildFile(); buildFresh = buildDefinition.isBuildFresh(); scheduleId = buildDefinition.getSchedule().getId(); defaultBuildDefinition = buildDefinition.isDefaultForProject(); Profile profile = buildDefinition.getProfile(); if ( profile != null ) { profileId = profile.getId(); } description = buildDefinition.getDescription(); buildDefinitionType = buildDefinition.getType(); alwaysBuild = buildDefinition.isAlwaysBuild(); } else { String preDefinedBuildFile = ""; if ( projectId != 0 ) { checkAddProjectBuildDefinitionAuthorization( getProjectGroupName() ); BuildDefinition bd = getContinuum().getDefaultBuildDefinition( projectId ); if ( bd != null ) { preDefinedBuildFile = bd.getBuildFile(); } } else { checkAddGroupBuildDefinitionAuthorization( getProjectGroupName() ); List bds = getContinuum().getBuildDefinitionsForProjectGroup( projectGroupId ); if ( bds != null && !bds.isEmpty() ) { preDefinedBuildFile = ( (BuildDefinition) bds.get( 0 ) ).getBuildFile(); } } if ( StringUtils.isEmpty( preDefinedBuildFile ) ) { if ( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR.equals( executor ) ) { buildFile = getContinuum().getConfiguration().getDefaultMavenTwoBuildDefinition().getBuildFile(); buildDefinitionType = ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR; } else if ( ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR.equals( executor ) ) { buildFile = getContinuum().getConfiguration().getDefaultMavenOneBuildDefinition().getBuildFile(); buildDefinitionType = ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR; } else if ( ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR.equals( executor ) ) { buildFile = getContinuum().getConfiguration().getDefaultAntBuildDefinition().getBuildFile(); buildDefinitionType = ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR; } else { buildDefinitionType = ContinuumBuildExecutorConstants.SHELL_BUILD_EXECUTOR; } } else { buildFile = preDefinedBuildFile; } } if ( StringUtils.isEmpty( buildDefinitionType ) ) { if ( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR.equals( executor ) ) { buildDefinitionType = ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR; } else if ( ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR.equals( executor ) ) { buildDefinitionType = ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR; } else if ( ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR.equals( executor ) ) { buildDefinitionType = ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR; } else { buildDefinitionType = ContinuumBuildExecutorConstants.SHELL_BUILD_EXECUTOR; } } } catch ( AuthorizationRequiredException authzE ) { return REQUIRES_AUTHORIZATION; } return SUCCESS; }
protected void executeQuery( ) { rset = null; IDataQueryDefinition query = design.getQuery( ); IBaseResultSet parentRset = getParentResultSet( ); context.setResultSet( parentRset ); if ( query != null ) { try { rset = (IQueryResultSet) context.executeQuery( parentRset, query ); context.setResultSet( rset ); if ( rset != null ) { rsetEmpty = !rset.next( ); return; } } catch ( BirtException ex ) { context.addException( ex ); } } }
protected void executeQuery( ) { rset = null; IDataQueryDefinition query = design.getQuery( ); IBaseResultSet parentRset = getParentResultSet( ); context.setResultSet( parentRset ); if ( query != null ) { try { rset = (IQueryResultSet) context.executeQuery( parentRset, query ); context.setResultSet( rset ); if ( rset != null ) { rsetEmpty = !rset.next( ); return; } } catch ( BirtException ex ) { rsetEmpty = true; context.addException( ex ); } } }
public Response addPermissions(Permission permission) throws BadRequestException { if (dao.findByUserROAndPermission(permission.getUser(), permission.getRo(), permission.getRole()).size() > 0) { throw new ConflictException("The permission was already given"); } if (!builder.getUser().getRole() .equals(pl.psnc.dl.wf4ever.dl.UserMetadata.Role.ADMIN)) { UserProfile userProfile = userProfileDAO.findByLogin(builder .getUser().getLogin()); if (userProfile == null) { throw new BadRequestException("There is no user like this"); } List<Permission> permissions = dao.findByUserROAndPermission( userProfile, permission.getRo(), Role.OWNER); if (permissions.size() == 0) { throw new BadRequestException( "The given ro doesn't exists or doesn't belong to user"); } else if (permissions.size() > 1) { LOGGER.error("Multiply RO ownership detected for" + permission.getRo()); throw new WebApplicationException(500); } } if (permission.getUser() == null) { throw new BadRequestException( "The given user login doesn't exists"); } dao.save(permission); permission.setUri(uriInfo.getRequestUri().resolve("") .resolve(permission.getId().toString())); return Response .created( uriInfo.getRequestUri().resolve("") .resolve(permission.getId().toString())) .type(MediaType.APPLICATION_JSON).entity(permission).build(); }
public Response addPermissions(Permission permission) throws BadRequestException { if (dao.findByUserROAndPermission(permission.getUser(), permission.getRo(), permission.getRole()).size() > 0) { throw new ConflictException("The permission was already given"); } if (!builder.getUser().getRole() .equals(pl.psnc.dl.wf4ever.dl.UserMetadata.Role.ADMIN)) { UserProfile userProfile = userProfileDAO.findByLogin(builder .getUser().getLogin()); if (userProfile == null) { throw new BadRequestException("There is no user like this"); } List<Permission> permissions = dao.findByUserROAndPermission( userProfile, permission.getRo(), Role.OWNER); if (permissions.size() == 0) { throw new BadRequestException( "The given ro doesn't exists or doesn't belong to user"); } else if (permissions.size() > 1) { LOGGER.error("Multiply RO ownership detected for" + permission.getRo()); throw new WebApplicationException(500); } } if (permission.getUser() == null) { throw new BadRequestException( "Given user login doesn't exist"); } dao.save(permission); permission.setUri(uriInfo.getRequestUri().resolve("") .resolve(permission.getId().toString())); return Response .created( uriInfo.getRequestUri().resolve("") .resolve(permission.getId().toString())) .type(MediaType.APPLICATION_JSON).entity(permission).build(); }
public void onClick(ClickEvent event) { if (event.getSource() == hr && hr.isEnabled()) { getTextArea().setFocus(true); Range range = getTextArea().getDocument().getSelection().getRangeAt(0); if (range != null) { range = EditorUtils.normalizeCaretPosition(range); int[] path = EditorUtils.toIntArray(EditorUtils.getLocator(range.getStartContainer())); int siteId = clientJupiter.getSiteId(); TreeCompositeOperation seq = null; if (range.getStartOffset() == 0) { TreeOperation newP = new TreeNewParagraph(siteId, path[0]); TreeOperation updateP = new TreeUpdateElement(siteId, new int[] { path[0] }, Tree.NODE_NAME, "hr"); TreeOperation newP2 = new TreeNewParagraph(siteId, path[0]); seq = new TreeCompositeOperation(newP, updateP, newP2); } else { TreeOperation splitP = new TreeInsertParagraph(siteId, range.getStartOffset(), path); TreeOperation newP = new TreeNewParagraph(siteId, path[0] + 1); TreeOperation updateP = new TreeUpdateElement(siteId, new int[] { path[0] + 1 }, Tree.NODE_NAME, "hr"); seq = new TreeCompositeOperation(splitP, newP, updateP); } clientJupiter.generate(seq); } } }
public void onClick(ClickEvent event) { if (event.getSource() == hr && hr.isEnabled()) { getTextArea().setFocus(true); Range range = getTextArea().getDocument().getSelection().getRangeAt(0); if (range != null) { range = EditorUtils.normalizeCaretPosition(range); int[] path = EditorUtils.toIntArray(EditorUtils.getLocator(range.getStartContainer())); int siteId = clientJupiter.getSiteId(); TreeCompositeOperation seq = null; if (range.getStartOffset() == 0) { TreeOperation newP = new TreeNewParagraph(siteId, path[0]); TreeOperation updateP = new TreeUpdateElement(siteId, new int[] { path[0] }, Tree.NODE_NAME, "hr"); TreeOperation newP2 = new TreeNewParagraph(siteId, path[0]); seq = new TreeCompositeOperation(newP, updateP, newP2); } else { TreeOperation splitP = new TreeInsertParagraph(siteId, range.getStartOffset(), path); TreeOperation newP = new TreeNewParagraph(siteId, path[0] + 1); TreeOperation updateP = new TreeUpdateElement(siteId, new int[] { path[0] + 1 }, Tree.NODE_NAME, "hr"); seq = new TreeCompositeOperation(splitP, newP, updateP); } seq.setSiteId(siteId); clientJupiter.generate(seq); } } }
private boolean recurse( File dir, Layer parent ) { boolean changed = false; File[] fs = dir.listFiles(); if ( fs != null ) { for ( File f : fs ) { String nm = f.getName(); if ( nm.equals( ".svn" ) ) { continue; } if ( f.isDirectory() ) { Layer newParent = parent.getChild( nm ); if ( newParent == null && f.listFiles().length > 0 ) { newParent = new EmptyLayer( nm, nm, parent ); if ( service.layers.containsKey( nm ) ) { LOG.warn( "The layer with name '{}' is defined more than once." + " This may lead to problems.", nm ); LOG.warn( "Requesting this name will get you the last defined layer." ); } service.layers.put( nm, newParent ); LOG.debug( "Loaded category layer {}", nm ); changed = true; parent.addOrReplace( newParent ); } changed |= recurse( f, newParent ); } else { if ( nm.length() > 4 ) { String layName = nm.substring( 0, nm.length() - 4 ); String fstr = f.toString(); if ( nm.toLowerCase().endsWith( ".shp" ) && parent.getChild( layName ) == null ) { try { FeatureLayer lay = new FeatureLayer( layName, layName, parent, fstr ); changed = true; if ( service.layers.containsKey( layName ) ) { LOG.warn( "The layer with name '{}' is defined more than once." + " This may lead to problems.", layName ); LOG.warn( "Requesting this name will get you the last defined layer." ); } service.layers.put( layName, lay ); parent.addOrReplace( lay ); LOG.debug( "Loaded shape file layer {}", layName ); } catch ( FileNotFoundException e ) { LOG.warn( "Shape file {} could not be deployed: {}", layName, e.getLocalizedMessage() ); LOG.trace( "Stack trace", e ); } catch ( IOException e ) { LOG.warn( "Shape file {} could not be deployed: {}", layName, e.getLocalizedMessage() ); LOG.trace( "Stack trace", e ); } } else if ( nm.toLowerCase().endsWith( ".shp" ) ) { try { String file = fstr.substring( 0, fstr.length() - 4 ); Layer lay = parent.getChild( layName ); File sld = new File( file + ".sld" ); if ( !sld.exists() ) { sld = new File( file + ".SLD" ); } if ( sld.exists() ) { changed |= service.registry.register( lay.getName(), sld, true ); } } catch ( FactoryConfigurationError e ) { LOG.warn( "Could not parse SLD/SE file for layer '{}'.", layName ); LOG.trace( "Stack trace: ", e ); } } } } } } return changed; }
private boolean recurse( File dir, Layer parent ) { boolean changed = false; File[] fs = dir.listFiles(); if ( fs != null ) { for ( File f : fs ) { String nm = f.getName(); if ( nm.equals( ".svn" ) ) { continue; } if ( f.isDirectory() ) { Layer newParent = parent.getChild( nm ); if ( newParent == null && f.listFiles().length > 0 ) { newParent = new EmptyLayer( nm, nm, parent ); if ( service.layers.containsKey( nm ) ) { LOG.warn( "The layer with name '{}' is defined more than once." + " This may lead to problems.", nm ); LOG.warn( "Requesting this name will get you the last defined layer." ); } service.layers.put( nm, newParent ); LOG.debug( "Loaded category layer {}", nm ); changed = true; parent.addOrReplace( newParent ); } changed |= recurse( f, newParent ); } else { if ( nm.length() > 4 ) { String layName = nm.substring( 0, nm.length() - 4 ); String fstr = f.toString(); if ( nm.toLowerCase().endsWith( ".shp" ) && parent.getChild( layName ) == null ) { try { FeatureLayer lay = new FeatureLayer( layName, layName, parent, fstr ); changed = true; if ( service.layers.containsKey( layName ) ) { LOG.warn( "The layer with name '{}' is defined more than once." + " This may lead to problems.", layName ); LOG.warn( "Requesting this name will get you the last defined layer." ); } service.layers.put( layName, lay ); parent.addOrReplace( lay ); LOG.debug( "Loaded shape file layer {}", layName ); try { String file = fstr.substring( 0, fstr.length() - 4 ); File sld = new File( file + ".sld" ); if ( !sld.exists() ) { sld = new File( file + ".SLD" ); } if ( sld.exists() ) { changed |= service.registry.register( lay.getName(), sld, true ); } } catch ( FactoryConfigurationError e ) { LOG.warn( "Could not parse SLD/SE file for layer '{}'.", layName ); LOG.trace( "Stack trace: ", e ); } } catch ( FileNotFoundException e ) { LOG.warn( "Shape file {} could not be deployed: {}", layName, e.getLocalizedMessage() ); LOG.trace( "Stack trace", e ); } catch ( IOException e ) { LOG.warn( "Shape file {} could not be deployed: {}", layName, e.getLocalizedMessage() ); LOG.trace( "Stack trace", e ); } } } } } } return changed; }
ConnThrottler(int max, int totalMax, long period) { _max = max; _totalMax = totalMax; if (max > 0) { SimpleScheduler.getInstance().addPeriodicEvent(new Cleaner(), period); this.counter = new ObjectCounter(); } else { this.counter = null; } if (totalMax > 0) _currentTotal = new AtomicInteger(); else _currentTotal = null; }
ConnThrottler(int max, int totalMax, long period) { _max = max; _totalMax = totalMax; SimpleScheduler.getInstance().addPeriodicEvent(new Cleaner(), period); if (max > 0) this.counter = new ObjectCounter(); else this.counter = null; if (totalMax > 0) _currentTotal = new AtomicInteger(); else _currentTotal = null; }
public J extract(final Tuple resultset, final String name) { @SuppressWarnings( "unchecked" ) final J result = (J) resultset.get( name ); if ( result == null ) { log.tracef( "found [null] as column [$s]", name ); return null; } else { if ( log.isTraceEnabled() ) { log.tracef( "found [$s] as column [$s]", javaTypeDescriptor.extractLoggableRepresentation( result ), name ); } return result; } }
public J extract(final Tuple resultset, final String name) { @SuppressWarnings( "unchecked" ) final J result = (J) resultset.get( name ); if ( result == null ) { log.tracef( "found [null] as column [$s]", name ); return null; } else { if ( log.isTraceEnabled() ) { log.tracef( "found [%1$s] as column [%2$s]", javaTypeDescriptor.extractLoggableRepresentation( result ), name ); } return result; } }
public Vector getEntries() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream())); Vector entries = new Vector(); try { baseFolder = br.readLine(); if(baseFolder==null) return entries; String line; StringTokenizer st; String name; String path; String currentDir = ""; long size; long date; boolean isDirectory; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm.ss"); while((line=br.readLine())!=null) { try { st = new StringTokenizer(line); name = st.nextToken().replace('\\', '/'); size = Long.parseLong(st.nextToken()); date = dateFormat.parse((st.nextToken()+" "+st.nextToken())).getTime(); if(name.endsWith("/")) { isDirectory = true; currentDir = name; path = currentDir; } else { isDirectory = false; path = currentDir+name; } entries.add(new SimpleArchiveEntry(path, date, size, isDirectory)); } catch(Exception e) { if(Debug.ON) { Debug.trace("Exception caught while parsing LST file:"); e.printStackTrace(); } throw new IOException(); } } return entries; } finally { if(br!=null) try { br.close(); } catch(IOException e) {} } }
public Vector getEntries() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream())); Vector entries = new Vector(); try { baseFolder = br.readLine(); if(baseFolder==null) return entries; String line; StringTokenizer st; String name; String path; String currentDir = ""; long size; long date; boolean isDirectory; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm.ss"); while((line=br.readLine())!=null) { try { st = new StringTokenizer(line, "\t"); name = st.nextToken().replace('\\', '/'); size = Long.parseLong(st.nextToken()); date = dateFormat.parse((st.nextToken()+" "+st.nextToken())).getTime(); if(name.endsWith("/")) { isDirectory = true; currentDir = name; path = currentDir; } else { isDirectory = false; path = currentDir+name; } entries.add(new SimpleArchiveEntry(path, date, size, isDirectory)); } catch(Exception e) { if(Debug.ON) { Debug.trace("Exception caught while parsing LST file:"); e.printStackTrace(); } throw new IOException(); } } return entries; } finally { if(br!=null) try { br.close(); } catch(IOException e) {} } }
protected void doDSPost(Context c, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String button = UIUtil.getSubmitButton(request, "submit"); if( button.equals("submit_collection") ) { Collection [] collections = Collection.findAll(c); request.setAttribute("collections", collections); JSPManager.showJSP(request, response, "/admin/collection-select.jsp" ); } else if( button.equals("submit_community") ) { Community [] communities = Community.findAll(c); request.setAttribute("communities", communities); JSPManager.showJSP(request, response, "/admin/community-select.jsp" ); } else if( button.equals("submit_advanced") ) { Collection [] collections = Collection.findAll(c); Group [] groups = Group.findAll(c, Group.NAME); request.setAttribute("collections", collections); request.setAttribute("groups", groups ); JSPManager.showJSP(request, response, "/admin/authorize-advanced.jsp" ); } else if( button.equals("submit_item") ) { JSPManager.showJSP(request, response, "/admin/item-select.jsp" ); } else if( button.equals("submit_item_select") ) { Item item = null; int item_id = UIUtil.getIntParameter ( request, "item_id"); String handle = request.getParameter ( "handle" ); if( item_id > 0 ) { item = Item.find(c, item_id); } else if(handle != null && !handle.equals("")) { DSpaceObject dso = HandleManager.resolveToObject(c, handle); if( dso != null && dso.getType() != Constants.ITEM ) { item = (Item) dso; } } if( item == null ) { request.setAttribute("invalid.id", new Boolean(true)); JSPManager.showJSP(request, response, "/admin/item-select.jsp"); } else { List item_policies = AuthorizeManager.getPolicies(c, item); request.setAttribute("item", item); request.setAttribute("item_policies", item_policies ); JSPManager.showJSP(request, response, "/admin/authorize-item-edit.jsp" ); } } else if( button.equals( "submit_item_add_policy") ) { Item item = Item.find(c, UIUtil.getIntParameter(request, "item_id")); ResourcePolicy policy = ResourcePolicy.create(c); policy.setResource( item ); policy.update(); Group [] groups = Group.findAll (c, Group.NAME ); EPerson [] epeople = EPerson.findAll(c, EPerson.EMAIL); request.setAttribute( "edit_title", "Item " + item.getID() ); request.setAttribute( "policy", policy ); request.setAttribute( "groups", groups ); request.setAttribute( "epeople", epeople ); request.setAttribute( "id_name", "item_id" ); request.setAttribute( "id", "" + item.getID() ); JSPManager.showJSP(request, response, "/admin/authorize-policy-edit.jsp" ); } else if( button.equals("submit_item_delete_policy") ) { Item item = Item.find(c, UIUtil.getIntParameter(request, "item_id")); ResourcePolicy policy = ResourcePolicy.find(c, UIUtil.getIntParameter(request, "policy_id")); policy.delete(); request.setAttribute("item", item ); List item_policies = AuthorizeManager.getPolicies(c, item); request.setAttribute("item_policies", item_policies); JSPManager.showJSP(request, response, "/admin/authorize-item-edit.jsp" ); } else if( button.equals( "submit_collection_add_policy") ) { Collection collection = Collection.find(c, UIUtil.getIntParameter(request, "collection_id")); ResourcePolicy policy = ResourcePolicy.create(c); policy.setResource( collection ); policy.update(); Group [] groups = Group.findAll (c, Group.NAME ); EPerson [] epeople = EPerson.findAll(c, EPerson.EMAIL); request.setAttribute( "edit_title", "Collection " + collection.getID() ); request.setAttribute( "policy", policy ); request.setAttribute( "groups", groups ); request.setAttribute( "epeople", epeople ); request.setAttribute( "id_name", "collection_id" ); request.setAttribute( "id", "" + collection.getID() ); JSPManager.showJSP(request, response, "/admin/authorize-policy-edit.jsp" ); } else if( button.equals("submit_community_select") ) { Community target = Community.find(c, UIUtil.getIntParameter(request, "community_id")); List policies = AuthorizeManager.getPolicies(c, target); request.setAttribute("community", target ); request.setAttribute("policies", policies ); JSPManager.showJSP(request, response, "/admin/authorize-community-edit.jsp" ); } else if( button.equals("submit_collection_delete_policy") ) { Collection collection = Collection.find(c, UIUtil.getIntParameter(request, "collection_id")); ResourcePolicy policy = ResourcePolicy.find(c, UIUtil.getIntParameter(request, "policy_id")); policy.delete(); request.setAttribute("collection", collection ); List policies = AuthorizeManager.getPolicies(c, collection); request.setAttribute("policies", policies); JSPManager.showJSP(request, response, "/admin/authorize-collection-edit.jsp" ); } else if( button.equals("submit_community_delete_policy") ) { Community community = Community.find(c, UIUtil.getIntParameter(request, "community_id")); ResourcePolicy policy = ResourcePolicy.find(c, UIUtil.getIntParameter(request, "policy_id")); policy.delete(); request.setAttribute("community", community ); List policies = AuthorizeManager.getPolicies(c, community); request.setAttribute("policies", policies); JSPManager.showJSP(request, response, "/admin/authorize-community-edit.jsp" ); } else if( button.equals("submit_collection_edit_policy") ) { Collection collection = Collection.find(c, UIUtil.getIntParameter(request, "collection_id")); int policy_id = UIUtil.getIntParameter(request, "policy_id"); ResourcePolicy policy = null; if( policy_id == -1 ) { policy = ResourcePolicy.create(c); policy.setResource( collection ); policy.update(); } else { policy = ResourcePolicy.find(c, policy_id); } Group [] groups = Group.findAll(c, Group.NAME); EPerson [] epeople = EPerson.findAll(c, EPerson.EMAIL); request.setAttribute( "edit_title", "Collection " + collection.getID() ); request.setAttribute( "policy", policy ); request.setAttribute( "groups", groups ); request.setAttribute( "epeople", epeople ); request.setAttribute( "id_name", "collection_id" ); request.setAttribute( "id", "" + collection.getID() ); JSPManager.showJSP(request, response, "/admin/authorize-policy-edit.jsp" ); } else if( button.equals("submit_community_edit_policy") ) { Community community = Community.find(c, UIUtil.getIntParameter(request, "community_id")); int policy_id = UIUtil.getIntParameter(request, "policy_id"); ResourcePolicy policy = null; if( policy_id == -1 ) { policy = ResourcePolicy.create(c); policy.setResource( community ); policy.update(); } else { policy = ResourcePolicy.find(c, policy_id); } Group [] groups = Group.findAll (c, Group.NAME ); EPerson [] epeople = EPerson.findAll(c, EPerson.EMAIL); request.setAttribute( "edit_title", "Community " + community.getID() ); request.setAttribute( "policy", policy ); request.setAttribute( "groups", groups ); request.setAttribute( "epeople", epeople ); request.setAttribute( "id_name", "community_id" ); request.setAttribute( "id", "" + community.getID() ); JSPManager.showJSP(request, response, "/admin/authorize-policy-edit.jsp" ); } else if( button.equals( "submit_collection_add_policy") ) { Collection collection = Collection.find(c, UIUtil.getIntParameter(request, "collection_id")); ResourcePolicy policy = ResourcePolicy.create(c); policy.setResource( collection ); policy.update(); Group [] groups = Group.findAll (c, Group.NAME ); EPerson [] epeople = EPerson.findAll(c, EPerson.EMAIL); request.setAttribute( "edit_title", "Collection " + collection.getID() ); request.setAttribute( "policy", policy ); request.setAttribute( "groups", groups ); request.setAttribute( "epeople", epeople ); request.setAttribute( "id_name", "collection_id" ); request.setAttribute( "id", "" + collection.getID() ); JSPManager.showJSP(request, response, "/admin/authorize-policy-edit.jsp" ); } else if( button.equals( "submit_community_add_policy") ) { Community community = Community.find(c, UIUtil.getIntParameter(request, "community_id")); ResourcePolicy policy = ResourcePolicy.create(c); policy.setResource( community ); policy.update(); Group [] groups = Group.findAll (c, Group.NAME ); EPerson [] epeople = EPerson.findAll(c, EPerson.EMAIL); request.setAttribute( "edit_title", "Community " + community.getID() ); request.setAttribute( "policy", policy ); request.setAttribute( "groups", groups ); request.setAttribute( "epeople", epeople ); request.setAttribute( "id_name", "community_id" ); request.setAttribute( "id", "" + community.getID() ); JSPManager.showJSP(request, response, "/admin/authorize-policy-edit.jsp" ); } else if( button.equals( "submit_save_policy" ) ) { int policy_id = UIUtil.getIntParameter(request, "policy_id" ); int action_id = UIUtil.getIntParameter(request, "action_id" ); int group_id = UIUtil.getIntParameter(request, "group_id" ); int collection_id = UIUtil.getIntParameter(request, "collection_id"); int community_id = UIUtil.getIntParameter(request, "community_id" ); int item_id = UIUtil.getIntParameter(request, "item_id" ); Item item = null; Collection collection = null; Community community = null; String display_page = null; ResourcePolicy policy = ResourcePolicy.find(c, policy_id); Group group = Group.find(c, group_id); if( collection_id != -1 ) { collection = Collection.find( c, collection_id ); policy.setAction ( action_id ); policy.setGroup ( group ); policy.update(); if( action_id == Constants.READ ) { List rps = AuthorizeManager.getPoliciesActionFilter(c, collection, Constants.READ); Bitstream bs = collection.getLogo(); if( bs != null ) { AuthorizeManager.removeAllPolicies(c, bs); AuthorizeManager.addPolicies(c, rps, bs); } } request.setAttribute("collection", collection ); request.setAttribute("policies", AuthorizeManager.getPolicies( c, collection ) ); display_page = "/admin/authorize-collection-edit.jsp"; } else if( community_id != -1 ) { community = Community.find( c, community_id ); policy.setAction ( action_id ); policy.setGroup ( group ); policy.update(); if( action_id == Constants.READ ) { List rps = AuthorizeManager.getPoliciesActionFilter(c, community, Constants.READ); Bitstream bs = community.getLogo(); if( bs != null ) { AuthorizeManager.removeAllPolicies(c, bs); AuthorizeManager.addPolicies(c, rps, bs); } } request.setAttribute("community", community ); request.setAttribute("policies", AuthorizeManager.getPolicies( c, community ) ); display_page = "/admin/authorize-community-edit.jsp"; } else if( item_id != -1 ) { item = Item.find( c, item_id ); policy.setAction ( action_id ); policy.setGroup ( group ); policy.update(); request.setAttribute("item", item ); request.setAttribute("item_policies", AuthorizeManager.getPolicies( c, item ) ); display_page = "/admin/authorize-item-edit.jsp"; } JSPManager.showJSP( request, response, display_page ); } else if( button.equals("submit_cancel_policy") ) { int collection_id =UIUtil.getIntParameter (request, "collection_id"); int community_id =UIUtil.getIntParameter (request, "community_id" ); String display_page = null; if( collection_id != -1 ) { Collection t = Collection.find( c, collection_id ); request.setAttribute("collection", t ); request.setAttribute("policies", AuthorizeManager.getPolicies( c, t ) ); display_page = "/admin/authorize-collection-edit.jsp"; } else if( community_id != -1 ) { Community t = Community.find( c, community_id ); request.setAttribute("community", t ); request.setAttribute("policies", AuthorizeManager.getPolicies( c, t ) ); display_page = "/admin/authorize-community-edit.jsp"; } JSPManager.showJSP(request, response, display_page ); } else if (button.equals("submit_advanced_clear")) { int collection_id = UIUtil.getIntParameter (request, "collection_id"); int resource_type = UIUtil.getIntParameter (request, "resource_type"); PolicySet.setPolicies(c, Constants.COLLECTION, collection_id, resource_type, 0, 0, false, true); if( resource_type == Constants.BITSTREAM ) { PolicySet.setPolicies(c, Constants.COLLECTION, collection_id, Constants.BUNDLE, 0, 0, false, true); } showMainPage(c, request, response); } else if (button.equals("submit_advanced_add")) { int collection_id = UIUtil.getIntParameter (request, "collection_id"); int resource_type = UIUtil.getIntParameter (request, "resource_type"); int action_id = UIUtil.getIntParameter (request, "action_id" ); int group_id = UIUtil.getIntParameter (request, "group_id" ); PolicySet.setPolicies(c, Constants.COLLECTION, collection_id, resource_type, action_id, group_id, false, false); if( resource_type == Constants.BITSTREAM ) { PolicySet.setPolicies(c, Constants.COLLECTION, collection_id, Constants.BUNDLE, action_id, group_id, false, false); } showMainPage(c, request, response); } else if( button.equals("submit_collection_select") ) { Collection collection = Collection.find(c, UIUtil.getIntParameter(request, "collection_id")); List policies = AuthorizeManager.getPolicies(c, collection); request.setAttribute("collection", collection ); request.setAttribute("policies", policies ); JSPManager.showJSP(request, response, "/admin/authorize-collection-edit.jsp" ); } else { showMainPage(c, request, response); } c.complete(); }
protected void doDSPost(Context c, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String button = UIUtil.getSubmitButton(request, "submit"); if( button.equals("submit_collection") ) { Collection [] collections = Collection.findAll(c); request.setAttribute("collections", collections); JSPManager.showJSP(request, response, "/admin/collection-select.jsp" ); } else if( button.equals("submit_community") ) { Community [] communities = Community.findAll(c); request.setAttribute("communities", communities); JSPManager.showJSP(request, response, "/admin/community-select.jsp" ); } else if( button.equals("submit_advanced") ) { Collection [] collections = Collection.findAll(c); Group [] groups = Group.findAll(c, Group.NAME); request.setAttribute("collections", collections); request.setAttribute("groups", groups ); JSPManager.showJSP(request, response, "/admin/authorize-advanced.jsp" ); } else if( button.equals("submit_item") ) { JSPManager.showJSP(request, response, "/admin/item-select.jsp" ); } else if( button.equals("submit_item_select") ) { Item item = null; int item_id = UIUtil.getIntParameter ( request, "item_id"); String handle = request.getParameter ( "handle" ); if( item_id > 0 ) { item = Item.find(c, item_id); } else if(handle != null && !handle.equals("")) { DSpaceObject dso = HandleManager.resolveToObject(c, handle); if( dso != null && dso.getType() == Constants.ITEM ) { item = (Item) dso; } } if( item == null ) { request.setAttribute("invalid.id", new Boolean(true)); JSPManager.showJSP(request, response, "/admin/item-select.jsp"); } else { List item_policies = AuthorizeManager.getPolicies(c, item); request.setAttribute("item", item); request.setAttribute("item_policies", item_policies ); JSPManager.showJSP(request, response, "/admin/authorize-item-edit.jsp" ); } } else if( button.equals( "submit_item_add_policy") ) { Item item = Item.find(c, UIUtil.getIntParameter(request, "item_id")); ResourcePolicy policy = ResourcePolicy.create(c); policy.setResource( item ); policy.update(); Group [] groups = Group.findAll (c, Group.NAME ); EPerson [] epeople = EPerson.findAll(c, EPerson.EMAIL); request.setAttribute( "edit_title", "Item " + item.getID() ); request.setAttribute( "policy", policy ); request.setAttribute( "groups", groups ); request.setAttribute( "epeople", epeople ); request.setAttribute( "id_name", "item_id" ); request.setAttribute( "id", "" + item.getID() ); JSPManager.showJSP(request, response, "/admin/authorize-policy-edit.jsp" ); } else if( button.equals("submit_item_delete_policy") ) { Item item = Item.find(c, UIUtil.getIntParameter(request, "item_id")); ResourcePolicy policy = ResourcePolicy.find(c, UIUtil.getIntParameter(request, "policy_id")); policy.delete(); request.setAttribute("item", item ); List item_policies = AuthorizeManager.getPolicies(c, item); request.setAttribute("item_policies", item_policies); JSPManager.showJSP(request, response, "/admin/authorize-item-edit.jsp" ); } else if( button.equals( "submit_collection_add_policy") ) { Collection collection = Collection.find(c, UIUtil.getIntParameter(request, "collection_id")); ResourcePolicy policy = ResourcePolicy.create(c); policy.setResource( collection ); policy.update(); Group [] groups = Group.findAll (c, Group.NAME ); EPerson [] epeople = EPerson.findAll(c, EPerson.EMAIL); request.setAttribute( "edit_title", "Collection " + collection.getID() ); request.setAttribute( "policy", policy ); request.setAttribute( "groups", groups ); request.setAttribute( "epeople", epeople ); request.setAttribute( "id_name", "collection_id" ); request.setAttribute( "id", "" + collection.getID() ); JSPManager.showJSP(request, response, "/admin/authorize-policy-edit.jsp" ); } else if( button.equals("submit_community_select") ) { Community target = Community.find(c, UIUtil.getIntParameter(request, "community_id")); List policies = AuthorizeManager.getPolicies(c, target); request.setAttribute("community", target ); request.setAttribute("policies", policies ); JSPManager.showJSP(request, response, "/admin/authorize-community-edit.jsp" ); } else if( button.equals("submit_collection_delete_policy") ) { Collection collection = Collection.find(c, UIUtil.getIntParameter(request, "collection_id")); ResourcePolicy policy = ResourcePolicy.find(c, UIUtil.getIntParameter(request, "policy_id")); policy.delete(); request.setAttribute("collection", collection ); List policies = AuthorizeManager.getPolicies(c, collection); request.setAttribute("policies", policies); JSPManager.showJSP(request, response, "/admin/authorize-collection-edit.jsp" ); } else if( button.equals("submit_community_delete_policy") ) { Community community = Community.find(c, UIUtil.getIntParameter(request, "community_id")); ResourcePolicy policy = ResourcePolicy.find(c, UIUtil.getIntParameter(request, "policy_id")); policy.delete(); request.setAttribute("community", community ); List policies = AuthorizeManager.getPolicies(c, community); request.setAttribute("policies", policies); JSPManager.showJSP(request, response, "/admin/authorize-community-edit.jsp" ); } else if( button.equals("submit_collection_edit_policy") ) { Collection collection = Collection.find(c, UIUtil.getIntParameter(request, "collection_id")); int policy_id = UIUtil.getIntParameter(request, "policy_id"); ResourcePolicy policy = null; if( policy_id == -1 ) { policy = ResourcePolicy.create(c); policy.setResource( collection ); policy.update(); } else { policy = ResourcePolicy.find(c, policy_id); } Group [] groups = Group.findAll(c, Group.NAME); EPerson [] epeople = EPerson.findAll(c, EPerson.EMAIL); request.setAttribute( "edit_title", "Collection " + collection.getID() ); request.setAttribute( "policy", policy ); request.setAttribute( "groups", groups ); request.setAttribute( "epeople", epeople ); request.setAttribute( "id_name", "collection_id" ); request.setAttribute( "id", "" + collection.getID() ); JSPManager.showJSP(request, response, "/admin/authorize-policy-edit.jsp" ); } else if( button.equals("submit_community_edit_policy") ) { Community community = Community.find(c, UIUtil.getIntParameter(request, "community_id")); int policy_id = UIUtil.getIntParameter(request, "policy_id"); ResourcePolicy policy = null; if( policy_id == -1 ) { policy = ResourcePolicy.create(c); policy.setResource( community ); policy.update(); } else { policy = ResourcePolicy.find(c, policy_id); } Group [] groups = Group.findAll (c, Group.NAME ); EPerson [] epeople = EPerson.findAll(c, EPerson.EMAIL); request.setAttribute( "edit_title", "Community " + community.getID() ); request.setAttribute( "policy", policy ); request.setAttribute( "groups", groups ); request.setAttribute( "epeople", epeople ); request.setAttribute( "id_name", "community_id" ); request.setAttribute( "id", "" + community.getID() ); JSPManager.showJSP(request, response, "/admin/authorize-policy-edit.jsp" ); } else if( button.equals( "submit_collection_add_policy") ) { Collection collection = Collection.find(c, UIUtil.getIntParameter(request, "collection_id")); ResourcePolicy policy = ResourcePolicy.create(c); policy.setResource( collection ); policy.update(); Group [] groups = Group.findAll (c, Group.NAME ); EPerson [] epeople = EPerson.findAll(c, EPerson.EMAIL); request.setAttribute( "edit_title", "Collection " + collection.getID() ); request.setAttribute( "policy", policy ); request.setAttribute( "groups", groups ); request.setAttribute( "epeople", epeople ); request.setAttribute( "id_name", "collection_id" ); request.setAttribute( "id", "" + collection.getID() ); JSPManager.showJSP(request, response, "/admin/authorize-policy-edit.jsp" ); } else if( button.equals( "submit_community_add_policy") ) { Community community = Community.find(c, UIUtil.getIntParameter(request, "community_id")); ResourcePolicy policy = ResourcePolicy.create(c); policy.setResource( community ); policy.update(); Group [] groups = Group.findAll (c, Group.NAME ); EPerson [] epeople = EPerson.findAll(c, EPerson.EMAIL); request.setAttribute( "edit_title", "Community " + community.getID() ); request.setAttribute( "policy", policy ); request.setAttribute( "groups", groups ); request.setAttribute( "epeople", epeople ); request.setAttribute( "id_name", "community_id" ); request.setAttribute( "id", "" + community.getID() ); JSPManager.showJSP(request, response, "/admin/authorize-policy-edit.jsp" ); } else if( button.equals( "submit_save_policy" ) ) { int policy_id = UIUtil.getIntParameter(request, "policy_id" ); int action_id = UIUtil.getIntParameter(request, "action_id" ); int group_id = UIUtil.getIntParameter(request, "group_id" ); int collection_id = UIUtil.getIntParameter(request, "collection_id"); int community_id = UIUtil.getIntParameter(request, "community_id" ); int item_id = UIUtil.getIntParameter(request, "item_id" ); Item item = null; Collection collection = null; Community community = null; String display_page = null; ResourcePolicy policy = ResourcePolicy.find(c, policy_id); Group group = Group.find(c, group_id); if( collection_id != -1 ) { collection = Collection.find( c, collection_id ); policy.setAction ( action_id ); policy.setGroup ( group ); policy.update(); if( action_id == Constants.READ ) { List rps = AuthorizeManager.getPoliciesActionFilter(c, collection, Constants.READ); Bitstream bs = collection.getLogo(); if( bs != null ) { AuthorizeManager.removeAllPolicies(c, bs); AuthorizeManager.addPolicies(c, rps, bs); } } request.setAttribute("collection", collection ); request.setAttribute("policies", AuthorizeManager.getPolicies( c, collection ) ); display_page = "/admin/authorize-collection-edit.jsp"; } else if( community_id != -1 ) { community = Community.find( c, community_id ); policy.setAction ( action_id ); policy.setGroup ( group ); policy.update(); if( action_id == Constants.READ ) { List rps = AuthorizeManager.getPoliciesActionFilter(c, community, Constants.READ); Bitstream bs = community.getLogo(); if( bs != null ) { AuthorizeManager.removeAllPolicies(c, bs); AuthorizeManager.addPolicies(c, rps, bs); } } request.setAttribute("community", community ); request.setAttribute("policies", AuthorizeManager.getPolicies( c, community ) ); display_page = "/admin/authorize-community-edit.jsp"; } else if( item_id != -1 ) { item = Item.find( c, item_id ); policy.setAction ( action_id ); policy.setGroup ( group ); policy.update(); request.setAttribute("item", item ); request.setAttribute("item_policies", AuthorizeManager.getPolicies( c, item ) ); display_page = "/admin/authorize-item-edit.jsp"; } JSPManager.showJSP( request, response, display_page ); } else if( button.equals("submit_cancel_policy") ) { int collection_id =UIUtil.getIntParameter (request, "collection_id"); int community_id =UIUtil.getIntParameter (request, "community_id" ); String display_page = null; if( collection_id != -1 ) { Collection t = Collection.find( c, collection_id ); request.setAttribute("collection", t ); request.setAttribute("policies", AuthorizeManager.getPolicies( c, t ) ); display_page = "/admin/authorize-collection-edit.jsp"; } else if( community_id != -1 ) { Community t = Community.find( c, community_id ); request.setAttribute("community", t ); request.setAttribute("policies", AuthorizeManager.getPolicies( c, t ) ); display_page = "/admin/authorize-community-edit.jsp"; } JSPManager.showJSP(request, response, display_page ); } else if (button.equals("submit_advanced_clear")) { int collection_id = UIUtil.getIntParameter (request, "collection_id"); int resource_type = UIUtil.getIntParameter (request, "resource_type"); PolicySet.setPolicies(c, Constants.COLLECTION, collection_id, resource_type, 0, 0, false, true); if( resource_type == Constants.BITSTREAM ) { PolicySet.setPolicies(c, Constants.COLLECTION, collection_id, Constants.BUNDLE, 0, 0, false, true); } showMainPage(c, request, response); } else if (button.equals("submit_advanced_add")) { int collection_id = UIUtil.getIntParameter (request, "collection_id"); int resource_type = UIUtil.getIntParameter (request, "resource_type"); int action_id = UIUtil.getIntParameter (request, "action_id" ); int group_id = UIUtil.getIntParameter (request, "group_id" ); PolicySet.setPolicies(c, Constants.COLLECTION, collection_id, resource_type, action_id, group_id, false, false); if( resource_type == Constants.BITSTREAM ) { PolicySet.setPolicies(c, Constants.COLLECTION, collection_id, Constants.BUNDLE, action_id, group_id, false, false); } showMainPage(c, request, response); } else if( button.equals("submit_collection_select") ) { Collection collection = Collection.find(c, UIUtil.getIntParameter(request, "collection_id")); List policies = AuthorizeManager.getPolicies(c, collection); request.setAttribute("collection", collection ); request.setAttribute("policies", policies ); JSPManager.showJSP(request, response, "/admin/authorize-collection-edit.jsp" ); } else { showMainPage(c, request, response); } c.complete(); }
private ObjectWalk setUpWalker( final Collection<? extends ObjectId> interestingObjects, final Collection<? extends ObjectId> uninterestingObjects, final boolean ignoreMissingUninteresting) throws MissingObjectException, IOException, IncorrectObjectTypeException { final ObjectWalk walker = new ObjectWalk(db); walker.sort(RevSort.TOPO, true); walker.sort(RevSort.COMMIT_TIME_DESC, true); if (thin) walker.sort(RevSort.BOUNDARY); for (ObjectId id : interestingObjects) { RevObject o = walker.parseAny(id); walker.markStart(o); } for (ObjectId id : uninterestingObjects) { final RevObject o; try { o = walker.parseAny(id); } catch (MissingObjectException x) { if (ignoreMissingUninteresting) continue; throw x; } walker.markUninteresting(o); } return walker; }
private ObjectWalk setUpWalker( final Collection<? extends ObjectId> interestingObjects, final Collection<? extends ObjectId> uninterestingObjects, final boolean ignoreMissingUninteresting) throws MissingObjectException, IOException, IncorrectObjectTypeException { final ObjectWalk walker = new ObjectWalk(db); walker.sort(RevSort.TOPO); walker.sort(RevSort.COMMIT_TIME_DESC, true); if (thin) walker.sort(RevSort.BOUNDARY, true); for (ObjectId id : interestingObjects) { RevObject o = walker.parseAny(id); walker.markStart(o); } for (ObjectId id : uninterestingObjects) { final RevObject o; try { o = walker.parseAny(id); } catch (MissingObjectException x) { if (ignoreMissingUninteresting) continue; throw x; } walker.markUninteresting(o); } return walker; }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_query_recipe_offline_view); recipeController = new RecipeController(this); ingredController = new IngredientController(this); QuertRecipeList = recipeController.getQueryRecipeList(ingredController); recipeListView = (ListView) findViewById(R.id.queryRecipeOfflinelistView); recipeListAdapter = new ArrayAdapter<RecipeModel>(this, android.R.layout.simple_list_item_1, QuertRecipeList); recipeListView.setAdapter(recipeListAdapter); recipeListView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { dialogNumber = position; AlertDialog.Builder builder = new AlertDialog.Builder( QueryRecipeOfflineView.this); String title = QuertRecipeList.get(position).getRecipeName(); String message = QuertRecipeList.get(position).getRecipeDesc(); builder.setMessage(message); builder.setTitle(title); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setNeutralButton("View", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { try { Intent viewRecipe = new Intent( "activities.RecipeOnlineView"); viewRecipe.putExtra("Recipe", QuertRecipeList.get(dialogNumber)); startActivity(viewRecipe); } catch (Throwable throwable) { throwable.printStackTrace(); } dialog.dismiss(); } }); builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { recipeController.remove(recipeController .findRecipe(QuertRecipeList.get( dialogNumber).getRecipeName())); recipeController.saveToFile(); dialog.dismiss(); updateList(); } }); AlertDialog dialog = builder.create(); dialog.show(); } }); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_query_recipe_offline_view); recipeController = new RecipeController(this); ingredController = new IngredientController(this); QuertRecipeList = recipeController.getQueryRecipeList(ingredController); recipeListView = (ListView) findViewById(R.id.queryRecipeOfflinelistView); recipeListAdapter = new ArrayAdapter<RecipeModel>(this, android.R.layout.simple_list_item_1, QuertRecipeList); recipeListView.setAdapter(recipeListAdapter); recipeListView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { dialogNumber = position; AlertDialog.Builder builder = new AlertDialog.Builder( QueryRecipeOfflineView.this); String title = QuertRecipeList.get(position).getRecipeName(); String message = QuertRecipeList.get(position).getRecipeDesc(); builder.setMessage(message); builder.setTitle(title); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setNeutralButton("View", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { try { Intent viewRecipe = new Intent( "activities.ViewRecipe"); viewRecipe.putExtra("Recipe", QuertRecipeList.get(dialogNumber)); startActivity(viewRecipe); } catch (Throwable throwable) { throwable.printStackTrace(); } dialog.dismiss(); } }); builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { recipeController.remove(recipeController .findRecipe(QuertRecipeList.get( dialogNumber).getRecipeName())); recipeController.saveToFile(); dialog.dismiss(); updateList(); } }); AlertDialog dialog = builder.create(); dialog.show(); } }); }
public boolean execute(ArenaMaster am, CommandSender sender, String... args) { String arg1 = (args.length > 0 ? args[0] : ""); String arg2 = (args.length > 1 ? args[1] : ""); if (args.length != 2 || !arg1.matches("(-)?[0-9]+")) { Messenger.tellPlayer(sender, "Usage: /ma expandlobbyregion <amount> up|down|out"); return false; } if (!am.getSelectedArena().getRegion().isLobbyDefined()) { Messenger.tellPlayer(sender, "You must first define l1 and l2"); return true; } if (arg2.equals("up")) { am.getSelectedArena().getRegion().expandLobbyUp(Integer.parseInt(arg1)); } else if (arg2.equals("down")) { am.getSelectedArena().getRegion().expandLobbyDown(Integer.parseInt(arg1)); } else if (arg2.equals("out")) { am.getSelectedArena().getRegion().expandLobbyOut(Integer.parseInt(arg1)); } else { Messenger.tellPlayer(sender, "Usage: /ma expandlobbyregion <amount> up|down|out"); return true; } am.getSelectedArena().getRegion().fixRegion(); Messenger.tellPlayer(sender, "Lobby region for '" + am.getSelectedArena().configName() + "' expanded " + arg2 + " by " + arg1 + " blocks."); am.getSelectedArena().getRegion().save(); return true; }
public boolean execute(ArenaMaster am, CommandSender sender, String... args) { String arg1 = (args.length > 0 ? args[0] : ""); String arg2 = (args.length > 1 ? args[1] : ""); if (args.length != 2 || !arg1.matches("(-)?[0-9]+")) { Messenger.tellPlayer(sender, "Usage: /ma expandlobbyregion <amount> up|down|out"); return false; } if (!am.getSelectedArena().getRegion().isLobbyDefined()) { Messenger.tellPlayer(sender, "You must first define l1 and l2"); return true; } if (arg2.equals("up")) { am.getSelectedArena().getRegion().expandLobbyUp(Integer.parseInt(arg1)); } else if (arg2.equals("down")) { am.getSelectedArena().getRegion().expandLobbyDown(Integer.parseInt(arg1)); } else if (arg2.equals("out")) { am.getSelectedArena().getRegion().expandLobbyOut(Integer.parseInt(arg1)); } else { Messenger.tellPlayer(sender, "Usage: /ma expandlobbyregion <amount> up|down|out"); return true; } am.getSelectedArena().getRegion().fixLobbyRegion(); Messenger.tellPlayer(sender, "Lobby region for '" + am.getSelectedArena().configName() + "' expanded " + arg2 + " by " + arg1 + " blocks."); am.getSelectedArena().getRegion().save(); return true; }
public void testGetSuitableVideoSize() { doTestGetSuitableVideoSize(720, 540, 200, 320, 240); doTestGetSuitableVideoSize(720, 540, 300, 320, 240); doTestGetSuitableVideoSize(720, 540, 400, 320, 240); doTestGetSuitableVideoSize(720, 540, 500, 320, 240); doTestGetSuitableVideoSize(720, 540, 600, 320, 240); doTestGetSuitableVideoSize(720, 540, 700, 480, 360); doTestGetSuitableVideoSize(720, 540, 800, 480, 360); doTestGetSuitableVideoSize(720, 540, 900, 480, 360); doTestGetSuitableVideoSize(720, 540, 1000, 480, 360); doTestGetSuitableVideoSize(720, 540, 1100, 640, 480); doTestGetSuitableVideoSize(720, 540, 1200, 640, 480); doTestGetSuitableVideoSize(720, 540, 1500, 640, 480); doTestGetSuitableVideoSize(720, 540, 2000, 640, 480); doTestGetSuitableVideoSize(960, 540, 200, 427, 240); doTestGetSuitableVideoSize(960, 540, 300, 427, 240); doTestGetSuitableVideoSize(960, 540, 400, 427, 240); doTestGetSuitableVideoSize(960, 540, 500, 427, 240); doTestGetSuitableVideoSize(960, 540, 600, 427, 240); doTestGetSuitableVideoSize(960, 540, 700, 640, 360); doTestGetSuitableVideoSize(960, 540, 800, 640, 360); doTestGetSuitableVideoSize(960, 540, 900, 640, 360); doTestGetSuitableVideoSize(960, 540, 1000, 640, 360); doTestGetSuitableVideoSize(960, 540, 1100, 853, 480); doTestGetSuitableVideoSize(960, 540, 1200, 853, 480); doTestGetSuitableVideoSize(960, 540, 1500, 853, 480); doTestGetSuitableVideoSize(960, 540, 2000, 853, 480); doTestGetSuitableVideoSize(100, 100, 1000, 100, 100); doTestGetSuitableVideoSize(100, 1000, 1000, 100, 1000); doTestGetSuitableVideoSize(1000, 100, 100, 1000, 100); doTestGetSuitableVideoSize(720, null, 200, 320, 240); doTestGetSuitableVideoSize(null, 540, 300, 320, 240); doTestGetSuitableVideoSize(null, null, 400, 320, 240); doTestGetSuitableVideoSize(720, null, 500, 320, 240); doTestGetSuitableVideoSize(null, 540, 600, 320, 240); doTestGetSuitableVideoSize(null, null, 700, 480, 360); doTestGetSuitableVideoSize(720, null, 1200, 640, 480); doTestGetSuitableVideoSize(null, 540, 1500, 640, 480); doTestGetSuitableVideoSize(null, null, 2000, 640, 480); }
public void testGetSuitableVideoSize() { doTestGetSuitableVideoSize(720, 540, 200, 320, 240); doTestGetSuitableVideoSize(720, 540, 300, 320, 240); doTestGetSuitableVideoSize(720, 540, 400, 320, 240); doTestGetSuitableVideoSize(720, 540, 500, 320, 240); doTestGetSuitableVideoSize(720, 540, 600, 320, 240); doTestGetSuitableVideoSize(720, 540, 700, 480, 360); doTestGetSuitableVideoSize(720, 540, 800, 480, 360); doTestGetSuitableVideoSize(720, 540, 900, 480, 360); doTestGetSuitableVideoSize(720, 540, 1000, 480, 360); doTestGetSuitableVideoSize(720, 540, 1100, 640, 480); doTestGetSuitableVideoSize(720, 540, 1200, 640, 480); doTestGetSuitableVideoSize(720, 540, 1500, 640, 480); doTestGetSuitableVideoSize(720, 540, 2000, 640, 480); doTestGetSuitableVideoSize(960, 540, 200, 428, 240); doTestGetSuitableVideoSize(960, 540, 300, 428, 240); doTestGetSuitableVideoSize(960, 540, 400, 428, 240); doTestGetSuitableVideoSize(960, 540, 500, 428, 240); doTestGetSuitableVideoSize(960, 540, 600, 428, 240); doTestGetSuitableVideoSize(960, 540, 700, 640, 360); doTestGetSuitableVideoSize(960, 540, 800, 640, 360); doTestGetSuitableVideoSize(960, 540, 900, 640, 360); doTestGetSuitableVideoSize(960, 540, 1000, 640, 360); doTestGetSuitableVideoSize(960, 540, 1100, 854, 480); doTestGetSuitableVideoSize(960, 540, 1200, 854, 480); doTestGetSuitableVideoSize(960, 540, 1500, 854, 480); doTestGetSuitableVideoSize(960, 540, 2000, 854, 480); doTestGetSuitableVideoSize(100, 100, 1000, 100, 100); doTestGetSuitableVideoSize(100, 1000, 1000, 100, 1000); doTestGetSuitableVideoSize(1000, 100, 100, 1000, 100); doTestGetSuitableVideoSize(720, null, 200, 320, 240); doTestGetSuitableVideoSize(null, 540, 300, 320, 240); doTestGetSuitableVideoSize(null, null, 400, 320, 240); doTestGetSuitableVideoSize(720, null, 500, 320, 240); doTestGetSuitableVideoSize(null, 540, 600, 320, 240); doTestGetSuitableVideoSize(null, null, 700, 480, 360); doTestGetSuitableVideoSize(720, null, 1200, 640, 480); doTestGetSuitableVideoSize(null, 540, 1500, 640, 480); doTestGetSuitableVideoSize(null, null, 2000, 640, 480); }
protected Integer doInBackground(Void... params) { int progressTotal = 0; int progressStep = 0; switch (mCurrentStep) { case DOWNLOAD_MANIFEST: progressTotal = 4; progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_download_manifest); if (downloadFile(MANIFEST_URL, "manifest")) { publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); } else { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); return STATUS_FINISHED_FAIL; } progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_parse_manifest); if (mManifest == null) { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); return STATUS_FINISHED_FAIL; } publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_latest_version); publishProgress(progressTotal, progressStep, progressStep, mManifest.version, CONSOLE_GREEN); progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_check_installed_version); int installedVersionCode = Util.getSuVersionCode(); String installedVersion = Util.getSuVersion(); if (installedVersionCode < mManifest.versionCode) { publishProgress(progressTotal, progressStep, progressStep, installedVersion, CONSOLE_RED); mCurrentStep = Step.DOWNLOAD_BUSYBOX; return STATUS_AWAITING_ACTION; } else { publishProgress(progressTotal, progressStep, progressStep, installedVersion, CONSOLE_GREEN); mCurrentStep = Step.DOWNLOAD_BUSYBOX; return STATUS_FINISHED_NO_NEED; } case DOWNLOAD_BUSYBOX: boolean fixDb = (Util.getSuVersionCode() == 0); if (fixDb) { progressTotal = 16; progressStep = 1; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_fix_db); SQLiteDatabase db = null; try { db = getActivity().openOrCreateDatabase( "permissions.sqlite", Context.MODE_PRIVATE, null); db.execSQL("CREATE TABLE IF NOT EXISTS apps (_id INTEGER, uid INTEGER, " + "package TEXT, name TEXT, exec_uid INTEGER, exec_cmd TEXT, " + " allow INTEGER, PRIMARY KEY (_id), UNIQUE (uid,exec_uid,exec_cmd))"); db.execSQL("CREATE TABLE IF NOT EXISTS logs (_id INTEGER, app_id INTEGER, " + "date INTEGER, type INTEGER, PRIMARY KEY (_id))"); db.execSQL("CREATE TABLE IF NOT EXISTS prefs (_id INTEGER, key TEXT, " + "value TEXT, PRIMARY KEY (_id))"); } catch (SQLException e) { Log.e(TAG, "Failed to fix database", e); publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); return STATUS_FINISHED_FAIL; } finally { if (db != null) { db.close(); } } publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); } else { progressTotal = 15; progressStep = 0; } progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_download_busybox); if (downloadFile(mManifest.busyboxUrl, "busybox")) { try { Process process = new ProcessBuilder() .command("chmod", "755", mBusyboxPath) .redirectErrorStream(true).start(); Log.d(TAG, "chmod 755 " + mBusyboxPath); process.waitFor(); process.destroy(); } catch (IOException e) { Log.e(TAG, "Failed to set busybox to executable", e); publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); return STATUS_FINISHED_FAIL; } catch (InterruptedException e) { Log.w(TAG, "Process interrupted", e); } publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); } else { Log.e(TAG, "Failed to download busybox"); publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail); return STATUS_FINISHED_FAIL; } progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_check_md5sum); if (verifyFile(mBusyboxPath, mManifest.busyboxMd5)) { publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); } else { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); return STATUS_FINISHED_FAIL; } progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_check_installed_path); String installedSu = whichSu(); Log.d(TAG, "su installed to " + installedSu); if (installedSu == null) { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_find_su_failed); return STATUS_FINISHED_FAIL; } else if (installedSu.equals("/sbin/su")) { publishProgress(progressTotal, progressStep - 1, progressStep, installedSu, CONSOLE_RED); publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_bad_install_location); return STATUS_FINISHED_FAIL; } publishProgress(progressTotal, progressStep, progressStep, installedSu, CONSOLE_GREEN); progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_download_su); String suPath; if (downloadFile(mManifest.binaryUrl, "su")) { suPath = getActivity().getFileStreamPath("su").toString(); publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); } else { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); return STATUS_FINISHED_FAIL; } progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_check_md5sum); if (verifyFile(suPath, mManifest.binaryMd5)) { publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); } else { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); return STATUS_FINISHED_FAIL; } Process process = null; try { progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_get_root); process = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(process.getOutputStream()); BufferedReader is = new BufferedReader(new InputStreamReader( new DataInputStream(process.getInputStream())), 64); os.writeBytes("id\n"); String inLine = is.readLine(); if (inLine == null) { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); return STATUS_FINISHED_FAIL; } Pattern pattern = Pattern.compile("uid=([\\d]+)"); Matcher matcher = pattern.matcher(inLine); if (!matcher.find() || !matcher.group(1).equals("0")) { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); return STATUS_FINISHED_FAIL; } publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_remount_rw); executeCommand(os, null, mBusyboxPath + " mount -o remount,rw /system"); inLine = executeCommand(os, is, mBusyboxPath + " touch /system/su && " + mBusyboxPath + " echo YEAH"); if (inLine == null || !inLine.equals("YEAH")) { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_ok, CONSOLE_RED); return STATUS_FINISHED_FAIL; } publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_cp); inLine = executeCommand(os, is, mBusyboxPath, "cp", suPath, "/system &&", mBusyboxPath, "echo YEAH"); if (inLine == null || !inLine.equals("YEAH")) { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); return STATUS_FINISHED_FAIL; } publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_check_md5sum); inLine = executeCommand(os, is, mBusyboxPath, "md5sum /system/su"); if (inLine == null || !inLine.split(" ")[0].equals(mManifest.binaryMd5)) { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); return STATUS_FINISHED_FAIL; } publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_mv); inLine = executeCommand(os, is, mBusyboxPath, "mv /system/su", installedSu, "&&", mBusyboxPath, "echo YEAH"); if (inLine == null || !inLine.equals("YEAH")) { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); return STATUS_FINISHED_FAIL; } publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_check_md5sum); inLine = executeCommand(os, is, mBusyboxPath, "md5sum /system/bin/su"); if (inLine == null || !inLine.split(" ")[0].equals(mManifest.binaryMd5)) { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); return STATUS_FINISHED_FAIL; } publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_chmod); inLine = executeCommand(os, is, mBusyboxPath, "chmod 06755 /system/bin/su &&", mBusyboxPath, "echo YEAH"); if (inLine == null || !inLine.equals("YEAH")) { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); } publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_remount_ro); executeCommand(os, null, mBusyboxPath, "mount -o remount,ro /system"); inLine = executeCommand(os, is, mBusyboxPath, "touch /system/su ||", mBusyboxPath, "echo YEAH"); if (inLine == null || !inLine.equals("YEAH")) { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); publishProgress(progressTotal, progressStep, progressStep, R.string.updater_remount_ro_failed); } publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); os.writeBytes("exit\n"); } catch (IOException e) { Log.e(TAG, "Failed to execute root commands", e); } finally { process.destroy(); } progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_check_installed_version); installedVersionCode = Util.getSuVersionCode(); installedVersion = Util.getSuVersion(); if (installedVersionCode == mManifest.versionCode) { publishProgress(progressTotal, progressStep, progressStep, installedVersion, CONSOLE_GREEN); } else { publishProgress(progressTotal, progressStep, progressStep, installedVersion, CONSOLE_RED); mCurrentStep = Step.DOWNLOAD_BUSYBOX; return STATUS_FINISHED_FAIL; } progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_clean_up); getActivity().deleteFile("busybox"); getActivity().deleteFile("su"); if (fixDb) { getActivity().deleteDatabase("permissions.sqlite"); } publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); return STATUS_FINISHED_SUCCESSFUL; } return -1; }
protected Integer doInBackground(Void... params) { int progressTotal = 0; int progressStep = 0; switch (mCurrentStep) { case DOWNLOAD_MANIFEST: progressTotal = 4; progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_download_manifest); if (downloadFile(MANIFEST_URL, "manifest")) { publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); } else { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); return STATUS_FINISHED_FAIL; } progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_parse_manifest); if (mManifest == null) { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); return STATUS_FINISHED_FAIL; } publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_latest_version); publishProgress(progressTotal, progressStep, progressStep, mManifest.version, CONSOLE_GREEN); progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_check_installed_version); int installedVersionCode = Util.getSuVersionCode(); String installedVersion = Util.getSuVersion(); if (installedVersionCode < mManifest.versionCode) { publishProgress(progressTotal, progressStep, progressStep, installedVersion, CONSOLE_RED); mCurrentStep = Step.DOWNLOAD_BUSYBOX; return STATUS_AWAITING_ACTION; } else { publishProgress(progressTotal, progressStep, progressStep, installedVersion, CONSOLE_GREEN); mCurrentStep = Step.DOWNLOAD_BUSYBOX; return STATUS_FINISHED_NO_NEED; } case DOWNLOAD_BUSYBOX: boolean fixDb = (Util.getSuVersionCode() == 0); if (fixDb) { progressTotal = 16; progressStep = 1; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_fix_db); SQLiteDatabase db = null; try { db = getActivity().openOrCreateDatabase( "permissions.sqlite", Context.MODE_PRIVATE, null); db.execSQL("CREATE TABLE IF NOT EXISTS apps (_id INTEGER, uid INTEGER, " + "package TEXT, name TEXT, exec_uid INTEGER, exec_cmd TEXT, " + " allow INTEGER, PRIMARY KEY (_id), UNIQUE (uid,exec_uid,exec_cmd))"); db.execSQL("CREATE TABLE IF NOT EXISTS logs (_id INTEGER, app_id INTEGER, " + "date INTEGER, type INTEGER, PRIMARY KEY (_id))"); db.execSQL("CREATE TABLE IF NOT EXISTS prefs (_id INTEGER, key TEXT, " + "value TEXT, PRIMARY KEY (_id))"); } catch (SQLException e) { Log.e(TAG, "Failed to fix database", e); publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); return STATUS_FINISHED_FAIL; } finally { if (db != null) { db.close(); } } publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); } else { progressTotal = 15; progressStep = 0; } progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_download_busybox); if (downloadFile(mManifest.busyboxUrl, "busybox")) { try { Process process = new ProcessBuilder() .command("chmod", "755", mBusyboxPath) .redirectErrorStream(true).start(); Log.d(TAG, "chmod 755 " + mBusyboxPath); process.waitFor(); process.destroy(); } catch (IOException e) { Log.e(TAG, "Failed to set busybox to executable", e); publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); return STATUS_FINISHED_FAIL; } catch (InterruptedException e) { Log.w(TAG, "Process interrupted", e); } publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); } else { Log.e(TAG, "Failed to download busybox"); publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail); return STATUS_FINISHED_FAIL; } progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_check_md5sum); if (verifyFile(mBusyboxPath, mManifest.busyboxMd5)) { publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); } else { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); return STATUS_FINISHED_FAIL; } progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_check_installed_path); String installedSu = whichSu(); Log.d(TAG, "su installed to " + installedSu); if (installedSu == null) { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_find_su_failed); return STATUS_FINISHED_FAIL; } else if (installedSu.equals("/sbin/su")) { publishProgress(progressTotal, progressStep - 1, progressStep, installedSu, CONSOLE_RED); publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_bad_install_location); return STATUS_FINISHED_FAIL; } publishProgress(progressTotal, progressStep, progressStep, installedSu, CONSOLE_GREEN); progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_download_su); String suPath; if (downloadFile(mManifest.binaryUrl, "su")) { suPath = getActivity().getFileStreamPath("su").toString(); publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); } else { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); return STATUS_FINISHED_FAIL; } progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_check_md5sum); if (verifyFile(suPath, mManifest.binaryMd5)) { publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); } else { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); return STATUS_FINISHED_FAIL; } Process process = null; try { progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_get_root); process = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(process.getOutputStream()); BufferedReader is = new BufferedReader(new InputStreamReader( new DataInputStream(process.getInputStream())), 64); os.writeBytes("id\n"); String inLine = is.readLine(); if (inLine == null) { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); return STATUS_FINISHED_FAIL; } Pattern pattern = Pattern.compile("uid=([\\d]+)"); Matcher matcher = pattern.matcher(inLine); if (!matcher.find() || !matcher.group(1).equals("0")) { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); return STATUS_FINISHED_FAIL; } publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_remount_rw); executeCommand(os, null, mBusyboxPath + " mount -o remount,rw /system"); inLine = executeCommand(os, is, mBusyboxPath + " touch /system/su && " + mBusyboxPath + " echo YEAH"); if (inLine == null || !inLine.equals("YEAH")) { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_ok, CONSOLE_RED); return STATUS_FINISHED_FAIL; } publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_cp); inLine = executeCommand(os, is, mBusyboxPath, "cp", suPath, "/system &&", mBusyboxPath, "echo YEAH"); if (inLine == null || !inLine.equals("YEAH")) { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); return STATUS_FINISHED_FAIL; } publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_check_md5sum); inLine = executeCommand(os, is, mBusyboxPath, "md5sum /system/su"); if (inLine == null || !inLine.split(" ")[0].equals(mManifest.binaryMd5)) { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); return STATUS_FINISHED_FAIL; } publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_mv); inLine = executeCommand(os, is, mBusyboxPath, "mv /system/su", installedSu, "&&", mBusyboxPath, "echo YEAH"); if (inLine == null || !inLine.equals("YEAH")) { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); return STATUS_FINISHED_FAIL; } publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_check_md5sum); inLine = executeCommand(os, is, mBusyboxPath, "md5sum", installedSu); if (inLine == null || !inLine.split(" ")[0].equals(mManifest.binaryMd5)) { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); return STATUS_FINISHED_FAIL; } publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_chmod); inLine = executeCommand(os, is, mBusyboxPath, "chmod 06755", installedSu, "&&", mBusyboxPath, "echo YEAH"); if (inLine == null || !inLine.equals("YEAH")) { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); } publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_remount_ro); executeCommand(os, null, mBusyboxPath, "mount -o remount,ro /system"); inLine = executeCommand(os, is, mBusyboxPath, "touch /system/su ||", mBusyboxPath, "echo YEAH"); if (inLine == null || !inLine.equals("YEAH")) { publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_fail, CONSOLE_RED); publishProgress(progressTotal, progressStep, progressStep, R.string.updater_remount_ro_failed); } publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); os.writeBytes("exit\n"); } catch (IOException e) { Log.e(TAG, "Failed to execute root commands", e); } finally { process.destroy(); } progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_check_installed_version); installedVersionCode = Util.getSuVersionCode(); installedVersion = Util.getSuVersion(); if (installedVersionCode == mManifest.versionCode) { publishProgress(progressTotal, progressStep, progressStep, installedVersion, CONSOLE_GREEN); } else { publishProgress(progressTotal, progressStep, progressStep, installedVersion, CONSOLE_RED); mCurrentStep = Step.DOWNLOAD_BUSYBOX; return STATUS_FINISHED_FAIL; } progressStep++; publishProgress(progressTotal, progressStep - 1, progressStep, R.string.updater_step_clean_up); getActivity().deleteFile("busybox"); getActivity().deleteFile("su"); if (fixDb) { getActivity().deleteDatabase("permissions.sqlite"); } publishProgress(progressTotal, progressStep, progressStep, R.string.updater_ok, CONSOLE_GREEN); return STATUS_FINISHED_SUCCESSFUL; } return -1; }
private void slideDownSlope(Player player, Vector2 pos, Vector2 vel, float dt) { if (player.isOnGround()) { int[] block = heightMap.getBlock((int) pos.x - 1, Player.WIDTH + 3); int maxIndex = -1, maxHeight = -1; for (int i = 1; i < block.length; i++) { int height = block[i]; if (maxHeight < height) { maxIndex = i; maxHeight = height; } } if (maxIndex == 1) { int slope = (int) pos.y - block[2]; if (slope > Player.MIN_SLIDE_SLOPE) { vel.x += 500 * dt; vel.y -= 50 * dt; } } else if (maxIndex == Player.WIDTH + 1) { int slope = (int) pos.y - block[Player.WIDTH]; if (slope > Player.MIN_SLIDE_SLOPE) { vel.x -= 500 * dt; vel.y -= 50 * dt; } } } }
private void slideDownSlope(Player player, Vector2 pos, Vector2 vel, float dt) { if (player.isOnGround()) { int[] block = heightMap.getBlock((int) pos.x - 1, Player.WIDTH + 3); int maxIndex = -1, maxHeight = -1; for (int i = 1; i < block.length; i++) { int height = block[i]; if (maxHeight < height) { maxIndex = i; maxHeight = height; } } if (maxIndex == 1) { int slope = (int) pos.y - block[2]; if (slope > Player.MIN_SLIDE_SLOPE) { vel.x += 500 * dt; vel.y -= 50 * dt; } } else if (maxIndex == Player.WIDTH + 2) { int slope = (int) pos.y - block[Player.WIDTH - 1]; if (slope > Player.MIN_SLIDE_SLOPE) { vel.x -= 500 * dt; vel.y -= 50 * dt; } } } }
public RecordType fromJson(ObjectNode node, Namespaces namespaces, Repository repository) throws JsonFormatException, RepositoryException, InterruptedException { TypeManager typeManager = repository.getTypeManager(); QName name = QNameConverter.fromJson(getString(node, "name"), namespaces); RecordType recordType = typeManager.newRecordType(name); String id = getString(node, "id", null); if (id != null) recordType.setId(id); if (node.get("fields") != null) { ArrayNode fields = getArray(node, "fields"); for (int i = 0; i < fields.size(); i++) { JsonNode field = fields.get(i); boolean mandatory = getBoolean(field, "mandatory", false); String fieldId = getString(field, "id", null); String fieldName = getString(field, "name", null); if (fieldId != null) { recordType.addFieldTypeEntry(fieldId, mandatory); } else if (fieldName != null) { QName fieldQName = QNameConverter.fromJson(fieldName, namespaces); try { fieldId = typeManager.getFieldTypeByName(fieldQName).getId(); } catch (RepositoryException e) { throw new JsonFormatException("Record type " + name + ": error looking up field type with name: " + fieldQName, e); } recordType.addFieldTypeEntry(fieldId, mandatory); } else { throw new JsonFormatException("Record type " + name + ": field entry should specify an id or name"); } } } if (node.get("mixins") != null) { ArrayNode mixins = getArray(node, "mixins", null); for (int i = 0; i < mixins.size(); i++) { JsonNode mixin = mixins.get(i); String rtId = getString(mixin, "id", null); String rtName = getString(mixin, "name", null); Long rtVersion = getLong(mixin, "version", null); if (rtId != null) { recordType.addMixin(rtId, rtVersion); } else if (rtName != null) { QName rtQName = QNameConverter.fromJson(rtName, namespaces); try { rtId = typeManager.getRecordTypeByName(rtQName, null).getId(); } catch (RepositoryException e) { throw new JsonFormatException("Record type " + name + ": error looking up mixin record type with name: " + rtQName, e); } recordType.addMixin(rtId, rtVersion == -1 ? null : rtVersion); } else { throw new JsonFormatException("Record type " + name + ": mixin should specify an id or name"); } } } return recordType; }
public RecordType fromJson(ObjectNode node, Namespaces namespaces, Repository repository) throws JsonFormatException, RepositoryException, InterruptedException { TypeManager typeManager = repository.getTypeManager(); QName name = QNameConverter.fromJson(getString(node, "name"), namespaces); RecordType recordType = typeManager.newRecordType(name); String id = getString(node, "id", null); if (id != null) recordType.setId(id); if (node.get("fields") != null) { ArrayNode fields = getArray(node, "fields"); for (int i = 0; i < fields.size(); i++) { JsonNode field = fields.get(i); boolean mandatory = getBoolean(field, "mandatory", false); String fieldId = getString(field, "id", null); String fieldName = getString(field, "name", null); if (fieldId != null) { recordType.addFieldTypeEntry(fieldId, mandatory); } else if (fieldName != null) { QName fieldQName = QNameConverter.fromJson(fieldName, namespaces); try { fieldId = typeManager.getFieldTypeByName(fieldQName).getId(); } catch (RepositoryException e) { throw new JsonFormatException("Record type " + name + ": error looking up field type with name: " + fieldQName, e); } recordType.addFieldTypeEntry(fieldId, mandatory); } else { throw new JsonFormatException("Record type " + name + ": field entry should specify an id or name"); } } } if (node.get("mixins") != null) { ArrayNode mixins = getArray(node, "mixins", null); for (int i = 0; i < mixins.size(); i++) { JsonNode mixin = mixins.get(i); String rtId = getString(mixin, "id", null); String rtName = getString(mixin, "name", null); Long rtVersion = getLong(mixin, "version", null); if (rtId != null) { recordType.addMixin(rtId, rtVersion); } else if (rtName != null) { QName rtQName = QNameConverter.fromJson(rtName, namespaces); try { rtId = typeManager.getRecordTypeByName(rtQName, null).getId(); } catch (RepositoryException e) { throw new JsonFormatException("Record type " + name + ": error looking up mixin record type with name: " + rtQName, e); } recordType.addMixin(rtId, rtVersion); } else { throw new JsonFormatException("Record type " + name + ": mixin should specify an id or name"); } } } return recordType; }
public TikaConfig(Element element) throws TikaException, IOException { Element mtr = getChild(element, "mimeTypeRepository"); if (mtr != null) { mimeTypes = MimeTypesFactory.create(mtr.getAttribute("resource")); } NodeList nodes = element.getElementsByTagName("parser"); for (int i = 0; i < nodes.getLength(); i++) { Element node = (Element) nodes.item(i); String name = node.getAttribute("class"); try { Parser parser = (Parser) Class.forName(name).newInstance(); NodeList mimes = node.getElementsByTagName("mime"); for (int j = 0; j < mimes.getLength(); j++) { parsers.put(getText(mimes.item(j)).trim(), parser); } } catch (Exception e) { throw new TikaException( "Invalid parser configuration: " + name, e); } } }
public TikaConfig(Element element) throws TikaException, IOException { Element mtr = getChild(element, "mimeTypeRepository"); if (mtr != null) { mimeTypes = MimeTypesFactory.create(mtr.getAttribute("resource")); } NodeList nodes = element.getElementsByTagName("parser"); for (int i = 0; i < nodes.getLength(); i++) { Element node = (Element) nodes.item(i); String name = node.getAttribute("class"); try { Parser parser = (Parser) Class.forName(name).newInstance(); NodeList mimes = node.getElementsByTagName("mime"); for (int j = 0; j < mimes.getLength(); j++) { parsers.put(getText(mimes.item(j)).trim(), parser); } } catch (Throwable t) { } } }
public static void checkPerformance() { final int COUNT = 100000; System.out.println("Checking performance of different access methods (" + COUNT + " iterations)"); final int SIZE = 8*1024; ByteBuffer b = ByteBuffer.allocateDirect(SIZE); b.order(ByteOrder.nativeOrder()); Pointer pb = Native.getDirectBufferPointer(b); String mname = Platform.isWindows()?"msvcrt":"m"; MathInterface mlib = (MathInterface) Native.loadLibrary(mname, MathInterface.class); Function f = NativeLibrary.getInstance(mname).getFunction("cos"); Object[] args = { new Double(0) }; double dresult; long start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { dresult = mlib.cos(0d); } long delta = System.currentTimeMillis() - start; System.out.println("cos (JNA interface): " + delta + "ms"); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { dresult = f.invokeDouble(args); } delta = System.currentTimeMillis() - start; System.out.println("cos (JNA function): " + delta + "ms"); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { dresult = MathLibrary.cos(0d); } delta = System.currentTimeMillis() - start; System.out.println("cos (JNA direct): " + delta + "ms"); long types = pb.peer; long cif; long resp; long argv; if (Native.POINTER_SIZE == 4) { b.putInt(0, (int)Structure.FFIType.get(double.class).peer); cif = Native.ffi_prep_cif(0, 1, Structure.FFIType.get(double.class).peer, types); resp = pb.peer + 4; argv = pb.peer + 12; double INPUT = 42; start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { b.putInt(12, (int)pb.peer + 16); b.putDouble(16, INPUT); Native.ffi_call(cif, f.peer, resp, argv); dresult = b.getDouble(4); } delta = System.currentTimeMillis() - start; } else { b.putLong(0, Structure.FFIType.get(double.class).peer); cif = Native.ffi_prep_cif(0, 1, Structure.FFIType.get(double.class).peer, types); resp = pb.peer + 8; argv = pb.peer + 16; double INPUT = 42; start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { b.putLong(16, pb.peer + 24); b.putDouble(24, INPUT); Native.ffi_call(cif, f.peer, resp, argv); dresult = b.getDouble(8); } delta = System.currentTimeMillis() - start; } System.out.println("cos (JNI ffi): " + delta + "ms"); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { dresult = JNI.cos(0d); } delta = System.currentTimeMillis() - start; System.out.println("cos (JNI): " + delta + "ms"); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { dresult = Math.cos(0d); } delta = System.currentTimeMillis() - start; System.out.println("cos (pure java): " + delta + "ms"); Pointer presult; String cname = Platform.isWindows()?"msvcrt":"c"; CInterface clib = (CInterface) Native.loadLibrary(cname, CInterface.class); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { presult = clib.memset(null, 0, 0); } delta = System.currentTimeMillis() - start; System.out.println("memset (JNA interface): " + delta + "ms"); f = NativeLibrary.getInstance(cname).getFunction("memset"); args = new Object[] { null, new Integer(0), new Integer(0)}; start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { presult = f.invokePointer(args); } delta = System.currentTimeMillis() - start; System.out.println("memset (JNA function): " + delta + "ms"); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { presult = CLibrary.memset((Pointer)null, 0, new CLibrary.size_t(0)); } delta = System.currentTimeMillis() - start; System.out.println("memset (JNA direct Pointer/size_t): " + delta + "ms"); start = System.currentTimeMillis(); if (Native.POINTER_SIZE == 4) { for (int i=0;i < COUNT;i++) { presult = CLibrary.memset((Pointer)null, 0, 0); } } else { for (int i=0;i < COUNT;i++) { presult = CLibrary.memset((Pointer)null, 0, 0L); } } delta = System.currentTimeMillis() - start; System.out.println("memset (JNA direct Pointer/primitive): " + delta + "ms"); int iresult; long jresult; start = System.currentTimeMillis(); if (Native.POINTER_SIZE == 4) { for (int i=0;i < COUNT;i++) { iresult = CLibrary.memset(0, 0, 0); } } else { for (int i=0;i < COUNT;i++) { jresult = CLibrary.memset(0L, 0, 0L); } } delta = System.currentTimeMillis() - start; System.out.println("memset (JNA direct primitives): " + delta + "ms"); if (Native.POINTER_SIZE == 4) { b.putInt(0, (int)Structure.FFIType.get(Pointer.class).peer); b.putInt(4, (int)Structure.FFIType.get(int.class).peer); b.putInt(8, (int)Structure.FFIType.get(int.class).peer); cif = Native.ffi_prep_cif(0, 3, Structure.FFIType.get(Pointer.class).peer, types); resp = pb.peer + 12; argv = pb.peer + 16; start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { b.putInt(16, (int)pb.peer + 28); b.putInt(20, (int)pb.peer + 32); b.putInt(24, (int)pb.peer + 36); b.putInt(28, 0); b.putInt(32, 0); b.putInt(36, 0); Native.ffi_call(cif, f.peer, resp, argv); b.getInt(12); } delta = System.currentTimeMillis() - start; } else { b.putLong(0, Structure.FFIType.get(Pointer.class).peer); b.putLong(8, Structure.FFIType.get(int.class).peer); b.putLong(16, Structure.FFIType.get(long.class).peer); cif = Native.ffi_prep_cif(0, 3, Structure.FFIType.get(Pointer.class).peer, types); resp = pb.peer + 24; argv = pb.peer + 32; start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { b.putLong(32, pb.peer + 56); b.putLong(40, pb.peer + 64); b.putLong(48, pb.peer + 72); b.putLong(56, 0); b.putInt(64, 0); b.putLong(72, 0); Native.ffi_call(cif, f.peer, resp, argv); b.getLong(24); } delta = System.currentTimeMillis() - start; } System.out.println("memset (JNI ffi): " + delta + "ms"); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { Native.setMemory(0L, 0L, (byte)0); } delta = System.currentTimeMillis() - start; System.out.println("memset (JNI): " + delta + "ms"); String str = "performance test"; start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { iresult = clib.strlen(str); } delta = System.currentTimeMillis() - start; System.out.println("strlen (JNA interface): " + delta + "ms"); f = NativeLibrary.getInstance(cname).getFunction("strlen"); args = new Object[] { str }; start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { iresult = f.invokeInt(args); } delta = System.currentTimeMillis() - start; System.out.println("strlen (JNA function): " + delta + "ms"); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { iresult = CLibrary.strlen(str); } delta = System.currentTimeMillis() - start; System.out.println("strlen (JNA direct - String): " + delta + "ms"); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { iresult = CLibrary.strlen(new NativeString(str).getPointer()); } delta = System.currentTimeMillis() - start; System.out.println("strlen (JNA direct - Pointer): " + delta + "ms"); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { iresult = CLibrary.strlen(Native.toByteArray(str)); } delta = System.currentTimeMillis() - start; System.out.println("strlen (JNA direct - byte[]): " + delta + "ms"); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { byte[] bytes = str.getBytes(); b.position(0); b.put(bytes); b.put((byte)0); iresult = CLibrary.strlen(b); } delta = System.currentTimeMillis() - start; System.out.println("strlen (JNA direct - Buffer): " + delta + "ms"); if (Native.POINTER_SIZE == 4) { b.putInt(0, (int)Structure.FFIType.get(Pointer.class).peer); cif = Native.ffi_prep_cif(0, 1, Structure.FFIType.get(int.class).peer, types); resp = pb.peer + 4; argv = pb.peer + 8; start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { b.putInt(8, (int)pb.peer + 12); b.putInt(12, (int)pb.peer + 16); b.position(16); b.put(str.getBytes()); b.put((byte)0); Native.ffi_call(cif, f.peer, resp, argv); iresult = b.getInt(4); } delta = System.currentTimeMillis() - start; } else { b.putLong(0, Structure.FFIType.get(Pointer.class).peer); cif = Native.ffi_prep_cif(0, 1, Structure.FFIType.get(long.class).peer, types); resp = pb.peer + 8; argv = pb.peer + 16; start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { b.putLong(16, pb.peer + 24); b.putLong(24, pb.peer + 32); b.position(32); b.put(str.getBytes()); b.put((byte)0); Native.ffi_call(cif, f.peer, resp, argv); jresult = b.getLong(8); } delta = System.currentTimeMillis() - start; } System.out.println("strlen (JNI ffi): " + delta + "ms"); byte[] bulk = new byte[SIZE]; start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { b.putInt(0, 0); } delta = System.currentTimeMillis() - start; System.out.println("direct Buffer write: " + delta + "ms"); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { b.position(0); b.put(bulk); } delta = System.currentTimeMillis() - start; System.out.println("direct Buffer write (bulk): " + delta + "ms"); Pointer p = new Memory(SIZE); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { p.setInt(0, 0); } delta = System.currentTimeMillis() - start; System.out.println("Memory write: " + delta + "ms"); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { p.write(0, bulk, 0, bulk.length); } delta = System.currentTimeMillis() - start; System.out.println("Memory write (bulk): " + delta + "ms"); TestInterface tlib = (TestInterface)Native.loadLibrary("testlib", TestInterface.class); start = System.currentTimeMillis(); TestInterface.Int32Callback cb = new TestInterface.Int32Callback() { public int invoke(int arg1, int arg2) { return arg1 + arg2; } }; tlib.callInt32CallbackRepeatedly(cb, 1, 2, COUNT); delta = System.currentTimeMillis() - start; System.out.println("callback (JNA interface): " + delta + "ms"); tlib = new TestLibrary(); start = System.currentTimeMillis(); tlib.callInt32CallbackRepeatedly(cb, 1, 2, COUNT); delta = System.currentTimeMillis() - start; System.out.println("callback (JNA direct): " + delta + "ms"); start = System.currentTimeMillis(); TestInterface.NativeLongCallback nlcb = new TestInterface.NativeLongCallback() { public NativeLong invoke(NativeLong arg1, NativeLong arg2) { return new NativeLong(arg1.longValue() + arg2.longValue()); } }; tlib.callLongCallbackRepeatedly(nlcb, new NativeLong(1), new NativeLong(2), COUNT); delta = System.currentTimeMillis() - start; System.out.println("callback w/NativeMapped (JNA interface): " + delta + "ms"); tlib = new TestLibrary(); start = System.currentTimeMillis(); tlib.callLongCallbackRepeatedly(nlcb, new NativeLong(1), new NativeLong(2), COUNT); delta = System.currentTimeMillis() - start; System.out.println("callback w/NativeMapped (JNA direct): " + delta + "ms"); }
public static void checkPerformance() { final int COUNT = 100000; System.out.println("Checking performance of different access methods (" + COUNT + " iterations)"); final int SIZE = 8*1024; ByteBuffer b = ByteBuffer.allocateDirect(SIZE); b.order(ByteOrder.nativeOrder()); Pointer pb = Native.getDirectBufferPointer(b); String mname = Platform.isWindows()?"msvcrt":"m"; MathInterface mlib = (MathInterface) Native.loadLibrary(mname, MathInterface.class); Function f = NativeLibrary.getInstance(mname).getFunction("cos"); Object[] args = { new Double(0) }; double dresult; long start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { dresult = mlib.cos(0d); } long delta = System.currentTimeMillis() - start; System.out.println("cos (JNA interface): " + delta + "ms"); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { dresult = f.invokeDouble(args); } delta = System.currentTimeMillis() - start; System.out.println("cos (JNA function): " + delta + "ms"); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { dresult = MathLibrary.cos(0d); } delta = System.currentTimeMillis() - start; System.out.println("cos (JNA direct): " + delta + "ms"); long types = pb.peer; long cif; long resp; long argv; if (Native.POINTER_SIZE == 4) { b.putInt(0, (int)Structure.FFIType.get(double.class).peer); cif = Native.ffi_prep_cif(0, 1, Structure.FFIType.get(double.class).peer, types); resp = pb.peer + 4; argv = pb.peer + 12; double INPUT = 42; start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { b.putInt(12, (int)pb.peer + 16); b.putDouble(16, INPUT); Native.ffi_call(cif, f.peer, resp, argv); dresult = b.getDouble(4); } delta = System.currentTimeMillis() - start; } else { b.putLong(0, Structure.FFIType.get(double.class).peer); cif = Native.ffi_prep_cif(1, 1, Structure.FFIType.get(double.class).peer, types); resp = pb.peer + 8; argv = pb.peer + 16; double INPUT = 42; start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { b.putLong(16, pb.peer + 24); b.putDouble(24, INPUT); Native.ffi_call(cif, f.peer, resp, argv); dresult = b.getDouble(8); } delta = System.currentTimeMillis() - start; } System.out.println("cos (JNI ffi): " + delta + "ms"); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { dresult = JNI.cos(0d); } delta = System.currentTimeMillis() - start; System.out.println("cos (JNI): " + delta + "ms"); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { dresult = Math.cos(0d); } delta = System.currentTimeMillis() - start; System.out.println("cos (pure java): " + delta + "ms"); Pointer presult; String cname = Platform.isWindows()?"msvcrt":"c"; CInterface clib = (CInterface) Native.loadLibrary(cname, CInterface.class); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { presult = clib.memset(null, 0, 0); } delta = System.currentTimeMillis() - start; System.out.println("memset (JNA interface): " + delta + "ms"); f = NativeLibrary.getInstance(cname).getFunction("memset"); args = new Object[] { null, new Integer(0), new Integer(0)}; start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { presult = f.invokePointer(args); } delta = System.currentTimeMillis() - start; System.out.println("memset (JNA function): " + delta + "ms"); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { presult = CLibrary.memset((Pointer)null, 0, new CLibrary.size_t(0)); } delta = System.currentTimeMillis() - start; System.out.println("memset (JNA direct Pointer/size_t): " + delta + "ms"); start = System.currentTimeMillis(); if (Native.POINTER_SIZE == 4) { for (int i=0;i < COUNT;i++) { presult = CLibrary.memset((Pointer)null, 0, 0); } } else { for (int i=0;i < COUNT;i++) { presult = CLibrary.memset((Pointer)null, 0, 0L); } } delta = System.currentTimeMillis() - start; System.out.println("memset (JNA direct Pointer/primitive): " + delta + "ms"); int iresult; long jresult; start = System.currentTimeMillis(); if (Native.POINTER_SIZE == 4) { for (int i=0;i < COUNT;i++) { iresult = CLibrary.memset(0, 0, 0); } } else { for (int i=0;i < COUNT;i++) { jresult = CLibrary.memset(0L, 0, 0L); } } delta = System.currentTimeMillis() - start; System.out.println("memset (JNA direct primitives): " + delta + "ms"); if (Native.POINTER_SIZE == 4) { b.putInt(0, (int)Structure.FFIType.get(Pointer.class).peer); b.putInt(4, (int)Structure.FFIType.get(int.class).peer); b.putInt(8, (int)Structure.FFIType.get(int.class).peer); cif = Native.ffi_prep_cif(0, 3, Structure.FFIType.get(Pointer.class).peer, types); resp = pb.peer + 12; argv = pb.peer + 16; start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { b.putInt(16, (int)pb.peer + 28); b.putInt(20, (int)pb.peer + 32); b.putInt(24, (int)pb.peer + 36); b.putInt(28, 0); b.putInt(32, 0); b.putInt(36, 0); Native.ffi_call(cif, f.peer, resp, argv); b.getInt(12); } delta = System.currentTimeMillis() - start; } else { b.putLong(0, Structure.FFIType.get(Pointer.class).peer); b.putLong(8, Structure.FFIType.get(int.class).peer); b.putLong(16, Structure.FFIType.get(long.class).peer); cif = Native.ffi_prep_cif(0, 3, Structure.FFIType.get(Pointer.class).peer, types); resp = pb.peer + 24; argv = pb.peer + 32; start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { b.putLong(32, pb.peer + 56); b.putLong(40, pb.peer + 64); b.putLong(48, pb.peer + 72); b.putLong(56, 0); b.putInt(64, 0); b.putLong(72, 0); Native.ffi_call(cif, f.peer, resp, argv); b.getLong(24); } delta = System.currentTimeMillis() - start; } System.out.println("memset (JNI ffi): " + delta + "ms"); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { Native.setMemory(0L, 0L, (byte)0); } delta = System.currentTimeMillis() - start; System.out.println("memset (JNI): " + delta + "ms"); String str = "performance test"; start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { iresult = clib.strlen(str); } delta = System.currentTimeMillis() - start; System.out.println("strlen (JNA interface): " + delta + "ms"); f = NativeLibrary.getInstance(cname).getFunction("strlen"); args = new Object[] { str }; start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { iresult = f.invokeInt(args); } delta = System.currentTimeMillis() - start; System.out.println("strlen (JNA function): " + delta + "ms"); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { iresult = CLibrary.strlen(str); } delta = System.currentTimeMillis() - start; System.out.println("strlen (JNA direct - String): " + delta + "ms"); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { iresult = CLibrary.strlen(new NativeString(str).getPointer()); } delta = System.currentTimeMillis() - start; System.out.println("strlen (JNA direct - Pointer): " + delta + "ms"); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { iresult = CLibrary.strlen(Native.toByteArray(str)); } delta = System.currentTimeMillis() - start; System.out.println("strlen (JNA direct - byte[]): " + delta + "ms"); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { byte[] bytes = str.getBytes(); b.position(0); b.put(bytes); b.put((byte)0); iresult = CLibrary.strlen(b); } delta = System.currentTimeMillis() - start; System.out.println("strlen (JNA direct - Buffer): " + delta + "ms"); if (Native.POINTER_SIZE == 4) { b.putInt(0, (int)Structure.FFIType.get(Pointer.class).peer); cif = Native.ffi_prep_cif(0, 1, Structure.FFIType.get(int.class).peer, types); resp = pb.peer + 4; argv = pb.peer + 8; start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { b.putInt(8, (int)pb.peer + 12); b.putInt(12, (int)pb.peer + 16); b.position(16); b.put(str.getBytes()); b.put((byte)0); Native.ffi_call(cif, f.peer, resp, argv); iresult = b.getInt(4); } delta = System.currentTimeMillis() - start; } else { b.putLong(0, Structure.FFIType.get(Pointer.class).peer); cif = Native.ffi_prep_cif(0, 1, Structure.FFIType.get(long.class).peer, types); resp = pb.peer + 8; argv = pb.peer + 16; start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { b.putLong(16, pb.peer + 24); b.putLong(24, pb.peer + 32); b.position(32); b.put(str.getBytes()); b.put((byte)0); Native.ffi_call(cif, f.peer, resp, argv); jresult = b.getLong(8); } delta = System.currentTimeMillis() - start; } System.out.println("strlen (JNI ffi): " + delta + "ms"); byte[] bulk = new byte[SIZE]; start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { b.putInt(0, 0); } delta = System.currentTimeMillis() - start; System.out.println("direct Buffer write: " + delta + "ms"); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { b.position(0); b.put(bulk); } delta = System.currentTimeMillis() - start; System.out.println("direct Buffer write (bulk): " + delta + "ms"); Pointer p = new Memory(SIZE); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { p.setInt(0, 0); } delta = System.currentTimeMillis() - start; System.out.println("Memory write: " + delta + "ms"); start = System.currentTimeMillis(); for (int i=0;i < COUNT;i++) { p.write(0, bulk, 0, bulk.length); } delta = System.currentTimeMillis() - start; System.out.println("Memory write (bulk): " + delta + "ms"); TestInterface tlib = (TestInterface)Native.loadLibrary("testlib", TestInterface.class); start = System.currentTimeMillis(); TestInterface.Int32Callback cb = new TestInterface.Int32Callback() { public int invoke(int arg1, int arg2) { return arg1 + arg2; } }; tlib.callInt32CallbackRepeatedly(cb, 1, 2, COUNT); delta = System.currentTimeMillis() - start; System.out.println("callback (JNA interface): " + delta + "ms"); tlib = new TestLibrary(); start = System.currentTimeMillis(); tlib.callInt32CallbackRepeatedly(cb, 1, 2, COUNT); delta = System.currentTimeMillis() - start; System.out.println("callback (JNA direct): " + delta + "ms"); start = System.currentTimeMillis(); TestInterface.NativeLongCallback nlcb = new TestInterface.NativeLongCallback() { public NativeLong invoke(NativeLong arg1, NativeLong arg2) { return new NativeLong(arg1.longValue() + arg2.longValue()); } }; tlib.callLongCallbackRepeatedly(nlcb, new NativeLong(1), new NativeLong(2), COUNT); delta = System.currentTimeMillis() - start; System.out.println("callback w/NativeMapped (JNA interface): " + delta + "ms"); tlib = new TestLibrary(); start = System.currentTimeMillis(); tlib.callLongCallbackRepeatedly(nlcb, new NativeLong(1), new NativeLong(2), COUNT); delta = System.currentTimeMillis() - start; System.out.println("callback w/NativeMapped (JNA direct): " + delta + "ms"); }
public boolean select(Viewer viewer, Object parent, Object element) { if (element instanceof MarkerItem) { if (element.getClass().getSimpleName().equals("MarkerCategory")) { try { if (markerCategoryMethod == null) { Class<?> markerCategoryClass = Class.forName("org.eclipse.ui.internal.views.markers.MarkerCategory"); markerCategoryMethod = markerCategoryClass.getDeclaredMethod("getChildren", new Class[] {}); markerCategoryMethod.setAccessible(true); } Object[] entries = (Object[]) markerCategoryMethod.invoke(element, new Object[] {}); if (entries != null && entries.length == 0) { return false; } else if (entries != null && entries.length != 0) { for (Object markerEntry : entries) { if (markerEntry.getClass().getSimpleName().equals("MarkerEntry") && isInteresting(((MarkerItem) markerEntry).getMarker(), viewer, parent)) { return true; } } return false; } } catch (Exception e) { StatusHandler.log(new Status(IStatus.ERROR, IdeUiBridgePlugin.ID_PLUGIN, "Could not access marker view elements.")); e.printStackTrace(); } return true; } else if (element.getClass().getSimpleName().equals("MarkerEntry")) { return isInteresting(((MarkerItem) element).getMarker(), viewer, parent); } } return false; }
public boolean select(Viewer viewer, Object parent, Object element) { if (element instanceof MarkerItem) { if (element.getClass().getSimpleName().equals("MarkerCategory")) { try { if (markerCategoryMethod == null) { Class<?> markerCategoryClass = Class.forName("org.eclipse.ui.internal.views.markers.MarkerCategory"); markerCategoryMethod = markerCategoryClass.getDeclaredMethod("getChildren", new Class[] {}); markerCategoryMethod.setAccessible(true); } Object[] entries = (Object[]) markerCategoryMethod.invoke(element, new Object[] {}); if (entries != null && entries.length == 0) { return false; } else if (entries != null && entries.length != 0) { for (Object markerEntry : entries) { if (markerEntry.getClass().getSimpleName().equals("MarkerEntry") && isInteresting(((MarkerItem) markerEntry).getMarker(), viewer, parent)) { return true; } } return false; } } catch (Exception e) { StatusHandler.log(new Status(IStatus.ERROR, IdeUiBridgePlugin.ID_PLUGIN, "Could not access marker view elements.")); } return true; } else if (element.getClass().getSimpleName().equals("MarkerEntry")) { return isInteresting(((MarkerItem) element).getMarker(), viewer, parent); } } return false; }
private void select() { ISourceViewer sourceViewer = editor.sourceViewer(); IRegion selection = editor.getUnSignedSelection(sourceViewer); boolean previousSelectionExists = Math.abs(selection.getLength()) > 0; int caretOffset = selection.getOffset(); if (previousSelectionExists) { caretOffset = selection.getOffset() - 1; } Tokens tokens = new Tokens(editor.getDocument(), caretOffset); if (tokens.tokenAtCaret().getData() == null) { showSelection(sourceViewer, tokens.getTokenOffset(), tokens.getTokenLength()); return; } int originalSelectionEnd = selection.getOffset() + selection.getLength(); IRegion region = null; while (region == null && caretOffset >= 0) { region = editor.getPairsMatcher().match(editor.getDocument(), caretOffset); if (region != null) { int newSelectionEnd = region.getOffset() + region.getLength(); if (newSelectionEnd < originalSelectionEnd) { region = null; } } if (region == null) { caretOffset--; } } if (region == null) { String error = ClojureEditorMessages.GotoMatchingBracket_error_noMatchingBracket; showError(sourceViewer, error); } else { int offset = region.getOffset(); int length = region.getLength(); if (length >= 1) { int anchor = editor.getPairsMatcher().getAnchor(); int targetOffset = ICharacterPairMatcher.RIGHT == anchor ? offset + 1 : offset + length; if (visible(sourceViewer, targetOffset)) { actualSelection(editor.getDocument(), sourceViewer, caretOffset, offset, length, anchor, targetOffset); } else { showError(sourceViewer, ClojureEditorMessages.GotoMatchingBracket_error_bracketOutsideSelectedElement); } } } }
private void select() { ISourceViewer sourceViewer = editor.sourceViewer(); IRegion selection = editor.getUnSignedSelection(sourceViewer); boolean previousSelectionExists = Math.abs(selection.getLength()) > 0; int caretOffset = selection.getOffset(); if (previousSelectionExists) { caretOffset = selection.getOffset() - 1; } Tokens tokens = new Tokens(editor.getDocument(), caretOffset); if (tokens.tokenAtCaret().getData() == null && !previousSelectionExists) { showSelection(sourceViewer, tokens.getTokenOffset(), tokens.getTokenLength()); return; } int originalSelectionEnd = selection.getOffset() + selection.getLength(); IRegion region = null; while (region == null && caretOffset >= 0) { region = editor.getPairsMatcher().match(editor.getDocument(), caretOffset); if (region != null) { int newSelectionEnd = region.getOffset() + region.getLength(); if (newSelectionEnd < originalSelectionEnd) { region = null; } } if (region == null) { caretOffset--; } } if (region == null) { String error = ClojureEditorMessages.GotoMatchingBracket_error_noMatchingBracket; showError(sourceViewer, error); } else { int offset = region.getOffset(); int length = region.getLength(); if (length >= 1) { int anchor = editor.getPairsMatcher().getAnchor(); int targetOffset = ICharacterPairMatcher.RIGHT == anchor ? offset + 1 : offset + length; if (visible(sourceViewer, targetOffset)) { actualSelection(editor.getDocument(), sourceViewer, caretOffset, offset, length, anchor, targetOffset); } else { showError(sourceViewer, ClojureEditorMessages.GotoMatchingBracket_error_bracketOutsideSelectedElement); } } } }
public void reduce(LongWritable key, Iterator<Text> values, OutputCollector<LongWritable, Text> output, Reporter reporter) throws IOException { LongWritable one = new LongWritable(1); long totalEdges = 0; Map<Long, ArrayList<Long>> components = new HashMap<Long, ArrayList<Long>>(); Set<Long> uniqueNodes = new HashSet<Long>(); while (values.hasNext()) { String[] line = values.next().toString().split(' '); Long node = Long.parseLong(line[0]); Long label = Long.parseLong(line[1]); Long edges = Long.parseLong(line[2]); if (!uniqueNodes.contains(node)) { uniqueNodes.add(node); ArrayList<Long> nodes = (components.containsKey(label)) ? components.get(label) : new ArrayList<Long>(); nodes.add(node); totalEdges += edges; } } totalEdges /= 2; long totalNodes = uniqueNodes.size(); long totalComponents = components.size(); float sum = 0; for (ArrayList<Long> componentNodes : components.values()) { int ccSize = componentNodes.size(); sum += ccSize * ccSize; } float averageBurnCount = sum / TOTAL_POINTS; float averageComponentSize = sum / totalNodes; String s = "Number of vertices: %s \n" + "Number of edges: %s \n" + "Number of distinct connected components: %s \n" + "Average size of connected components: %s \n" + "Average burn count: %s \n"; String stats = String.format(s, Long.toString(totalNodes), Long.toString(totalEdges), Long.toString(totalComponents), Float.toString(averageComponentSize), Float.toString(averageBurnCount)); output.collect(one, new Text(stats)); }
public void reduce(LongWritable key, Iterator<Text> values, OutputCollector<LongWritable, Text> output, Reporter reporter) throws IOException { LongWritable one = new LongWritable(1); long totalEdges = 0; HashMap<Long, ArrayList<Long>> components = new HashMap<Long, ArrayList<Long>>(); HashSet<Long> uniqueNodes = new HashSet<Long>(); while (values.hasNext()) { String[] line = values.next().toString().split(" "); Long node = Long.parseLong(line[0]); Long label = Long.parseLong(line[1]); Long edges = Long.parseLong(line[2]); if (!uniqueNodes.contains(node)) { uniqueNodes.add(node); ArrayList<Long> nodes = (components.containsKey(label)) ? components.get(label) : new ArrayList<Long>(); nodes.add(node); totalEdges += edges; } } totalEdges /= 2; long totalNodes = uniqueNodes.size(); long totalComponents = components.size(); float sum = 0; for (ArrayList<Long> componentNodes : components.values()) { int ccSize = componentNodes.size(); sum += ccSize * ccSize; } float averageBurnCount = sum / TOTAL_POINTS; float averageComponentSize = sum / totalNodes; String s = "Number of vertices: %s \n" + "Number of edges: %s \n" + "Number of distinct connected components: %s \n" + "Average size of connected components: %s \n" + "Average burn count: %s \n"; String stats = String.format(s, Long.toString(totalNodes), Long.toString(totalEdges), Long.toString(totalComponents), Float.toString(averageComponentSize), Float.toString(averageBurnCount)); output.collect(one, new Text(stats)); }
public ExpressionNodeType determineNodeType(ProgramNode node) { if( node instanceof KnownConstNode) { return ExpressionNodeType.Variable; } if (node.getName().equals("#const")) { return ExpressionNodeType.ConstVal; } if (node.getName().equals("#var")) { return ExpressionNodeType.Variable; } if( node.getChildNodes().size()!=2 ) { return ExpressionNodeType.Function; } String name = node.getName(); if( !Character.isAlphabetic(name.charAt(0)) ) { return ExpressionNodeType.Operator; } return ExpressionNodeType.Function; }
public ExpressionNodeType determineNodeType(ProgramNode node) { if( node instanceof KnownConstNode) { return ExpressionNodeType.Variable; } if (node.getName().equals("#const")) { return ExpressionNodeType.ConstVal; } if (node.getName().equals("#var")) { return ExpressionNodeType.Variable; } if( node.getChildNodes().size()!=2 ) { return ExpressionNodeType.Function; } String name = node.getName(); if( !Character.isLetterOrDigit(name.charAt(0)) ) { return ExpressionNodeType.Operator; } return ExpressionNodeType.Function; }
public void renderInventory(Graphics gfx, InventoryType type) { GFX.drawText(0, 0, _hWidth, INV_TITLE_HEIGHT, GFX.TEXT_CENTER, GFX.TEXT_CENTER, Resources.getFont(2), Color.white, type.toString()); gfx.setColor(Color.darkGray); gfx.fillRect(INV_LIST_MARGIN, INV_TITLE_HEIGHT, _hWidth - INV_LIST_MARGIN*2f, _invHeightList); float scrollHeight = _invHeightScroll/(float)_currentList.size(); gfx.setColor(Color.white); gfx.fillRect(_invXScroll, _invYScroll + (getPosition()-1)*scrollHeight, _invWidthScroll, scrollHeight); clip(0, INV_TITLE_HEIGHT, _hWidth, _invHeightList); for(int id = 0;id < _currentList.size();id++) { Item item = _currentList.get(id); Color color = id == _currentPositions.get(_currentType) ? Color.white : Color.lightGray; GFX.drawTextCenteredV(INV_LIST_MARGIN + INV_LIST_PADDING, _invYList + (id- getPosition())*INV_LINE_HEIGHT, 0, Resources.getFont(1), color, item.getName()); } unClip(); }
public void renderInventory(Graphics gfx, InventoryType type) { GFX.drawText(0, 0, _hWidth, INV_TITLE_HEIGHT, GFX.TEXT_CENTER, GFX.TEXT_CENTER, Resources.getFont(2), Color.white, type.toString()); gfx.setColor(Color.darkGray); gfx.fillRect(INV_LIST_MARGIN, INV_TITLE_HEIGHT, _hWidth - INV_LIST_MARGIN*2f, _invHeightList); float scrollHeight = _invHeightScroll/(float)_currentList.size(); gfx.setColor(Color.white); gfx.fillRect(_invXScroll, _invYScroll + (getPosition())*scrollHeight, _invWidthScroll, scrollHeight); clip(0, INV_TITLE_HEIGHT, _hWidth, _invHeightList); for(int id = 0;id < _currentList.size();id++) { Item item = _currentList.get(id); Color color = id == _currentPositions.get(_currentType) ? Color.white : Color.lightGray; GFX.drawTextCenteredV(INV_LIST_MARGIN + INV_LIST_PADDING, _invYList + (id- getPosition())*INV_LINE_HEIGHT, 0, Resources.getFont(1), color, item.getName()); } unClip(); }
public boolean onCreateOptionsMenu(final Menu menu) { switch (currentMode) { case SELECTION: getMenuInflater().inflate(R.menu.photo_overview_selection_menu, menu); final ShareActionProvider shareActionProvider = (ShareActionProvider) menu.findItem(R.id.photo_overview_menu_share).getActionProvider(); final Intent shareIntent = new Intent(Intent.ACTION_SEND_MULTIPLE); shareIntent.setType("image/jpeg"); shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, makeCurrentSelectedUris()); shareActionProvider.setShareIntent(shareIntent); final MenuItem addTagsMenu = menu.findItem(R.id.photo_overview_menu_add_tag_menu); final SubMenu tagsSubmenu = addTagsMenu.getSubMenu(); tagsSubmenu.removeGroup(R.id.photo_overview_menu_existing_tag); final Map<String, Integer> selectedKeywordCounts = new HashMap<String, Integer>(); for (final EntryValues entryValues : selectedEntries.values()) { for (final String keyword : entryValues.keywords) { final Integer existingKeyword = selectedKeywordCounts.get(keyword); if (existingKeyword != null) { selectedKeywordCounts.put(keyword, Integer.valueOf(existingKeyword.intValue() + 1)); } else { selectedKeywordCounts.put(keyword, Integer.valueOf(1)); } if (!knownKeywords.contains(keyword)) { knownKeywords.add(keyword); } } } for (final String keyword : knownKeywords) { final Integer count = selectedKeywordCounts.get(keyword); final String keywordDisplay = count != null ? keyword + " (" + count + ")" : keyword; final MenuItem item = tagsSubmenu.add(R.id.photo_overview_menu_existing_tag, Menu.NONE, Menu.NONE, keywordDisplay); item.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(final MenuItem item) { setTagToSelectedEntries(keyword); return true; } }); } final MenuItem removeTagsMenu = menu.findItem(R.id.photo_overview_menu_remove_tag_menu); final SubMenu removeTagsSubmenu = removeTagsMenu.getSubMenu(); removeTagsSubmenu.clear(); final ArrayList<String> keywordsByCount = KeywordUtil.orderKeywordsByFrequent(selectedKeywordCounts); for (final String keyword : keywordsByCount) { final String keywordDisplay = keyword + " (" + selectedKeywordCounts.get(keyword) + ")"; final MenuItem removeTagItem = removeTagsSubmenu.add(keywordDisplay); removeTagItem.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(final MenuItem item) { removeTagFromSelectedEntries(keyword); return true; } }); } break; case NAVIGATION: getMenuInflater().inflate(R.menu.photo_overview_navigation_menu, menu); final MenuItem shareItem = menu.findItem(R.id.photo_overview_share_album); final SubMenu subMenu = shareItem.getSubMenu(); subMenu.clear(); final Handler handler = new Handler(); new SimpleAsync() { private final List<Pair<String, String>> menuEntries = new ArrayList<Pair<String, String>>(); @Override protected void doInBackground() { final Cursor storagesCursor = getContentResolver().query( Client.STORAGE_URI, new String[] { Client.Storage.STORAGE_ID, Client.Storage.STORAGE_NAME, Client.Storage.TAKE_ALL_REPOSITORIES }, null, null, null); if (storagesCursor.moveToFirst()) { final int idColumn = storagesCursor.getColumnIndexOrThrow(Client.Storage.STORAGE_ID); final int nameColumn = storagesCursor.getColumnIndexOrThrow(Client.Storage.STORAGE_NAME); final int allRepositoriesColumn = storagesCursor.getColumnIndexOrThrow(Client.Storage.TAKE_ALL_REPOSITORIES); do { final String storageId = storagesCursor.getString(idColumn); final String storageName = storagesCursor.getString(nameColumn); if (storagesCursor.getInt(allRepositoriesColumn) != 0) { continue; } menuEntries.add(new Pair<String, String>(storageId, storageName)); } while (storagesCursor.moveToNext()); } storagesCursor.registerContentObserver(new ContentObserver(handler) { @Override public void onChange(final boolean selfChange) { super.onChange(selfChange); invalidateOptionsMenu(); } }); Collections.sort(menuEntries, new Comparator<Pair<String, String>>() { @Override public int compare(final Pair<String, String> lhs, final Pair<String, String> rhs) { return lhs.second.compareTo(rhs.second); } }); } @Override protected void onPostExecute() { for (final Pair<String, String> entry : menuEntries) { final String entryId = entry.first; final String entryName = entry.second; final MenuItem storageItem = subMenu.add(entryName); storageItem.setCheckable(true); final boolean enabled = enabledStorages.contains(entryId); storageItem.setChecked(enabled); storageItem.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(final MenuItem item) { enableStorage(entryId, !enabled); return true; } }); } } }.execute(); final MenuItem searchClearItem = menu.findItem(R.id.photo_overview_clear_search_album); searchClearItem.setVisible(currentFilter != null); searchClearItem.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(final MenuItem item) { initLoaderWithFilter(null); return true; } }); final SearchView searchView = (SearchView) menu.findItem(R.id.photo_overview_search_album).getActionView(); if (currentFilter != null) { final Criterium filter = Criterium.decodeString(currentFilter); if (filter instanceof Compare) { final Compare comp = (Compare) filter; final Value op1 = comp.getOp1(); final Value op2 = comp.getOp2(); if (op1 instanceof Field && ((Field) op1).getFieldName().equals(Client.AlbumEntry.META_KEYWORDS) && comp.getOperator() == Operator.CONTAINS && op2 instanceof Constant) { final String value = (String) ((Constant) op2).getValue(); searchView.setQuery(value, false); searchView.setIconified(false); } } } searchView.setOnQueryTextListener(new OnQueryTextListener() { @Override public boolean onQueryTextChange(final String newText) { return false; } @Override public boolean onQueryTextSubmit(final String query) { initLoaderWithFilter(Criterium.contains(new Field(Client.AlbumEntry.META_KEYWORDS), new Constant(query.trim())).makeString()); return true; } }); break; } return true; }
public boolean onCreateOptionsMenu(final Menu menu) { switch (currentMode) { case SELECTION: getMenuInflater().inflate(R.menu.photo_overview_selection_menu, menu); final ShareActionProvider shareActionProvider = (ShareActionProvider) menu.findItem(R.id.photo_overview_menu_share).getActionProvider(); final Intent shareIntent = new Intent(Intent.ACTION_SEND_MULTIPLE); shareIntent.setType("image/jpeg"); shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, makeCurrentSelectedUris()); shareActionProvider.setShareIntent(shareIntent); final MenuItem addTagsMenu = menu.findItem(R.id.photo_overview_menu_add_tag_menu); final SubMenu tagsSubmenu = addTagsMenu.getSubMenu(); tagsSubmenu.removeGroup(R.id.photo_overview_menu_existing_tag); final Map<String, Integer> selectedKeywordCounts = new HashMap<String, Integer>(); for (final EntryValues entryValues : selectedEntries.values()) { for (final String keyword : entryValues.keywords) { final Integer existingKeyword = selectedKeywordCounts.get(keyword); if (existingKeyword != null) { selectedKeywordCounts.put(keyword, Integer.valueOf(existingKeyword.intValue() + 1)); } else { selectedKeywordCounts.put(keyword, Integer.valueOf(1)); } if (!knownKeywords.contains(keyword)) { knownKeywords.add(keyword); } } } for (final String keyword : knownKeywords) { final Integer count = selectedKeywordCounts.get(keyword); final String keywordDisplay = count != null ? keyword + " (" + count + ")" : keyword; final MenuItem item = tagsSubmenu.add(R.id.photo_overview_menu_existing_tag, Menu.NONE, Menu.NONE, keywordDisplay); item.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(final MenuItem item) { setTagToSelectedEntries(keyword); return true; } }); } final MenuItem removeTagsMenu = menu.findItem(R.id.photo_overview_menu_remove_tag_menu); final SubMenu removeTagsSubmenu = removeTagsMenu.getSubMenu(); removeTagsSubmenu.clear(); final ArrayList<String> keywordsByCount = KeywordUtil.orderKeywordsByFrequent(selectedKeywordCounts); for (final String keyword : keywordsByCount) { final String keywordDisplay = keyword + " (" + selectedKeywordCounts.get(keyword) + ")"; final MenuItem removeTagItem = removeTagsSubmenu.add(keywordDisplay); removeTagItem.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(final MenuItem item) { removeTagFromSelectedEntries(keyword); return true; } }); } break; case NAVIGATION: getMenuInflater().inflate(R.menu.photo_overview_navigation_menu, menu); final MenuItem shareItem = menu.findItem(R.id.photo_overview_share_album); final SubMenu subMenu = shareItem.getSubMenu(); subMenu.clear(); final Handler handler = new Handler(); new SimpleAsync() { private final List<Pair<String, String>> menuEntries = new ArrayList<Pair<String, String>>(); @Override protected void doInBackground() { final Cursor storagesCursor = getContentResolver().query( Client.STORAGE_URI, new String[] { Client.Storage.STORAGE_ID, Client.Storage.STORAGE_NAME, Client.Storage.TAKE_ALL_REPOSITORIES }, null, null, null); if (storagesCursor.moveToFirst()) { final int idColumn = storagesCursor.getColumnIndexOrThrow(Client.Storage.STORAGE_ID); final int nameColumn = storagesCursor.getColumnIndexOrThrow(Client.Storage.STORAGE_NAME); final int allRepositoriesColumn = storagesCursor.getColumnIndexOrThrow(Client.Storage.TAKE_ALL_REPOSITORIES); do { final String storageId = storagesCursor.getString(idColumn); final String storageName = storagesCursor.getString(nameColumn); if (storagesCursor.getInt(allRepositoriesColumn) != 0) { continue; } menuEntries.add(new Pair<String, String>(storageId, storageName)); } while (storagesCursor.moveToNext()); } storagesCursor.registerContentObserver(new ContentObserver(handler) { @Override public void onChange(final boolean selfChange) { super.onChange(selfChange); invalidateOptionsMenu(); } }); Collections.sort(menuEntries, new Comparator<Pair<String, String>>() { @Override public int compare(final Pair<String, String> lhs, final Pair<String, String> rhs) { return lhs.second.compareTo(rhs.second); } }); } @Override protected void onPostExecute() { for (final Pair<String, String> entry : menuEntries) { final String entryId = entry.first; final String entryName = entry.second; final MenuItem storageItem = subMenu.add(entryName); storageItem.setCheckable(true); final boolean enabled = enabledStorages.contains(entryId); storageItem.setChecked(enabled); storageItem.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(final MenuItem item) { enableStorage(entryId, !enabled); return true; } }); } } }.execute(); final MenuItem searchClearItem = menu.findItem(R.id.photo_overview_clear_search_album); final SearchView searchView = (SearchView) menu.findItem(R.id.photo_overview_search_album).getActionView(); searchClearItem.setVisible(currentFilter != null); searchClearItem.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(final MenuItem item) { initLoaderWithFilter(null); searchView.setQuery("", false); return true; } }); if (currentFilter != null) { final Criterium filter = Criterium.decodeString(currentFilter); if (filter instanceof Compare) { final Compare comp = (Compare) filter; final Value op1 = comp.getOp1(); final Value op2 = comp.getOp2(); if (op1 instanceof Field && ((Field) op1).getFieldName().equals(Client.AlbumEntry.META_KEYWORDS) && comp.getOperator() == Operator.CONTAINS && op2 instanceof Constant) { final String value = (String) ((Constant) op2).getValue(); searchView.setQuery(value, false); searchView.setIconified(false); } } } searchView.setOnQueryTextListener(new OnQueryTextListener() { @Override public boolean onQueryTextChange(final String newText) { return false; } @Override public boolean onQueryTextSubmit(final String query) { initLoaderWithFilter(Criterium.contains(new Field(Client.AlbumEntry.META_KEYWORDS), new Constant(query.trim())).makeString()); return true; } }); break; } return true; }
private void initComponents() { getContentPane().setLayout(new GridBagLayout()); setTitle("Examine the History of " + cell); setName(""); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { doButton(false); } }); ProjectLibrary pl = pdb.findProjectLibrary(cell.getLibrary()); List<ProjectCell> versions = new ArrayList<ProjectCell>(); for(Iterator<ProjectCell> it = pl.getProjectCells(); it.hasNext(); ) { ProjectCell pc = it.next(); if (pc.getCellName().equals(cell.getName()) && pc.getView() == cell.getView()) { pc.setCheckInDate("Not In Repository Yet"); versions.add(pc); } } String dirName = pl.getProjectDirectory() + File.separator + cell.getName(); File dir = new File(dirName); File [] filesInDir = dir.listFiles(); for(int i=0; i<filesInDir.length; i++) { File subFile = filesInDir[i]; Date modDate = new Date(subFile.lastModified()); int version = TextUtils.atoi(subFile.getName()); boolean found = false; for(ProjectCell pc : versions) { if (pc.getVersion() == version) { pc.setCheckInDate(TextUtils.formatDate(modDate)); found = true; break; } } if (!found) { ProjectCell pc = new ProjectCell(null, pl); pc.setCheckInDate(TextUtils.formatDate(modDate)); pc.setCellName(cell.getName()); pc.setVersion(version); versions.add(pc); } } Collections.sort(versions, new ProjectCellByVersion()); int numVersions = versions.size(); Object [][] data = new Object[numVersions][4]; int index = 0; for(ProjectCell pc : versions) { data[index][0] = Integer.toString(pc.getVersion()); data[index][1] = pc.getCheckInDate(); data[index][2] = pc.getLastOwner(); if (pc.getOwner().length() > 0) data[index][2] = pc.getOwner(); data[index][3] = pc.getComment(); index++; } dataModel = new HistoryTableModel(data); table = new JTable(dataModel); TableColumn versCol = table.getColumnModel().getColumn(0); TableColumn dateCol = table.getColumnModel().getColumn(1); TableColumn userCol = table.getColumnModel().getColumn(2); TableColumn commentCol = table.getColumnModel().getColumn(3); versCol.setPreferredWidth(10); dateCol.setPreferredWidth(30); userCol.setPreferredWidth(20); commentCol.setPreferredWidth(40); JScrollPane tableScrollPane = new JScrollPane(table); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 2; gbc.weightx = gbc.weighty = 1; gbc.fill = GridBagConstraints.BOTH; gbc.insets = new Insets(4, 4, 4, 4); getContentPane().add(tableScrollPane, gbc); JButton ok = new JButton("Retrieve"); gbc = new GridBagConstraints(); gbc.gridx = 1; gbc.gridy = 1; gbc.anchor = GridBagConstraints.CENTER; gbc.insets = new Insets(4, 4, 4, 4); getContentPane().add(ok, gbc); ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { doButton(true); } }); JButton cancel = new JButton("Done"); getRootPane().setDefaultButton(cancel); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 1; gbc.anchor = GridBagConstraints.CENTER; gbc.insets = new Insets(4, 4, 4, 4); getContentPane().add(cancel, gbc); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { doButton(false); } }); pack(); }
private void initComponents() { getContentPane().setLayout(new GridBagLayout()); setTitle("Examine the History of " + cell); setName(""); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { doButton(false); } }); ProjectLibrary pl = pdb.findProjectLibrary(cell.getLibrary()); List<ProjectCell> versions = new ArrayList<ProjectCell>(); for(Iterator<ProjectCell> it = pl.getProjectCells(); it.hasNext(); ) { ProjectCell pc = it.next(); if (pc.getCellName().equals(cell.getName()) && pc.getView() == cell.getView()) { pc.setCheckInDate("Not In Repository Yet"); versions.add(pc); } } String dirName = pl.getProjectDirectory() + File.separator + cell.getName(); File dir = new File(dirName); File [] filesInDir = dir.listFiles(); for(int i=0; i<filesInDir.length; i++) { File subFile = filesInDir[i]; Date modDate = new Date(subFile.lastModified()); int version = TextUtils.atoi(subFile.getName()); boolean found = false; for(ProjectCell pc : versions) { if (pc.getVersion() == version) { pc.setCheckInDate(TextUtils.formatDate(modDate)); found = true; break; } } if (!found) { ProjectCell pc = new ProjectCell(null, pl); pc.setCheckInDate(TextUtils.formatDate(modDate)); pc.setCellName(cell.getName()); pc.setVersion(version); versions.add(pc); } } Collections.sort(versions, new ProjectCellByVersion()); int numVersions = versions.size(); Object [][] data = new Object[numVersions][4]; int index = 0; for(ProjectCell pc : versions) { data[index][0] = Integer.toString(pc.getVersion()); data[index][1] = pc.getCheckInDate(); data[index][2] = pc.getLastOwner(); if (pc.getOwner().length() > 0) data[index][2] = pc.getOwner(); data[index][3] = (pc.getComment() != null) ? pc.getComment() : ""; index++; } dataModel = new HistoryTableModel(data); table = new JTable(dataModel); TableColumn versCol = table.getColumnModel().getColumn(0); TableColumn dateCol = table.getColumnModel().getColumn(1); TableColumn userCol = table.getColumnModel().getColumn(2); TableColumn commentCol = table.getColumnModel().getColumn(3); versCol.setPreferredWidth(10); dateCol.setPreferredWidth(30); userCol.setPreferredWidth(20); commentCol.setPreferredWidth(40); JScrollPane tableScrollPane = new JScrollPane(table); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 2; gbc.weightx = gbc.weighty = 1; gbc.fill = GridBagConstraints.BOTH; gbc.insets = new Insets(4, 4, 4, 4); getContentPane().add(tableScrollPane, gbc); JButton ok = new JButton("Retrieve"); gbc = new GridBagConstraints(); gbc.gridx = 1; gbc.gridy = 1; gbc.anchor = GridBagConstraints.CENTER; gbc.insets = new Insets(4, 4, 4, 4); getContentPane().add(ok, gbc); ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { doButton(true); } }); JButton cancel = new JButton("Done"); getRootPane().setDefaultButton(cancel); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 1; gbc.anchor = GridBagConstraints.CENTER; gbc.insets = new Insets(4, 4, 4, 4); getContentPane().add(cancel, gbc); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { doButton(false); } }); pack(); }
public void handleData() { if (mob != null) { if (data != null) { if (data.contains("baby")) { metadata.watch(12, -23999); } else { metadata.watch(12, 0); } if (data.contains("black")) { metadata.watch(16, (byte) 15); } else if (data.contains("blue")) { metadata.watch(16, (byte) 11); } else if (data.contains("brown")) { metadata.watch(16, (byte) 12); } else if (data.contains("cyan")) { metadata.watch(16, (byte) 9); } else if (data.contains("gray")) { metadata.watch(16, (byte) 7); } else if (data.contains("green")) { metadata.watch(16, (byte) 13); } else if (data.contains("lightblue")) { metadata.watch(16, (byte) 3); } else if (data.contains("lime")) { metadata.watch(16, (byte) 5); } else if (data.contains("magenta")) { metadata.watch(16, (byte) 2); } else if (data.contains("orange")) { metadata.watch(16, (byte) 1); } else if (data.contains("pink")) { metadata.watch(16, (byte) 6); } else if (data.contains("purple")) { metadata.watch(16, (byte) 10); } else if (data.contains("red")) { metadata.watch(16, (byte) 14); } else if (data.contains("silver")) { metadata.watch(16, (byte) 8); } else if (data.contains("white")) { metadata.watch(16, (byte) 0); } else if (data.contains("yellow")) { metadata.watch(16, (byte) 4); } else if (data.contains("sheared")) { metadata.watch(16, (byte) 16); } else { if (mob == MobType.Sheep) { metadata.watch(16, (byte) 0); } } if (data.contains("charged")) { metadata.watch(17, (byte) 1); } if (data.contains("tiny")) { metadata.watch(16, (byte) 1); } else if (data.contains("small")) { metadata.watch(16, (byte) 2); } else if (data.contains("big")) { metadata.watch(16, (byte) 4); } if (data.contains("sitting")) { try { metadata.a(16, (byte) 1); } catch (IllegalArgumentException e) { metadata.watch(16, (byte) 1); } } else if (data.contains("aggressive")) { try { metadata.a(16, (byte) 2); } catch (IllegalArgumentException e) { metadata.watch(16, (byte) 2); } } else if (data.contains("tamed")) { try { metadata.a(16, (byte) 0); } catch (IllegalArgumentException e) { metadata.watch(16, (byte) 0); } } } } }
public void handleData() { if (mob != null) { if (data != null) { if (data.contains("baby")) { metadata.watch(12, -23999); } else { metadata.watch(12, 0); } if (data.contains("black")) { metadata.watch(16, (byte) 15); } else if (data.contains("blue")) { metadata.watch(16, (byte) 11); } else if (data.contains("brown")) { metadata.watch(16, (byte) 12); } else if (data.contains("cyan")) { metadata.watch(16, (byte) 9); } else if (data.contains("gray")) { metadata.watch(16, (byte) 7); } else if (data.contains("green")) { metadata.watch(16, (byte) 13); } else if (data.contains("lightblue")) { metadata.watch(16, (byte) 3); } else if (data.contains("lime")) { metadata.watch(16, (byte) 5); } else if (data.contains("magenta")) { metadata.watch(16, (byte) 2); } else if (data.contains("orange")) { metadata.watch(16, (byte) 1); } else if (data.contains("pink")) { metadata.watch(16, (byte) 6); } else if (data.contains("purple")) { metadata.watch(16, (byte) 10); } else if (data.contains("red")) { metadata.watch(16, (byte) 14); } else if (data.contains("silver")) { metadata.watch(16, (byte) 8); } else if (data.contains("white")) { metadata.watch(16, (byte) 0); } else if (data.contains("yellow")) { metadata.watch(16, (byte) 4); } else if (data.contains("sheared")) { metadata.watch(16, (byte) 16); } else { if (mob == MobType.Sheep) { metadata.watch(16, (byte) 0); } } if (data.contains("charged")) { metadata.watch(17, (byte) 1); } if (data.contains("tiny")) { metadata.watch(16, (byte) 1); } else if (data.contains("small")) { metadata.watch(16, (byte) 2); } else if (data.contains("big")) { metadata.watch(16, (byte) 4); } if (data.contains("sitting")) { try { metadata.a(16, (byte) 1); } catch (IllegalArgumentException e) { metadata.watch(16, (byte) 1); } } else if (data.contains("aggressive")) { try { metadata.a(16, (byte) 2); } catch (IllegalArgumentException e) { metadata.watch(16, (byte) 2); } } else if (data.contains("tamed")) { try { metadata.a(16, (byte) 4); } catch (IllegalArgumentException e) { metadata.watch(16, (byte) 4); } } } } }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; if (urlService.isCandidateForDecoding(httpRequest)) { DocumentView docView = urlService.getDocumentViewFromRequest(httpRequest); if (docView != null) { urlService.setDocumentViewInRequest(httpRequest, docView); String jsfOutcome = docView.getViewId(); String target = dummyNavigationHandler.getViewIdFromOutcome(jsfOutcome); RequestDispatcher dispatcher; if (target != null) { dispatcher = httpRequest.getRequestDispatcher(target); } else { throw new MalformedURLException("Target Page is not valid: "+ target); } try { request.setAttribute( URLPolicyService.FORCE_URL_ENCODING_REQUEST_KEY, true); dispatcher.forward(new FancyURLRequestWrapper(httpRequest, docView), wrapResponse(httpRequest, httpResponse)); return; } catch (Exception e) { } } } chain.doFilter(request, wrapResponse(httpRequest, httpResponse)); }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; if (urlService.isCandidateForDecoding(httpRequest)) { DocumentView docView = urlService.getDocumentViewFromRequest(httpRequest); if (docView != null) { urlService.setDocumentViewInRequest(httpRequest, docView); String jsfOutcome = docView.getViewId(); String target = dummyNavigationHandler.getViewIdFromOutcome(jsfOutcome); RequestDispatcher dispatcher; if (target != null) { dispatcher = httpRequest.getRequestDispatcher(target); } else { dispatcher = httpRequest.getRequestDispatcher("/malformed_url_error_page.faces"); } try { request.setAttribute( URLPolicyService.FORCE_URL_ENCODING_REQUEST_KEY, true); dispatcher.forward(new FancyURLRequestWrapper(httpRequest, docView), wrapResponse(httpRequest, httpResponse)); return; } catch (Exception e) { } } } chain.doFilter(request, wrapResponse(httpRequest, httpResponse)); }
public void openFont (Context c) { stop (c); int tmpSize = FixFloat.fix2int (((SFFloat)m_field[0]).getValue ()); size = getNativeFontSize (tmpSize); String str = ((SFString)m_field[1]).getValue(); if (str == null) { style = Font.STYLE_PLAIN; } else if (str.equals ("bold")) { style = Font.STYLE_BOLD; } else if (str.equals ("italic")) { style = Font.STYLE_ITALIC; } else if (str.equals ("bolditalic")) { style = Font.STYLE_ITALIC | Font.STYLE_BOLD; } else { style = Font.STYLE_PLAIN; } str = ((MFString)m_field[2]).getValue(0); if (str == null) { justifyH = LEFT; } else if (str.equalsIgnoreCase ("MIDDLE")) { justifyH = MIDDLE; } else if (str.equalsIgnoreCase ("RIGHT")) { justifyH = RIGHT; } else { justifyH = LEFT; } str = ((MFString)m_field[2]).getValue(1); if (str == null) { justifyV = TOP; } else if (str.equalsIgnoreCase ("BOTTOM")) { justifyV = BOTTOM; } else if (str.equalsIgnoreCase ("BASELINE")) { justifyV = BASELINE; } else if (str.equalsIgnoreCase ("MIDDLE")) { justifyV = MIDDLE; } else { justifyV = TOP; } int nbFamilies = ((MFString)m_field[3]).m_size; for (int i = 0; i < nbFamilies; i++) { str = ((MFString)m_field[3]).getValue(0); if (str == null) { family = Font.FACE_SYSTEM; break; } else if (str.equalsIgnoreCase ("SERIF")) { family = Font.FACE_MONOSPACE; break; } else if (str.equalsIgnoreCase ("SANS")) { family = Font.FACE_PROPORTIONAL; break; } else if (str.equalsIgnoreCase ("TYPEWRITER")) { family = Font.FACE_SYSTEM; break; } else { family = -1; int index = str.indexOf ('/'); if (index > 0) { str = str.substring (0, index); } if ( (m_externFont = ExternFont.open (c.decoder, str, tmpSize)) != null) { break; } else { family = Font.FACE_MONOSPACE; } } } if (m_externFont == null) { m_externFont = ExternFont.open (family, style, size); } }
public void openFont (Context c) { stop (c); int tmpSize = FixFloat.fix2int (((SFFloat)m_field[0]).getValue ()); size = getNativeFontSize (tmpSize); String str = ((SFString)m_field[1]).getValue(); if (str == null) { style = Font.STYLE_PLAIN; } else if (str.equals ("bold")) { style = Font.STYLE_BOLD; } else if (str.equals ("italic")) { style = Font.STYLE_ITALIC; } else if (str.equals ("bolditalic")) { style = Font.STYLE_ITALIC | Font.STYLE_BOLD; } else { style = Font.STYLE_PLAIN; } str = ((MFString)m_field[2]).getValue(0); if (str == null) { justifyH = LEFT; } else if (str.equalsIgnoreCase ("MIDDLE")) { justifyH = MIDDLE; } else if (str.equalsIgnoreCase ("RIGHT")) { justifyH = RIGHT; } else { justifyH = LEFT; } str = ((MFString)m_field[2]).getValue(1); if (str == null) { justifyV = TOP; } else if (str.equalsIgnoreCase ("BOTTOM")) { justifyV = BOTTOM; } else if (str.equalsIgnoreCase ("BASELINE")) { justifyV = BASELINE; } else if (str.equalsIgnoreCase ("MIDDLE")) { justifyV = MIDDLE; } else { justifyV = TOP; } int nbFamilies = ((MFString)m_field[3]).m_size; for (int i = 0; i < nbFamilies; i++) { str = ((MFString)m_field[3]).getValue(0); if (str == null) { family = Font.FACE_SYSTEM; break; } else if (str.equalsIgnoreCase ("SERIF")) { family = Font.FACE_MONOSPACE; break; } else if (str.equalsIgnoreCase ("SANS")) { family = Font.FACE_PROPORTIONAL; break; } else if (str.equalsIgnoreCase ("TYPEWRITER")) { family = Font.FACE_SYSTEM; break; } else { family = -1; int index = str.indexOf ('/'); if (index > 0) { str = str.substring (0, index); } if ( (m_externFont = ExternFont.open (c.decoder, str, tmpSize)) != null) { break; } else { family = Font.FACE_SYSTEM; } } } if (m_externFont == null) { m_externFont = ExternFont.open (family, style, size); } }
public String renderText(String templateName, Map<String, String> params) { String result; ST template = group.getInstanceOf(templateName); if (template != null) { for (Object attr : template.getAttributes().keySet()) { String attrStr = attr.toString(); template.add(attrStr, params.get(attrStr) == null ? "" : params.get(attrStr)); } result = template.render(); } else { throw new IllegalArgumentException(String.format("Template %s is not found at path %s", templateName, path)); } return result; }
public String renderText(String templateName, Map<String, String> params) { String result; ST template = group.getInstanceOf(templateName); if (template != null) { Map<String, Object> attributes = template.getAttributes(); if(attributes != null) { for (Object attr : attributes.keySet()) { String attrStr = attr.toString(); template.add(attrStr, params.get(attrStr) == null ? "" : params.get(attrStr)); } } result = template.render(); } else { throw new IllegalArgumentException(String.format("Template %s is not found at path %s", templateName, path)); } return result; }