answer
stringlengths
17
10.2M
package org.nuxeo.ecm.automation.jsf.operations; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jboss.seam.core.Events; import org.nuxeo.ecm.automation.core.Constants; import org.nuxeo.ecm.automation.core.annotations.Operation; import org.nuxeo.ecm.automation.core.annotations.OperationMethod; import org.nuxeo.ecm.automation.core.annotations.Param; import org.nuxeo.ecm.automation.core.util.StringList; import org.nuxeo.ecm.automation.jsf.OperationHelper; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.platform.ui.web.api.NavigationContext; import org.nuxeo.ecm.webapp.helpers.EventNames; /** * Operation that: * <ul> * <li>refreshes the content view cache;</li> * <li>raises standard seam events to trigger refresh of most seam component;</li> * <li>raises additional configurable seam events.</li> * </ul> * * @author <a href="mailto:td@nuxeo.com">Thierry Delprat</a> */ @Operation(id = RefreshUI.ID, category = Constants.CAT_UI, requires = Constants.SEAM_CONTEXT, label = "Refresh", description = "Refresh the UI cache. This is a void operation - the input object is returned back as the oputput") public class RefreshUI { public static final String ID = "Seam.Refresh"; protected static final Log log = LogFactory.getLog(RefreshUI.class); /** * Additional list of seam event names to raise * * @since 5.5 */ @Param(name = "additional list of seam events to raise", required = false) protected StringList additionalSeamEvents; @OperationMethod public void run() { if (OperationHelper.isSeamContextAvailable()) { OperationHelper.getContentViewActions().resetAllContent(); NavigationContext context = OperationHelper.getNavigationContext(); DocumentModel dm = context.getCurrentDocument(); if (dm != null) { Events.instance().raiseEvent(EventNames.DOCUMENT_CHANGED, dm); Events.instance().raiseEvent(EventNames.DOCUMENT_CHILDREN_CHANGED, dm); } if (additionalSeamEvents != null) { for (String event : additionalSeamEvents) { Events.instance().raiseEvent(event); } } } else { log.debug("Skip Seam.Refresh operation since Seam context has not been initialized"); } } }
package org.project.openbaton.common.vnfm_sdk.jms; import org.apache.activemq.ActiveMQConnectionFactory; import org.project.openbaton.catalogue.nfvo.CoreMessage; import org.project.openbaton.catalogue.nfvo.EndpointType; import org.project.openbaton.catalogue.nfvo.VnfmManagerEndpoint; import org.project.openbaton.common.vnfm_sdk.AbstractVnfm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.jms.annotation.EnableJms; import org.springframework.jms.config.DefaultJmsListenerContainerFactory; import org.springframework.jms.config.JmsListenerContainerFactory; import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.core.MessageCreator; import javax.annotation.PreDestroy; import javax.jms.*; import java.io.Serializable; @SpringBootApplication @EnableJms public abstract class AbstractVnfmSpringJMS extends AbstractVnfm implements CommandLineRunner { @Autowired protected JmsListenerContainerFactory topicJmsContainerFactory; private boolean exit = false; protected String SELECTOR; private VnfmManagerEndpoint vnfmManagerEndpoint; public String getSELECTOR() { return SELECTOR; } public void setSELECTOR(String SELECTOR) { this.SELECTOR = SELECTOR; } @Autowired private JmsTemplate jmsTemplate; @PreDestroy private void shutdown(){ log.debug("PREDESTROY"); this.unregister(vnfmManagerEndpoint); } @Override protected void unregister(VnfmManagerEndpoint endpoint) { this.sendMessageToQueue("vnfm-unregister", endpoint); } @Bean ConnectionFactory connectionFactory() { return new ActiveMQConnectionFactory(); } @Bean JmsListenerContainerFactory<?> jmsListenerContainerFactory(ConnectionFactory connectionFactory) { DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); factory.setCacheLevelName("CACHE_AUTO"); factory.setConnectionFactory(connectionFactory); factory.setConcurrency("5"); return factory; } // @Bean // JmsListenerContainerFactory<?> topicJmsContainerFactory(ConnectionFactory connectionFactory) { // DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); // factory.setCacheLevelName("CACHE_CONNECTION"); // factory.setConnectionFactory(connectionFactory); // factory.setConcurrency("1"); // factory.setPubSubDomain(true); // factory.setSubscriptionDurable(true); // factory.setClientId(""+ Thread.currentThread().getId()); // return factory; // @JmsListener(destination = "core-vnfm-actions", containerFactory = "queueJmsContainerFactory") private void onMessage() throws JMSException { Message msg = jmsTemplate.receive("core-" + this.type + "-actions"); CoreMessage message = (CoreMessage) ((ObjectMessage)msg).getObject(); log.trace("VNFM-DUMMY: received " + message); this.onAction(message); } private CoreMessage receiveCoreMessage(String destination, String selector) throws JMSException { jmsTemplate.setPubSubDomain(true); jmsTemplate.setPubSubNoLocal(true); CoreMessage message = (CoreMessage) ((ObjectMessage) jmsTemplate.receiveSelected(destination, "type = \'" + selector + "\'")).getObject(); jmsTemplate.setPubSubDomain(false); jmsTemplate.setPubSubNoLocal(false); return message; } protected Serializable sendAndReceiveMessage(String receiveFromQueueName, String sendToQueueName, final Serializable vduMessage) throws JMSException { sendMessageToQueue(sendToQueueName, vduMessage); ObjectMessage objectMessage = (ObjectMessage) jmsTemplate.receive(receiveFromQueueName); log.debug("Received: " + objectMessage.getObject()); // VDUMessage answer = (VDUMessage) objectMessage.getObject(); // if (answer.getLifecycleEvent().ordinal() != Event.ERROR.ordinal()){ // return true; return objectMessage.getObject(); } protected String sendAndReceiveStringMessage(String receiveFromQueueName, String sendToQueueName, final String stringMessage) throws JMSException { log.debug("Sending message: " + stringMessage + " to Queue: " + sendToQueueName); MessageCreator messageCreator = new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { TextMessage textMessage = session.createTextMessage(stringMessage); return textMessage; } }; jmsTemplate.setPubSubDomain(false); jmsTemplate.setPubSubNoLocal(false); jmsTemplate.send(sendToQueueName, messageCreator); TextMessage textMessage = (TextMessage) jmsTemplate.receive(receiveFromQueueName); jmsTemplate.setPubSubDomain(true); jmsTemplate.setPubSubNoLocal(true); String answer = textMessage.getText(); log.debug("Received: " + answer); // check errors /*if (answer.equals("error")){ return null; }*/ return answer; } protected void sendMessageToQueue(String sendToQueueName, final Serializable vduMessage) { log.debug("Sending message: " + vduMessage + " to Queue: " + sendToQueueName); MessageCreator messageCreator = new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { ObjectMessage objectMessage = session.createObjectMessage(vduMessage); return objectMessage; } }; jmsTemplate.setPubSubDomain(false); jmsTemplate.setPubSubNoLocal(false); jmsTemplate.send(sendToQueueName, messageCreator); jmsTemplate.setPubSubDomain(true); jmsTemplate.setPubSubNoLocal(true); } @Override public void run(String... args) throws Exception { //TODO initialize and register loadProperties(); this.setSELECTOR(this.getEndpoint()); log.debug("SELECTOR: " + this.getEndpoint()); vnfmManagerEndpoint = new VnfmManagerEndpoint(); vnfmManagerEndpoint.setType(this.type); vnfmManagerEndpoint.setEndpoint(this.endpoint); vnfmManagerEndpoint.setEndpointType(EndpointType.JMS); log.debug("Registering to queue: vnfm-register"); sendMessageToQueue("vnfm-register", vnfmManagerEndpoint); try { while (true) onMessage(); }catch (Exception e){ e.printStackTrace(); } } }
package org.project.openbaton.common.vnfm_sdk.jms; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import org.apache.activemq.ActiveMQConnectionFactory; import org.project.openbaton.catalogue.nfvo.CoreMessage; import org.project.openbaton.common.vnfm_sdk.AbstractVnfm; import org.project.openbaton.common.vnfm_sdk.exception.VnfmSdkException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.jms.annotation.JmsListenerConfigurer; import org.springframework.jms.config.DefaultJmsListenerContainerFactory; import org.springframework.jms.config.JmsListenerContainerFactory; import org.springframework.jms.config.JmsListenerEndpointRegistrar; import org.springframework.jms.config.SimpleJmsListenerEndpoint; import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.core.MessageCreator; import javax.jms.*; import javax.jms.IllegalStateException; import java.io.Serializable; @SpringBootApplication public abstract class AbstractVnfmSpringJMS extends AbstractVnfm implements MessageListener, JmsListenerConfigurer { @Autowired protected JmsListenerContainerFactory topicJmsContainerFactory; private boolean exit = false; protected String SELECTOR; protected Gson parser = new GsonBuilder().create(); @Autowired private JmsTemplate jmsTemplate; @Autowired private JmsListenerContainerFactory<?> jmsListenerContainerFactory; @Bean ConnectionFactory connectionFactory() { return new ActiveMQConnectionFactory(); } @Bean JmsListenerContainerFactory<?> jmsListenerContainerFactory(ConnectionFactory connectionFactory) { DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); factory.setCacheLevelName("CACHE_CONNECTION"); factory.setConnectionFactory(connectionFactory); factory.setConcurrency("15"); return factory; } @Override public void configureJmsListeners(JmsListenerEndpointRegistrar registrar) { registrar.setContainerFactory(jmsListenerContainerFactory); SimpleJmsListenerEndpoint endpoint = new SimpleJmsListenerEndpoint(); endpoint.setDestination("core-" + this.type + "-actions"); endpoint.setMessageListener(this); endpoint.setConcurrency("15"); endpoint.setId(String.valueOf(Thread.currentThread().getId())); registrar.registerEndpoint(endpoint); } @Override public void onMessage(Message message) { CoreMessage msg = null; try { msg = (CoreMessage) ((ObjectMessage) message).getObject(); } catch (JMSException e) { e.printStackTrace(); System.exit(1); } log.trace("VNFM: received " + msg); this.onAction(msg); } protected void sendMessageToQueue(String sendToQueueName, final Serializable message) { log.debug("Sending message: " + message + " to Queue: " + sendToQueueName); MessageCreator messageCreator; if (message instanceof java.lang.String ) messageCreator =getTextMessageCreator((String) message); else messageCreator = getObjectMessageCreator(message); jmsTemplate.setPubSubDomain(false); jmsTemplate.setPubSubNoLocal(false); jmsTemplate.send(sendToQueueName, messageCreator); } private MessageCreator getTextMessageCreator(final String string) { MessageCreator messageCreator = new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { TextMessage objectMessage = session.createTextMessage(string); return objectMessage; } }; return messageCreator; } private MessageCreator getObjectMessageCreator(final Serializable message) { MessageCreator messageCreator = new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { ObjectMessage objectMessage = session.createObjectMessage(message); return objectMessage; } }; return messageCreator; } /** * This method should be used for receiving text message from EMS * * resp = { * 'output': out, // the output of the command * 'err': err, // the error outputs of the commands * 'status': status // the exit status of the command * } * * @param queueName * @return * @throws JMSException */ protected String receiveTextFromQueue(String queueName) throws JMSException { return ((TextMessage)this.jmsTemplate.receive(queueName)).getText(); } @Override protected void executeActionOnEMS(String vduHostname, String command) throws JMSException, VnfmSdkException { this.sendMessageToQueue("vnfm-" + vduHostname + "-actions", command); String response = receiveTextFromQueue(vduHostname + "-vnfm-actions"); log.debug("Received from EMS ("+vduHostname+"): " + response); if(response==null) { throw new NullPointerException("Response from EMS is null"); } JsonObject jsonObject = parser.fromJson(response,JsonObject.class); if(jsonObject.get("status").getAsInt()==0){ log.debug("Output from EMS ("+vduHostname+") is: " + jsonObject.get("output").getAsString()); } else{ log.error(jsonObject.get("err").getAsString()); throw new VnfmSdkException("EMS ("+vduHostname+") had the following error: "+jsonObject.get("err").getAsString()); } } @Override protected void setup() { loadProperties(); this.setSELECTOR(this.getEndpoint()); log.debug("SELECTOR: " + this.getEndpoint()); String response = receiveTextFromQueue(vduHostname + "-vnfm-actions"); log.debug("Received from EMS ("+vduHostname+"): " + response); if(response==null) { throw new NullPointerException("Response from EMS is null"); } JsonObject jsonObject = parser.fromJson(response,JsonObject.class); if(jsonObject.get("status").getAsInt()==0){ try { log.debug("Output from EMS ("+vduHostname+") is: " + jsonObject.get("output")); }catch (Exception e){ e.printStackTrace(); throw e; } } else{ log.error(jsonObject.get("err").getAsString()); throw new VnfmSdkException("EMS ("+vduHostname+") had the following error: "+jsonObject.get("err").getAsString()); } return response; } @Override protected void unregister() { this.sendMessageToQueue("vnfm-unregister", vnfmManagerEndpoint); } @Override protected void sendToNfvo(final CoreMessage coreMessage) { sendMessageToQueue(nfvoQueue,coreMessage); } @Override protected void register() { this.sendMessageToQueue("vnfm-register", vnfmManagerEndpoint); } }
package org.lamport.tla.toolbox.editor.basic.tla; import java.util.Arrays; import java.util.HashSet; public interface ITLAReserveredWords { public final static String ACTION = "ACTION"; public final static String ASSUME = "ASSUME"; public final static String ASSUMPTION = "ASSUMPTION"; public final static String AXIOM = "AXIOM"; public final static String BY = "BY"; public final static String CASE = "CASE"; public final static String CHOOSE = "CHOOSE"; public final static String CONSTANT = "CONSTANT"; public final static String CONSTANTS = "CONSTANTS"; public final static String DEF = "DEF"; public final static String DEFINE = "DEFINE"; public final static String DEFS = "DEFS"; public final static String DOMAIN = "DOMAIN"; public final static String ELSE = "ELSE"; public final static String ENABLED = "ENABLED"; public final static String EXCEPT = "EXCEPT"; public final static String EXTENDS = "EXTENDS"; public final static String HAVE = "HAVE"; public final static String HIDE = "HIDE"; public final static String IF = "IF"; public final static String IN = "IN"; public final static String INSTANCE = "INSTANCE"; public final static String LET = "LET"; public final static String LAMBDA = "LAMBDA"; public final static String LEMMA = "LEMMA"; public final static String LOCAL = "LOCAL"; public final static String MODULE = "MODULE"; public final static String NEW = "NEW"; public final static String OBVIOUS = "OBVIOUS"; public final static String OMITTED = "OMITTED"; public final static String ONLY = "ONLY"; // Added 23 May 2012 by LL public final static String OTHER = "OTHER"; public final static String PICK = "PICK"; public final static String PROOF = "PROOF"; public final static String PROPOSITION = "PROPOSITION"; public final static String PROVE = "PROVE"; public final static String QED = "QED"; public final static String RECURSIVE = "RECURSIVE"; public final static String SF_ = "SF_"; public final static String STATE = "STATE"; public final static String SUFFICES = "SUFFICES"; public final static String SUBSET = "SUBSET"; public final static String TAKE = "TAKE"; public final static String TEMPORAL = "TEMPORAL"; public final static String THEN = "THEN"; public final static String THEOREM = "THEOREM"; public final static String UNCHANGED = "UNCHANGED"; public final static String UNION = "UNION"; public final static String USE = "USE"; public final static String VARIABLE = "VARIABLE"; public final static String VARIABLES = "VARIABLES"; public final static String WF_ = "WF_"; public final static String WITH = "WITH"; public final static String WITNESS = "WITNESS"; public final static String TRUE = "TRUE"; public final static String FALSE = "FALSE"; public final static String[] ALL_WORDS_ARRAY = new String[] { ACTION, ASSUME, ASSUMPTION, AXIOM, BY, CASE, CHOOSE, CONSTANT, CONSTANTS, DEF, DEFINE, DEFS, DOMAIN, ELSE, ENABLED, EXCEPT, EXTENDS, HAVE, HIDE, IF, IN, INSTANCE, LAMBDA, LEMMA, LET, LOCAL, MODULE, NEW, OBVIOUS, OMITTED, ONLY, OTHER, PICK, PROOF, PROPOSITION, PROVE, QED, RECURSIVE, SF_, STATE, SUBSET, SUFFICES, TAKE, TEMPORAL, THEN, THEOREM, UNCHANGED, UNION, USE, VARIABLE, VARIABLES, WF_, WITH, WITNESS }; public static final String[] ALL_VALUES_ARRAY = { TRUE, FALSE }; public final static HashSet ALL_WORDS_SET = new HashSet(Arrays.asList(ALL_WORDS_ARRAY)); }
package org.spoofax.interpreter.library.jsglr; import static org.spoofax.interpreter.core.Tools.*; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import org.spoofax.interpreter.adapter.aterm.WrappedATerm; import org.spoofax.interpreter.adapter.aterm.WrappedATermFactory; import org.spoofax.interpreter.core.IContext; import org.spoofax.interpreter.core.InterpreterException; import org.spoofax.interpreter.core.Tools; import org.spoofax.interpreter.library.IOAgent; import org.spoofax.interpreter.library.ssl.SSLLibrary; import org.spoofax.interpreter.stratego.Strategy; import org.spoofax.interpreter.terms.IStrategoAppl; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.interpreter.terms.TermConverter; import org.spoofax.jsglr.ParseTable; import org.spoofax.jsglr.SGLR; import org.spoofax.jsglr.SGLRException; public class JSGLR_parse_string_pt extends JSGLRPrimitive { private final WrappedATermFactory factory; private SGLRException lastException; private String lastPath; protected JSGLR_parse_string_pt(WrappedATermFactory factory) { super("JSGLR_parse_string_pt", 1, 4); this.factory = factory; } protected JSGLR_parse_string_pt(WrappedATermFactory factory, String name, int svars, int tvars) { super(name, svars, tvars); this.factory = factory; } public String getLastPath() { return lastPath; } public SGLRException getLastException() { return lastException; } public void clearLastException() { lastException = null; } @Override public boolean call(IContext env, Strategy[] svars, IStrategoTerm[] tvars) throws InterpreterException { clearLastException(); if (!Tools.isTermString(tvars[0])) return false; if (!Tools.isTermInt(tvars[1])) return false; if(!Tools.isTermString(tvars[3])) return false; String startSymbol; if (Tools.isTermString(tvars[2])) { startSymbol = Tools.asJavaString(tvars[2]); } else if (tvars[2].getSubtermCount() == 0 && tvars[2].getTermType() == IStrategoTerm.APPL && ((IStrategoAppl) tvars[2]).getConstructor().getName().equals("None")) { startSymbol = null; } else { return false; } lastPath = asJavaString(tvars[3]); JSGLRLibrary lib = getLibrary(env); ParseTable table = lib.getParseTable(asJavaInt(tvars[1])); if (table == null) return false; try { IStrategoTerm result = call(env, asJavaString(tvars[0]), table, startSymbol, tvars[0] instanceof WrappedATerm); env.setCurrent(result); return result != null; } catch (IOException e) { PrintStream err = SSLLibrary.instance(env).getIOAgent().getOutputStream(IOAgent.CONST_STDERR); err.println("JSGLR_parse_string_pt: could not parse " + getLastPath() + " - " + e.getMessage()); return false; } catch (SGLRException e) { lastException = e; IStrategoTerm errorTerm = factory.wrapTerm(e.toTerm(lastPath)); env.setCurrent(TermConverter.convert(env.getFactory(), errorTerm)); // FIXME: Stratego doesn't seem to print the erroneous line in Java return svars[0].evaluate(env); } } public IStrategoTerm call(IContext env, String input, ParseTable table, String startSymbol, boolean outputWrappedATerm) throws InterpreterException, IOException, SGLRException { SGLR parser = new SGLR(factory.getFactory(), table); // TODO: Use SGLR.parse(String, String) instead InputStream is = new ByteArrayInputStream(input.getBytes("ISO-8859-1")); IStrategoTerm result = factory.wrapTerm(parser.parse(is, startSymbol)); if (!outputWrappedATerm) result = TermConverter.convert(env.getFactory(), result); return result; } }
package org.tigris.subversion.subclipse.ui.actions; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import org.eclipse.compare.CompareConfiguration; import org.eclipse.compare.CompareUI; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.action.IAction; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.ui.actions.WorkspaceModifyOperation; import org.osgi.service.prefs.BackingStoreException; import org.tigris.subversion.subclipse.core.ISVNLocalResource; import org.tigris.subversion.subclipse.core.SVNException; import org.tigris.subversion.subclipse.core.resources.SVNWorkspaceRoot; import org.tigris.subversion.subclipse.core.util.File2Resource; import org.tigris.subversion.subclipse.ui.ISVNUIConstants; import org.tigris.subversion.subclipse.ui.Policy; import org.tigris.subversion.subclipse.ui.SVNUIPlugin; import org.tigris.subversion.subclipse.ui.conflicts.ConflictsCompareInput; import org.tigris.subversion.subclipse.ui.conflicts.MergeFileAssociation; import org.tigris.subversion.svnclientadapter.utils.Command; /** * Action to edit conflicts */ public class EditConflictsAction extends WorkbenchWindowAction { private IFile selectedResource; public EditConflictsAction() { super(); } public EditConflictsAction(IFile selectedResource) { this(); this.selectedResource = selectedResource; } /** * edit the conflicts using built-in merger * * @param resource * @param conflictOldFile * @param conflictWorkingFile * @param conflictNewFile * @throws InvocationTargetException */ private void editConflictsInternal(IFile resource, IFile conflictOldFile, IFile conflictWorkingFile, IFile conflictNewFile) throws InvocationTargetException, InterruptedException { CompareConfiguration cc = new CompareConfiguration(); ConflictsCompareInput fInput = new ConflictsCompareInput(cc); fInput.setResources(conflictOldFile, conflictWorkingFile, conflictNewFile, (IFile) resource); CompareUI.openCompareEditorOnPage(fInput, getTargetPage()); } /** * edit the conflicts using an external merger * * @param resource * @param conflictOldFile * @param conflictWorkingFile * @param conflictNewFile * @throws InvocationTargetException */ private void editConflictsExternal(IFile resource, IFile conflictOldFile, IFile conflictWorkingFile, IFile conflictNewFile, String mergeProgramLocation, String mergeProgramParameters) throws CoreException, InvocationTargetException, InterruptedException { try { if (mergeProgramLocation.equals("")) { //$NON-NLS-1$ throw new SVNException(Policy .bind("EditConflictsAction.noMergeProgramConfigured")); //$NON-NLS-1$ } File mergeProgramFile = new File(mergeProgramLocation); if (!mergeProgramFile.exists()) { throw new SVNException(Policy .bind("EditConflictsAction.mergeProgramDoesNotExist")); //$NON-NLS-1$ } Command command = new Command(mergeProgramLocation); String[] parameters = mergeProgramParameters.split(" "); for (int i = 0; i < parameters.length; i++) { parameters[i] = replaceParameter(parameters[i], "${theirs}", //$NON-NLS-1$ conflictNewFile.getLocation().toFile() .getAbsolutePath()); parameters[i] = replaceParameter(parameters[i], "${yours}", //$NON-NLS-1$ conflictWorkingFile.getLocation().toFile() .getAbsolutePath()); parameters[i] = replaceParameter(parameters[i], "${base}", //$NON-NLS-1$ conflictOldFile.getLocation().toFile() .getAbsolutePath()); parameters[i] = replaceParameter(parameters[i], "${merged}", //$NON-NLS-1$ resource.getLocation().toFile().getAbsolutePath()); } command.setParameters(parameters); command.exec(); command.waitFor(); resource.refreshLocal(IResource.DEPTH_ZERO, null); } catch (IOException e) { throw new InvocationTargetException(e); } } /* * (non-Javadoc) * * @see org.tigris.subversion.subclipse.ui.actions.SVNAction#execute(org.eclipse.jface.action.IAction) */ protected void execute(final IAction action) throws InvocationTargetException, InterruptedException { run(new WorkspaceModifyOperation() { public void execute(IProgressMonitor monitor) throws CoreException, InvocationTargetException, InterruptedException { IFile resource; if (selectedResource == null) resource = (IFile) getSelectedResources()[0]; else resource = selectedResource; ISVNLocalResource svnResource = SVNWorkspaceRoot .getSVNResourceFor(resource); try { IFile conflictNewFile = (IFile) File2Resource .getResource(svnResource.getStatus() .getConflictNew()); IFile conflictOldFile = (IFile) File2Resource .getResource(svnResource.getStatus() .getConflictOld()); IFile conflictWorkingFile = (IFile) File2Resource .getResource(svnResource.getStatus() .getConflictWorking()); MergeFileAssociation mergeFileAssociation = null; try { mergeFileAssociation = SVNUIPlugin.getPlugin().getMergeFileAssociation(resource.getName()); } catch (BackingStoreException e) { mergeFileAssociation = new MergeFileAssociation(); } if (mergeFileAssociation.getType() == MergeFileAssociation.BUILT_IN) { editConflictsInternal(resource, conflictOldFile, conflictWorkingFile, conflictNewFile); } else if (mergeFileAssociation.getType() == MergeFileAssociation.DEFAULT_EXTERNAL) { IPreferenceStore preferenceStore = SVNUIPlugin.getPlugin().getPreferenceStore(); String mergeProgramLocation = preferenceStore.getString(ISVNUIConstants.PREF_MERGE_PROGRAM_LOCATION); String mergeProgramParameters = preferenceStore.getString(ISVNUIConstants.PREF_MERGE_PROGRAM_PARAMETERS); editConflictsExternal(resource, conflictOldFile, conflictWorkingFile, conflictNewFile, mergeProgramLocation, mergeProgramParameters); } else { editConflictsExternal(resource, conflictOldFile, conflictWorkingFile, conflictNewFile, mergeFileAssociation.getMergeProgram(), mergeFileAssociation.getParameters()); } } catch (SVNException e) { throw new InvocationTargetException(e); } } }, false /* cancelable */, PROGRESS_BUSYCURSOR); } /* * (non-Javadoc) * * @see org.tigris.subversion.subclipse.ui.actions.SVNAction#getErrorTitle() */ protected String getErrorTitle() { return Policy.bind("EditConflictsAction.errorTitle"); //$NON-NLS-1$ } /** * @see org.tigris.subversion.subclipse.ui.actions.WorkspaceAction#isEnabledForSVNResource(org.tigris.subversion.subclipse.core.ISVNResource) */ protected boolean isEnabledForSVNResource(ISVNLocalResource svnResource) { try { if (!svnResource.getStatus().isTextConflicted()) { return false; } IFile conflictWorkingFile = (IFile) File2Resource .getResource(svnResource.getStatus() .getConflictWorking()); return conflictWorkingFile != null; } catch (SVNException e) { return false; } } /** * Method isEnabledForAddedResources. * * @return boolean */ protected boolean isEnabledForMultipleResources() { return false; } private String replaceParameter(String input, String pattern, String value) { StringBuffer result = new StringBuffer(); //startIdx and idxOld delimit various chunks of input; these //chunks always end where pattern begins int startIdx = 0; int idxOld = 0; while ((idxOld = input.indexOf(pattern, startIdx)) >= 0) { //grab a part of input which does not include pattern result.append( input.substring(startIdx, idxOld) ); //add value to take place of pattern result.append( value ); //reset the startIdx to just after the current match, to see //if there are any further matches startIdx = idxOld + pattern.length(); } //the final chunk will go to the end of input result.append( input.substring(startIdx) ); return result.toString(); } protected String getImageId() { return ISVNUIConstants.IMG_MENU_EDITCONFLICT; } }
package com.intellij.openapi.externalSystem.settings; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Comparing; import com.intellij.util.xmlb.annotations.Transient; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.HashSet; import java.util.Set; import static com.intellij.util.PlatformUtils.getPlatformPrefix; import static com.intellij.util.PlatformUtils.isIntelliJ; /** * Holds settings specific to a particular project imported from an external system. * * @author Denis Zhdanov */ public abstract class ExternalProjectSettings implements Comparable<ExternalProjectSettings>, Cloneable { private static Logger LOG = Logger.getInstance("#com.intellij.openapi.externalSystem.autoimport"); private String myExternalProjectPath; @Nullable private Set<String> myModules = new HashSet<>(); @NotNull public Set<String> getModules() { return myModules == null ? Collections.emptySet() : myModules; } public void setModules(@Nullable Set<String> modules) { this.myModules = modules; } private boolean myUseQualifiedModuleNames = !isIntelliJ() && !"AndroidStudio".equals(getPlatformPrefix()); // backward-compatible defaults /** * @deprecated left for settings backward-compatibility */ @SuppressWarnings("DeprecatedIsStillUsed") @Deprecated private boolean myCreateEmptyContentRootDirectories; // Used to gradually migrate new project to the new defaults. public void setupNewProjectDefault() { myUseQualifiedModuleNames = true; } public String getExternalProjectPath() { return myExternalProjectPath; } public void setExternalProjectPath(@NotNull String externalProjectPath) { myExternalProjectPath = externalProjectPath; } /** * @deprecated see {@link ExternalProjectSettings#setUseAutoImport} for details */ @Transient @Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.1") public boolean isUseAutoImport() { return true; } /** * @deprecated Auto-import cannot be disabled * @see com.intellij.openapi.externalSystem.autoimport.ExternalSystemProjectTracker for details */ @Transient @Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.1") public void setUseAutoImport(@SuppressWarnings("unused") boolean useAutoImport) { LOG.warn(new Throwable("Auto-import cannot be disabled")); } /** * @deprecated left for settings backward-compatibility */ @Deprecated public boolean isCreateEmptyContentRootDirectories() { return myCreateEmptyContentRootDirectories; } /** * @deprecated left for settings backward-compatibility */ @Deprecated public void setCreateEmptyContentRootDirectories(boolean createEmptyContentRootDirectories) { myCreateEmptyContentRootDirectories = createEmptyContentRootDirectories; } public boolean isUseQualifiedModuleNames() { return myUseQualifiedModuleNames; } public void setUseQualifiedModuleNames(boolean useQualifiedModuleNames) { myUseQualifiedModuleNames = useQualifiedModuleNames; } @Override public int compareTo(@NotNull ExternalProjectSettings that) { return Comparing.compare(myExternalProjectPath, that.myExternalProjectPath); } @Override public int hashCode() { return myExternalProjectPath != null ? myExternalProjectPath.hashCode() : 0; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ExternalProjectSettings that = (ExternalProjectSettings)o; return myExternalProjectPath == null ? that.myExternalProjectPath == null : myExternalProjectPath.equals(that.myExternalProjectPath); } @Override public String toString() { return myExternalProjectPath; } @Override @NotNull public abstract ExternalProjectSettings clone(); protected void copyTo(@NotNull ExternalProjectSettings receiver) { receiver.myExternalProjectPath = myExternalProjectPath; receiver.myModules = myModules != null ? new HashSet<>(myModules) : new HashSet<>(); receiver.myCreateEmptyContentRootDirectories = myCreateEmptyContentRootDirectories; receiver.myUseQualifiedModuleNames = myUseQualifiedModuleNames; } }
package com.google.eclipse.mechanic.plugin.ui; import org.eclipse.swt.widgets.Shell; /** * The dialog to obtain properties for outputting a .kbd task file. */ public class KeybindingsOutputDialog extends BaseOutputDialog { /** * Create an output dialog for the given shell. * * @param parentShell the shell to create this dialog in. */ public KeybindingsOutputDialog(Shell parentShell) { super(parentShell, "kbd"); } @Override protected void configureShell(Shell shell) { super.configureShell(shell); shell.setText("Export Keyboard Preferences"); } @Override protected void okPressed() { if (!isReady()) { return; // Should never happen, since we disable OK when not ready } } }
package com.redhat.ceylon.eclipse.code.propose; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.AIDENTIFIER; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.ASTRING_LITERAL; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.AVERBATIM_STRING; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.CHAR_LITERAL; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.EOF; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.FLOAT_LITERAL; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.LBRACE; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.LIDENTIFIER; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.LINE_COMMENT; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.MULTI_COMMENT; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.NATURAL_LITERAL; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.PIDENTIFIER; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.RBRACE; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.SEMICOLON; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.STRING_END; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.STRING_LITERAL; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.STRING_MID; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.STRING_START; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.UIDENTIFIER; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.VERBATIM_STRING; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.WS; import static com.redhat.ceylon.eclipse.code.editor.CeylonAutoEditStrategy.getDefaultIndent; import static com.redhat.ceylon.eclipse.code.hover.DocHover.getDocumentationFor; import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.ANN_STYLER; import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.ARCHIVE; import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.ID_STYLER; import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.KW_STYLER; import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.PACKAGE; import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.TYPE_STYLER; import static com.redhat.ceylon.eclipse.code.parse.CeylonSourcePositionLocator.getTokenIndexAtCharacter; import static com.redhat.ceylon.eclipse.code.parse.CeylonTokenColorer.keywords; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.EXPRESSION; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.EXTENDS; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.IMPORT; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.META; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.OF; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.PARAMETER_LIST; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.SATISFIES; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.TYPE_ARGUMENT_LIST; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.TYPE_PARAMETER_LIST; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.UPPER_BOUND; import static com.redhat.ceylon.eclipse.code.quickfix.CeylonQuickFixAssistant.getIndent; import static java.lang.Character.isJavaIdentifierPart; import static java.lang.Character.isLowerCase; import static java.lang.Character.isUpperCase; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import org.antlr.runtime.CommonToken; import org.antlr.runtime.Token; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.viewers.StyledString; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import com.redhat.ceylon.cmr.api.ModuleQuery; import com.redhat.ceylon.cmr.api.ModuleSearchResult; import com.redhat.ceylon.cmr.api.ModuleSearchResult.ModuleDetails; import com.redhat.ceylon.compiler.loader.AbstractModelLoader; import com.redhat.ceylon.compiler.typechecker.TypeChecker; import com.redhat.ceylon.compiler.typechecker.model.Class; import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.DeclarationWithProximity; import com.redhat.ceylon.compiler.typechecker.model.Functional; import com.redhat.ceylon.compiler.typechecker.model.FunctionalParameter; import com.redhat.ceylon.compiler.typechecker.model.Generic; import com.redhat.ceylon.compiler.typechecker.model.Getter; import com.redhat.ceylon.compiler.typechecker.model.ImportList; import com.redhat.ceylon.compiler.typechecker.model.Interface; import com.redhat.ceylon.compiler.typechecker.model.IntersectionType; import com.redhat.ceylon.compiler.typechecker.model.Method; import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.NothingType; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.model.Parameter; import com.redhat.ceylon.compiler.typechecker.model.ParameterList; import com.redhat.ceylon.compiler.typechecker.model.ProducedReference; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.ProducedTypedReference; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.TypeAlias; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypeParameter; import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration; import com.redhat.ceylon.compiler.typechecker.model.Unit; import com.redhat.ceylon.compiler.typechecker.model.Value; import com.redhat.ceylon.compiler.typechecker.model.ValueParameter; import com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer; import com.redhat.ceylon.compiler.typechecker.tree.Node; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Tree.MemberLiteral; import com.redhat.ceylon.compiler.typechecker.tree.Util; import com.redhat.ceylon.compiler.typechecker.tree.Visitor; import com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider; import com.redhat.ceylon.eclipse.code.parse.CeylonParseController; import com.redhat.ceylon.eclipse.code.parse.FindNodeVisitor; import com.redhat.ceylon.eclipse.core.builder.CeylonBuilder; import com.redhat.ceylon.eclipse.ui.CeylonPlugin; import com.redhat.ceylon.eclipse.ui.CeylonResources; public class CeylonContentProposer { public static Image DEFAULT_REFINEMENT = CeylonPlugin.getInstance() .getImageRegistry().get(CeylonResources.CEYLON_DEFAULT_REFINEMENT); public static Image FORMAL_REFINEMENT = CeylonPlugin.getInstance() .getImageRegistry().get(CeylonResources.CEYLON_FORMAL_REFINEMENT); /** * Returns an array of content proposals applicable relative to the AST of the given * parse controller at the given position. * * (The provided ITextViewer is not used in the default implementation provided here * but but is stipulated by the IContentProposer interface for purposes such as accessing * the IDocument for which content proposals are sought.) * * @param controller A parse controller from which the AST of the document being edited * can be obtained * @param int The offset for which content proposals are sought * @param viewer The viewer in which the document represented by the AST in the given * parse controller is being displayed (may be null for some implementations) * @return An array of completion proposals applicable relative to the AST of the given * parse controller at the given position */ public ICompletionProposal[] getContentProposals(CeylonParseController controller, final int offset, ITextViewer viewer, boolean filter) { if (controller==null || viewer==null) { return null; } CeylonParseController cpc = (CeylonParseController) controller; cpc.parse(viewer.getDocument(), new NullProgressMonitor(), null); cpc.getHandler().updateAnnotations(); List<CommonToken> tokens = cpc.getTokens(); if (tokens==null) { return null; } Tree.CompilationUnit rn = cpc.getRootNode(); if (rn==null) { return null; } //compensate for the fact that we get sent an old //tree that doesn't contain the characters the user //just typed PositionedPrefix result = compensateForMissingCharacter(offset, viewer, tokens); if (result==null) { return null; } //adjust the token to account for unclosed blocks //we search for the first non-whitespace/non-comment //token to the left of the caret int tokenIndex = getTokenIndexAtCharacter(tokens, result.start); if (tokenIndex<0) tokenIndex = -tokenIndex; CommonToken adjustedToken = adjust(tokenIndex, offset, tokens); int tt = adjustedToken.getType(); if (offset<=adjustedToken.getStopIndex() && offset>=adjustedToken.getStartIndex()) { if (tt==MULTI_COMMENT||tt==LINE_COMMENT) { return null; } if (tt==STRING_LITERAL || tt==STRING_END || tt==STRING_MID || tt==STRING_START || tt==VERBATIM_STRING || tt==AVERBATIM_STRING || tt==ASTRING_LITERAL || tt==CHAR_LITERAL || tt==FLOAT_LITERAL || tt==NATURAL_LITERAL) { return null; } } int line=-1; try { line = viewer.getDocument().getLineOfOffset(offset); } catch (BadLocationException e) { e.printStackTrace(); } if (tt==LINE_COMMENT && offset>=adjustedToken.getStartIndex() && adjustedToken.getLine()==line+1) { return null; } //find the node at the token Node node = getTokenNode(adjustedToken.getStartIndex(), adjustedToken.getStopIndex()+1, tt, rn); //find the type that is expected in the current //location so we can prioritize proposals of that //type //TODO: this breaks as soon as the user starts typing // an expression, since RequiredTypeVisitor // doesn't know how to search up the tree for // the containing InvocationExpression RequiredTypeVisitor rtv = new RequiredTypeVisitor(node); rtv.visit(rn); ProducedType requiredType = rtv.getType(); //finally, construct and sort proposals Map<String, DeclarationWithProximity> proposals = getProposals(node, result.prefix, result.isMemberOp, rn); filterProposals(filter, rn, requiredType, proposals); Set<DeclarationWithProximity> sortedProposals = sortProposals(result.prefix, requiredType, proposals); ICompletionProposal[] completions = constructCompletions(offset, result.prefix, sortedProposals, cpc, node, adjustedToken, result.isMemberOp, viewer.getDocument(), filter); return completions; } private void filterProposals(boolean filter, Tree.CompilationUnit rn, ProducedType requiredType, Map<String, DeclarationWithProximity> proposals) { if (filter) { Iterator<Map.Entry<String, DeclarationWithProximity>> iter = proposals.entrySet().iterator(); while (iter.hasNext()) { Declaration d = iter.next().getValue().getDeclaration(); ProducedType type = type(d); ProducedType fullType = fullType(d); if (requiredType!=null && (type==null || (!type.isSubtypeOf(requiredType) && !fullType.isSubtypeOf(requiredType)) || type.isSubtypeOf(rn.getUnit().getNullDeclaration().getType()))) { iter.remove(); } } } } private static OccurrenceLocation getOccurrenceLocation(Tree.CompilationUnit cu, Node node) { if (node.getToken()==null) return null; FindOccurrenceLocationVisitor visitor = new FindOccurrenceLocationVisitor(node); cu.visit(visitor); return visitor.getOccurrenceLocation(); } private static PositionedPrefix compensateForMissingCharacter(final int offset, ITextViewer viewer, List<CommonToken> tokens) { //What is going on here is that when I have a list of proposals open //and then I type a character, IMP sends us the old syntax tree and //doesn't bother to even send us the character I just typed, except //in the ITextViewer. So we need to do some guessing to figure out //that there is a missing character in the token stream and take //corrective action. This should be fixed in IMP! return getPositionedPrefix(offset, viewer, getTokenAtCaret(offset, viewer, tokens)); } private static PositionedPrefix getPositionedPrefix(final int offset, ITextViewer viewer, CommonToken token) { String text = viewer.getDocument().get(); if (token==null || offset==0) { //no earlier token, so we're typing at the //start of an empty file return new PositionedPrefix(text.substring(0, offset), 0); } //try to guess the character the user just typed //(it would be the character immediately behind //the caret, i.e. at offset-1) char charAtOffset = text.charAt(offset-1); int offsetInToken = offset-1-token.getStartIndex(); boolean inToken = offsetInToken>=0 && offsetInToken<token.getText().length(); //int end = offset; if (inToken && charAtOffset==token.getText().charAt(offsetInToken)) { //then we're not missing the typed character //from the tree we were passed by IMP if (isIdentifierOrKeyword(token)) { return new PositionedPrefix( token.getText().substring(0, offsetInToken+1), token.getStartIndex()); } else { return new PositionedPrefix(offset, isMemberOperator(token)); } } else { //then we are missing the typed character from //the tree, along with possibly some other //previously typed characters boolean isIdentifierChar = isJavaIdentifierPart(charAtOffset); if (isIdentifierChar) { if (token.getType()==CeylonLexer.WS) { //we are typing in or after whitespace String prefix = text.substring(token.getStartIndex(), offset).trim(); return new PositionedPrefix(prefix, offset-prefix.length()-1); } else if (isIdentifierOrKeyword(token)) { //we are typing in or after within an //identifier or keyword String prefix = text.substring(token.getStartIndex(), offset); return new PositionedPrefix(prefix, token.getStartIndex()); } else if (offset<=token.getStopIndex()+1) { //we are typing in or after a comment //block or strings, etc - not much //useful compensation we can do here return new PositionedPrefix( Character.toString(charAtOffset), offset-1); } else { //after a member dereference and other //misc cases of punctuation, etc return new PositionedPrefix( text.substring(token.getStopIndex()+1, offset), token.getStopIndex()); } } //disable this for now cos it causes problem in //import statements /*else if (charAtOffset=='.') { return new PositionedPrefix(offset-2, true); } else {*/ return new PositionedPrefix(offset-1, false); } } private static CommonToken getTokenAtCaret(final int offset, ITextViewer viewer, List<CommonToken> tokens) { //find the token behind the caret, adjusting to an //earlier token if the token we find is not at the //same position in the current text (in which case //it is probably a token that actually comes after //what we are currently typing) if (offset==0) { return null; } int index = getTokenIndexAtCharacter(tokens, offset-1); if (index<0) index = -index; while (index>=0) { CommonToken token = (CommonToken) tokens.get(index); String text = viewer.getDocument().get(); boolean tokenHasMoved = text.charAt(token.getStartIndex())!= token.getText().charAt(0); if (!tokenHasMoved) { return token; } index } return null; } private static class PositionedPrefix { String prefix; int start; boolean isMemberOp; PositionedPrefix(String prefix, int start) { this.prefix=prefix; this.start=start; this.isMemberOp=false; } PositionedPrefix(int start, boolean isMemberOp) { this.prefix=""; this.isMemberOp=isMemberOp; this.start=start; } } private static CommonToken adjust(int tokenIndex, int offset, List<CommonToken> tokens) { CommonToken adjustedToken = tokens.get(tokenIndex); while (--tokenIndex>=0 && (adjustedToken.getType()==WS //ignore whitespace || adjustedToken.getType()==EOF || adjustedToken.getStartIndex()==offset)) { //don't consider the token to the right of the caret adjustedToken = tokens.get(tokenIndex); if (adjustedToken.getChannel()!=WS && adjustedToken.getType()!=EOF) { //don't adjust to a ws token break; } } return adjustedToken; } private static Boolean isDirectlyInsideBlock(Node node, CommonToken token, List<CommonToken> tokens) { Scope scope = node.getScope(); if (scope instanceof Interface || scope instanceof Package) { return false; } else { //TODO: check that it is not the opening/closing // brace of a named argument list! return !(node instanceof Tree.SequenceEnumeration) && occursAfterBraceOrSemicolon(token, tokens); } } private static Boolean occursAfterBraceOrSemicolon(CommonToken token, List<CommonToken> tokens) { if (token.getTokenIndex()==0) { return false; } else { int tokenType = token.getType(); if (tokenType==LBRACE || tokenType==RBRACE || tokenType==SEMICOLON) { return true; } int previousTokenType = adjust(token.getTokenIndex()-1, token.getStartIndex(), tokens).getType(); return previousTokenType==LBRACE || previousTokenType==RBRACE || previousTokenType==SEMICOLON; } } private static Node getTokenNode(int adjustedStart, int adjustedEnd, int tokenType, Tree.CompilationUnit rn) { FindNodeVisitor visitor = new FindNodeVisitor(adjustedStart, adjustedEnd) { public void visit(Tree.MemberLiteral that) { if (inBounds(that)) { node = that; } } }; rn.visit(visitor); Node node = visitor.getNode(); if (tokenType==RBRACE || tokenType==SEMICOLON) { //We are to the right of a } or ; //so the returned node is the previous //statement/declaration. Look for the //containing body. class BodyVisitor extends Visitor { Node node, currentBody, result; BodyVisitor(Node node, Node root) { this.node = node; currentBody = root; } @Override public void visitAny(Node that) { if (that==node) { result = currentBody; } else { Node cb = currentBody; if (that instanceof Tree.Body) { currentBody = that; } if (that instanceof Tree.NamedArgumentList) { currentBody = that; } super.visitAny(that); currentBody = cb; } } } BodyVisitor mv = new BodyVisitor(node, rn); mv.visit(rn); node = mv.result; } if (node==null) node = rn; //we're in whitespace at the start of the file return node; } private static void addPackageCompletions(CeylonParseController cpc, int offset, String prefix, Tree.ImportPath path, Node node, List<ICompletionProposal> result) { String fullPath = fullPath(offset, prefix, path); addPackageCompletions(offset, prefix, node, result, fullPath.length(), fullPath+prefix, cpc); } private static void addModuleCompletions(CeylonParseController cpc, int offset, String prefix, Tree.ImportPath path, Node node, List<ICompletionProposal> result) { String fullPath = fullPath(offset, prefix, path); addModuleCompletions(offset, prefix, node, result, fullPath.length(), fullPath+prefix, cpc); } private static String fullPath(int offset, String prefix, Tree.ImportPath path) { StringBuilder fullPath = new StringBuilder(); if (path!=null) { fullPath.append(Util.formatPath(path.getIdentifiers())); fullPath.append('.'); fullPath.setLength(offset-path.getStartIndex()-prefix.length()); } return fullPath.toString(); } private static void addPackageCompletions(int offset, String prefix, Node node, List<ICompletionProposal> result, int len, String pfp, final CeylonParseController cpc) { //TODO: someday it would be nice to propose from all packages // and auto-add the module dependency! /*TypeChecker tc = CeylonBuilder.getProjectTypeChecker(cpc.getProject().getRawProject()); if (tc!=null) { for (Module m: tc.getContext().getModules().getListOfModules()) {*/ //Set<Package> packages = new HashSet<Package>(); Unit unit = node.getUnit(); if (unit!=null) { //a null unit can occur if we have not finished parsing the file Module module = unit.getPackage().getModule(); for (final Package p: module.getAllPackages()) { //if (!packages.contains(p)) { //packages.add(p); //if ( p.getModule().equals(module) || p.isShared() ) { String pkg = p.getQualifiedNameString(); if (!pkg.isEmpty() && pkg.startsWith(pfp)) { boolean already = false; if (!pfp.equals(pkg)) { //don't add already imported packages, unless //it is an exact match to the typed path for (ImportList il: node.getUnit().getImportLists()) { if (il.getImportedScope()==p) { already = true; break; } } } if (!already) { result.add(new CompletionProposal(offset, prefix, PACKAGE, pkg, pkg.substring(len), false) { @Override public String getAdditionalProposalInfo() { return getDocumentationFor(cpc, p); } }); } } } } } private static final SortedSet<String> JDK_MODULE_VERSION_SET = new TreeSet<String>(); { JDK_MODULE_VERSION_SET.add(AbstractModelLoader.JDK_MODULE_VERSION); } private static void addModuleCompletions(int offset, String prefix, Node node, List<ICompletionProposal> result, int len, String pfp, final CeylonParseController cpc) { final TypeChecker tc = cpc.getTypeChecker(); if (tc!=null) { ModuleSearchResult results = tc.getContext().getRepositoryManager() .completeModules(new ModuleQuery(pfp, ModuleQuery.Type.JVM)); for (final ModuleDetails module: results.getResults()) { if (!module.getName().equals(Module.DEFAULT_MODULE_NAME)) { for (final String version : module.getVersions().descendingSet()) { String versioned = getModuleString(module.getName(), version); result.add(new CompletionProposal(offset, prefix, ARCHIVE, versioned, versioned.substring(len), false) { @Override public String getAdditionalProposalInfo() { return getDocumentationFor(module, version); } }); } } } } } private static String getModuleString(final String name, final String version) { return name + " '" + version + "'"; } private static boolean isIdentifierOrKeyword(Token token) { int type = token.getType(); return type==LIDENTIFIER || type==UIDENTIFIER || type==AIDENTIFIER || type==PIDENTIFIER || keywords.contains(token.getText()); } private static ICompletionProposal[] constructCompletions(final int offset, final String prefix, Set<DeclarationWithProximity> set, final CeylonParseController cpc, final Node node, CommonToken token, boolean memberOp, IDocument doc, boolean filter) { final List<ICompletionProposal> result = new ArrayList<ICompletionProposal>(); if (isEmptyModuleDescriptor(cpc)) { addModuleDescriptorCompletion(cpc, offset, prefix, result); } else if (isEmptyPackageDescriptor(cpc)) { addPackageDescriptorCompletion(cpc, offset, prefix, result); } if (node instanceof Tree.Import && offset>token.getStopIndex()+1) { addPackageCompletions(cpc, offset, prefix, null, node, result); } else if (node instanceof Tree.ImportModule && offset>token.getStopIndex()+1) { addModuleCompletions(cpc, offset, prefix, null, node, result); } else if (node instanceof Tree.ImportPath) { new Visitor() { @Override public void visit(Tree.Import that) { super.visit(that); if (that.getImportPath()==node) { addPackageCompletions(cpc, offset, prefix, (Tree.ImportPath) node, node, result); } } @Override public void visit(Tree.ImportModule that) { super.visit(that); if (that.getImportPath()==node) { addModuleCompletions(cpc, offset, prefix, (Tree.ImportPath) node, node, result); } } }.visit(cpc.getRootNode()); } else if (node instanceof Tree.TypeConstraint) { for (DeclarationWithProximity dwp: set) { Declaration dec = dwp.getDeclaration(); if (isTypeParameterOfCurrentDeclaration(node, dec)) { addBasicProposal(offset, prefix, cpc, result, dwp, dec, null); } } } else { if ((node instanceof Tree.SimpleType || node instanceof Tree.BaseTypeExpression || node instanceof Tree.QualifiedTypeExpression) && prefix.isEmpty() && !memberOp) { addMemberNameProposal(offset, node, result); } else if (node instanceof Tree.Declaration && !(node instanceof Tree.Variable && ((Tree.Variable)node).getType() instanceof Tree.SyntheticVariable) && !(node instanceof Tree.InitializerParameter)) { addMemberNameProposal(offset, node, result); } else { OccurrenceLocation ol = getOccurrenceLocation(cpc.getRootNode(), node); if (//isKeywordProposable(ol) && !filter && !(node instanceof Tree.QualifiedMemberOrTypeExpression) && ol!=META) { addKeywordProposals(cpc, offset, prefix, result, node); //addTemplateProposal(offset, prefix, result); } boolean isModuleDescriptor = isModuleDescriptor(cpc); for (DeclarationWithProximity dwp: set) { Declaration dec = dwp.getDeclaration(); if (isModuleDescriptor) { String qualifiedName = dec.getQualifiedNameString(); if (!qualifiedName.equals("ceylon.language::shared") && !qualifiedName.equals("ceylon.language::optional")) { continue; } } if (isParameterOfNamedArgInvocation(node, dwp)) { if (isDirectlyInsideNamedArgumentList(cpc, node, token)) { addNamedArgumentProposal(offset, prefix, cpc, result, dwp, dec, ol); addInlineFunctionProposal(offset, prefix, cpc, node, result, dec, doc); } } CommonToken nextToken = getNextToken(cpc, token); boolean noParamsFollow = noParametersFollow(nextToken); if (isInvocationProposable(dwp, ol) && !(node instanceof Tree.QualifiedType) && !(node instanceof Tree.QualifiedMemberOrTypeExpression && ((Tree.QualifiedMemberOrTypeExpression) node).getStaticMethodReference())) { if (noParamsFollow || ol==EXTENDS) { for (Declaration d: overloads(dec)) { ProducedReference pr = node instanceof Tree.QualifiedMemberOrTypeExpression ? getQualifiedProducedReference(node, d) : getRefinedProducedReference(node, d); addInvocationProposals(offset, prefix, cpc, result, new DeclarationWithProximity(d, dwp), pr, ol); } } } if (isProposable(dwp, ol, node.getScope())) { if (noParamsFollow || ol==SATISFIES || ol==OF || ol==UPPER_BOUND || dwp.getDeclaration() instanceof Functional) { addBasicProposal(offset, prefix, cpc, result, dwp, dec, ol); } if (isDirectlyInsideBlock(node, token, cpc.getTokens()) && !memberOp && !filter) { addForProposal(offset, prefix, cpc, result, dwp, dec, ol); addIfExistsProposal(offset, prefix, cpc, result, dwp, dec, ol); addSwitchProposal(offset, prefix, cpc, result, dwp, dec, ol, node, doc); } } if (isRefinementProposable(dec, ol) && !memberOp && !filter) { for (Declaration d: overloads(dec)) { addRefinementProposal(offset, prefix, cpc, node, result, d, doc); } } } } } return result.toArray(new ICompletionProposal[result.size()]); } private static boolean isModuleDescriptor(CeylonParseController cpc) { return cpc.getRootNode().getUnit().getFilename().equals("module.ceylon"); } private static boolean isEmptyModuleDescriptor(CeylonParseController cpc) { return isModuleDescriptor(cpc) && cpc.getRootNode() != null && cpc.getRootNode().getModuleDescriptor() == null; } private static void addModuleDescriptorCompletion(CeylonParseController cpc, int offset, String prefix, List<ICompletionProposal> result) { IFile file = cpc.getProject().getFile(cpc.getPath()); String moduleName = CeylonBuilder.getPackageName(file); String moduleDesc = "module " + moduleName; String moduleText = "module " + moduleName + " 'version' {}"; final int selectionStart = offset - prefix.length() + moduleName.length() + 9; final int selectionLength = 7; result.add(new CompletionProposal(offset, prefix, ARCHIVE, moduleDesc, moduleText, false) { @Override public Point getSelection(IDocument document) { return new Point(selectionStart, selectionLength); }}); } private static boolean isEmptyPackageDescriptor(CeylonParseController cpc) { return cpc.getRootNode().getUnit().getFilename().equals("package.ceylon") && cpc.getRootNode() != null && cpc.getRootNode().getPackageDescriptor() == null; } private static void addPackageDescriptorCompletion(CeylonParseController cpc, int offset, String prefix, List<ICompletionProposal> result) { IFile file = cpc.getProject().getFile(cpc.getPath()); String packageName = CeylonBuilder.getPackageName(file); String packageDesc = "package " + packageName; String packageText = "package " + packageName + ";"; result.add(new CompletionProposal(offset, prefix, PACKAGE, packageDesc, packageText, false)); } private static boolean noParametersFollow(CommonToken nextToken) { return nextToken==null || //should we disable this, since a statement //can in fact begin with an LPAREN?? nextToken.getType()!=CeylonLexer.LPAREN //disabled now because a declaration can //begin with an LBRACE (an Iterable type) /*&& nextToken.getType()!=CeylonLexer.LBRACE*/; } private static CommonToken getNextToken(final CeylonParseController cpc, CommonToken token) { int i = token.getTokenIndex(); CommonToken nextToken=null; List<CommonToken> tokens = cpc.getTokens(); do { if (++i<tokens.size()) { nextToken = tokens.get(i); } else { break; } } while (nextToken.getChannel()==CommonToken.HIDDEN_CHANNEL); return nextToken; } private static boolean isDirectlyInsideNamedArgumentList( CeylonParseController cpc, Node node, CommonToken token) { return node instanceof Tree.NamedArgumentList || (!(node instanceof Tree.SequenceEnumeration) && occursAfterBraceOrSemicolon(token, cpc.getTokens())); } private static boolean isMemberOperator(Token token) { int type = token.getType(); return type==CeylonLexer.MEMBER_OP || type==CeylonLexer.SPREAD_OP || type==CeylonLexer.SAFE_MEMBER_OP; } private static List<Declaration> overloads(Declaration dec) { List<Declaration> decs; if (dec instanceof Functional && ((Functional)dec).isAbstraction()) { decs = ((Functional)dec).getOverloads(); } else { decs = Collections.singletonList(dec); } return decs; } /*private static boolean isKeywordProposable(OccurrenceLocation ol) { return ol==null || ol==EXPRESSION; }*/ private static boolean isRefinementProposable(Declaration dec, OccurrenceLocation ol) { return ol==null && (dec instanceof MethodOrValue || dec instanceof Class); } private static boolean isInvocationProposable(DeclarationWithProximity dwp, OccurrenceLocation ol) { Declaration dec = dwp.getDeclaration(); return dec instanceof Functional && //!((Functional) dec).getParameterLists().isEmpty() && (ol==null || ol==EXPRESSION || ol==EXTENDS && dec instanceof Class) && dwp.getNamedArgumentList()==null; } private static boolean isProposable(DeclarationWithProximity dwp, OccurrenceLocation ol, Scope scope) { Declaration dec = dwp.getDeclaration(); return (dec instanceof Class || ol!=EXTENDS) && (dec instanceof Interface || ol!=SATISFIES) && (dec instanceof Class || (dec instanceof Value && ((Value) dec).getTypeDeclaration() != null && ((Value) dec).getTypeDeclaration().isAnonymous()) || ol!=OF) && (dec instanceof TypeDeclaration || (ol!=TYPE_ARGUMENT_LIST && ol!=UPPER_BOUND)) && (dec instanceof TypeDeclaration || dec instanceof Method && dec.isToplevel() || //i.e. an annotation dec instanceof Value && dec.getContainer().equals(scope) || ol!=PARAMETER_LIST) && (ol!=IMPORT || !dwp.isUnimported()) && ol!=TYPE_PARAMETER_LIST && dwp.getNamedArgumentList()==null; } private static boolean isTypeParameterOfCurrentDeclaration(Node node, Declaration d) { //TODO: this is a total mess and totally error-prone - figure out something better! return d instanceof TypeParameter && (((TypeParameter) d).getContainer()==node.getScope() || ((Tree.TypeConstraint) node).getDeclarationModel()!=null && ((TypeParameter) d).getContainer()==((Tree.TypeConstraint) node).getDeclarationModel().getContainer()); } private static void addInlineFunctionProposal(int offset, String prefix, CeylonParseController cpc, Node node, List<ICompletionProposal> result, Declaration d, IDocument doc) { //TODO: type argument substitution using the ProducedReference of the primary node if (d instanceof Parameter) { Parameter p = (Parameter) d; result.add(new RefinementCompletionProposal(offset, prefix, getInlineFunctionDescriptionFor(p, null), getInlineFunctionTextFor(p, null, "\n" + getIndent(node, doc)), cpc, d)); } } /*private static boolean isParameterOfNamedArgInvocation(Node node, Declaration d) { if (node instanceof Tree.NamedArgumentList) { ParameterList pl = ((Tree.NamedArgumentList) node).getNamedArgumentList() .getParameterList(); return d instanceof Parameter && pl!=null && pl.getParameters().contains(d); } else if (node.getScope() instanceof NamedArgumentList) { ParameterList pl = ((NamedArgumentList) node.getScope()).getParameterList(); return d instanceof Parameter && pl!=null && pl.getParameters().contains(d); } else { return false; } }*/ private static boolean isParameterOfNamedArgInvocation(Node node, DeclarationWithProximity d) { return node.getScope()==d.getNamedArgumentList(); } private static void addRefinementProposal(int offset, String prefix, final CeylonParseController cpc, Node node, List<ICompletionProposal> result, final Declaration d, IDocument doc) { if ((d.isDefault() || d.isFormal()) && node.getScope() instanceof ClassOrInterface && ((ClassOrInterface) node.getScope()).isInheritedFromSupertype(d)) { boolean isInterface = node.getScope() instanceof Interface; ProducedReference pr = getRefinedProducedReference(node, d); //TODO: if it is equals() or hash, fill in the implementation result.add(new RefinementCompletionProposal(offset, prefix, getRefinementDescriptionFor(d, pr), getRefinementTextFor(d, pr, isInterface, "\n" + getIndent(node, doc)), cpc, d)); } } public static ProducedReference getQualifiedProducedReference(Node node, Declaration d) { ProducedType pt = ((Tree.QualifiedMemberOrTypeExpression) node) .getPrimary().getTypeModel(); if (pt!=null && d.isClassOrInterfaceMember()) { pt = pt.getSupertype((TypeDeclaration)d.getContainer()); } return d.getProducedReference(pt, Collections.<ProducedType>emptyList()); } public static ProducedReference getRefinedProducedReference(Node node, Declaration d) { return refinedProducedReference(node.getScope().getDeclaringType(d), d); } public static ProducedReference getRefinedProducedReference(ProducedType superType, Declaration d) { if (superType.getDeclaration() instanceof IntersectionType) { for (ProducedType pt: superType.getDeclaration().getSatisfiedTypes()) { ProducedReference result = getRefinedProducedReference(pt, d); if (result!=null) return result; } return null; //never happens? } else { ProducedType declaringType = superType.getDeclaration().getDeclaringType(d); if (declaringType==null) return null; ProducedType outerType = superType.getSupertype(declaringType.getDeclaration()); return refinedProducedReference(outerType, d); } } private static ProducedReference refinedProducedReference(ProducedType outerType, Declaration d) { List<ProducedType> params = new ArrayList<ProducedType>(); if (d instanceof Generic) { for (TypeParameter tp: ((Generic)d).getTypeParameters()) { params.add(tp.getType()); } } return d.getProducedReference(outerType, params); } private static void addBasicProposal(int offset, String prefix, CeylonParseController cpc, List<ICompletionProposal> result, DeclarationWithProximity dwp, Declaration d, OccurrenceLocation ol) { result.add(new DeclarationCompletionProposal(offset, prefix, getDescriptionFor(dwp, ol), getTextFor(dwp, ol), true, cpc, d, dwp.isUnimported())); } private static void addForProposal(int offset, String prefix, CeylonParseController cpc, List<ICompletionProposal> result, DeclarationWithProximity dwp, Declaration d, OccurrenceLocation ol) { if (d instanceof Value || d instanceof Getter || d instanceof ValueParameter) { TypedDeclaration td = (TypedDeclaration) d; if (td.getType()!=null && d.getUnit().isIterableType(td.getType())) { String elemName; if (d.getName().length()==1) { elemName = "element"; } else if (d.getName().endsWith("s")) { elemName = d.getName().substring(0, d.getName().length()-1); } else { elemName = d.getName().substring(0, 1); } result.add(new DeclarationCompletionProposal(offset, prefix, "for (" + elemName + " in " + getDescriptionFor(dwp, ol) + ")", "for (" + elemName + " in " + getTextFor(dwp, ol) + ") {}", true, cpc, d)); } } } private static void addIfExistsProposal(int offset, String prefix, CeylonParseController cpc, List<ICompletionProposal> result, DeclarationWithProximity dwp, Declaration d, OccurrenceLocation ol) { if (!dwp.isUnimported()) { if (d instanceof Value || d instanceof ValueParameter) { TypedDeclaration v = (TypedDeclaration) d; if (v.getType()!=null && d.getUnit().isOptionalType(v.getType()) && !v.isVariable()) { result.add(new DeclarationCompletionProposal(offset, prefix, "if (exists " + getDescriptionFor(dwp, ol) + ")", "if (exists " + getTextFor(dwp, ol) + ") {}", true, cpc, d)); } } } } private static void addSwitchProposal(int offset, String prefix, CeylonParseController cpc, List<ICompletionProposal> result, DeclarationWithProximity dwp, Declaration d, OccurrenceLocation ol, Node node, IDocument doc) { if (!dwp.isUnimported()) { if (d instanceof Value || d instanceof ValueParameter) { TypedDeclaration v = (TypedDeclaration) d; if (v.getType()!=null && v.getType().getCaseTypes()!=null && !v.isVariable()) { StringBuilder body = new StringBuilder(); String indent = getIndent(node, doc); for (ProducedType pt: v.getType().getCaseTypes()) { body.append(indent).append("case ("); if (!pt.getDeclaration().isAnonymous()) { body.append("is "); } body.append(pt.getProducedTypeName()); body.append(") {}\n"); } body.append(indent); result.add(new DeclarationCompletionProposal(offset, prefix, "switch (" + getDescriptionFor(dwp, ol) + ")", "switch (" + getTextFor(dwp, ol) + ")\n" + body, true, cpc, d)); } } } } private static void addNamedArgumentProposal(int offset, String prefix, CeylonParseController cpc, List<ICompletionProposal> result, DeclarationWithProximity dwp, Declaration d, OccurrenceLocation ol) { result.add(new DeclarationCompletionProposal(offset, prefix, getDescriptionFor(dwp, ol), getTextFor(dwp, ol) + " = nothing;", true, cpc, d)); } private static void addInvocationProposals(int offset, String prefix, CeylonParseController cpc, List<ICompletionProposal> result, DeclarationWithProximity dwp, ProducedReference pr, OccurrenceLocation ol) { Declaration d = pr.getDeclaration(); if (!(d instanceof Functional)) return; boolean isAbstractClass = d instanceof Class && ((Class) d).isAbstract(); Functional fd = (Functional) d; List<ParameterList> pls = fd.getParameterLists(); if (!pls.isEmpty()) { List<Parameter> ps = pls.get(0).getParameters(); int defaulted = 0; for (Parameter p: ps) { if (p.isDefaulted()) { defaulted ++; } } if (!isAbstractClass || ol==EXTENDS) { if (defaulted>0) { result.add(new DeclarationCompletionProposal(offset, prefix, getPositionalInvocationDescriptionFor(dwp, ol, pr, false), getPositionalInvocationTextFor(dwp, ol, pr, false), true, cpc, d, dwp.isUnimported())); } result.add(new DeclarationCompletionProposal(offset, prefix, getPositionalInvocationDescriptionFor(dwp, ol, pr, true), getPositionalInvocationTextFor(dwp, ol, pr, true), true, cpc, d, dwp.isUnimported())); } if (!isAbstractClass && ol!=EXTENDS && !fd.isOverloaded()) { //if there is more than one parameter, //suggest a named argument invocation if (defaulted>0 && ps.size()-defaulted>1) { result.add(new DeclarationCompletionProposal(offset, prefix, getNamedInvocationDescriptionFor(dwp, pr, false), getNamedInvocationTextFor(dwp, pr, false), true, cpc, d, dwp.isUnimported())); } if (ps.size()>1) { result.add(new DeclarationCompletionProposal(offset, prefix, getNamedInvocationDescriptionFor(dwp, pr, true), getNamedInvocationTextFor(dwp, pr, true), true, cpc, d, dwp.isUnimported())); } } } } protected static void addMemberNameProposal(int offset, Node node, List<ICompletionProposal> result) { String suggestedName = null; String prefix = ""; if (node instanceof Tree.TypeDeclaration) { /*Tree.TypeDeclaration td = (Tree.TypeDeclaration) node; prefix = td.getIdentifier()==null ? "" : td.getIdentifier().getText(); suggestedName = prefix;*/ //TODO: dictionary completions? return; } else if (node instanceof Tree.TypedDeclaration) { Tree.TypedDeclaration td = (Tree.TypedDeclaration) node; prefix = td.getIdentifier()==null ? "" : td.getIdentifier().getText(); suggestedName = prefix; if (td.getType() instanceof Tree.SimpleType) { String type = ((Tree.SimpleType) td.getType()).getIdentifier().getText(); if (lower(type).startsWith(prefix)) { result.add(new CompletionProposal(offset, prefix, null, lower(type), escape(lower(type)), false)); } if (!suggestedName.endsWith(type)) { suggestedName += type; } result.add(new CompletionProposal(offset, prefix, null, lower(suggestedName), escape(lower(suggestedName)), false)); } return; } else if (node instanceof Tree.SimpleType) { suggestedName = ((Tree.SimpleType) node).getIdentifier().getText(); } else if (node instanceof Tree.BaseTypeExpression) { suggestedName = ((Tree.BaseTypeExpression) node).getIdentifier().getText(); } else if (node instanceof Tree.QualifiedTypeExpression) { suggestedName = ((Tree.QualifiedTypeExpression) node).getIdentifier().getText(); } if (suggestedName!=null) { result.add(new CompletionProposal(offset, "", null, lower(suggestedName), escape(lower(suggestedName)), false)); } } private static String lower(String suggestedName) { return Character.toLowerCase(suggestedName.charAt(0)) + suggestedName.substring(1); } private static String escape(String suggestedName) { if (keywords.contains(suggestedName)) { return "\\i" + suggestedName; } else { return suggestedName; } } private static void addKeywordProposals(CeylonParseController cpc, int offset, String prefix, List<ICompletionProposal> result, Node node) { if( isModuleDescriptor(cpc) ) { if( prefix.isEmpty() || "import".startsWith(prefix) ) { if (node instanceof Tree.CompilationUnit) { Tree.ModuleDescriptor moduleDescriptor = ((Tree.CompilationUnit) node).getModuleDescriptor(); if (moduleDescriptor != null && moduleDescriptor.getImportModuleList() != null && moduleDescriptor.getImportModuleList().getStartIndex() < offset ) { addKeywordProposal(offset, prefix, result, "import"); } } else if (node instanceof Tree.ImportModuleList || node instanceof Tree.BaseMemberExpression) { addKeywordProposal(offset, prefix, result, "import"); } } } else if (!prefix.isEmpty()) { for (String keyword: keywords) { if (keyword.startsWith(prefix)) { addKeywordProposal(offset, prefix, result, keyword); } } } } private static void addKeywordProposal(int offset, String prefix, List<ICompletionProposal> result, final String keyword) { result.add(new CompletionProposal(offset, prefix, null, keyword, keyword, true) { @Override public StyledString getStyledDisplayString() { return new StyledString(keyword, CeylonLabelProvider.KW_STYLER); } }); } /*private static void addTemplateProposal(int offset, String prefix, List<ICompletionProposal> result) { if (!prefix.isEmpty()) { if ("class".startsWith(prefix)) { String prop = "class Class() {}"; result.add(sourceProposal(offset, prefix, null, null, prop, prop, true)); } if ("interface".startsWith(prefix)) { String prop = "interface Interface {}"; result.add(sourceProposal(offset, prefix, null, null, prop, prop, true)); } if ("void".startsWith(prefix)) { String prop = "void method() {}"; result.add(sourceProposal(offset, prefix, null, null, prop, prop, true)); } if ("function".startsWith(prefix)) { String prop = "function method() { return nothing; }"; result.add(sourceProposal(offset, prefix, null, null, prop, prop, true)); } if ("value".startsWith(prefix)) { String prop = "value attribute = nothing;"; result.add(sourceProposal(offset, prefix, null, null, prop, prop, true)); prop = "value attribute { return nothing; }"; result.add(sourceProposal(offset, prefix, null, null, prop, prop, true)); } if ("object".startsWith(prefix)) { String prop = "object instance {}"; result.add(sourceProposal(offset, prefix, null, null, prop, prop, true)); } } }*/ /*private static String getDocumentationFor(CeylonParseController cpc, Declaration d) { return getDocumentation(getReferencedNode(d, getCompilationUnit(cpc, d))); }*/ private static Set<DeclarationWithProximity> sortProposals(final String prefix, final ProducedType type, Map<String, DeclarationWithProximity> proposals) { Set<DeclarationWithProximity> set = new TreeSet<DeclarationWithProximity>( new Comparator<DeclarationWithProximity>() { public int compare(DeclarationWithProximity x, DeclarationWithProximity y) { ProducedType xtype = type(x.getDeclaration()); ProducedType ytype = type(y.getDeclaration()); boolean xbottom = xtype!=null && xtype.getDeclaration() instanceof NothingType; boolean ybottom = ytype!=null && ytype.getDeclaration() instanceof NothingType; if (xbottom && !ybottom) { return 1; } if (ybottom && !xbottom) { return -1; } String xName = x.getName(); String yName = y.getName(); if (!prefix.isEmpty() && isUpperCase(prefix.charAt(0))) { if (isLowerCase(xName.charAt(0)) && isUpperCase(yName.charAt(0))) { return 1; } else if (isUpperCase(xName.charAt(0)) && isLowerCase(yName.charAt(0))) { return -1; } } if (type!=null) { boolean xassigns = xtype!=null && xtype.isSubtypeOf(type); boolean yassigns = ytype!=null && ytype.isSubtypeOf(type); if (xassigns && !yassigns) { return -1; } if (yassigns && !xassigns) { return 1; } if (xassigns && yassigns) { boolean xtd = x.getDeclaration() instanceof TypedDeclaration; boolean ytd = y.getDeclaration() instanceof TypedDeclaration; if (xtd && !ytd) { return -1; } if (ytd && !xtd) { return 1; } } } if (x.getProximity()!=y.getProximity()) { return new Integer(x.getProximity()).compareTo(y.getProximity()); } //if (!prefix.isEmpty() && isLowerCase(prefix.charAt(0))) { if (isLowerCase(xName.charAt(0)) && isUpperCase(yName.charAt(0))) { return -1; } else if (isUpperCase(xName.charAt(0)) && isLowerCase(yName.charAt(0))) { return 1; } int nc = xName.compareTo(yName); if (nc==0) { String xqn = x.getDeclaration().getQualifiedNameString(); String yqn = y.getDeclaration().getQualifiedNameString(); return xqn.compareTo(yqn); } else { return nc; } } }); set.addAll(proposals.values()); return set; } static ProducedType type(Declaration d) { if (d instanceof TypeDeclaration) { if (d instanceof Class) { if (!((Class) d).isAbstract()) { return ((TypeDeclaration) d).getType(); } } return null; } else if (d instanceof TypedDeclaration) { return ((TypedDeclaration) d).getType(); } else { return null;//impossible } } static ProducedType fullType(Declaration d) { //TODO: substitute type args from surrounding scope return d.getProducedReference(null, Collections.<ProducedType>emptyList()).getFullType(); } public static Map<String, DeclarationWithProximity> getProposals(Node node, Tree.CompilationUnit cu) { return getProposals(node, "", false, cu); } private static Map<String, DeclarationWithProximity> getProposals(Node node, String prefix, boolean memberOp, Tree.CompilationUnit cu) { if (node instanceof MemberLiteral) { //this case is very ugly! it's actually of form `Type. ProducedType type = ((Tree.MemberLiteral) node).getType().getTypeModel(); if (type!=null) { return type.resolveAliases().getDeclaration() .getMatchingMemberDeclarations(node.getScope(), prefix, 0); } else { return Collections.emptyMap(); } } else if (node instanceof Tree.QualifiedMemberOrTypeExpression) { Tree.QualifiedMemberOrTypeExpression qmte = (Tree.QualifiedMemberOrTypeExpression) node; ProducedType type = getPrimaryType((Tree.QualifiedMemberOrTypeExpression) node); if (qmte.getStaticMethodReference()) { type = node.getUnit().getCallableReturnType(type); } if (type!=null) { return type.resolveAliases().getDeclaration() .getMatchingMemberDeclarations(node.getScope(), prefix, 0); } else if (qmte.getPrimary() instanceof Tree.MemberOrTypeExpression) { //it might be a qualified type or even a static method reference Declaration pmte = ((Tree.MemberOrTypeExpression) qmte.getPrimary()).getDeclaration(); if (pmte instanceof TypeDeclaration) { type = ((TypeDeclaration) pmte).getType(); if (type!=null) { return type.resolveAliases().getDeclaration() .getMatchingMemberDeclarations(node.getScope(), prefix, 0); } } } return Collections.emptyMap(); } else if (node instanceof Tree.QualifiedType) { ProducedType type = ((Tree.QualifiedType) node).getOuterType().getTypeModel(); if (type!=null) { return type.resolveAliases().getDeclaration() .getMatchingMemberDeclarations(node.getScope(), prefix, 0); } else { return Collections.emptyMap(); } } else if (memberOp && node instanceof Tree.Term) { ProducedType type = ((Tree.Term)node).getTypeModel(); if (type!=null) { return type.resolveAliases().getDeclaration() .getMatchingMemberDeclarations(node.getScope(), prefix, 0); } else { return Collections.emptyMap(); } } else { Scope scope = node.getScope(); if (scope instanceof ImportList) { return ((ImportList) scope).getMatchingDeclarations(null, prefix, 0); } else { return scope==null ? //a null scope occurs when we have not finished parsing the file getUnparsedProposals(cu, prefix) : scope.getMatchingDeclarations(node.getUnit(), prefix, 0); } } } private static ProducedType getPrimaryType(Tree.QualifiedMemberOrTypeExpression qme) { ProducedType type = qme.getPrimary().getTypeModel(); if (type==null) return null; if (qme.getMemberOperator() instanceof Tree.SafeMemberOp) { return qme.getUnit().getDefiniteType(type); } else if (qme.getMemberOperator() instanceof Tree.SpreadOp) { return qme.getUnit().getIteratedType(type); } else { return type; } } private static Map<String, DeclarationWithProximity> getUnparsedProposals(Node node, String prefix) { if (node == null) { return new TreeMap<String, DeclarationWithProximity>(); } Unit unit = node.getUnit(); if (unit == null) { return new TreeMap<String, DeclarationWithProximity>(); } Package pkg = unit.getPackage(); if (pkg == null) { return new TreeMap<String, DeclarationWithProximity>(); } return pkg.getModule().getAvailableDeclarations(prefix); } private static boolean forceExplicitTypeArgs(Declaration d, OccurrenceLocation ol) { if (ol==EXTENDS) { return true; } else { //TODO: this is a pretty limited implementation // for now, but eventually we could do // something much more sophisticated to // guess is explicit type args will be // necessary (variance, etc) if (d instanceof Functional) { List<ParameterList> pls = ((Functional) d).getParameterLists(); return pls.isEmpty() || pls.get(0).getParameters().isEmpty(); } else { return false; } } } private static String name(DeclarationWithProximity d) { return name(d.getDeclaration(), d.getName()); } private static String name(Declaration d) { return name(d, d.getName()); } private static String name(Declaration d, String alias) { char c = alias.charAt(0); if (d instanceof TypedDeclaration && (isUpperCase(c)||"object".equals(alias))) { return "\\i" + alias; } else if (d instanceof TypeDeclaration && !(d instanceof Class && d.isAnonymous()) && isLowerCase(c)) { return "\\I" + alias; } else { return alias; } } private static String getTextFor(DeclarationWithProximity d, OccurrenceLocation ol) { StringBuilder result = new StringBuilder(name(d)); if (ol!=IMPORT) appendTypeParameters(d.getDeclaration(), result); return result.toString(); } private static String getPositionalInvocationTextFor(DeclarationWithProximity d, OccurrenceLocation ol, ProducedReference pr, boolean includeDefaulted) { StringBuilder result = new StringBuilder(name(d)); if (forceExplicitTypeArgs(d.getDeclaration(), ol)) appendTypeParameters(d.getDeclaration(), result); appendPositionalArgs(d.getDeclaration(), pr, result, includeDefaulted); return result.toString(); } private static String getNamedInvocationTextFor(DeclarationWithProximity d, ProducedReference pr, boolean includeDefaulted) { StringBuilder result = new StringBuilder(name(d)); if (forceExplicitTypeArgs(d.getDeclaration(), null)) appendTypeParameters(d.getDeclaration(), result); appendNamedArgs(d.getDeclaration(), pr, result, includeDefaulted, false); return result.toString(); } private static String getDescriptionFor(DeclarationWithProximity d, OccurrenceLocation ol) { StringBuilder result = new StringBuilder(d.getName()); if (ol!=IMPORT) appendTypeParameters(d.getDeclaration(), result); return result.toString(); } private static String getPositionalInvocationDescriptionFor(DeclarationWithProximity d, OccurrenceLocation ol, ProducedReference pr, boolean includeDefaulted) { StringBuilder result = new StringBuilder(d.getName()); if (forceExplicitTypeArgs(d.getDeclaration(), ol)) appendTypeParameters(d.getDeclaration(), result); appendPositionalArgs(d.getDeclaration(), pr, result, includeDefaulted); return result.toString(); } private static String getNamedInvocationDescriptionFor(DeclarationWithProximity d, ProducedReference pr, boolean includeDefaulted) { StringBuilder result = new StringBuilder(d.getName()); if (forceExplicitTypeArgs(d.getDeclaration(), null)) appendTypeParameters(d.getDeclaration(), result); appendNamedArgs(d.getDeclaration(), pr, result, includeDefaulted, true); return result.toString(); } public static String getRefinementTextFor(Declaration d, ProducedReference pr, boolean isInterface, String indent) { StringBuilder result = new StringBuilder("shared actual "); if (isVariable(d) && !isInterface) { result.append("variable "); } appendDeclarationText(d, pr, result); appendTypeParameters(d, result); appendParameters(d, pr, result); if (d instanceof Class) { result.append(extraIndent(extraIndent(indent))) .append(" extends super.").append(d.getName()); appendPositionalArgs(d, pr, result, true); } appendConstraints(d, pr, indent, result); appendImpl(d, isInterface, indent, result); return result.toString(); } private static void appendConstraints(Declaration d, ProducedReference pr, String indent, StringBuilder result) { if (d instanceof Functional) { for (TypeParameter tp: ((Functional) d).getTypeParameters()) { List<ProducedType> sts = tp.getSatisfiedTypes(); if (!sts.isEmpty()) { result.append(extraIndent(extraIndent(indent))) .append("given ").append(tp.getName()) .append(" satisfies "); boolean first = true; for (ProducedType st: sts) { if (first) { first = false; } else { result.append("&"); } result.append(st.substitute(pr.getTypeArguments()).getProducedTypeName()); } } } } } private static String getInlineFunctionTextFor(Parameter p, ProducedReference pr, String indent) { StringBuilder result = new StringBuilder(); appendNamedArgumentText(p, pr, result); appendTypeParameters(p, result); appendParameters(p, pr, result); appendImpl(p, false, indent, result); return result.toString(); } private static boolean isVariable(Declaration d) { return d instanceof TypedDeclaration && ((TypedDeclaration) d).isVariable(); } /*private static String getAttributeRefinementTextFor(Declaration d) { StringBuilder result = new StringBuilder(); result.append("super.").append(d.getName()) .append(" = ").append(d.getName()).append(";"); return result.toString(); }*/ private static String getRefinementDescriptionFor(Declaration d, ProducedReference pr) { StringBuilder result = new StringBuilder("shared actual "); if (isVariable(d)) { result.append("variable "); } appendDeclarationText(d, pr, result); appendTypeParameters(d, result); appendParameters(d, pr, result); /*result.append(" - refine declaration in ") .append(((Declaration) d.getContainer()).getName());*/ return result.toString(); } private static String getInlineFunctionDescriptionFor(Parameter p, ProducedReference pr) { StringBuilder result = new StringBuilder(); appendNamedArgumentText(p, pr, result); appendTypeParameters(p, result); appendParameters(p, pr, result); /*result.append(" - refine declaration in ") .append(((Declaration) d.getContainer()).getName());*/ return result.toString(); } public static String getDescriptionFor(Declaration d) { StringBuilder result = new StringBuilder(); if (d!=null) { if (d.isFormal()) result.append("formal "); if (d.isDefault()) result.append("default "); appendDeclarationText(d, result); appendTypeParameters(d, result); appendParameters(d, result); /*result.append(" - refine declaration in ") .append(((Declaration) d.getContainer()).getName());*/ } return result.toString(); } public static StyledString getStyledDescriptionFor(Declaration d) { StyledString result = new StyledString(); if (d!=null) { if (d.isFormal()) result.append("formal ", ANN_STYLER); if (d.isDefault()) result.append("default ", ANN_STYLER); appendDeclarationText(d, result); appendTypeParameters(d, result); appendParameters(d, result); /*result.append(" - refine declaration in ") .append(((Declaration) d.getContainer()).getName());*/ } return result; } private static void appendPositionalArgs(Declaration d, ProducedReference pr, StringBuilder result, boolean includeDefaulted) { if (d instanceof Functional) { List<Parameter> params = getParameters((Functional) d, includeDefaulted); if (params.isEmpty()) { result.append("()"); } else { result.append("("); for (Parameter p: params) { appendParameters(p, pr.getTypedParameter(p), result); if (p instanceof FunctionalParameter) { result.append(" => "); } result.append(p.getName()).append(", "); } result.setLength(result.length()-2); result.append(")"); } } } private static List<Parameter> getParameters(Functional fd, boolean includeDefaults) { List<ParameterList> plists = fd.getParameterLists(); if (plists==null || plists.isEmpty()) { return Collections.<Parameter>emptyList(); } List<Parameter> pl = plists.get(0).getParameters(); if (includeDefaults) { return pl; } else { List<Parameter> list = new ArrayList<Parameter>(); for (Parameter p: pl) { if (!p.isDefaulted()) list.add(p); } return list; } } private static void appendNamedArgs(Declaration d, ProducedReference pr, StringBuilder result, boolean includeDefaulted, boolean descriptionOnly) { if (d instanceof Functional) { List<Parameter> params = getParameters((Functional) d, includeDefaulted); if (params.isEmpty()) { result.append(" {}"); } else { result.append(" { "); for (Parameter p: params) { if (!p.isSequenced()) { if (p instanceof FunctionalParameter) { result.append("function ").append(p.getName()); appendParameters(p, pr.getTypedParameter(p), result); if (descriptionOnly) { result.append("; "); } else { result.append(" => ") //.append(CeylonQuickFixAssistant.defaultValue(p.getUnit(), p.getType())) .append("nothing") .append("; "); } } else { result.append(p.getName()).append(" = ") //.append(CeylonQuickFixAssistant.defaultValue(p.getUnit(), p.getType())) .append("nothing") .append("; "); } } } result.append("}"); } } } private static void appendTypeParameters(Declaration d, StringBuilder result) { if (d instanceof Generic) { List<TypeParameter> types = ((Generic) d).getTypeParameters(); if (!types.isEmpty()) { result.append("<"); for (TypeParameter p: types) { result.append(p.getName()).append(", "); } result.setLength(result.length()-2); result.append(">"); } } } private static void appendTypeParameters(Declaration d, StyledString result) { if (d instanceof Generic) { List<TypeParameter> types = ((Generic) d).getTypeParameters(); if (!types.isEmpty()) { result.append("<"); int len = types.size(), i = 0; for (TypeParameter p: types) { result.append(p.getName(), TYPE_STYLER); if (++i<len) result.append(", "); } result.append(">"); } } } private static void appendDeclarationText(Declaration d, StringBuilder result) { appendDeclarationText(d, null, result); } private static void appendDeclarationText(Declaration d, ProducedReference pr, StringBuilder result) { if (d instanceof Class) { if (d.isAnonymous()) { result.append("object"); } else { result.append("class"); } } else if (d instanceof Interface) { result.append("interface"); } else if (d instanceof TypeAlias) { result.append("alias"); } else if (d instanceof TypedDeclaration) { TypedDeclaration td = (TypedDeclaration) d; ProducedType type = td.getType(); if (type!=null) { boolean isSequenced = (d instanceof Parameter) && ((Parameter) d).isSequenced(); if (pr!=null) { type = type.substitute(pr.getTypeArguments()); } if (isSequenced) { type = d.getUnit().getIteratedType(type); } String typeName = type.getProducedTypeName(); if (td instanceof Value && td.getTypeDeclaration().isAnonymous()) { result.append("object"); } else if (d instanceof Method || d instanceof FunctionalParameter) { if (((Functional) d).isDeclaredVoid()) { result.append("void"); } else { result.append(typeName); } } else { result.append(typeName); } if (isSequenced) { if (((Parameter) d).isAtLeastOne()) { result.append("+"); } else { result.append("*"); } } } } result.append(" ").append(name(d)); } private static void appendNamedArgumentText(Parameter p, ProducedReference pr, StringBuilder result) { if (p instanceof FunctionalParameter) { FunctionalParameter fp = (FunctionalParameter) p; result.append(fp.isDeclaredVoid() ? "void" : "function"); } else { result.append("value"); } result.append(" ").append(p.getName()); } private static void appendDeclarationText(Declaration d, StyledString result) { if (d instanceof Class) { if (d.isAnonymous()) { result.append("object", KW_STYLER); } else { result.append("class", KW_STYLER); } } else if (d instanceof Interface) { result.append("interface", KW_STYLER); } else if (d instanceof TypeAlias) { result.append("alias", KW_STYLER); } else if (d instanceof TypedDeclaration) { TypedDeclaration td = (TypedDeclaration) d; ProducedType type = td.getType(); if (type!=null) { boolean isSequenced = (d instanceof Parameter) && ((Parameter) d).isSequenced(); if (isSequenced) { type = d.getUnit().getIteratedType(type); } String typeName = type.getProducedTypeName(); if (td instanceof Value && td.getTypeDeclaration().isAnonymous()) { result.append("object", KW_STYLER); } else if (d instanceof Method || d instanceof FunctionalParameter) { if (((Functional)d).isDeclaredVoid()) { result.append("void", KW_STYLER); } else { result.append(typeName, TYPE_STYLER); } } else { result.append(typeName, TYPE_STYLER); } if (isSequenced) { result.append("*"); } } } result.append(" "); if (d instanceof TypeDeclaration) { result.append(d.getName(), TYPE_STYLER); } else { result.append(d.getName(), ID_STYLER); } } /*private static void appendPackage(Declaration d, StringBuilder result) { if (d.isToplevel()) { result.append(" - ").append(getPackageLabel(d)); } if (d.isClassOrInterfaceMember()) { result.append(" - "); ClassOrInterface td = (ClassOrInterface) d.getContainer(); result.append( td.getName() ); appendPackage(td, result); } }*/ private static void appendImpl(Declaration d, boolean isInterface, String indent, StringBuilder result) { if (d instanceof Method || d instanceof FunctionalParameter) { result.append(((Functional) d).isDeclaredVoid() ? " {}" : " => nothing;"); result.append(" /* TODO auto-generated stub */"); } else if (d instanceof MethodOrValue) { if (isInterface) { result.append(" => nothing; /* TODO auto-generated stub */"); if (isVariable(d)) { result.append(indent + "assign " + d.getName() + " {} /* TODO auto-generated stub */"); } } else { result.append(" = nothing; /* TODO auto-generated stub */"); } } else if (d instanceof ValueParameter) { result.append(" => nothing;"); } else { //TODO: in the case of a class, formal member refinements! result.append(" {}"); } } private static String extraIndent(String indent) { return indent.contains("\n") ? indent + getDefaultIndent() : indent; } private static void appendParameters(Declaration d, StringBuilder result) { appendParameters(d, null, result); } private static void appendParameters(Declaration d, ProducedReference pr, StringBuilder result) { if (d instanceof Functional) { List<ParameterList> plists = ((Functional) d).getParameterLists(); if (plists!=null) { for (ParameterList params: plists) { if (params.getParameters().isEmpty()) { result.append("()"); } else { result.append("("); for (Parameter p: params.getParameters()) { ProducedTypedReference ppr = pr==null ? null : pr.getTypedParameter(p); appendDeclarationText(p, ppr, result); appendParameters(p, ppr, result); /*ProducedType type = p.getType(); if (pr!=null) { type = type.substitute(pr.getTypeArguments()); } result.append(type.getProducedTypeName()).append(" ") .append(p.getName()); if (p instanceof FunctionalParameter) { result.append("("); FunctionalParameter fp = (FunctionalParameter) p; for (Parameter pp: fp.getParameterLists().get(0).getParameters()) { result.append(pp.getType().substitute(pr.getTypeArguments()) .getProducedTypeName()) .append(" ").append(pp.getName()).append(", "); } result.setLength(result.length()-2); result.append(")"); }*/ if (p.isDefaulted()) result.append("="); result.append(", "); } result.setLength(result.length()-2); result.append(")"); } } } } } private static void appendParameters(Declaration d, StyledString result) { if (d instanceof Functional) { List<ParameterList> plists = ((Functional) d).getParameterLists(); if (plists!=null) { for (ParameterList params: plists) { if (params.getParameters().isEmpty()) { result.append("()"); } else { result.append("("); int len = params.getParameters().size(), i=0; for (Parameter p: params.getParameters()) { appendDeclarationText(p, result); appendParameters(p, result); /*result.append(p.getType().getProducedTypeName(), TYPE_STYLER) .append(" ").append(p.getName(), ID_STYLER); if (p instanceof FunctionalParameter) { result.append("("); FunctionalParameter fp = (FunctionalParameter) p; List<Parameter> fpl = fp.getParameterLists().get(0).getParameters(); int len2 = fpl.size(), j=0; for (Parameter pp: fpl) { result.append(pp.getType().getProducedTypeName(), TYPE_STYLER) .append(" ").append(pp.getName(), ID_STYLER); if (++j<len2) result.append(", "); } result.append(")"); }*/ if (++i<len) result.append(", "); } result.append(")"); } } } } } }
package imagej.plugins.uis.swing.viewer.image; import imagej.data.Dataset; import imagej.display.Display; import imagej.options.event.OptionsEvent; import imagej.ui.common.awt.AWTDropTargetEventDispatcher; import imagej.ui.common.awt.AWTInputEventDispatcher; import imagej.ui.viewer.DisplayWindow; import imagej.ui.viewer.image.AbstractImageDisplayViewer; import org.scijava.event.EventHandler; import org.scijava.event.EventService; import org.scijava.plugin.Parameter; /** * A Swing image display viewer, which displays 2D planes in grayscale or * composite color. Intended to be subclassed by a concrete implementation that * provides a {@link DisplayWindow} in which the display should be housed. * * @author Curtis Rueden * @author Lee Kamentsky * @author Grant Harris * @author Barry DeZonia */ public abstract class AbstractSwingImageDisplayViewer extends AbstractImageDisplayViewer implements SwingImageDisplayViewer { protected AWTInputEventDispatcher dispatcher; @Parameter private EventService eventService; private JHotDrawImageCanvas imgCanvas; private SwingDisplayPanel imgPanel; // -- SwingImageDisplayViewer methods -- @Override public JHotDrawImageCanvas getCanvas() { return imgCanvas; } // -- DisplayViewer methods -- @Override public void view(final DisplayWindow w, final Display<?> d) { super.view(w, d); dispatcher = new AWTInputEventDispatcher(getDisplay(), eventService); // broadcast input events (keyboard and mouse) imgCanvas = new JHotDrawImageCanvas(this); imgCanvas.addEventDispatcher(dispatcher); // broadcast drag-and-drop events final AWTDropTargetEventDispatcher dropDispatcher = new AWTDropTargetEventDispatcher(getDisplay(), eventService); imgCanvas.addEventDispatcher(dropDispatcher); imgPanel = new SwingDisplayPanel(this, getWindow()); setPanel(imgPanel); updateTitle(); } @Override public SwingDisplayPanel getPanel() { return imgPanel; } @Override public Dataset capture() { return getCanvas().capture(); } // -- Disposable methods -- @Override public void dispose() { super.dispose(); if (imgCanvas != null) { imgCanvas.removeAll(); imgCanvas = null; } } // -- Event handlers -- @EventHandler protected void onEvent(@SuppressWarnings("unused") final OptionsEvent e) { updateLabel(); } }
package ca.cumulonimbus.pressurenetsdk; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Date; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.app.TaskStackBuilder; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.database.Cursor; import android.location.Location; import android.net.ConnectivityManager; import android.os.AsyncTask; import android.os.BatteryManager; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.os.SystemClock; import android.preference.PreferenceManager; import android.provider.Settings.Secure; /** * Represent developer-facing pressureNET API Background task; manage and run * everything Handle Intents * * @author jacob * */ public class CbService extends Service { private CbDataCollector dataCollector; private CbLocationManager locationManager; private CbSettingsHandler settingsHandler; private CbDb db; public CbService service = this; private String mAppDir; IBinder mBinder; ReadingSender sender; Message recentMsg; String serverURL = "https://pressurenet.cumulonimbus.ca/"; private int runningCount = 0; private static final int NOTIFICATION_ID = 12345; public static String ACTION_SEND_MEASUREMENT = "SendMeasurement"; // Service Interaction API Messages public static final int MSG_OKAY = 0; public static final int MSG_STOP = 1; public static final int MSG_GET_BEST_LOCATION = 2; public static final int MSG_BEST_LOCATION = 3; public static final int MSG_GET_BEST_PRESSURE = 4; public static final int MSG_BEST_PRESSURE = 5; public static final int MSG_START_AUTOSUBMIT = 6; public static final int MSG_STOP_AUTOSUBMIT = 7; public static final int MSG_SET_SETTINGS = 8; public static final int MSG_GET_SETTINGS = 9; public static final int MSG_SETTINGS = 10; public static final int MSG_START_DATA_STREAM = 11; public static final int MSG_DATA_STREAM = 12; public static final int MSG_STOP_DATA_STREAM = 13; // pressureNET Live API public static final int MSG_GET_LOCAL_RECENTS = 14; public static final int MSG_LOCAL_RECENTS = 15; public static final int MSG_GET_API_RECENTS = 16; public static final int MSG_API_RECENTS = 17; public static final int MSG_MAKE_API_CALL = 18; public static final int MSG_API_RESULT_COUNT = 19; // pressureNET API Cache public static final int MSG_CLEAR_LOCAL_CACHE = 20; public static final int MSG_REMOVE_FROM_PRESSURENET = 21; public static final int MSG_CLEAR_API_CACHE = 22; // Current Conditions public static final int MSG_ADD_CURRENT_CONDITION = 23; public static final int MSG_GET_CURRENT_CONDITIONS = 24; public static final int MSG_CURRENT_CONDITIONS = 25; // Sending Data public static final int MSG_SEND_OBSERVATION = 26; public static final int MSG_SEND_CURRENT_CONDITION = 27; // Current Conditions API public static final int MSG_MAKE_CURRENT_CONDITIONS_API_CALL = 28; // Notifications public static final int MSG_CHANGE_NOTIFICATION = 31; // Data management public static final int MSG_COUNT_LOCAL_OBS = 32; public static final int MSG_COUNT_API_CACHE = 33; public static final int MSG_COUNT_LOCAL_OBS_TOTALS = 34; public static final int MSG_COUNT_API_CACHE_TOTALS = 35; // Graphing public static final int MSG_GET_API_RECENTS_FOR_GRAPH = 36; public static final int MSG_API_RECENTS_FOR_GRAPH = 37; long lastAPICall = System.currentTimeMillis(); private CbObservation collectedObservation; private final Handler mHandler = new Handler(); Messenger mMessenger = new Messenger(new IncomingHandler()); ArrayList<CbObservation> offlineBuffer = new ArrayList<CbObservation>(); private long lastPressureChangeAlert = 0; /** * Find all the data for an observation. * * Location, Measurement values, etc. * * @return */ public CbObservation collectNewObservation() { try { CbObservation pressureObservation = new CbObservation(); log("cb collecting new observation"); // Location values locationManager = new CbLocationManager(getApplicationContext()); locationManager.startGettingLocations(); // Measurement values pressureObservation = dataCollector.getPressureObservation(); pressureObservation.setLocation(locationManager.getCurrentBestLocation()); // stop listening for locations LocationStopper stop = new LocationStopper(); mHandler.postDelayed(stop, 1000 * 10); return pressureObservation; } catch (Exception e) { return null; } } private class LocationStopper implements Runnable { @Override public void run() { try { locationManager.stopGettingLocations(); } catch(Exception e) { } } } /** * Send a single reading. * TODO: This is ugly copy+paste from the original ReadingSender. Fix that. */ public class SingleReadingSender implements Runnable { @Override public void run() { log("collecting and submitting single " + settingsHandler.getServerURL()); long base = SystemClock.uptimeMillis(); dataCollector.startCollectingData(null); CbObservation singleObservation = new CbObservation(); if (settingsHandler.isCollectingData()) { // Collect singleObservation = collectNewObservation(); if (singleObservation.getObservationValue() != 0.0) { // Store in database db.open(); long count = db.addObservation(singleObservation); db.close(); try { if (settingsHandler.isSharingData()) { // Send if we're online if (isNetworkAvailable()) { log("online and sending single"); singleObservation .setClientKey(getApplicationContext() .getPackageName()); sendCbObservation(singleObservation); // also check and send the offline buffer if (offlineBuffer.size() > 0) { System.out.println("sending " + offlineBuffer.size() + " offline buffered obs"); for (CbObservation singleOffline : offlineBuffer) { sendCbObservation(singleObservation); } offlineBuffer.clear(); } } else { log("didn't send"); // / offline buffer variable // TODO: put this in the DB to survive longer offlineBuffer.add(singleObservation); } } } catch (Exception e) { e.printStackTrace(); } } } } } /** * Collect and send data in a different thread. This runs itself every * "settingsHandler.getDataCollectionFrequency()" milliseconds */ private class ReadingSender implements Runnable { public void run() { log("collecting and submitting " + settingsHandler.getServerURL()); int dataCollecting = dataCollector.startCollectingData(null); long base = SystemClock.uptimeMillis(); boolean okayToGo = true; // Check if we're supposed to be charging and if we are. // Bail if appropriate if(settingsHandler.isOnlyWhenCharging()) { if(!isCharging()) { okayToGo = false; } } if (okayToGo && settingsHandler.isCollectingData()) { // Collect CbObservation singleObservation = new CbObservation(); singleObservation = collectNewObservation(); if(singleObservation != null) { if (singleObservation.getObservationValue() != 0.0) { // Store in database db.open(); long count = db.addObservation(singleObservation); db.close(); try { if (settingsHandler.isSharingData()) { // Send if we're online if (isNetworkAvailable()) { log("online and sending"); singleObservation .setClientKey(getApplicationContext() .getPackageName()); sendCbObservation(singleObservation); // also check and send the offline buffer if (offlineBuffer.size() > 0) { System.out.println("sending " + offlineBuffer.size() + " offline buffered obs"); for (CbObservation singleOffline : offlineBuffer) { sendCbObservation(singleObservation); } offlineBuffer.clear(); } } else { log("didn't send"); // / offline buffer variable // TODO: put this in the DB to survive longer offlineBuffer.add(singleObservation); } } // If notifications are enabled, if (settingsHandler.isSendNotifications()) { // check for pressure local trend changes and notify // the client // ensure this only happens every once in a while long rightNow = System.currentTimeMillis(); long threeHours = 1000 * 60 * 60 * 3; if (rightNow - lastPressureChangeAlert > (threeHours)) { long timeLength = 1000 * 60 * 60 * 6; db.open(); Cursor localCursor = db.runLocalAPICall(-90, 90, -180, 180, System.currentTimeMillis() - (timeLength), System.currentTimeMillis(), 100); ArrayList<CbObservation> recents = new ArrayList<CbObservation>(); while (localCursor.moveToNext()) { // just need observation value, time, and // location CbObservation obs = new CbObservation(); obs.setObservationValue(localCursor .getDouble(7)); obs.setTime(localCursor.getLong(9)); Location location = new Location("network"); location.setLatitude(localCursor .getDouble(1)); location.setLongitude(localCursor .getDouble(2)); obs.setLocation(location); recents.add(obs); } String tendencyChange = CbScience .changeInTrend(recents); db.close(); if (tendencyChange.contains(",") && (!tendencyChange.toLowerCase() .contains("unknown"))) { String[] tendencies = tendencyChange .split(","); if (!tendencies[0].equals(tendencies[1])) { System.out.println("Trend change! " + tendencyChange); // String tendency = // CbScience.findApproximateTendency(recents); // System.out.println("CbService CbScience submit-time tendency " // + tendency + " from " + // recents.size()); Notification.Builder mBuilder = new Notification.Builder( service) .setSmallIcon( android.R.drawable.ic_dialog_info) .setContentTitle("pressureNET") .setContentText( "Trend change: " + tendencyChange); // Creates an explicit intent for an // Activity in your app Intent resultIntent = new Intent(); // The stack builder object will contain // an artificial back stack for the // started Activity. // This ensures that navigating backward // from the Activity leads out of // your application to the Home screen. TaskStackBuilder stackBuilder = TaskStackBuilder .create(service); // Adds the back stack for the Intent // (but not the Intent itself) // stackBuilder.addParentStack(CbService.class); // Adds the Intent that starts the // Activity to the top of the stack stackBuilder .addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder .getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // mId allows you to update the // notification later on. mNotificationManager.notify( NOTIFICATION_ID, mBuilder.build()); lastPressureChangeAlert = rightNow; } else { System.out.println("trends equal " + tendencyChange); } } } else { // wait } } } catch (Exception e) { e.printStackTrace(); } } } } else { log("tried collecting, reading zero"); } mHandler.postAtTime(this, base + (settingsHandler.getDataCollectionFrequency())); } } public boolean isNetworkAvailable() { log("is net available?"); ConnectivityManager cm = (ConnectivityManager) this .getSystemService(Context.CONNECTIVITY_SERVICE); // test for connection if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected()) { log("yes"); return true; } else { log("no"); return false; } } /** * Stop all listeners, active sensors, etc, and shut down. * */ public void stopAutoSubmit() { if (locationManager != null) { locationManager.stopGettingLocations(); } if (dataCollector != null) { dataCollector.stopCollectingData(); } mHandler.removeCallbacks(sender); } /** * Send the observation to the server * * @param observation * @return */ public boolean sendCbObservation(CbObservation observation) { try { CbDataSender sender = new CbDataSender(getApplicationContext()); sender.setSettings(settingsHandler, locationManager, dataCollector); sender.execute(observation.getObservationAsParams()); return true; } catch (Exception e) { return false; } } /** * Send a new account to the server * * @param account * @return */ public boolean sendCbAccount(CbAccount account) { try { CbDataSender sender = new CbDataSender(getApplicationContext()); sender.setSettings(settingsHandler, locationManager, dataCollector); sender.execute(account.getAccountAsParams()); return true; } catch (Exception e) { return false; } } /** * Send the current condition to the server * * @param observation * @return */ public boolean sendCbCurrentCondition(CbCurrentCondition condition) { log("sending cbcurrent condition"); try { CbDataSender sender = new CbDataSender(getApplicationContext()); sender.setSettings(settingsHandler, locationManager, dataCollector); sender.execute(condition.getCurrentConditionAsParams()); return true; } catch (Exception e) { return false; } } /** * Start the periodic data collection. */ public void startAutoSubmit() { log("CbService: Starting to auto-collect and submit data."); sender = new ReadingSender(); mHandler.post(sender); } @Override public void onDestroy() { log("on destroy"); stopAutoSubmit(); super.onDestroy(); } @Override public void onCreate() { setUpFiles(); log("cb on create"); db = new CbDb(getApplicationContext()); super.onCreate(); } /** * Check charge state for preferences. * TODO: In future, adjust our collection and submission frequency * based on battery level. */ public boolean isCharging() { // Check battery and charging status IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); Intent batteryStatus = getApplicationContext().registerReceiver(null, ifilter); // Are we charging / charged? int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1); boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL; // How are we charging? /* int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1); boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB; boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC; */ return isCharging; } /** * Start running background data collection methods. * */ @Override public int onStartCommand(Intent intent, int flags, int startId) { log("cb onstartcommand"); if(intent!= null) { if(intent.getAction() != null ) { if(intent.getAction().equals(ACTION_SEND_MEASUREMENT)) { // send just a single measurement System.out.println("sending single observation, request from intent"); sendSingleObs(); return 0; } } } // Check the intent for Settings initialization dataCollector = new CbDataCollector(getID(), getApplicationContext()); if(runningCount==0) { log("starting service code, run count 0"); if (intent != null) { startWithIntent(intent); return START_STICKY; } else { log("INTENT NULL; checking db"); startWithDatabase(); } runningCount++; } else { log("not starting, run count " + runningCount); } super.onStartCommand(intent, flags, startId); return START_STICKY; } /** * Convert time ago text to ms. TODO: not this. values in xml. * * @param timeAgo * @return */ public static long stringTimeToLongHack(String timeAgo) { if (timeAgo.equals("1 minute")) { return 1000 * 60; } else if (timeAgo.equals("5 minutes")) { return 1000 * 60 * 5; } else if (timeAgo.equals("10 minutes")) { return 1000 * 60 * 10; } else if (timeAgo.equals("30 minutes")) { return 1000 * 60 * 30; } else if (timeAgo.equals("1 hour")) { return 1000 * 60 * 60; } return 1000 * 60 * 5; } public void startWithIntent(Intent intent) { try { settingsHandler = new CbSettingsHandler(getApplicationContext()); settingsHandler.setServerURL(serverURL); settingsHandler.setAppID("ca.cumulonimbus.barometernetwork"); SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(this); String preferenceCollectionFrequency = sharedPreferences.getString( "autofrequency", "10 minutes"); boolean preferenceShareData = sharedPreferences.getBoolean( "autoupdate", true); String preferenceShareLevel = sharedPreferences.getString( "sharing_preference", "Us, Researchers and Forecasters"); boolean preferenceSendNotifications = sharedPreferences.getBoolean( "send_notifications", false); settingsHandler .setDataCollectionFrequency(stringTimeToLongHack(preferenceCollectionFrequency)); settingsHandler.setSendNotifications(preferenceSendNotifications); boolean useGPS = sharedPreferences.getBoolean("use_gps", false); boolean onlyWhenCharging = sharedPreferences.getBoolean("only_when_charging", false); System.out.println("starting with intent gps " + useGPS); settingsHandler.setUseGPS(useGPS); settingsHandler.setOnlyWhenCharging(onlyWhenCharging); // Seems like new settings. Try adding to the db. settingsHandler.saveSettings(); // are we creating a new user? if (intent.hasExtra("add_account")) { log("adding new user"); CbAccount account = new CbAccount(); account.setEmail(intent.getStringExtra("email")); account.setTimeRegistered(intent.getLongExtra("time", 0)); account.setUserID(intent.getStringExtra("userID")); sendCbAccount(account); } // Start a new thread and return startAutoSubmit(); } catch (Exception e) { for (StackTraceElement ste : e.getStackTrace()) { log(ste.getMethodName() + ste.getLineNumber()); } } } public void startWithDatabase() { try { db.open(); // Check the database for Settings initialization settingsHandler = new CbSettingsHandler(getApplicationContext()); // db.clearDb(); Cursor allSettings = db.fetchAllSettings(); log("cb intent null; checking db, size " + allSettings.getCount()); while (allSettings.moveToNext()) { settingsHandler.setAppID(allSettings.getString(1)); settingsHandler.setDataCollectionFrequency(allSettings .getLong(2)); settingsHandler.setServerURL(serverURL); settingsHandler.setShareLevel(allSettings.getString(7)); // booleans int onlyWhenCharging = allSettings.getInt(4); int useGPS = allSettings.getInt(9); boolean boolCharging = (onlyWhenCharging == 1) ? true : false; boolean boolGPS = (useGPS == 1) ? true : false; System.out.println("only when charging raw " + onlyWhenCharging + " gps " + useGPS); System.out.println("only when charging processed " + boolCharging + " gps " + boolGPS); settingsHandler.setOnlyWhenCharging(boolCharging); settingsHandler.setUseGPS(boolGPS); settingsHandler.saveSettings(); startAutoSubmit(); // but just once break; } db.close(); } catch (Exception e) { for (StackTraceElement ste : e.getStackTrace()) { log(ste.getMethodName() + ste.getLineNumber()); } } } /** * Handler of incoming messages from clients. */ class IncomingHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_STOP: log("message. bound service says stop"); stopAutoSubmit(); break; case MSG_GET_BEST_LOCATION: log("message. bound service requesting location"); if (locationManager != null) { Location best = locationManager.getCurrentBestLocation(); try { log("service sending best location"); msg.replyTo.send(Message.obtain(null, MSG_BEST_LOCATION, best)); } catch (RemoteException re) { re.printStackTrace(); } } else { log("error: location null, not returning"); } break; case MSG_GET_BEST_PRESSURE: log("message. bound service requesting pressure"); if (dataCollector != null) { CbObservation pressure = dataCollector .getPressureObservation(); try { log("service sending best pressure"); msg.replyTo.send(Message.obtain(null, MSG_BEST_PRESSURE, pressure)); } catch (RemoteException re) { re.printStackTrace(); } } else { log("error: data collector null, not returning"); } break; case MSG_START_AUTOSUBMIT: log("start autosubmit"); startWithDatabase(); break; case MSG_STOP_AUTOSUBMIT: log("stop autosubmit"); stopAutoSubmit(); break; case MSG_GET_SETTINGS: log("get settings"); try { msg.replyTo.send(Message.obtain(null, MSG_SETTINGS, settingsHandler)); } catch (RemoteException re) { re.printStackTrace(); } break; case MSG_START_DATA_STREAM: startDataStream(msg.replyTo); break; case MSG_STOP_DATA_STREAM: stopDataStream(); break; case MSG_SET_SETTINGS: log("set settings"); CbSettingsHandler newSettings = (CbSettingsHandler) msg.obj; newSettings.saveSettings(); break; case MSG_GET_LOCAL_RECENTS: log("get local recents"); recentMsg = msg; CbApiCall apiCall = (CbApiCall) msg.obj; if (apiCall == null) { System.out.println("apicall null, bailing"); break; } // run API call db.open(); Cursor cursor = db.runLocalAPICall(apiCall.getMinLat(), apiCall.getMaxLat(), apiCall.getMinLon(), apiCall.getMaxLon(), apiCall.getStartTime(), apiCall.getEndTime(), 2000); ArrayList<CbObservation> results = new ArrayList<CbObservation>(); while (cursor.moveToNext()) { // TODO: This is duplicated in CbDataCollector. Fix that CbObservation obs = new CbObservation(); Location location = new Location("network"); location.setLatitude(cursor.getDouble(1)); location.setLongitude(cursor.getDouble(2)); location.setAltitude(cursor.getDouble(3)); location.setAccuracy(cursor.getInt(4)); location.setProvider(cursor.getString(5)); obs.setLocation(location); obs.setObservationType(cursor.getString(6)); obs.setObservationUnit(cursor.getString(7)); obs.setObservationValue(cursor.getDouble(8)); obs.setSharing(cursor.getString(9)); obs.setTime(cursor.getLong(10)); obs.setTimeZoneOffset(cursor.getInt(11)); obs.setUser_id(cursor.getString(12)); obs.setTrend(cursor.getString(18)); // TODO: Add sensor information results.add(obs); } db.close(); log("cbservice: " + results.size() + " local api results"); try { msg.replyTo.send(Message.obtain(null, MSG_LOCAL_RECENTS, results)); } catch (RemoteException re) { re.printStackTrace(); } break; case MSG_GET_API_RECENTS: CbApiCall apiCacheCall = (CbApiCall) msg.obj; log("get api recents " + apiCacheCall.toString()); // run API call try { db.open(); Cursor cacheCursor = db.runAPICacheCall( apiCacheCall.getMinLat(), apiCacheCall.getMaxLat(), apiCacheCall.getMinLon(), apiCacheCall.getMaxLon(), apiCacheCall.getStartTime(), apiCacheCall.getEndTime(), apiCacheCall.getLimit()); ArrayList<CbObservation> cacheResults = new ArrayList<CbObservation>(); while (cacheCursor.moveToNext()) { CbObservation obs = new CbObservation(); Location location = new Location("network"); location.setLatitude(cacheCursor.getDouble(1)); location.setLongitude(cacheCursor.getDouble(2)); obs.setLocation(location); obs.setObservationValue(cacheCursor.getDouble(3)); obs.setTime(cacheCursor.getLong(4)); cacheResults.add(obs); } db.close(); try { msg.replyTo.send(Message.obtain(null, MSG_API_RECENTS, cacheResults)); } catch (RemoteException re) { re.printStackTrace(); } } catch(Exception e) { } break; case MSG_GET_API_RECENTS_FOR_GRAPH: // TODO: Put this in a method. It's a copy+paste from GET_API_RECENTS CbApiCall apiCacheCallGraph = (CbApiCall) msg.obj; log("get api recents " + apiCacheCallGraph.toString()); // run API call db.open(); Cursor cacheCursorGraph = db.runAPICacheCall( apiCacheCallGraph.getMinLat(), apiCacheCallGraph.getMaxLat(), apiCacheCallGraph.getMinLon(), apiCacheCallGraph.getMaxLon(), apiCacheCallGraph.getStartTime(), apiCacheCallGraph.getEndTime(), apiCacheCallGraph.getLimit()); ArrayList<CbObservation> cacheResultsGraph = new ArrayList<CbObservation>(); while (cacheCursorGraph.moveToNext()) { CbObservation obs = new CbObservation(); Location location = new Location("network"); location.setLatitude(cacheCursorGraph.getDouble(1)); location.setLongitude(cacheCursorGraph.getDouble(2)); obs.setLocation(location); obs.setObservationValue(cacheCursorGraph.getDouble(3)); obs.setTime(cacheCursorGraph.getLong(4)); cacheResultsGraph.add(obs); } db.close(); try { msg.replyTo.send(Message.obtain(null, MSG_API_RECENTS_FOR_GRAPH, cacheResultsGraph)); } catch (RemoteException re) { re.printStackTrace(); } break; case MSG_MAKE_API_CALL: CbApi api = new CbApi(getApplicationContext()); CbApiCall liveApiCall = (CbApiCall) msg.obj; liveApiCall.setCallType("Readings"); long timeDiff = System.currentTimeMillis() - lastAPICall; deleteOldData(); lastAPICall = api.makeAPICall(liveApiCall, service, msg.replyTo, "Readings"); break; case MSG_MAKE_CURRENT_CONDITIONS_API_CALL: CbApi conditionApi = new CbApi(getApplicationContext()); CbApiCall conditionApiCall = (CbApiCall) msg.obj; conditionApiCall.setCallType("Conditions"); conditionApi.makeAPICall(conditionApiCall, service, msg.replyTo, "Conditions"); break; case MSG_CLEAR_LOCAL_CACHE: db.open(); db.clearLocalCache(); long count = db.getUserDataCount(); db.close(); try { msg.replyTo.send(Message.obtain(null, MSG_COUNT_LOCAL_OBS_TOTALS, (int) count, 0)); } catch (RemoteException re) { re.printStackTrace(); } break; case MSG_REMOVE_FROM_PRESSURENET: // TODO: Implement break; case MSG_CLEAR_API_CACHE: db.open(); db.clearAPICache(); db.open(); long countCache = db.getDataCacheCount(); db.close(); try { msg.replyTo.send(Message.obtain(null, MSG_COUNT_API_CACHE_TOTALS, (int) countCache, 0)); } catch (RemoteException re) { re.printStackTrace(); } break; case MSG_ADD_CURRENT_CONDITION: CbCurrentCondition cc = (CbCurrentCondition) msg.obj; db.open(); db.addCondition(cc); db.close(); break; case MSG_GET_CURRENT_CONDITIONS: recentMsg = msg; db.open(); CbApiCall currentConditionAPI = (CbApiCall) msg.obj; Cursor ccCursor = db.getCurrentConditions( currentConditionAPI.getMinLat(), currentConditionAPI.getMaxLat(), currentConditionAPI.getMinLon(), currentConditionAPI.getMaxLon(), currentConditionAPI.getStartTime(), currentConditionAPI.getEndTime(), 1000); ArrayList<CbCurrentCondition> conditions = new ArrayList<CbCurrentCondition>(); while (ccCursor.moveToNext()) { CbCurrentCondition cur = new CbCurrentCondition(); Location location = new Location("network"); location.setLatitude(ccCursor.getDouble(1)); location.setLongitude(ccCursor.getDouble(2)); location.setAltitude(ccCursor.getDouble(3)); location.setAccuracy(ccCursor.getInt(4)); location.setProvider(ccCursor.getString(5)); cur.setLocation(location); cur.setTime(ccCursor.getLong(6)); cur.setTime(ccCursor.getLong(7)); cur.setUser_id(ccCursor.getString(9)); cur.setGeneral_condition(ccCursor.getString(10)); cur.setWindy(ccCursor.getString(11)); cur.setFog_thickness(ccCursor.getString(12)); cur.setCloud_type(ccCursor.getString(13)); cur.setPrecipitation_type(ccCursor.getString(14)); cur.setPrecipitation_amount(ccCursor.getDouble(15)); cur.setPrecipitation_unit(ccCursor.getString(16)); cur.setThunderstorm_intensity(ccCursor.getString(17)); cur.setUser_comment(ccCursor.getString(18)); conditions.add(cur); } db.close(); try { msg.replyTo.send(Message.obtain(null, MSG_CURRENT_CONDITIONS, conditions)); } catch (RemoteException re) { re.printStackTrace(); } break; case MSG_SEND_CURRENT_CONDITION: CbCurrentCondition condition = (CbCurrentCondition) msg.obj; condition.setSharing_policy(settingsHandler.getShareLevel()); sendCbCurrentCondition(condition); break; case MSG_SEND_OBSERVATION: System.out.println("sending single observation, request from app"); sendSingleObs(); break; case MSG_COUNT_LOCAL_OBS: db.open(); long countLocalObsOnly = db.getUserDataCount(); db.close(); try { msg.replyTo.send(Message.obtain(null, MSG_COUNT_LOCAL_OBS_TOTALS, (int) countLocalObsOnly, 0)); } catch (RemoteException re) { re.printStackTrace(); } break; case MSG_COUNT_API_CACHE: db.open(); long countCacheOnly = db.getDataCacheCount(); db.close(); try { msg.replyTo.send(Message .obtain(null, MSG_COUNT_API_CACHE_TOTALS, (int) countCacheOnly, 0)); } catch (RemoteException re) { re.printStackTrace(); } break; default: super.handleMessage(msg); } } } public void sendSingleObs() { SingleReadingSender singleSender = new SingleReadingSender(); mHandler.post(singleSender); } /** * Remove older data from cache to keep the size reasonable * * @return */ public void deleteOldData() { System.out.println("deleting old data"); db.open(); db.deleteOldCacheData(); db.close(); } public boolean notifyAPIResult(Messenger reply, int count) { try { if (reply == null) { System.out.println("cannot notify, reply is null"); } else { reply.send(Message.obtain(null, MSG_API_RESULT_COUNT, count, 0)); } } catch (RemoteException re) { re.printStackTrace(); } catch (NullPointerException npe) { npe.printStackTrace(); } return false; } public CbObservation recentPressureFromDatabase() { CbObservation obs = new CbObservation(); double pressure = 0.0; try { long rowId = db.fetchObservationMaxID(); Cursor c = db.fetchObservation(rowId); while (c.moveToNext()) { pressure = c.getDouble(8); } log(pressure + " pressure from db"); if (pressure == 0.0) { log("returning null"); return null; } obs.setObservationValue(pressure); return obs; } catch(Exception e) { obs.setObservationValue(pressure); return obs; } } private class StreamObservation extends AsyncTask<Messenger, Void, String> { @Override protected String doInBackground(Messenger... m) { try { for (Messenger msgr : m) { if (msgr != null) { msgr.send(Message.obtain(null, MSG_DATA_STREAM, recentPressureFromDatabase())); } else { log("messenger is null"); } } } catch (RemoteException re) { re.printStackTrace(); } return " } @Override protected void onPostExecute(String result) { } @Override protected void onPreExecute() { } @Override protected void onProgressUpdate(Void... values) { } } public void startDataStream(Messenger m) { log("cbService starting stream " + (m == null)); dataCollector.startCollectingData(m); new StreamObservation().execute(m); } public void stopDataStream() { log("cbservice stopping stream"); if(dataCollector!=null) { dataCollector.stopCollectingData(); } } /** * Get a hash'd device ID * * @return */ public String getID() { try { MessageDigest md = MessageDigest.getInstance("MD5"); String actual_id = Secure.getString(getApplicationContext() .getContentResolver(), Secure.ANDROID_ID); byte[] bytes = actual_id.getBytes(); byte[] digest = md.digest(bytes); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { hexString.append(Integer.toHexString(0xFF & digest[i])); } return hexString.toString(); } catch (Exception e) { return " } } // Used to write a log to SD card. Not used unless logging enabled. public void setUpFiles() { try { File homeDirectory = getExternalFilesDir(null); if (homeDirectory != null) { mAppDir = homeDirectory.getAbsolutePath(); } } catch (Exception e) { e.printStackTrace(); } } // Log data to SD card for debug purposes. // To enable logging, ensure the Manifest allows writing to SD card. public void logToFile(String text) { try { OutputStream output = new FileOutputStream(mAppDir + "/log.txt", true); String logString = (new Date()).toString() + ": " + text + "\n"; output.write(logString.getBytes()); output.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } @Override public IBinder onBind(Intent intent) { log("on bind"); return mMessenger.getBinder(); } @Override public void onRebind(Intent intent) { log("on rebind"); super.onRebind(intent); } public void log(String message) { // logToFile(message); System.out.println(message); } public CbDataCollector getDataCollector() { return dataCollector; } public void setDataCollector(CbDataCollector dataCollector) { this.dataCollector = dataCollector; } public CbLocationManager getLocationManager() { return locationManager; } public void setLocationManager(CbLocationManager locationManager) { this.locationManager = locationManager; } }
package ca.patricklam.judodb.client; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; import com.google.gwt.dom.client.DivElement; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.FormElement; import com.google.gwt.dom.client.Style.Display; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.i18n.client.NumberFormat; import com.google.gwt.safehtml.client.SafeHtmlTemplates; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Grid; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.Hidden; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.ValueBoxBase; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.user.datepicker.client.CalendarUtil; public class ClientWidget extends Composite { interface MyUiBinder extends UiBinder<Widget, ClientWidget> {} public static MyUiBinder uiBinder = GWT.create(MyUiBinder.class); private final JudoDB jdb; @UiField DivElement cid; @UiField HTMLPanel clientMain; @UiField TextBox nom; @UiField TextBox prenom; @UiField TextBox ddn; @UiField TextBox sexe; @UiField Anchor copysib; @UiField TextBox adresse; @UiField TextBox ville; @UiField TextBox codePostal; @UiField TextBox tel; @UiField TextBox courriel; @UiField TextBox affiliation; @UiField TextBox grade; @UiField Anchor showgrades; @UiField TextBox date_grade; @UiField TextBox carte_anjou; @UiField TextBox nom_recu_impot; @UiField TextBox tel_contact_urgence; @UiField ListBox date_inscription; @UiField Anchor inscrire; @UiField Anchor modifier; @UiField Anchor desinscrire; @UiField TextBox saisons; @UiField CheckBox verification; @UiField TextBox categorie; @UiField TextBox categorieFrais; @UiField ListBox cours; @UiField ListBox sessions; @UiField ListBox escompte; @UiField TextBox cas_special_note; @UiField TextBox cas_special_pct; @UiField TextBox escompteFrais; @UiField CheckBox sans_affiliation; @UiField TextBox affiliationFrais; @UiField TextBox judogi; @UiField CheckBox passeport; @UiField CheckBox non_anjou; @UiField TextBox suppFrais; @UiField CheckBox solde; @UiField TextBox frais; @UiField Hidden grades_encoded; @UiField Hidden grade_dates_encoded; @UiField Hidden date_inscription_encoded; @UiField Hidden saisons_encoded; @UiField Hidden verification_encoded; @UiField Hidden categorieFrais_encoded; @UiField Hidden cours_encoded; @UiField Hidden sessions_encoded; @UiField Hidden escompte_encoded; @UiField Hidden cas_special_note_encoded; @UiField Hidden cas_special_pct_encoded; @UiField Hidden escompteFrais_encoded; @UiField Hidden sans_affiliation_encoded; @UiField Hidden affiliationFrais_encoded; @UiField Hidden judogi_encoded; @UiField Hidden passeport_encoded; @UiField Hidden non_anjou_encoded; @UiField Hidden suppFrais_encoded; @UiField Hidden solde_encoded; @UiField Hidden frais_encoded; @UiField Hidden guid_on_form; @UiField Hidden sid; @UiField Hidden deleted; @UiField Button saveClientButton; @UiField Button saveAndReturnClientButton; @UiField Button deleteClientButton; @UiField Button discardClientButton; @UiField HTMLPanel blurb; @UiField HTMLPanel gradeHistory; @UiField Grid gradeTable; @UiField Anchor saveGrades; @UiField Anchor annulerGrades; private final FormElement clientform; private static final String PULL_ONE_CLIENT_URL = JudoDB.BASE_URL + "pull_one_client.php?id="; private static final String CALLBACK_URL_SUFFIX = "&callback="; private static final String PUSH_ONE_CLIENT_URL = JudoDB.BASE_URL + "push_one_client.php"; private static final String CONFIRM_PUSH_URL = JudoDB.BASE_URL + "confirm_push.php?guid="; private int pushTries; public interface BlurbTemplate extends SafeHtmlTemplates { @Template ("<p>Je {0} certifie que les informations inscrites sur ce formulaire sont véridiques. "+ "J'adhère au Club Judo Anjou. J'accepte tous les risques d'accident liés à la pratique du "+ "judo qui pourraient survenir dans les locaux ou lors d'activités extérieurs organisées par le Club. "+ "J'accepte de respecter les règlements du Club.</p>"+ "<h4>Politique de remboursement</h4>"+ "<p>Aucun remboursement ne sera accordé sans présentation d'un certificat médical du participant. "+ "Seuls les frais de cours correspondant à la période restante sont remboursables. "+ "En cas d'annulation par le participant, un crédit pourra être émis par le Club, "+ "pour les frais de cours correspondant à la période restante.</p>"+ "<p>Signature {1}: <span style='float:right'>Date: _________</span></p>"+ "<p>Signature résponsable du club: <span style='float:right'>Date: {2}</span></p>") SafeHtml blurb(String nom, String membreOuParent, String today); } private static final BlurbTemplate BLURB = GWT.create(BlurbTemplate.class); private ClientData cd; private String guid; private int currentServiceNumber; public int getCurrentServiceNumber() { return currentServiceNumber; } private String sibid; private List<ChangeHandler> onPopulated = new ArrayList<ChangeHandler>(); public ClientWidget(int cid, JudoDB jdb) { this.jdb = jdb; initWidget(uiBinder.createAndBindUi(this)); clientform = FormElement.as(clientMain.getElementById("clientform")); clientform.setAction(PUSH_ONE_CLIENT_URL); jdb.pleaseWait(); deleted.setValue(""); for (Constants.Cours c : Constants.COURS) { cours.addItem(c.name, c.seqno); } sessions.addItem("1"); sessions.addItem("2"); for (Constants.Escompte e : Constants.ESCOMPTES) { escompte.addItem(e.name, Integer.toString(e.amount)); } gradeHistory.setVisible(false); categorie.setReadOnly(true); saisons.setReadOnly(true); categorieFrais.setReadOnly(true); categorieFrais.setAlignment(ValueBoxBase.TextAlignment.RIGHT); cas_special_pct.setAlignment(ValueBoxBase.TextAlignment.RIGHT); escompteFrais.setReadOnly(true); escompteFrais.setAlignment(ValueBoxBase.TextAlignment.RIGHT); judogi.setAlignment(ValueBoxBase.TextAlignment.RIGHT); affiliationFrais.setReadOnly(true); affiliationFrais.setAlignment(ValueBoxBase.TextAlignment.RIGHT); suppFrais.setReadOnly(true); suppFrais.setAlignment(ValueBoxBase.TextAlignment.RIGHT); frais.setReadOnly(true); frais.setAlignment(ValueBoxBase.TextAlignment.RIGHT); ((Element)cas_special_note.getElement().getParentNode()).getStyle().setDisplay(Display.NONE); ((Element)cas_special_pct.getElement().getParentNode()).getStyle().setDisplay(Display.NONE); sessions.setItemSelected(1, true); inscrire.addClickHandler(inscrireClickHandler); modifier.addClickHandler(modifierClickHandler); desinscrire.addClickHandler(desinscrireClickHandler); showgrades.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { gradeHistory.setVisible(true); } ; }); saveGrades.addClickHandler(saveGradesHandler); annulerGrades.addClickHandler(annulerGradesHandler); adresse.addChangeHandler(updateCopySibHandler); ville.addChangeHandler(updateCopySibHandler); codePostal.addChangeHandler(updateCopySibHandler); tel.addChangeHandler(updateCopySibHandler); tel_contact_urgence.addChangeHandler(updateCopySibHandler); courriel.addChangeHandler(updateCopySibHandler); ddn.addChangeHandler(recomputeHandler); grade.addChangeHandler(directGradeChangeHandler); date_grade.addChangeHandler(directGradeDateChangeHandler); grade.addChangeHandler(recomputeHandler); date_inscription.addChangeHandler(changeSaisonHandler); sessions.addChangeHandler(recomputeHandler); escompte.addChangeHandler(recomputeHandler); cas_special_pct.addChangeHandler(clearEscompteAmtAndRecomputeHandler); escompteFrais.addChangeHandler(clearEscomptePctAndRecomputeHandler); sans_affiliation.addValueChangeHandler(recomputeValueHandler); judogi.addChangeHandler(recomputeHandler); passeport.addValueChangeHandler(recomputeValueHandler); non_anjou.addValueChangeHandler(recomputeValueHandler); saveAndReturnClientButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { pushClientDataToServer(); ClientWidget.this.jdb.popMode(); } }); saveClientButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { pushClientDataToServer(); } }); discardClientButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { ClientWidget.this.jdb.clearStatus(); ClientWidget.this.jdb.popMode(); } }); deleteClientButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { pushDeleteToServer(); ClientWidget.this.jdb.popMode(); } }); copysib.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { copysib(); } }); if (cid != -1) getJsonForPull(jdb.jsonRequestId++, PULL_ONE_CLIENT_URL + cid + CALLBACK_URL_SUFFIX, this); else { this.cd = JavaScriptObject.createObject().cast(); this.cd.setID(null); this.cd.setNom(""); this.cd.makeDefault(); JsArray<ServiceData> sa = JavaScriptObject.createArray().cast(); ServiceData sd = ServiceData.newServiceData(); sd.inscrireAujourdhui(); sa.set(0, sd); this.cd.setServices(sa); // new client: first service, // which exists because we called inscrireAujourdhui currentServiceNumber = 0; JsArray<GradeData> ga = JavaScriptObject.createArray().cast(); GradeData gd = JavaScriptObject.createObject().cast(); gd.setGrade("Blanche"); gd.setDateGrade(DateTimeFormat.getFormat("yyyy-MM-dd").format(new Date())); ga.set(0, gd); this.cd.setGrades(ga); loadClientData(); jdb.clearStatus(); } } @SuppressWarnings("deprecation") private void updateBlurb() { if (cd.getDDNString() == null) return; Date ddn = cd.getDDN(), today = new Date(); if (cd.getDDN() == null) return; int by = ddn.getYear(), bm = ddn.getMonth(), bd = ddn.getDate(), ny = today.getYear(), nm = today.getMonth(), nd = ddn.getDate(); int y = ny - by; if (bm > nm || (bm == nm && bd > nd)) y String nom = cd.getPrenom() + " " + cd.getNom(); String nn, mm; if (y >= 18) { nn = nom; mm = "membre"; } else { nn = "__________________________, parent ou tuteur du membre,"; mm = "parent ou tuteur"; } SafeHtml blurbContents = BLURB.blurb(nn, mm, DateTimeFormat.getFormat("yyyy-MM-dd").format(today)); blurb.clear(); blurb.add(new HTMLPanel(blurbContents)); } /** Takes data from ClientData into the form. */ private void loadClientData () { cid.setInnerText(cd.getID()); nom.setText(cd.getNom()); prenom.setText(cd.getPrenom()); ddn.setText(cd.getDDNString()); sexe.setText(cd.getSexe()); adresse.setText(cd.getAdresse()); ville.setText(cd.getVille()); codePostal.setText(cd.getCodePostal()); tel.setText(cd.getTel()); courriel.setText(cd.getCourriel()); affiliation.setText(cd.getJudoQC()); carte_anjou.setText(cd.getCarteAnjou()); nom_recu_impot.setText(cd.getNomRecuImpot()); tel_contact_urgence.setText(cd.getTelContactUrgence()); ServiceData sd; if (currentServiceNumber == -1) { sd = ServiceData.newServiceData(); sd.inscrireAujourdhui(); } else sd = cd.getServices().get(currentServiceNumber); loadGradesData(); date_inscription.clear(); boolean hasToday = false, isToday = false; boolean hasThisSession = cd.getServiceFor(Constants.currentSession()) != null; String todayString = DateTimeFormat.getFormat("yyyy-MM-dd").format(new Date()); for (int i = 0; i < cd.getServices().length(); i++) { ServiceData ssd = cd.getServices().get(i); if (todayString.equals(ssd.getDateInscription())) { hasToday = true; isToday = (i == currentServiceNumber); } date_inscription.addItem(ssd.getDateInscription(), Integer.toString(i)); } date_inscription.setSelectedIndex(currentServiceNumber); inscrire.setVisible(!hasToday && !hasThisSession); modifier.setVisible(!hasToday && hasThisSession); desinscrire.setVisible(cd.getServices().length() > 0); // categories is set in recompute(). saisons.setText(sd.getSaisons()); verification.setValue(sd.getVerification()); int cnum = Integer.parseInt(sd.getCours()); if (cnum >= 0 && cnum < cours.getItemCount()) cours.setItemSelected(cnum, true); sessions.setItemSelected(sd.getSessionCount()-1, true); sessions.setEnabled(isToday); categorieFrais.setText(sd.getCategorieFrais()); sans_affiliation.setValue(sd.getSansAffiliation()); sans_affiliation.setEnabled(isToday); affiliationFrais.setText(sd.getAffiliationFrais()); escompte.setSelectedIndex(sd.getEscompteType()); escompte.setEnabled(isToday); cas_special_note.setText(sd.getCasSpecialNote()); cas_special_note.setReadOnly(!isToday); cas_special_pct.setValue(sd.getCasSpecialPct()); cas_special_pct.setReadOnly(!isToday); escompteFrais.setText(sd.getEscompteFrais()); judogi.setText(sd.getJudogi()); judogi.setReadOnly(!isToday); passeport.setValue(sd.getPasseport()); passeport.setEnabled(isToday); non_anjou.setValue(sd.getNonAnjou()); non_anjou.setEnabled(isToday); suppFrais.setText(sd.getSuppFrais()); frais.setText(sd.getFrais()); solde.setValue(sd.getSolde()); recompute(); } /** Puts data from the form back onto ClientData. */ private void saveClientData() { cd.setNom(nom.getText()); cd.setPrenom(prenom.getText()); cd.setDDNString(ddn.getText()); cd.setSexe(sexe.getText()); cd.setAdresse(adresse.getText()); cd.setVille(ville.getText()); cd.setCodePostal(codePostal.getText()); cd.setTel(tel.getText()); cd.setCourriel(courriel.getText()); cd.setJudoQC(affiliation.getText()); cd.setCarteAnjou(carte_anjou.getText()); cd.setNomRecuImpot(nom_recu_impot.getText()); cd.setTelContactUrgence(tel_contact_urgence.getText()); if (currentServiceNumber == -1) return; ServiceData sd = cd.getServices().get(currentServiceNumber); sd.setDateInscription(removeCommas(date_inscription.getItemText(currentServiceNumber))); sd.setSaisons(removeCommas(saisons.getText())); sd.setVerification(verification.getValue()); sd.setCours(Integer.toString(cours.getSelectedIndex())); sd.setSessionCount(sessions.getSelectedIndex()+1); sd.setCategorieFrais(stripDollars(categorieFrais.getText())); sd.setSansAffiliation(sans_affiliation.getValue()); sd.setAffiliationFrais(stripDollars(affiliationFrais.getText())); sd.setEscompteType(escompte.getSelectedIndex()); sd.setCasSpecialNote(removeCommas(cas_special_note.getText())); sd.setCasSpecialPct(stripDollars(cas_special_pct.getText())); sd.setEscompteFrais(stripDollars(escompteFrais.getText())); sd.setJudogi(stripDollars(judogi.getText())); sd.setPasseport(passeport.getValue()); sd.setNonAnjou(non_anjou.getValue()); sd.setSuppFrais(stripDollars(suppFrais.getText())); sd.setFrais(stripDollars(frais.getText())); sd.setSolde(solde.getValue()); } /** Load grades data from ClientData into the gradeTable & grade/date_grade. */ private void loadGradesData() { gradeTable.clear(); gradeTable.resize(cd.getGrades().length()+2, 2); gradeTable.setText(0, 0, "Grade"); gradeTable.getCellFormatter().setStyleName(0, 0, "{style.lwp}"); gradeTable.setText(0, 1, "Date"); gradeTable.getCellFormatter().setStyleName(0, 1, "{style.lwp}"); JsArray<GradeData> grades_ = cd.getGrades(); GradeData[] grades = new GradeData[grades_.length()]; for (int i = 0; i < grades_.length(); i++) grades[i] = grades_.get(i); Arrays.sort(grades, new GradeData.GradeComparator()); for (int i = 0; i < grades.length; i++) { setGradesTableRow(i+1, grades[i].getGrade(), grades[i].getDateGrade()); } setGradesTableRow(grades.length+1, "", ""); grade.setText(cd.getGrade()); date_grade.setText(cd.getDateGrade()); } private void setGradesTableRow(int row, String grade, String dateGrade) { TextBox g = new TextBox(); TextBox gd = new TextBox(); g.setValue(grade); g.setVisibleLength(5); gd.setValue(dateGrade); gd.setVisibleLength(10); gradeTable.setWidget(row, 0, g); gradeTable.setWidget(row, 1, gd); ((TextBox)gradeTable.getWidget(row, 0)).addChangeHandler(ensureGradeSpace); ((TextBox)gradeTable.getWidget(row, 1)).addChangeHandler(ensureGradeSpace); } private TextBox getGradeTableTextBox(int row, int col) { return (TextBox) gradeTable.getWidget(row, col); } /** If there are any empty rows in the middle, move them up. * If there is no empty row at the end, create one. */ private ChangeHandler ensureGradeSpace = new ChangeHandler() { public void onChange(ChangeEvent e) { int rc = gradeTable.getRowCount(); for (int i = 1; i < rc-2; i++) { if (getGradeTableTextBox(i, 0).getText().equals("") && getGradeTableTextBox(i, 1).getText().equals("")) { for (int j = i; j < rc-1; j++) { getGradeTableTextBox(j, 0).setText(getGradeTableTextBox(j+1, 0).getText()); getGradeTableTextBox(j, 1).setText(getGradeTableTextBox(j+1, 1).getText()); } getGradeTableTextBox(rc-1, 0).setText(""); getGradeTableTextBox(rc-1, 1).setText(""); } } if (!getGradeTableTextBox(rc-1, 0).getText().equals("") && !getGradeTableTextBox(rc-1, 1).getText().equals("")) { gradeTable.resize(rc+1, 2); setGradesTableRow(rc, "", ""); } } }; /** Save data from the grades table into the ClientData. */ private void saveGradesData() { JsArray<GradeData> newGradesJS = JavaScriptObject.createArray().cast(); ArrayList<GradeData> newGradesList = new ArrayList<GradeData>(); for (int i = 1; i < gradeTable.getRowCount(); i++) { String g = getGradeTableTextBox(i, 0).getText(), gdate = getGradeTableTextBox(i, 1).getText(); if (!g.equals("")) { GradeData gd = GradeData.createObject().cast(); gd.setGrade(g.replaceAll(",", ";")); gd.setDateGrade(gdate.replaceAll(",", ";")); newGradesList.add(gd); } } Collections.sort(newGradesList, new GradeData.GradeComparator()); int gi = 0; for (GradeData gd : newGradesList) { newGradesJS.set(gi++, gd); } cd.setGrades(newGradesJS); } private String encodeGrades() { StringBuffer sb = new StringBuffer(); JsArray<GradeData> grades = cd.getGrades(); for (int i = 0; i < grades.length(); i++) { GradeData gd = grades.get(i); if (i > 0) sb.append(","); sb.append(gd.getGrade()); } return sb.toString(); } private String encodeGradeDates() { StringBuffer sb = new StringBuffer(); JsArray<GradeData> grades = cd.getGrades(); for (int i = 0; i < grades.length(); i++) { GradeData gd = grades.get(i); if (i > 0) sb.append(","); sb.append(gd.getDateGrade()); } return sb.toString(); } private final ChangeHandler directGradeChangeHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { // either no previous grade or no previous date-grade; // erase the old grade if (date_grade.getText().equals("0000-00-00") || cd.getGrade().equals("")) { date_grade.setText(DateTimeFormat.getFormat("yyyy-MM-dd").format(new Date())); setGradesTableRow(1, grade.getText(), date_grade.getText()); saveGradesData(); } else { // old grade set, and has date; keep the old grade-date in the array // and update the array. ensureGradeSpace.onChange(null); date_grade.setText(DateTimeFormat.getFormat("yyyy-MM-dd").format(new Date())); setGradesTableRow(0, grade.getText(), date_grade.getText()); saveGradesData(); } } }; private final ChangeHandler directGradeDateChangeHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { // if you change the grade-date, and grade is not empty, then // update the array. } }; private final ChangeHandler recomputeHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { recompute(); } }; private final ChangeHandler changeSaisonHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { saveClientData(); currentServiceNumber = Integer.parseInt(date_inscription.getValue(date_inscription.getSelectedIndex())); loadClientData(); } }; private final ChangeHandler updateCopySibHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { updateCopySib(); } }; private final ValueChangeHandler<Boolean> recomputeValueHandler = new ValueChangeHandler<Boolean>() { public void onValueChange(ValueChangeEvent<Boolean> e) { recompute(); } }; private final ChangeHandler clearEscomptePctAndRecomputeHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { cas_special_pct.setValue("-1"); recompute(); } }; private final ChangeHandler clearEscompteAmtAndRecomputeHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { escompteFrais.setValue("-1"); recompute(); } }; /** Create a new inscription for the current session. */ private final ClickHandler inscrireClickHandler = new ClickHandler() { public void onClick(ClickEvent e) { saveClientData(); ServiceData sd = cd.getServiceFor(Constants.currentSession()); if (sd == null) { sd = ServiceData.newServiceData(); cd.getServices().push(sd); } // actually, sd != null should not occur; that should be modify. sd.inscrireAujourdhui(); currentServiceNumber = cd.getMostRecentServiceNumber(); loadClientData(); recompute(); } }; /** Resets the date d'inscription for the current seesion to today's date. */ private final ClickHandler modifierClickHandler = new ClickHandler() { public void onClick(ClickEvent e) { ServiceData sd = cd.getServiceFor(Constants.currentSession()); // shouldn't happen, actually. if (sd == null) return; saveClientData(); sd.inscrireAujourdhui(); currentServiceNumber = cd.getMostRecentServiceNumber(); loadClientData(); recompute(); } }; private final ClickHandler desinscrireClickHandler = new ClickHandler() { public void onClick(ClickEvent e) { saveClientData(); JsArray<ServiceData> newServices = JavaScriptObject.createArray().cast(); for (int i = 0, j = 0; i < cd.getServices().length(); i++) { if (i != currentServiceNumber) newServices.set(j++, cd.getServices().get(i)); } cd.setServices(newServices); currentServiceNumber = cd.getMostRecentServiceNumber(); loadClientData(); recompute(); } }; private int emptyGradeDates() { int empty = 0; for (int i = 1; i < gradeTable.getRowCount(); i++) { String gv = getGradeTableTextBox(i, 0).getText(); String gdv = getGradeTableTextBox(i, 1).getText(); if (gdv.equals("0000-00-00") || (!gv.equals("") && gv.equals(""))) empty++; } return empty; } private final ClickHandler saveGradesHandler = new ClickHandler() { public void onClick(ClickEvent e) { if (emptyGradeDates() > 1) { jdb.setStatus("Seulement une grade sans date est permise."); new Timer() { public void run() { jdb.clearStatus(); } }.schedule(2000); return; } saveGradesData(); loadGradesData(); gradeHistory.setVisible(false); } }; private final ClickHandler annulerGradesHandler = new ClickHandler() { public void onClick(ClickEvent e) { loadGradesData(); gradeHistory.setVisible(false); } }; /** We use , as a separator, so get rid of it in the input. */ private String removeCommas(String s) { return s.replaceAll(",", ";"); } // argh NumberFormat doesn't work for me at all! // stupidly, it says that you have to use ',' as the decimal separator, but people use both '.' and ','. private String stripDollars(String s) { StringBuffer ss = new StringBuffer(""); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '$' || s.charAt(i) == ' ' || s.charAt(i) == ')' || s.charAt(i) == '\u00a0') continue; if (s.charAt(i) == ',') ss.append("."); else if (s.charAt(i) == '(') ss.append("-"); else ss.append(s.charAt(i)); } return ss.toString(); } private static native float parseFloat(String s) /*-{ return parseFloat(s); }-*/; @SuppressWarnings("deprecation") private boolean sameDate(Date d1, Date d2) { return d1.getYear() == d2.getYear() && d1.getMonth() == d2.getMonth() && d1.getDate() == d2.getDate(); } private double proratedFrais(int sessionId, Constants.Categorie c, int sessionCount, Date dateInscription) { // calculate number of weeks between start of session and dateInscription // calculate total number of weeks // divide, then add Constants.PRORATA_PENALITE double baseCost = Constants.getFraisCours(sessionId, c, sessionCount); Date sessionStart = Constants.session(sessionId).debut_cours; Date sessionEnd = Constants.session(sessionId).fin_cours; double totalWeeks = (CalendarUtil.getDaysBetween(sessionStart, sessionEnd) + 6) / 7.0; double elapsedWeeks = (CalendarUtil.getDaysBetween(dateInscription, sessionEnd) + 6) / 7.0; double prorataCost = baseCost * ((elapsedWeeks + Constants.PRORATA_PENALITE) / totalWeeks); return Math.min(baseCost, prorataCost); } private void updateFrais() { ServiceData sd = cd.getServices().get(currentServiceNumber); Date dateInscription = DateTimeFormat.getFormat("yyyy-MM-dd").parse(sd.getDateInscription()); escompteFrais.setReadOnly(true); // do not update frais for previous inscriptions if (!sameDate(dateInscription, new Date())) return; NumberFormat cf = NumberFormat.getCurrencyFormat("CAD"); int sessionCount = 1; if (sessions.getValue(sessions.getSelectedIndex()).equals("2")) { sessionCount = 2; } saisons.setText(Constants.getCurrentSessionIds(sessionCount)); Constants.Categorie c = cd.getCategorie(Constants.currentSession().effective_year); double dCategorieFrais = proratedFrais(Constants.currentSessionNo(), c, sessionCount, dateInscription); double dEscompteFrais = 0.0; if (escompte.getValue(escompte.getSelectedIndex()).equals("-1")) { NumberFormat nf = NumberFormat.getDecimalFormat(); if (cas_special_pct.getValue().equals("-1")) { String ef = stripDollars(escompteFrais.getValue()); float fEf = parseFloat(ef); cas_special_pct.setValue(nf.format(-100 * fEf / dCategorieFrais)); if (fEf > 0) { fEf *= -1; escompteFrais.setValue(nf.format(fEf)); } } else if (escompteFrais.getValue().equals("-1")) { String cpct = stripDollars(cas_special_pct.getValue()); float fCpct = parseFloat(cpct); if (fCpct < 0) { fCpct *= -1; cas_special_pct.setValue(nf.format(fCpct)); } escompteFrais.setValue(nf.format(-fCpct * dCategorieFrais / 100.0)); } dEscompteFrais = parseFloat(stripDollars(escompteFrais.getValue())); escompteFrais.setReadOnly(false); } else { dEscompteFrais = -dCategorieFrais * parseFloat(escompte.getValue(escompte.getSelectedIndex())) / 100; } double dAffiliationFrais = 0.0; if (!sans_affiliation.getValue()) dAffiliationFrais = Constants.getFraisJudoQC(Constants.currentSessionNo(), c); double dSuppFrais = parseFloat(stripDollars(judogi.getText())); if (passeport.getValue()) dSuppFrais += Constants.PASSEPORT_JUDO_QC; if (non_anjou.getValue()) dSuppFrais += Constants.NON_ANJOU; categorieFrais.setText (cf.format(dCategorieFrais)); affiliationFrais.setText (cf.format(dAffiliationFrais)); escompteFrais.setValue(cf.format(dEscompteFrais)); suppFrais.setText(cf.format(dSuppFrais)); frais.setText(cf.format(dCategorieFrais + dAffiliationFrais + dEscompteFrais + dSuppFrais)); } private void updateCopySib() { copysib.setVisible(false); // check 1) address fields are empty and 2) there exists a sibling // Note that the following check relies on the data being saved // to the ClientData, which is true after you enter the birthday. if (!cd.isDefault()) return; // oh well, tough luck! if (jdb.allClients == null) return; for (int i = 0; i < jdb.allClients.length(); i++) { ClientSummary cs = jdb.allClients.get(i); if (cs.getId().equals(cd.getID())) continue; String csn = cs.getNom().toLowerCase(); String n = nom.getText().toLowerCase(); if (n.equals(csn)) { sibid = cs.getId(); copysib.setVisible(true); } } } private void copysib() { final ClientWidget cp = new ClientWidget(Integer.parseInt(sibid), jdb); cp.onPopulated.add (new ChangeHandler () { public void onChange(ChangeEvent e) { cp.actuallyCopy(ClientWidget.this); } }); } private void actuallyCopy(ClientWidget d) { d.adresse.setText(adresse.getText()); d.ville.setText(ville.getText()); d.codePostal.setText(codePostal.getText()); d.tel.setText(tel.getText()); d.tel_contact_urgence.setText(tel_contact_urgence.getText()); d.courriel.setText(courriel.getText()); d.updateCopySib(); } private void recompute() { saveClientData(); Display d = Display.NONE; if (escompte.getValue(escompte.getSelectedIndex()).equals("-1")) d = Display.INLINE; ((Element)cas_special_note.getElement().getParentNode()).getStyle().setDisplay(d); ((Element)cas_special_pct.getElement().getParentNode()).getStyle().setDisplay(d); ServiceData sd = cd.getServices().get(currentServiceNumber); if (sd != null && !sd.getSaisons().equals("")) { Constants.Categorie c = cd.getCategorie(Constants.session(sd.getSaisons()).effective_year); categorie.setText(c.abbrev); } updateBlurb(); updateFrais(); updateCopySib(); } private void encodeServices() { StringBuffer di = new StringBuffer(), sais = new StringBuffer(), v = new StringBuffer(), cf = new StringBuffer(), c = new StringBuffer(), sess = new StringBuffer(), e = new StringBuffer(), csn = new StringBuffer(), csp = new StringBuffer(), ef = new StringBuffer(), sa = new StringBuffer(), af = new StringBuffer(), j = new StringBuffer(), p = new StringBuffer(), n = new StringBuffer(), sf = new StringBuffer(), s = new StringBuffer(), f = new StringBuffer(); JsArray<ServiceData> services = cd.getServices(); for (int i = 0; i < services.length(); i++) { ServiceData sd = services.get(i); di.append(sd.getDateInscription()+","); sais.append(sd.getSaisons()+","); v.append(sd.getVerification() ? "1," : "0,"); cf.append(sd.getCategorieFrais()+","); c.append(sd.getCours()+","); sess.append(Integer.toString(sd.getSessionCount())+","); e.append(Integer.toString(sd.getEscompteType())+","); csn.append(sd.getCasSpecialNote()+","); csp.append(sd.getCasSpecialPct()+","); ef.append(sd.getEscompteFrais()+","); sa.append(sd.getSansAffiliation() ? "1," : "0,"); af.append(sd.getAffiliationFrais()+","); j.append(sd.getJudogi()+","); p.append(sd.getPasseport()+","); n.append(sd.getNonAnjou()+","); sf.append(sd.getSuppFrais()+","); s.append(sd.getSolde() ? "1,":"0,"); f.append(sd.getFrais()+","); } date_inscription_encoded.setValue(di.toString()); saisons_encoded.setValue(sais.toString()); verification_encoded.setValue(v.toString()); categorieFrais_encoded.setValue(cf.toString()); cours_encoded.setValue(c.toString()); sessions_encoded.setValue(sess.toString()); escompte_encoded.setValue(e.toString()); cas_special_note_encoded.setValue(csn.toString()); cas_special_pct_encoded.setValue(csp.toString()); escompteFrais_encoded.setValue(ef.toString()); sans_affiliation_encoded.setValue(sa.toString()); affiliationFrais_encoded.setValue(af.toString()); judogi_encoded.setValue(j.toString()); passeport_encoded.setValue(p.toString()); non_anjou_encoded.setValue(n.toString()); suppFrais_encoded.setValue(sf.toString()); solde_encoded.setValue(s.toString()); frais_encoded.setValue(f.toString()); } private void pushClientDataToServer() { if (cd.getNom().equals("") || cd.getPrenom().equals("")) { jdb.displayError("pas de nom ou prenom"); return; } guid = UUID.uuid(); sid.setValue(cd.getID()); guid_on_form.setValue(guid); grades_encoded.setValue(encodeGrades()); grade_dates_encoded.setValue(encodeGradeDates()); saveClientData(); loadClientData(); encodeServices(); clientform.submit(); pushTries = 0; new Timer() { public void run() { getJsonForStageTwoPush(jdb.jsonRequestId++, CONFIRM_PUSH_URL + guid + CALLBACK_URL_SUFFIX, ClientWidget.this); } }.schedule(500); } private void pushDeleteToServer() { // no need to delete if there's no ID yet. if (cd.getID().equals("")) return; guid = UUID.uuid(); sid.setValue(cd.getID()); guid_on_form.setValue(guid); deleted.setValue("true"); clientform.submit(); pushTries = 0; new Timer() { public void run() { getJsonForStageTwoPush(jdb.jsonRequestId++, CONFIRM_PUSH_URL + guid + CALLBACK_URL_SUFFIX, ClientWidget.this); } }.schedule(500); } /** * Make call to remote server to request client information. */ public native static void getJsonForPull(int requestId, String url, ClientWidget handler) /*-{ var callback = "callback" + requestId; var script = document.createElement("script"); script.setAttribute("src", url+callback); script.setAttribute("type", "text/javascript"); window[callback] = function(jsonObj) { handler.@ca.patricklam.judodb.client.ClientWidget::handleJsonPullResponse(Lcom/google/gwt/core/client/JavaScriptObject;)(jsonObj); window[callback + "done"] = true; } setTimeout(function() { if (!window[callback + "done"]) { handler.@ca.patricklam.judodb.client.ClientWidget::handleJsonPullResponse(Lcom/google/gwt/core/client/JavaScriptObject;)(null); } document.body.removeChild(script); delete window[callback]; delete window[callback + "done"]; }, 5000); document.body.appendChild(script); }-*/; /** * Handle the response to the request for data from a remote server. */ public void handleJsonPullResponse(JavaScriptObject jso) { if (jso == null) { jdb.displayError("Couldn't retrieve JSON"); return; } this.cd = jso.cast(); currentServiceNumber = cd.getMostRecentServiceNumber(); loadClientData(); jdb.clearStatus(); for (ChangeHandler ch : onPopulated) { ch.onChange(null); } } /** * Make call to remote server to request client information. */ public native static void getJsonForStageTwoPush(int requestId, String url, ClientWidget handler) /*-{ var callback = "callback" + requestId; var script = document.createElement("script"); script.setAttribute("src", url+callback); script.setAttribute("type", "text/javascript"); window[callback] = function(jsonObj) { handler.@ca.patricklam.judodb.client.ClientWidget::handleJsonStageTwoPushResponse(Lcom/google/gwt/core/client/JavaScriptObject;)(jsonObj); window[callback + "done"] = true; } setTimeout(function() { if (!window[callback + "done"]) { handler.@ca.patricklam.judodb.client.ClientWidget::handleJsonStageTwoPushResponse(Lcom/google/gwt/core/client/JavaScriptObject;)(null); } document.body.removeChild(script); delete window[callback]; delete window[callback + "done"]; }, 5000); document.body.appendChild(script); }-*/; /** * Handle the response to the request for data from a remote server. */ public void handleJsonStageTwoPushResponse(JavaScriptObject jso) { if (jso == null) { if (pushTries == 3) { jdb.displayError("pas de réponse"); new Timer() { public void run() { jdb.clearStatus(); } }.schedule(2000); return; } else { tryConfirmPushAgain(); } } ConfirmResponseObject cro = jso.cast(); if (cro.getResult().equals("NOTYET")) { tryConfirmPushAgain(); return; } if (!cro.getResult().equals("OK")) { jdb.displayError("le serveur n'a pas accepté les données"); new Timer() { public void run() { jdb.clearStatus(); } }.schedule(2000); } else { jdb.setStatus("Sauvegardé."); jdb.invalidateListWidget(); new Timer() { public void run() { jdb.clearStatus(); } }.schedule(2000); if (cd.getID() == null || cd.getID().equals("")) { cd.setID(Integer.toString(cro.getSid())); loadClientData(); } } } private void tryConfirmPushAgain() { pushTries++; new Timer() { public void run() { ClientWidget.getJsonForStageTwoPush (jdb.jsonRequestId++, CONFIRM_PUSH_URL + guid + CALLBACK_URL_SUFFIX, ClientWidget.this); }}.schedule(1000); } }
// -*- indent-tabs-mode:nil; c-basic-offset:4; -*- package ca.patricklam.judodb.client; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JsArray; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsonUtils; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HasHorizontalAlignment; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.FormPanel; import com.google.gwt.user.client.ui.Hidden; import com.google.gwt.user.client.ui.ResizeLayoutPanel; import com.google.gwt.user.client.ui.TabLayoutPanel; import com.google.gwt.user.cellview.client.Column; import com.google.gwt.user.cellview.client.CellTable; import com.google.gwt.cell.client.Cell; import com.google.gwt.cell.client.AbstractEditableCell; import com.google.gwt.cell.client.EditTextCell; import com.google.gwt.cell.client.FieldUpdater; import com.google.gwt.view.client.ProvidesKey; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.cell.client.TextCell; import com.google.gwt.dom.client.Style.Unit; import org.gwtbootstrap3.client.ui.TabListItem; import org.gwtbootstrap3.client.ui.AnchorListItem; import org.gwtbootstrap3.client.ui.Button; import org.gwtbootstrap3.client.ui.ButtonGroup; import org.gwtbootstrap3.client.ui.FormGroup; import org.gwtbootstrap3.client.ui.Container; import org.gwtbootstrap3.client.ui.TextBox; import org.gwtbootstrap3.client.ui.ListBox; import org.gwtbootstrap3.client.ui.DropDownMenu; import org.gwtbootstrap3.extras.toggleswitch.client.ui.ToggleSwitch; import java.util.List; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Set; import java.util.HashSet; import java.util.TreeSet; public class ConfigWidget extends Composite { interface MyUiBinder extends UiBinder<Widget, ConfigWidget> {} public static MyUiBinder uiBinder = GWT.create(MyUiBinder.class); @UiField FlowPanel sessionTab; @UiField FlowPanel coursTab; @UiField FlowPanel prixTab; @UiField FlowPanel escompteTab; @UiField FlowPanel produitTab; @UiField Button retour; @UiField FormPanel configEditForm; @UiField FormGroup ajustable; @UiField Hidden current_session; @UiField Hidden dataToSave; @UiField Hidden guid_on_form; private String guid; private int pushTries; private final JudoDB jdb; CellTable<SessionSummary> sessions; // contains the [add session] link also private final List<SessionSummary> sessionData = new ArrayList<>(); private final List<SessionSummary> rawSessionData = new ArrayList<>(); CellTable<CoursSummary> cours; // rawCoursData is unconsolidated, coursData is merged by session private final List<CoursSummary> rawCoursData = new ArrayList<>(); private final List<CoursSummary> coursData = new ArrayList<>(); private final HashMap<String, List<String>> coursShortDescToDbIds = new HashMap<>(); private final HashSet<CoursSummary> duplicateCours = new HashSet<>(); private final List<Prix> rawPrixData = new ArrayList<>(); private final List<CoursPrix> prixRows = new ArrayList<>(); private SessionSummary currentPrixSession; private String currentPrixSeqnoString; private boolean isPairPrixSession; CellTable<EscompteSummary> escomptes; private final List<EscompteSummary> escompteData = new ArrayList<>(); CellTable<ProduitSummary> produits; private final List<ProduitSummary> produitData = new ArrayList<>(); // not done yet: for each club, // montants--namely, (should theoretically be stored with the session) // frais passeport judo QC [5] // penalty for prorata (constant factor, in addition to percent of cost) [5] // misc: // age veteran [35] // not needed for now: // for each division: // name [Junior] // abbrev [U20N] // years_ago [20] // noire [true] // aka [U20] @UiField ButtonGroup dropDownUserClubsButtonGroup; @UiField Button dropDownUserClubsButton; @UiField DropDownMenu dropDownUserClubs; void selectClub(ClubSummary club) { jdb.selectClub(club); if (club == null) dropDownUserClubsButton.setText(JudoDB.TOUS); else dropDownUserClubsButton.setText(club.getClubText()); if (club != null) { retrieveSessions(club.getId()); retrieveCours(club.getNumeroClub()); retrievePrix(club.getId()); retrieveEscomptes(club.getId()); retrieveProduits(club.getId()); } else { retrieveSessions("0"); retrievePrix("0"); clearCours(); clearPrix(); clearEscomptes(); clearProduits(); } populateCurrentClub(); } class ConfigClubListHandlerFactory implements JudoDB.ClubListHandlerFactory { public ClickHandler instantiate(ClubSummary s) { return new ClubListHandler(s); } } class ClubListHandler implements ClickHandler { final ClubSummary club; ClubListHandler(ClubSummary club) { this.club = club; } @Override public void onClick(ClickEvent e) { selectClub(club); } } public ConfigWidget(JudoDB jdb, ClubSummary selectedClub) { this.jdb = jdb; initWidget(uiBinder.createAndBindUi(this)); retour.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { ConfigWidget.this.jdb.switchMode(new JudoDB.Mode(JudoDB.Mode.ActualMode.MAIN)); }}); jdb.pleaseWait(); jdb.populateClubList(true, dropDownUserClubs, new ConfigClubListHandlerFactory()); initializeSessionTable(); sessionTab.add(sessions); initializeCoursTable(); coursTab.add(cours); initializePrixTable(); prixTab.add(prix); initializeEscompteTable(); escompteTab.add(escomptes); initializeProduitTable(); produitTab.add(produits); configEditForm.setAction(JudoDB.PUSH_MULTI_CLIENTS_URL); jdb.clearStatus(); selectClub(selectedClub); } /* accepts something like A14 H15 A15 H16 * returns a list of sessions, ignoring linked_seqnos. */ private List<SessionSummary> parseSessionIds(String sessionAbbrevs) { String[] sessionAbbrevArray = sessionAbbrevs.split(" "); List<SessionSummary> retval = new ArrayList<>(); for (String s : sessionAbbrevArray) { SessionSummary ts = seqAbbrevToSession.get(s); if (ts != null) retval.add(ts); } return retval; } private HashMap<String, SessionSummary> seqnoToSession = new HashMap<>(); // primary session only, not linked private HashMap<String, SessionSummary> seqAbbrevToSession = new HashMap<>(); private void updateSessionToNameMapping() { seqnoToSession.clear(); seqAbbrevToSession.clear(); for (SessionSummary s : sessionData) seqnoToSession.put(s.getSeqno(), s); for (SessionSummary s : sessionData) { SessionSummary linkedSession = seqnoToSession.get(s.getLinkedSeqno()); if (s.isPrimary()) seqAbbrevToSession.put(s.getAbbrev(), s); } } @UiField TextBox nom_club; @UiField TextBox nom_short; @UiField TextBox numero_club; @UiField TextBox ville; @UiField TextBox prefix_codepostale; @UiField TextBox indicatif_regional; @UiField TextBox escompte_resident; @UiField TextBox supplement_prorata; @UiField ToggleSwitch default_prorata; @UiField ToggleSwitch afficher_paypal; ValueChangeHandler<String> newValueChangeHandler(final String key) { return new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { refreshClub = true; pushEdit("-1,c" + key + "," + event.getValue() + "," + jdb.getSelectedClubID() + ";"); } }; } ValueChangeHandler<Boolean> newValueChangeHandlerBoolean(final String key) { return new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { refreshClub = true; refreshPrix = true; pushEdit("-1,c" + key + "," + (event.getValue() ? "1" : "0") + "," + jdb.getSelectedClubID() + ";"); } }; } private boolean clubHandlersInstalled = false; void initializeClubFields() { nom_club.setText(""); nom_club.setReadOnly(true); numero_club.setText(""); numero_club.setReadOnly(true); nom_short.setText(""); ville.setText(""); prefix_codepostale.setText(""); indicatif_regional.setText(""); escompte_resident.setText(""); supplement_prorata.setText(""); default_prorata.setValue(false); if (!clubHandlersInstalled) { clubHandlersInstalled = true; nom_short.addValueChangeHandler(newValueChangeHandler("nom_short")); ville.addValueChangeHandler(newValueChangeHandler("ville")); prefix_codepostale.addValueChangeHandler(newValueChangeHandler("prefix_codepostale")); indicatif_regional.addValueChangeHandler(newValueChangeHandler("indicatif_regional")); escompte_resident.addValueChangeHandler(newValueChangeHandler("escompte_resident")); supplement_prorata.addValueChangeHandler(newValueChangeHandler("supplement_prorata")); default_prorata.addValueChangeHandler(newValueChangeHandlerBoolean("pro_rata")); afficher_paypal.addValueChangeHandler(newValueChangeHandlerBoolean("afficher_paypal")); } boolean setEverythingReadOnly = false; if (jdb.getSelectedClubID() == null) { nom_club.setText("n/d"); setEverythingReadOnly = true; } nom_short.setReadOnly(setEverythingReadOnly); ville.setReadOnly(setEverythingReadOnly); prefix_codepostale.setReadOnly(setEverythingReadOnly); indicatif_regional.setReadOnly(setEverythingReadOnly); escompte_resident.setReadOnly(setEverythingReadOnly); supplement_prorata.setEnabled(!setEverythingReadOnly); default_prorata.setEnabled(!setEverythingReadOnly); afficher_paypal.setEnabled(!setEverythingReadOnly); } void populateCurrentClub() { String selectedClub = jdb.getSelectedClubID(); initializeClubFields(); if (selectedClub == null) { ajustable.setVisible(false); return; } ClubSummary cs = jdb.getClubSummaryByID(jdb.getSelectedClubID()); nom_club.setText(cs.getNom()); nom_short.setText(cs.getNomShort()); numero_club.setText(cs.getNumeroClub()); ville.setText(cs.getVille()); prefix_codepostale.setText(cs.getPrefixCodepostale()); indicatif_regional.setText(cs.getIndicatifRegional()); escompte_resident.setText(cs.getEscompteResident()); supplement_prorata.setText(cs.getSupplementProrata()); default_prorata.setValue(cs.getEnableProrata()); afficher_paypal.setValue(cs.getAfficherPaypal()); // on prix tab, but set by club: ajustable.setVisible(true); ajustableCours.setValue(cs.getAjustableCours()); ajustableDivision.setValue(cs.getAjustableDivision()); } private static final ProvidesKey<SessionSummary> SESSION_KEY_PROVIDER = new ProvidesKey<SessionSummary>() { @Override public Object getKey(SessionSummary item) { return item.getSeqno(); } }; private class ColumnFields { public ColumnFields(String key, String name, int width, Unit widthUnits) { this.key = key; this.name = name; this.width = width; this.widthUnits = widthUnits; } public String key; public String name; public int width; public Unit widthUnits; } private static final String DELETE_SESSION_KEY = "DELETE"; private final ColumnFields NAME_COLUMN = new ColumnFields("name", "Nom", 10, Unit.EM), ABBREV_COLUMN = new ColumnFields("abbrev", "Abbr", 4, Unit.EM), YEAR_COLUMN = new ColumnFields("year", "Année", 5, Unit.EM), SEQNO_COLUMN = new ColumnFields("seqno", "no seq", 3, Unit.EM), LINKED_SEQNO_COLUMN = new ColumnFields("linked_seqno", "seq alt", 3, Unit.EM), FIRST_CLASS_COLUMN = new ColumnFields("first_class_date", "début cours" , 10, Unit.EM), FIRST_SIGNUP_COLUMN = new ColumnFields("first_signup_date", "début inscription", 10, Unit.EM), LAST_CLASS_COLUMN = new ColumnFields("last_class_date", "fin cours", 10, Unit.EM), LAST_SIGNUP_COLUMN = new ColumnFields("last_signup_date", "fin inscription", 10, Unit.EM), DELETE_SESSION_COLUMN = new ColumnFields(DELETE_SESSION_KEY, "", 1, Unit.EM); private List<ColumnFields> perClubColumns = Collections.unmodifiableList(Arrays.asList(FIRST_CLASS_COLUMN, FIRST_SIGNUP_COLUMN, LAST_CLASS_COLUMN, LAST_SIGNUP_COLUMN, DELETE_SESSION_COLUMN)); private static final String BALLOT_X = "x"; private Column<SessionSummary, String> addSessionColumn(final CellTable<SessionSummary> t, final ColumnFields c, final boolean editable) { final Cell<String> cell = editable ? new EditTextCell() : new TextCell(); Column<SessionSummary, String> newColumn = new Column<SessionSummary, String>(cell) { public String getValue(SessionSummary object) { if (c.key.equals(DELETE_SESSION_KEY)) { return BALLOT_X; } return object.get(c.key); } }; sessions.addColumn(newColumn, c.name); newColumn.setFieldUpdater(new FieldUpdater<SessionSummary, String>() { @Override public void update(int index, SessionSummary object, String value) { if (c.key == null) return; String oldValue = object.get(c.key); object.set(c.key, value); if (perClubColumns.contains(c)) { if (object.getId().equals("-1")) { refreshSessions = true; pushEdit("-1,F" + c.key + "," + value + "," + jdb.getSelectedClub().getNumeroClub() + "," + object.getSeqno() + ";"); } else { if (c.key.equals(FIRST_SIGNUP_COLUMN.key) || c.key.equals(LAST_SIGNUP_COLUMN.key)) { boolean error = false; try { SessionSummary conflicting = JudoDB.getSessionForDate(new Date(value), sessionData); if (conflicting != object && conflicting != null) { error = true; jdb.displayError("conflit de dates entre "+object.getAbbrev()+ " et "+conflicting.getAbbrev()); new Timer() { public void run() { jdb.clearStatus(); } }.schedule(5000); } } catch (IllegalArgumentException e) { error = true; } if (error) { object.set(c.key, oldValue); ((EditTextCell)cell).clearViewData (SESSION_KEY_PROVIDER.getKey(object)); t.redraw(); return; } } pushEdit("-1,f" + c.key + "," + value + "," + object.getClub() + "," + object.getId() + ";"); } } else { pushEdit("-1,e" + c.key + "," + value + "," + object.getSeqno() + ";"); } updateSessionToNameMapping(); t.redraw(); } }); sessions.setColumnWidth(newColumn, c.width, c.widthUnits); return newColumn; } void initializeSessionTable() { sessions = new CellTable<>(SESSION_KEY_PROVIDER); sessions.setWidth("60em", true); initializeSessionColumns(); } final private static String ADD_SESSION_VALUE = "[ajouter session]"; void addAddSessionSession() { int maxSeqno = -1; for (SessionSummary s : rawSessionData) { if (Integer.parseInt(s.getSeqno()) > maxSeqno) maxSeqno = Integer.parseInt(s.getSeqno()); } SessionSummary addNewSession = JsonUtils.<SessionSummary>safeEval ("{\"seqno\":\""+(maxSeqno+1)+"\",\"name\":\""+ADD_SESSION_VALUE+"\"}"); addNewSession.setAbbrev(""); addNewSession.setYear(""); addNewSession.setLinkedSeqno(""); sessionData.add(addNewSession); } void initializeSessionColumns() { while (sessions.getColumnCount() > 0) sessions.removeColumn(0); // name is special: handle inserting a new session final Column<SessionSummary, String> nameColumn = addSessionColumn(sessions, NAME_COLUMN, !jdb.isClubSelected()); nameColumn.setFieldUpdater(new FieldUpdater<SessionSummary, String>() { @Override public void update(int index, SessionSummary object, String value) { if (object.get(NAME_COLUMN.key).equals(ADD_SESSION_VALUE)) { pushEdit("-1,E" + NAME_COLUMN.key + "," + value + "," + object.getSeqno() + ";"); addAddSessionSession(); } else { pushEdit("-1,e" + NAME_COLUMN.key + "," + value + "," + object.getSeqno() + ";"); } object.set(NAME_COLUMN.key, value); sessions.setRowData(sessionData); sessions.redraw(); } }); addSessionColumn(sessions, ABBREV_COLUMN, !jdb.isClubSelected()); addSessionColumn(sessions, YEAR_COLUMN, !jdb.isClubSelected()); if (jdb.isClubSelected()) { addSessionColumn(sessions, FIRST_CLASS_COLUMN, true); addSessionColumn(sessions, FIRST_SIGNUP_COLUMN, true); addSessionColumn(sessions, LAST_CLASS_COLUMN, true); addSessionColumn(sessions, LAST_SIGNUP_COLUMN, true); } else { if (jdb.isAdmin) { addSessionColumn(sessions, SEQNO_COLUMN, false); addSessionColumn(sessions, LINKED_SEQNO_COLUMN, !jdb.isClubSelected()); } } addSessionColumn(sessions, DELETE_SESSION_COLUMN, false); } private void populateSessions(JsArray<SessionSummary> sessionArray) { // reset the editable status of the cells initializeSessionColumns(); sessionData.clear(); for (int i = 0; i < sessionArray.length(); i++) { sessionData.add(sessionArray.get(i)); } rawSessionData.clear(); rawSessionData.addAll(sessionData); if (!jdb.isClubSelected()) { addAddSessionSession(); } sessions.setRowData(sessionData); sessions.redraw(); updateSessionToNameMapping(); populateSessionsForPrix(); } /* test script: * - create a new cours by entering a description * - add another session to that cours * - edit the short_desc * - delete a session from that cours * * - edit the session of the "add new cours" cours * - change that session to a disjoint session (eg A15 H16 -> A14) * - edit the session of the "add new cours" cours again, should see a merge * * - edit a short_desc so that it is the same as some other existing short_desc */ private static final ProvidesKey<CoursSummary> COURS_KEY_PROVIDER = new ProvidesKey<CoursSummary>() { @Override public Object getKey(CoursSummary item) { return item.getId(); } }; private final ColumnFields COURS_SESSION_COLUMN = new ColumnFields("session", "Session", 2, Unit.EM), DESC_COLUMN = new ColumnFields("short_desc", "Description", 4, Unit.EM); private List<ColumnFields> perCoursColumns = Collections.unmodifiableList(Arrays.asList(COURS_SESSION_COLUMN, DESC_COLUMN)); void initializeCoursTable() { cours = new CellTable<>(COURS_KEY_PROVIDER); cours.setWidth("60em", true); initializeCoursColumns(); } private Column<CoursSummary, String> addCoursColumn(final CellTable t, final ColumnFields c, final boolean editable) { final Cell<String> cell = editable ? new EditTextCell() : new TextCell(); Column<CoursSummary, String> newColumn = new Column<CoursSummary, String>(cell) { public String getValue(CoursSummary object) { return object.get(c.key); } }; cours.addColumn(newColumn, c.name); // this handles updating the short_desc column newColumn.setFieldUpdater(new FieldUpdater<CoursSummary, String>() { @Override public void update(int index, CoursSummary object, String value) { List<SessionSummary> sessions = parseSessionIds(value); StringBuffer sb = new StringBuffer(); refreshCours = true; if (object.get(DESC_COLUMN.key).equals(ADD_COURS_VALUE)) { // ... of a new cours, case (2) assert (object.get(COURS_SESSION_COLUMN.key).equals("")); String currentSessions = JudoDB.getSessionIds(new Date(), 2, sessionData); object.set(COURS_SESSION_COLUMN.key, currentSessions); sessions = parseSessionIds(currentSessions); List<String> cs = new ArrayList<>(); StringBuffer edits = new StringBuffer(); for (SessionSummary ss : sessions) { cs.add(ss.getAbbrev()); edits.append("-1,R," + ss.getSeqno() + "," + value + "," + /* supplement */ "," + jdb.getSelectedClubID() + ";"); } pushEdit(edits.toString()); coursShortDescToDbIds.put(value, cs); addAddCoursCours(); } else { // ... of an existing cours, case (4) assert coursShortDescToDbIds.containsKey(object.getShortDesc()); StringBuffer edits = new StringBuffer(); for (String coursId : coursShortDescToDbIds.get(object.getShortDesc())) { edits.append("-1,r" + c.key + "," + coursId + "," + value + "," + jdb.getSelectedClubID() + ";"); } removeDuplicateCours(edits); pushEdit(edits.toString()); } object.set(c.key, value); cours.setRowData(coursData); t.redraw(); } }); cours.setColumnWidth(newColumn, c.width, c.widthUnits); return newColumn; } void initializeCoursColumns() { while (cours.getColumnCount() > 0) cours.removeColumn(0); final Column<CoursSummary, String> sessionColumn = addCoursColumn(sessions, COURS_SESSION_COLUMN, true); // implement changes to the session column // todo: have a button for deleting all sessions? sessionColumn.setFieldUpdater(new FieldUpdater<CoursSummary, String>() { @Override public void update(int index, CoursSummary object, String value) { List<SessionSummary> newSessions = parseSessionIds(value); List<SessionSummary> oldSessions = parseSessionIds(object.get(COURS_SESSION_COLUMN.key)); if (oldSessions.equals(newSessions)) return; refreshCours = true; List<SessionSummary> addedSessions = new ArrayList<>(), removedSessions = new ArrayList<>(); for (SessionSummary s : newSessions) if (!oldSessions.contains(s)) addedSessions.add(s); for (SessionSummary s : oldSessions) if (!newSessions.contains(s)) removedSessions.add(s); StringBuffer sb = new StringBuffer(); if (object.get(DESC_COLUMN.key).equals(ADD_COURS_VALUE)) { object.set(DESC_COLUMN.key, ""); // if there is already a blank desc_column it automatically gets merged assert (removedSessions.isEmpty()); StringBuffer edits = new StringBuffer(); for (SessionSummary ss : newSessions) { edits.append("-1,R," + ss.getSeqno() + "," + object.getShortDesc() + "," + jdb.getSelectedClubID() + ";"); } pushEdit(edits.toString()); addAddCoursCours(); } else { // add added sessions StringBuffer edits = new StringBuffer(); for (SessionSummary ss : addedSessions) { edits.append("-1,R," + ss.getSeqno() + "," + object.getShortDesc() + "," + jdb.getSelectedClubID() + ";"); } // remove deleted sessions assert coursShortDescToDbIds.containsKey(object.getShortDesc()); for (SessionSummary ss : removedSessions) { for (CoursSummary cs : rawCoursData) { if (cs.getShortDesc().equals(object.getShortDesc()) && cs.getSession().equals(ss.getSeqno())) { edits.append("-1,O," + cs.getId() + "," + object.getShortDesc() + "," + jdb.getSelectedClubID() + ";"); } } } removeDuplicateCours(edits); pushEdit(edits.toString()); } } }); addCoursColumn(sessions, DESC_COLUMN, true); } private void removeDuplicateCours(StringBuffer edits) { for (CoursSummary cs : duplicateCours) { edits.append("-1,O," + cs.getId() + "," + cs.getShortDesc() + "," + jdb.getSelectedClubID() + ";"); } duplicateCours.clear(); } final private static String ADD_COURS_VALUE = "[ajouter cours]"; void addAddCoursCours() { int maxId = -1; for (CoursSummary c : coursData) { if (Integer.parseInt(c.getId()) > maxId) maxId = Integer.parseInt(c.getId()); } CoursSummary addNewCours = JsonUtils.<CoursSummary>safeEval ("{\"id\":\""+(maxId+1)+"\"}"); addNewCours.setSession(""); addNewCours.setClubId(jdb.getSelectedClubID()); addNewCours.setShortDesc(ADD_COURS_VALUE); coursData.add(addNewCours); } // requires sessions to be populated first private void populateCours(List<CoursSummary> coursArray) { // combine cours across sessions // l has keys shortdesc, values sessions // m has keys shortdesc, values ids HashMap<String, StringBuffer> l = new HashMap<>(); HashMap<String, Set<String>> ll = new HashMap<>(); HashMap<String, List<String>> m = new HashMap<>(); rawCoursData.clear(); rawCoursData.addAll(coursArray); duplicateCours.clear(); for (CoursSummary cs : coursArray) { if (!l.containsKey(cs.getShortDesc())) { l.put(cs.getShortDesc(), new StringBuffer()); ll.put(cs.getShortDesc(), new HashSet<String>()); m.put(cs.getShortDesc(), new ArrayList<String>()); } StringBuffer b = l.get(cs.getShortDesc()); List<String> ids = m.get(cs.getShortDesc()); ids.add(cs.getId()); SessionSummary ss = seqnoToSession.get(cs.getSession()); if (ss == null) continue; if (ll.get(cs.getShortDesc()).contains(ss.getAbbrev())) { duplicateCours.add(cs); continue; } ll.get(cs.getShortDesc()).add(ss.getAbbrev()); if (b.length() > 0) b.append(" "); b.append(ss.getAbbrev()); String ls = ss.getLinkedSeqno(); if (!ls.equals("")) { b.append(" "); b.append(seqnoToSession.get(ls).getAbbrev()); ll.get(cs.getShortDesc()).add(seqnoToSession.get(ls).getAbbrev()); } } coursData.clear(); int id = 0; for (String s : l.keySet()) { CoursSummary cs = (CoursSummary)JavaScriptObject.createObject().cast(); cs.setId(String.valueOf(id)); cs.setShortDesc(s); cs.setSession(l.get(s).toString()); coursShortDescToDbIds.put(cs.getShortDesc(), m.get(s)); coursData.add(cs); id++; } addAddCoursCours(); cours.setRowData(coursData); cours.redraw(); } private void clearCours() { coursData.clear(); cours.setRowData(coursData); cours.redraw(); } @UiField ButtonGroup prixSessionButtonGroup; @UiField Button prixSessionsButton; @UiField DropDownMenu prixSessions; @UiField ToggleSwitch ajustableCours; @UiField ToggleSwitch ajustableDivision; @UiField CellTable<CoursPrix> prix; // session: A15/H16/A15 H16 [H16 => copier A15] // next two visible when there is a club: // prix uniforme par cours O/N // prix uniforme par age O/N // when no club, take entries for Affiliation JQ // if all no: // U8 U10 U12 U14 U16 U16N U18 U18N U20 U20N S SN // cours 1... // cours 2... // if not ajustable par cours: // U8 U10 U12 U14 U16 U16N U18 U18N U20 U20N S SN // prix: ... // if not ajustable par age: // cours 1... // cours 2 ... // prix cours is a function of: club, session, division, cours class CoursPrix { CoursSummary c; List<Prix> prix; } private static final Object AFFILIATION_PRIX_KEY = new Object(); private static final ProvidesKey<CoursPrix> PRIX_KEY_PROVIDER = new ProvidesKey<CoursPrix>() { @Override public Object getKey(CoursPrix item) { if (item.c == null) return AFFILIATION_PRIX_KEY; return item.c.getId(); } }; void initializePrixTable() { ajustableCours.addValueChangeHandler(newValueChangeHandlerBoolean("ajustable_cours")); ajustableDivision.addValueChangeHandler(newValueChangeHandlerBoolean("ajustable_division")); prix = new CellTable<>(PRIX_KEY_PROVIDER); } private boolean isUnidivision() { return jdb.getSelectedClub() != null && !ajustableDivision.getValue(); } void initializePrixUnidivisionColumn() { Column<CoursPrix, String> col = new Column<CoursPrix, String>(new EditTextCell()) { public String getValue(CoursPrix object) { for (Prix p : object.prix) { if (p.getDivisionAbbrev().equals(FraisCoursCalculator.ALL_DIVISIONS)) return p.getFrais(); } return ""; } }; col.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT); prix.addColumn(col, "TOUS"); prix.setColumnWidth(col, 3, Unit.EM); col.setFieldUpdater(new FieldUpdater<CoursPrix, String>() { @Override public void update(int index, CoursPrix object, String value) { if (object == null || object.prix.size() < 1) return; Prix p = null; for (Prix pp : object.prix) { if (p.getDivisionAbbrev().equals(FraisCoursCalculator.ALL_DIVISIONS)) { p = pp; break; } } // should not happen; we should always have a match (even for new Prix) if (p == null) return; p.setFrais(value); StringBuilder edits = new StringBuilder(); String coursId; if (object.c == null) { coursId = "-1"; } else { coursId = object.c.getId(); } if (p.getId().equals("0")) { // new prix, not previously in db edits.append("-1,P," + value + "," + p.getClubId() + "," + p.getSessionSeqno() + "," + FraisCoursCalculator.ALL_DIVISIONS + "," + coursId + ";"); } else { edits.append("-1,p," + p.getId() + "," + value + "," + p.getClubId() + "," + p.getSessionSeqno() + "," + FraisCoursCalculator.ALL_DIVISIONS + "," + coursId + ";"); } pushEdit(edits.toString()); refreshPrix = true; } }); } void initializePrixDivisionColumns() { for (final Constants.Division d : Constants.DIVISIONS) { Column<CoursPrix, String> col = new Column<CoursPrix, String>(new EditTextCell()) { public String getValue(CoursPrix object) { if (object == null) return ""; for (Prix p : object.prix) { if (p.getDivisionAbbrev().equals(d.abbrev)) return p.getFrais(); } return ""; } }; col.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT); prix.addColumn(col, d.abbrev); prix.setColumnWidth(col, 2, Unit.EM); col.setFieldUpdater(new FieldUpdater<CoursPrix, String>() { @Override public void update(int index, CoursPrix object, String value) { Prix p = null; for (Prix pp : object.prix) { if (pp.getDivisionAbbrev().equals(d.abbrev)) { p = pp; break; } } // should not happen; we should always have a match (even for new Prix) if (p == null) return; p.setFrais(value); StringBuilder edits = new StringBuilder(); String coursId; if (object.c == null) { // indicate frais d'affiliation with coursId -1 (and clubId -1 also) // note: on server side, only admin can write clubId -1 coursId = "-1"; } else { coursId = object.c.getId(); } if (p.getId().equals("0")) { // new prix, not previously in db edits.append("-1,P," + value + "," + p.getClubId() + "," + p.getSessionSeqno() + "," + p.getDivisionAbbrev() + "," + coursId + ";"); } else { edits.append("-1,p," + p.getId() + "," + value + "," + p.getClubId() + "," + p.getSessionSeqno() + "," + p.getDivisionAbbrev() + "," + coursId + ";"); } pushEdit(edits.toString()); refreshPrix = true; } }); } } void initializePrixColumns() { while (prix.getColumnCount() > 0) prix.removeColumn(0); Column<CoursPrix, String> coursColumn = new Column<CoursPrix, String>(new TextCell()) { public String getValue(CoursPrix object) { if (object == null) return ""; if (jdb.getSelectedClub() != null && !ajustableCours.getValue()) return "TOUS"; if (object.c == null || object.c.equals("")) return "Affiliation"; return object.c.getShortDesc(); } }; prix.addColumn(coursColumn, "Cours"); prix.setColumnWidth(coursColumn, 10, Unit.EM); if (isUnidivision()) { initializePrixUnidivisionColumn(); } else { initializePrixDivisionColumns(); } } private void populatePrix(List<Prix> lcp) { initializePrixColumns(); rawPrixData.clear(); rawPrixData.addAll(lcp); populatePrixRows(); } private void addPrixRow(CoursSummary cs) { String coursId = cs == null ? FraisCoursCalculator.ALL_COURS : cs.getId(); List<Prix> ps = FraisCoursCalculator.getPrixForClubSessionCours (rawPrixData, jdb.getSelectedClubID(), currentPrixSeqnoString, coursId, isUnidivision()); CoursPrix cp = new CoursPrix(); cp.c = cs; cp.prix = ps; prixRows.add(cp); } private void populatePrixRows() { if (currentPrixSession == null) return; prixRows.clear(); if (jdb.getSelectedClub() == null || !ajustableCours.getValue()) { addPrixRow(null); } else { for (CoursSummary cs : rawCoursData) { if (!coursApplicableToCurrentSession(cs)) continue; addPrixRow(cs); } } refreshPrix(); } private void refreshPrix() { prix.setRowData(prixRows); prix.redraw(); } private void clearPrix() { prixRows.clear(); refreshPrix(); } class SessionAnchorListItem extends AnchorListItem implements Comparable<SessionAnchorListItem> { int effective_seqno; boolean isPair; public SessionAnchorListItem(String label, int effective_seqno, boolean isPair) { super(label); this.effective_seqno = effective_seqno; this.isPair = isPair; } @Override public int compareTo(SessionAnchorListItem other) { return other.effective_seqno * 2 + (other.isPair ? 1 : 0) - (effective_seqno * 2 + (isPair ? 1 : 0)); } } class SessionItemHandler implements ClickHandler { final SessionSummary session; final boolean isPair; SessionItemHandler(SessionSummary session, boolean isPair) { this.session = session; this.isPair = isPair; } @Override public void onClick(ClickEvent e) { selectSession(session, isPair); } } private AnchorListItem addSali(SessionSummary s, Set<SessionAnchorListItem> sss, int pos) { SessionAnchorListItem sali = new SessionAnchorListItem(s.getAbbrev(), pos, false); sali.addClickHandler(new SessionItemHandler(s, false)); // only display paired sessions when in affiliation mode if (jdb.getSelectedClub() != null) sss.add(sali); if (s.isPrimary()) { StringBuilder a = new StringBuilder(s.getAbbrev()); a.append(" "); a.append(JudoDB.getLinkedSession(s, rawSessionData).getAbbrev()); SessionAnchorListItem sali2 = new SessionAnchorListItem(a.toString(), pos, true); sali2.addClickHandler(new SessionItemHandler(s, true)); sss.add(sali2); return sali2; } return sali; } void populateSessionsForPrix() { prixSessions.clear(); SessionSummary currentSession = null; Date today = new Date(); TreeSet<SessionAnchorListItem> sss = new TreeSet<>(); SessionSummary latest = null; for (SessionSummary s : rawSessionData) { if (latest == null || (s.isPrimary() && Integer.parseInt(s.getSeqno()) > Integer.parseInt(latest.getSeqno()))) latest = s; try { Date inscrBegin = Constants.DB_DATE_FORMAT.parse(s.getFirstSignupDate()); Date inscrEnd = Constants.DB_DATE_FORMAT.parse(s.getLastSignupDate()); if (today.after(inscrBegin) && today.before(inscrEnd)) { currentSession = s; continue; } } catch (IllegalArgumentException e) {} addSali(s, sss, Integer.parseInt(s.getSeqno())); } AnchorListItem cs = null; if (currentSession != null) { cs = addSali(currentSession, sss, Integer.parseInt(currentSession.getSeqno())); prixSessions.add(cs); } for (AnchorListItem s : sss) { if (s != cs) { prixSessions.add(s); } } if (currentSession != null) selectSession(currentSession, true); else { // isPair certainly true when in affiliation mode (club == TOUS) // otherwise we might not have a pairee... selectSession(latest, jdb.getSelectedClub() == null); } } private void selectSession(SessionSummary session, boolean isPair) { if (session != null) { StringBuilder a = new StringBuilder(session.getAbbrev()); if (isPair) { a.append(" "); a.append(JudoDB.getLinkedSession(session, rawSessionData).getAbbrev()); } String as = a.toString(); prixSessionsButton.setText(as); currentPrixSeqnoString = as; } else { currentPrixSeqnoString = session.getAbbrev(); } currentPrixSeqnoString = JudoDB.sessionSeqnosFromAbbrevs(currentPrixSeqnoString, rawSessionData); currentPrixSession = session; this.isPairPrixSession = isPair; populatePrixRows(); } private boolean coursApplicableToCurrentSession(CoursSummary cs) { if (cs.getSession().equals(currentPrixSession.getSeqno()) || cs.getSession().equals(currentPrixSession.getLinkedSeqno())) return true; return false; } private static final ProvidesKey<EscompteSummary> ESCOMPTE_KEY_PROVIDER = new ProvidesKey<EscompteSummary>() { @Override public Object getKey(EscompteSummary item) { return item.getId(); } }; private final ColumnFields NOM_COLUMN = new ColumnFields("nom", "Nom", 2, Unit.EM), AMOUNT_PERCENT_COLUMN = new ColumnFields("amount_percent", "%", 1, Unit.EM), AMOUNT_ABSOLUTE_COLUMN = new ColumnFields("amount_absolute", "$", 1, Unit.EM); private List<ColumnFields> perEscompteColumns = Collections.unmodifiableList(Arrays.asList(NOM_COLUMN, AMOUNT_PERCENT_COLUMN, AMOUNT_ABSOLUTE_COLUMN)); void initializeEscompteTable() { escomptes = new CellTable<>(ESCOMPTE_KEY_PROVIDER); escomptes.setWidth("60em", true); initializeEscompteColumns(); } private Column<EscompteSummary, String> addEscompteColumn(final CellTable t, final ColumnFields c, final boolean editable) { final Cell<String> cell = editable ? new EditTextCell() : new TextCell(); Column<EscompteSummary, String> newColumn = new Column<EscompteSummary, String>(cell) { public String getValue(EscompteSummary object) { return object.get(c.key); } }; escomptes.addColumn(newColumn, c.name); newColumn.setFieldUpdater(new FieldUpdater<EscompteSummary, String>() { @Override public void update(int index, EscompteSummary object, String value) { refreshEscomptes = true; if (object.get(NOM_COLUMN.key).equals(ADD_ESCOMPTE_VALUE)) { // NB: do the set before the update because we read from object String nom; if (c.key.equals(AMOUNT_PERCENT_COLUMN.key) || c.key.equals(AMOUNT_ABSOLUTE_COLUMN.key)) { nom = "Escompte "+object.getId(); object.set(c.key, value); } else { nom = value; object.set(c.key, value); } pushEdit("-1,Z," + object.getId() + "," + nom + "," + object.get(AMOUNT_PERCENT_COLUMN.key) + "," + object.get(AMOUNT_ABSOLUTE_COLUMN.key) + "," + jdb.getSelectedClubID() + ";"); addAddEscompteEscompte(); } else { StringBuffer edits = new StringBuffer(); String otherValue = ""; if (value.equals("-1")) otherValue = "-1"; if (c.key.equals(AMOUNT_PERCENT_COLUMN.key)) { String k = AMOUNT_ABSOLUTE_COLUMN.key; edits.append("-1,z" + k + "," + object.getId() + "," + otherValue + "," + jdb.getSelectedClubID() + ";"); object.set(k, otherValue); } else if (c.key.equals(AMOUNT_ABSOLUTE_COLUMN.key)) { String k = AMOUNT_PERCENT_COLUMN.key; edits.append("-1,z" + k + "," + object.getId() + "," + otherValue + "," + jdb.getSelectedClubID() + ";"); object.set(k, otherValue); } edits.append("-1,z" + c.key + "," + object.getId() + "," + value + "," + jdb.getSelectedClubID() + ";"); pushEdit(edits.toString()); object.set(c.key, value); } t.redraw(); } }); escomptes.setColumnWidth(newColumn, c.width, c.widthUnits); return newColumn; } void initializeEscompteColumns() { while (escomptes.getColumnCount() > 0) escomptes.removeColumn(0); addEscompteColumn(escomptes, NOM_COLUMN, true); addEscompteColumn(escomptes, AMOUNT_PERCENT_COLUMN, true); addEscompteColumn(escomptes, AMOUNT_ABSOLUTE_COLUMN, true); } final private static String ADD_ESCOMPTE_VALUE = "[ajouter escompte]"; void addAddEscompteEscompte() { int maxId = 0; for (EscompteSummary c : escompteData) { if (Integer.parseInt(c.getId()) > maxId) maxId = Integer.parseInt(c.getId()); } EscompteSummary addNewEscompte = JsonUtils.<EscompteSummary>safeEval ("{\"id\":\""+(maxId+1)+"\"}"); addNewEscompte.setClubId(jdb.getSelectedClubID()); addNewEscompte.setNom(ADD_ESCOMPTE_VALUE); addNewEscompte.setAmountPercent(""); addNewEscompte.setAmountAbsolute(""); escompteData.add(addNewEscompte); } private void populateEscomptes(List<EscompteSummary> escompteArray) { initializeEscompteColumns(); escompteData.clear(); for (EscompteSummary es : escompteArray) { escompteData.add(es); } if (jdb.isClubSelected()) addAddEscompteEscompte(); escomptes.setRowData(escompteData); escomptes.redraw(); } private void clearEscomptes() { escompteData.clear(); escomptes.setRowData(escompteData); escomptes.redraw(); } private static final ProvidesKey<ProduitSummary> PRODUIT_KEY_PROVIDER = new ProvidesKey<ProduitSummary>() { @Override public Object getKey(ProduitSummary item) { return item.getId(); } }; private final ColumnFields NOM_PRODUIT_COLUMN = new ColumnFields("nom", "Nom", 2, Unit.EM), MONTANT_COLUMN = new ColumnFields("montant", "Montant", 1, Unit.EM); private List<ColumnFields> perProduitColumns = Collections.unmodifiableList(Arrays.asList(NOM_PRODUIT_COLUMN, MONTANT_COLUMN)); void initializeProduitTable() { produits = new CellTable<>(PRODUIT_KEY_PROVIDER); produits.setWidth("60em", true); initializeProduitColumns(); } private Column<ProduitSummary, String> addProduitColumn(final CellTable t, final ColumnFields c, final boolean editable) { final Cell<String> cell = editable ? new EditTextCell() : new TextCell(); Column<ProduitSummary, String> newColumn = new Column<ProduitSummary, String>(cell) { public String getValue(ProduitSummary object) { return object.get(c.key); } }; produits.addColumn(newColumn, c.name); newColumn.setFieldUpdater(new FieldUpdater<ProduitSummary, String>() { @Override public void update(int index, ProduitSummary object, String value) { refreshProduits = true; if (object.get(NOM_PRODUIT_COLUMN.key).equals(ADD_PRODUIT_VALUE)) { // NB: do the set before the update because we read from object String nom; if (c.key.equals(MONTANT_COLUMN.key)) { nom = "Produit "+object.getId(); object.set(c.key, value); } else { nom = value; object.set(c.key, value); } pushEdit("-1,J," + object.getId() + "," + nom + "," + object.get(MONTANT_COLUMN.key) + "," + jdb.getSelectedClubID() + ";"); addAddProduitProduit(); } else { StringBuffer edits = new StringBuffer(); if (c.key.equals(MONTANT_COLUMN.key)) { String k = MONTANT_COLUMN.key; edits.append("-1,j" + k + "," + object.getId() + "," + "" + "," + jdb.getSelectedClubID() + ";"); object.set(k, ""); } edits.append("-1,j" + c.key + "," + object.getId() + "," + value + "," + jdb.getSelectedClubID() + ";"); pushEdit(edits.toString()); object.set(c.key, value); } t.redraw(); } }); produits.setColumnWidth(newColumn, c.width, c.widthUnits); return newColumn; } void initializeProduitColumns() { while (produits.getColumnCount() > 0) produits.removeColumn(0); addProduitColumn(produits, NOM_PRODUIT_COLUMN, true); addProduitColumn(produits, MONTANT_COLUMN, true); } final private static String ADD_PRODUIT_VALUE = "[ajouter produit]"; void addAddProduitProduit() { int maxId = 0; for (ProduitSummary c : produitData) { if (Integer.parseInt(c.getId()) > maxId) maxId = Integer.parseInt(c.getId()); } ProduitSummary addNewProduit = JsonUtils.<ProduitSummary>safeEval ("{\"id\":\""+(maxId+1)+"\"}"); addNewProduit.setClubId(jdb.getSelectedClubID()); addNewProduit.setNom(ADD_PRODUIT_VALUE); addNewProduit.setMontant(""); produitData.add(addNewProduit); } private void populateProduits(List<ProduitSummary> produitArray) { initializeProduitColumns(); produitData.clear(); for (ProduitSummary es : produitArray) { produitData.add(es); } if (jdb.isClubSelected()) addAddProduitProduit(); produits.setRowData(produitData); produits.redraw(); } private void clearProduits() { produitData.clear(); produits.setRowData(produitData); produits.redraw(); } private boolean gotSessions = false; public void retrieveSessions(String club_id) { String url = JudoDB.PULL_SESSIONS_URL; url += "?club_id=" + club_id; RequestCallback rc = jdb.createRequestCallback(new JudoDB.Function() { public void eval(String s) { gotSessions = true; populateSessions(JsonUtils.<JsArray<SessionSummary>>safeEval(s)); jdb.clearStatus(); } }); jdb.retrieve(url, rc); } public void retrievePrix(final String club_id) { if (!gotSessions) { new Timer() { public void run() { retrievePrix(club_id); } }.schedule(100); return; } prixRows.clear(); rawPrixData.clear(); ClubSummary cs = jdb.getClubSummaryByID(jdb.getSelectedClubID()); String url = JudoDB.PULL_CLUB_PRIX_URL + "?club_id=" + club_id; RequestCallback rc = jdb.createRequestCallback(new JudoDB.Function() { public void eval(String s) { List<Prix> lp = new ArrayList<Prix>(); JsArray<Prix> cp = JsonUtils.<JsArray<Prix>>safeEval(s); for (int i = 0; i < cp.length(); i++) lp.add(cp.get(i)); populatePrix(lp); } }); jdb.retrieve(url, rc); } private boolean gotCours = false; // requires sessions public void retrieveCours(final String numero_club) { rawCoursData.clear(); coursData.clear(); if (numero_club.equals("")) return; if (!gotSessions) { new Timer() { public void run() { retrieveCours(numero_club); } }.schedule(100); return; } String url = JudoDB.PULL_CLUB_COURS_URL; url += "?numero_club="+numero_club; RequestCallback rc = jdb.createRequestCallback(new JudoDB.Function() { public void eval(String s) { gotCours = true; List<CoursSummary> lcs = new ArrayList<>(); JsArray<CoursSummary> jcs = JsonUtils.<JsArray<CoursSummary>>safeEval(s); for (int i = 0; i < jcs.length(); i++) lcs.add(jcs.get(i)); populateCours(lcs); jdb.clearStatus(); } }); jdb.retrieve(url, rc); } private boolean gotEscomptes = false; public void retrieveEscomptes(String club_id) { if (club_id.equals("")) return; String url = JudoDB.PULL_ESCOMPTE_URL; url += "?club_id="+club_id; RequestCallback rc = jdb.createRequestCallback(new JudoDB.Function() { public void eval(String s) { gotEscomptes = true; List<EscompteSummary> les = new ArrayList<>(); JsArray<EscompteSummary> jes = JsonUtils.<JsArray<EscompteSummary>>safeEval(s); for (int i = 0; i < jes.length(); i++) les.add(jes.get(i)); populateEscomptes(les); jdb.clearStatus(); } }); jdb.retrieve(url, rc); } private boolean gotProduits = false; public void retrieveProduits(String club_id) { if (club_id.equals("")) return; String url = JudoDB.PULL_PRODUIT_URL; url += "?club_id="+club_id; RequestCallback rc = jdb.createRequestCallback(new JudoDB.Function() { public void eval(String s) { gotProduits = true; List<ProduitSummary> les = new ArrayList<>(); JsArray<ProduitSummary> jes = JsonUtils.<JsArray<ProduitSummary>>safeEval(s); for (int i = 0; i < jes.length(); i++) les.add(jes.get(i)); populateProduits(les); jdb.clearStatus(); } }); jdb.retrieve(url, rc); } private boolean refreshClub = false; private boolean refreshSessions = false; private boolean refreshCours = false; private boolean refreshPrix = false; private boolean refreshEscomptes = false; private boolean refreshProduits = false; public void pushChanges(final String guid) { String url = JudoDB.CONFIRM_PUSH_URL + "?guid=" + guid; RequestCallback rc = jdb.createRequestCallback(new JudoDB.Function() { public void eval(String s) { ConfirmResponseObject cro = JsonUtils.<ConfirmResponseObject>safeEval(s); String rs = cro.getResult(); if (rs.equals("NOT_YET")) { if (pushTries >= 3) { jdb.displayError("le serveur n'a pas accepté les données"); return; } new Timer() { public void run() { pushChanges(guid); } }.schedule(2000); pushTries++; } else { jdb.setStatus("Sauvegardé."); if (refreshClub) { refreshClub = false; jdb.retrieveClubList(true); } if (refreshSessions) { refreshSessions = false; retrieveSessions(jdb.getSelectedClub().getNumeroClub()); } if (refreshCours) { refreshCours = false; ClubSummary cs = jdb.getClubSummaryByID(jdb.getSelectedClubID()); if (cs != null) { retrieveCours(cs.getNumeroClub()); } } if (refreshPrix) { refreshPrix = false; ClubSummary cs = jdb.getClubSummaryByID(jdb.getSelectedClubID()); if (cs != null) { retrievePrix(cs.getId()); } else { retrievePrix("0"); } } if (refreshEscomptes) { refreshEscomptes = false; retrieveEscomptes(jdb.getSelectedClubID()); } if (refreshProduits) { refreshProduits = false; retrieveProduits(jdb.getSelectedClubID()); } } new Timer() { public void run() { jdb.clearStatus(); } }.schedule(2000); } }); jdb.retrieve(url, rc); } private void pushEdit(String dv) { guid = UUID.uuid(); guid_on_form.setValue(guid); current_session.setValue("A00"); dataToSave.setValue(dv.toString()); configEditForm.submit(); pushTries = 0; new Timer() { public void run() { pushChanges(guid); } }.schedule(500); } }
package com.alkber.strongpassword; import java.util.Random; * -- {[(~!@#$%^&*_+-/*.,|>=<?:)]}; * <p> * - There is only one occurrence of the same character. * <p> * - Upper case / lower case characters are followed by either a digit, other characters. * <p> * - At most one occurrence of a character from the given set. * <p> * - There are no consecutive occurrence of characters from the same set * <p> * <p> * <code> allowDuplicate = false </code> * <p> * - Minimum input password length is 6 * <p> * - Maximum input password length is 45. * <p> * <code> allowDuplicate = true </code> * <p> * - Minimum input password length is 6 * <p> * - Maximum input password length is 100. * <p> * Beyond 45 it is not possible ensure all the above password constraints are met. Usually, the * first constraint "occurrence of same character once" fails and take too long to complete the * generation * <p> * Usage * <p> * Generate password of length 6 and no duplicate tokens * <p> * StrongPassword.generate(6, false); * <p> * Generate password of lenthg 12 and allow duplicate tokens * <p> * StrongPassword.generate(6, true); * * @author Althaf K Backer <althafkbacker@gmail.com> * 15 APR 15 12:37 PM IST */ public class StrongPassword { private final static String ABC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private final static String abc = ABC.toLowerCase(); private final static String DIGITS = "0123456789"; private final static String OTHERS = "{[(~!@ private final static String SCOPE_abc_DIGITS_ABC = abc + DIGITS + ABC; private final static String SCOPE_ABC_OTHERS_abc = ABC + OTHERS + abc; private final static String SCOPE_DIGITS_OTHERS = DIGITS + OTHERS; private final static String SCOPE_FULL = ABC + abc + OTHERS + DIGITS; private final static Random rd = new java.util.Random(); private final static int MIN_PASSWORD_LEN = 6; private final static int MAX_PASSWORD_LEN_NO_DUP = 45; private final static int MAX_PASSWORD_LEN_DUP = 100; // SCOPE_CURRENT and SCOPE_CURRENT_LEN is altered by <code> setNextScope(...) </code> private String SCOPE_CURRENT = SCOPE_FULL; private int SCOPE_CURRENT_LEN = SCOPE_CURRENT.length(); public static String generate(int passwordLength, boolean allowDuplicateToken) throws IllegalArgumentException { // we are creating this temporary object as <code> SCOPE_CURRENT </code> and // <code> SCOPE_CURRENT_LEN </code> should be individual state of an object. // we still have the comfort to invoke this method, // </code> StrongPassword.generate(...) </code> StrongPassword currentSession = new StrongPassword(); if(passwordLength < MIN_PASSWORD_LEN) { throw new IllegalArgumentException("minimum password length is 6"); } if(!allowDuplicateToken && (passwordLength > MAX_PASSWORD_LEN_NO_DUP)) { throw new IllegalArgumentException("max password length when allowDuplicateToken = " + "false is " + MAX_PASSWORD_LEN_NO_DUP); } if(allowDuplicateToken && (passwordLength > MAX_PASSWORD_LEN_DUP)) { throw new IllegalArgumentException("max password length when allowDuplicateToken = " + "true is " + MAX_PASSWORD_LEN_DUP); } // initial scope of password characters currentSession.SCOPE_CURRENT = SCOPE_FULL; currentSession.SCOPE_CURRENT_LEN = currentSession.SCOPE_CURRENT.length(); StringBuilder password = new StringBuilder(""); boolean qualityCheckFailed = true; do { // reset the password as QA failed password = new StringBuilder(""); for(int i = 0;i < passwordLength;i++) { char token; if(allowDuplicateToken) { token = currentSession.SCOPE_CURRENT.charAt(rd.nextInt(currentSession .SCOPE_CURRENT_LEN)); } else { token = currentSession.getNextToken(password.toString()); } password = password.append(token); currentSession.setNextScope(token); } qualityCheckFailed = !currentSession.checkPasswordQuality(password.toString()); } while(qualityCheckFailed); return password.toString(); } /** * Responsible for ensuring that, a particular character from <code> SCOPE_CURRENT * </code> doesn't reappear twice in the partial password. * * @param partialPassword partial password till the time of call * @return next non repeated token */ private char getNextToken(String partialPassword) { char token = SCOPE_CURRENT.charAt(rd.nextInt(SCOPE_CURRENT_LEN)); //check to see if current token already exist in previous partial password, if so //find another one till we get a unique one while(-1 != partialPassword.indexOf(token)) { token = SCOPE_CURRENT.charAt(rd.nextInt(SCOPE_CURRENT_LEN)); } return token; } /** * Set the next scope of character set based on current token, this ensure that next token * generated by <code> getNextToken() </code> will not in the same character set as * the previous token.This will help prevent, occurrence of a dictionary word by chance. * All in all, this will ensure that all the scope of characters are covered. * <p> * Changes following class members * -SCOPE_CURRENT * -SCOPE_CURRENT_LEN * * @param token current token is used to understand the current scope and choose a new scope */ private void setNextScope(char token) { if(-1 != ABC.indexOf(token) || -1 != abc.indexOf(token)) { SCOPE_CURRENT = SCOPE_DIGITS_OTHERS; } else if(-1 != DIGITS.indexOf(token)) { SCOPE_CURRENT = SCOPE_ABC_OTHERS_abc; } else if(-1 != OTHERS.indexOf(token)) { SCOPE_CURRENT = SCOPE_abc_DIGITS_ABC; } SCOPE_CURRENT_LEN = SCOPE_CURRENT.length(); } /** * Quality check ensure that, we have character set from all the SCOPE covered. * * @param password newly generated password * @return <code> true </code> if password cover all the scope * <code> false </code> if password doesn't cover all the scope */ private boolean checkPasswordQuality(String password) { return password.matches(".*[0-9].*") && password.matches(".*[A-Z].*") && password.matches(".*[a-z].*") && password.matches(".*[{\\[(~!@ } }
package com.golaszewski.lava.tokenizer; import java.util.HashMap; import java.util.Map; import java.util.Queue; /** * @author Ennis Golaszewski */ public class Tokenizer { private int row; private int column; private Processor[][] stateTable; /** * Classifications for different types of characters. These will allow the * tokenizing state machine to make decisions on which state/action to pursue * based on the current character. */ private enum Classification { ALPHABETIC, DIGIT, LEFT_PARENTHESES, RIGHT_PARENTHESES, SPACE, NEW_LINE, OTHER; /** * Classifies the input character, matching it to one of the enumerations. * * @param c, the character to classify. * @return the most appropriate enumeration in the Classification enum. */ public static Classification classify(char c) { Classification result; c = Character.toLowerCase(c); if ('a' < c && c < 'z') { result = Classification.ALPHABETIC; } else if ('0' < c && c < '9') { result = Classification.DIGIT; } else if (c == '(') { result = Classification.LEFT_PARENTHESES; } else if (c == ')') { result = Classification.RIGHT_PARENTHESES; } else if (c == '\n') { result = Classification.NEW_LINE; } else if (c == ' ') { result = Classification.SPACE; } else { result = Classification.OTHER; } return result; } } /** * Provides a base class for the processor objects - these are wrappers for a * processing function. The function in question resides in a state machine * table. */ private abstract class Processor { public abstract void process(char c, TokenizerContext context); public void updateContextPosition(TokenizerContext context) { if (context.getState() == TokenizerState.READY) { context.setRow(row); context.setColumn(column); } } } /** * Used to process/build identifiers. */ private class IdentifierProcessor extends Processor { @Override public void process(char c, TokenizerContext context) { updateContextPosition(context); context.setState(TokenizerState.IDENTIFIER); context.pushCharacter(c); column += 1; } } /** * Used to process/build numbers. */ private class NumberProcessor extends Processor { @Override public void process(char c, TokenizerContext context) { updateContextPosition(context); context.setState(TokenizerState.NUMBER); context.pushCharacter(c); column += 1; } } /** * Used to process left parenthesis. */ private class LeftParenthesisProcessor extends Processor { @Override public void process(char c, TokenizerContext context) { updateContextPosition(context); context.setState(TokenizerState.LEFT_PARENTHESIS); context.pushCharacter(c); context.popToken(); column += 1; } } /** * Used to process right parenthesis. */ private class RightParenthesisProcessor extends Processor { @Override public void process(char c, TokenizerContext context) { if (context.getState() != TokenizerState.READY) { context.popToken(); } updateContextPosition(context); context.setState(TokenizerState.RIGHT_PARENTHESIS); context.pushCharacter(c); context.popToken(); column += 1; } } /** * Used to process a blank space. */ private class SpaceProcessor extends Processor { @Override public void process(char c, TokenizerContext context) { if (context.getState() != TokenizerState.READY) { context.popToken(); } column += 1; } } /** * Used to process a new line. */ private class NewLineProcessor extends Processor { @Override public void process(char c, TokenizerContext context) { if (context.getState() != TokenizerState.READY) { context.popToken(); } column = 0; row += 1; } } private static Map<Classification, Integer> classificationIndexes = new HashMap<Classification, Integer>(); private static Map<TokenizerState, Integer> stateIndexes = new HashMap<TokenizerState, Integer>(); /* * In order to quickly determine the next state, we construct a 2D array of * state transitions. To ensure easy access by indexes, the row/column * enumerations need to be mapped to integer indecies. */ static { classificationIndexes.put(Classification.ALPHABETIC, 0); classificationIndexes.put(Classification.DIGIT, 1); classificationIndexes.put(Classification.LEFT_PARENTHESES, 2); classificationIndexes.put(Classification.RIGHT_PARENTHESES, 3); classificationIndexes.put(Classification.SPACE, 4); classificationIndexes.put(Classification.NEW_LINE, 5); classificationIndexes.put(Classification.OTHER, 6); stateIndexes.put(TokenizerState.READY, 0); stateIndexes.put(TokenizerState.IDENTIFIER, 1); stateIndexes.put(TokenizerState.NUMBER, 2); } /** * Initializes the state table. This depends on the indexes being statically * configured. */ private void initializeStateTable() { Processor identifier = new IdentifierProcessor(); Processor number = new NumberProcessor(); Processor lParen = new LeftParenthesisProcessor(); Processor rParen = new RightParenthesisProcessor(); Processor space = new SpaceProcessor(); Processor newLine = new NewLineProcessor(); // @formatter:off stateTable = new Processor[][] { /* READY | IDENTIFIER | NUMBER */ { identifier, identifier, null }, /* ALPHABETIC */ { number , identifier, number }, /* DIGIT */ { lParen , null , null }, /* L_PAREN */ { rParen , rParen , rParen }, /* R_PAREN */ { space , space , space }, /* SPACE */ { newLine , newLine , newLine }, /* NEW_LINE */ { identifier, identifier, null } /* OTHER */ }; // @formatter:on } /** * Tokenizes the input. * * @param input, a string. This should be an s-expression. * @return list of tokens in the input. */ public Queue<Token> tokenize(String input) { TokenizerContext context = new TokenizerContext(); initializeStateTable(); for (char c : input.toCharArray()) { Classification classification = Classification.classify(c); TokenizerState state = context.getState(); int tableColumn = stateIndexes.get(state); int tableRow = classificationIndexes.get(classification); Processor processor = stateTable[tableRow][tableColumn]; processor.process(c, context); } // To handle a case of a single symbol not contained by a list, we need to // pop anything left after parsing. context.popToken(); return context.getQueue(); } }
package com.jme.intersection; import java.util.ArrayList; import com.jme.math.Ray; import com.jme.scene.Geometry; import com.jme.scene.TriMesh; /** * TrianglePickResults creates a PickResults object that calculates picking to * the triangle accuracy. PickData objects are added to the pick list as they * happen, these data objects refer to the two meshes, as well as their triangle * lists. While TrianglePickResults defines a processPick method, it is empty * and should be further defined by the user if so desired. * * NOTE: Only TriMesh objects may obtain triangle accuracy, all others will * result in Bounding accuracy. * * @author Mark Powell * @version $Id: TrianglePickResults.java,v 1.2 2004/10/14 01:23:12 mojomonkey * Exp $ */ public class TrianglePickResults extends PickResults { /** * Convenience wrapper for * addPick(Ray, Geometry, int) * collidability (first bit of the collidable bit mask). * * @see #addPick(Ray, Geometry, int) */ public void addPick(Ray ray, Geometry g) { addPick(ray,g,1); } /** * <code>addPick</code> adds a Geometry object to the pick list. If the * Geometry object is not a TriMesh, the process stops here. However, if the * Geometry is a TriMesh, further processing occurs to obtain the triangle * lists that the ray passes through. * * @param ray * the ray that is doing the picking. * @param g * the Geometry to add to the pick list. * @param requiredOnBits TrianglePick will only be considered if 'this' * has these bits of its collision masks set. * * @see com.jme.intersection.PickResults#addPick(Ray, Geometry) */ public void addPick(Ray ray, Geometry g, int requiredOnBits) { //find the triangle that is being hit. //add this node and the triangle to the CollisionResults // list. if (!(g instanceof TriMesh)) { PickData data = new PickData(ray, g, willCheckDistance()); addPickData(data); } else { ArrayList<Integer> a = new ArrayList<Integer>(); ((TriMesh) g).findTrianglePick(ray, a, requiredOnBits); PickData data = new TrianglePickData(ray, ((TriMesh) g), a, willCheckDistance()); addPickData(data); } } /** * <code>processPick</code> will handle processing of the pick list. This * is very application specific and therefore left as an empty method. * Applications wanting an automated picking system should extend * TrianglePickResults and override this method. * * @see com.jme.intersection.PickResults#processPick() */ public void processPick() { } }
package com.jwetherell.algorithms.graph; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.TreeMap; import com.jwetherell.algorithms.data_structures.Graph; /** * Dijkstra's shortest path. Only works on non-negative path weights. Returns a * tuple of total cost of shortest path and the path. * * Worst case: O(|E| + |V| log |V|) * * @author Justin Wetherell <phishman3579@gmail.com> */ public class Dijkstra { private static Map<Graph.Vertex<Integer>, Graph.CostVertexPair<Integer>> costs = null; private static Map<Graph.Vertex<Integer>, Set<Graph.Edge<Integer>>> paths = null; private static Queue<Graph.CostVertexPair<Integer>> unvisited = null; private Dijkstra() { } public static Map<Graph.Vertex<Integer>, Graph.CostPathPair<Integer>> getShortestPaths(Graph<Integer> g, Graph.Vertex<Integer> start) { getShortestPath(g, start, null); Map<Graph.Vertex<Integer>, Graph.CostPathPair<Integer>> map = new HashMap<Graph.Vertex<Integer>, Graph.CostPathPair<Integer>>(); for (Graph.CostVertexPair<Integer> pair : costs.values()) { int cost = pair.getCost(); Graph.Vertex<Integer> vertex = pair.getVertex(); Set<Graph.Edge<Integer>> path = paths.get(vertex); map.put(vertex, new Graph.CostPathPair<Integer>(cost, path)); } return map; } public static Graph.CostPathPair<Integer> getShortestPath(Graph<Integer> g, Graph.Vertex<Integer> start, Graph.Vertex<Integer> end) { if (g == null) throw (new NullPointerException("Graph must be non-NULL.")); // Reset variables costs = null; paths = null; unvisited = null; // Dijkstra's algorithm only works on positive cost graphs boolean hasNegativeEdge = checkForNegativeEdges(g.getVerticies()); if (hasNegativeEdge) throw (new IllegalArgumentException("Negative cost Edges are not allowed.")); paths = new TreeMap<Graph.Vertex<Integer>, Set<Graph.Edge<Integer>>>(); for (Graph.Vertex<Integer> v : g.getVerticies()) paths.put(v, new LinkedHashSet<Graph.Edge<Integer>>()); costs = new TreeMap<Graph.Vertex<Integer>, Graph.CostVertexPair<Integer>>(); for (Graph.Vertex<Integer> v : g.getVerticies()) { if (v.equals(start)) costs.put(v, new Graph.CostVertexPair<Integer>(0, v)); else costs.put(v, new Graph.CostVertexPair<Integer>(Integer.MAX_VALUE, v)); } unvisited = new PriorityQueue<Graph.CostVertexPair<Integer>>(); unvisited.addAll(costs.values()); // Shallow copy which is O(n log n) Graph.Vertex<Integer> vertex = start; while (true) { // Compute costs from current vertex to all reachable vertices which // haven't been visited for (Graph.Edge<Integer> e : vertex.getEdges()) { Graph.CostVertexPair<Integer> pair = costs.get(e.getToVertex()); // O(log n) Graph.CostVertexPair<Integer> lowestCostToThisVertex = costs.get(vertex); // O(log n) int cost = lowestCostToThisVertex.getCost() + e.getCost(); if (pair.getCost() == Integer.MAX_VALUE) { // Haven't seen this vertex yet pair.setCost(cost); // Need to remove the pair and re-insert, so the priority queue keeps it's invariants unvisited.remove(pair); unvisited.add(pair); // O(log n) // Update the paths Set<Graph.Edge<Integer>> set = paths.get(e.getToVertex()); // O(log n) set.addAll(paths.get(e.getFromVertex())); // O(log n) set.add(e); } else if (cost < pair.getCost()) { // Found a shorter path to a reachable vertex pair.setCost(cost); // Need to remove the pair and re-insert, so the priority queue keeps it's invariants unvisited.remove(pair); unvisited.add(pair); // O(log n) // Update the paths Set<Graph.Edge<Integer>> set = paths.get(e.getToVertex()); // O(log n) set.clear(); set.addAll(paths.get(e.getFromVertex())); // O(log n) set.add(e); } } // Termination conditions if (end != null && vertex.equals(end)) { // If we are looking for shortest path, we found it. break; } else if (unvisited.size() > 0) { // If there are other vertices to visit (which haven't been visited yet) Graph.CostVertexPair<Integer> pair = unvisited.remove(); // O(log n) vertex = pair.getVertex(); if (pair.getCost() == Integer.MAX_VALUE) { // If the only edge left to explore has MAX_VALUE then it // cannot be reached from the starting vertex break; } } else { // No more edges to explore, we are done. break; } } if (end != null) { Graph.CostVertexPair<Integer> pair = costs.get(end); Set<Graph.Edge<Integer>> set = paths.get(end); return (new Graph.CostPathPair<Integer>(pair.getCost(), set)); } return null; } private static boolean checkForNegativeEdges(List<Graph.Vertex<Integer>> vertitices) { for (Graph.Vertex<Integer> v : vertitices) { for (Graph.Edge<Integer> e : v.getEdges()) { if (e.getCost() < 0) return true; } } return false; } }
package com.maddyhome.idea.vim.group; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.event.*; import com.intellij.openapi.editor.ex.DocumentEx; import com.intellij.openapi.editor.ex.util.EditorUtil; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManagerEvent; import com.intellij.openapi.fileEditor.FileEditorManagerListener; import com.intellij.openapi.fileEditor.TextEditor; import com.intellij.openapi.fileEditor.impl.EditorTabbedContainer; import com.intellij.openapi.fileEditor.impl.EditorWindow; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.VirtualFileSystem; import com.maddyhome.idea.vim.EventFacade; import com.maddyhome.idea.vim.KeyHandler; import com.maddyhome.idea.vim.VimPlugin; import com.maddyhome.idea.vim.action.motion.MotionEditorAction; import com.maddyhome.idea.vim.action.motion.TextObjectAction; import com.maddyhome.idea.vim.command.*; import com.maddyhome.idea.vim.common.Jump; import com.maddyhome.idea.vim.common.Mark; import com.maddyhome.idea.vim.common.TextRange; import com.maddyhome.idea.vim.ex.ExOutputModel; import com.maddyhome.idea.vim.handler.ExecuteMethodNotOverriddenException; import com.maddyhome.idea.vim.helper.CaretData; import com.maddyhome.idea.vim.helper.EditorData; import com.maddyhome.idea.vim.helper.EditorHelper; import com.maddyhome.idea.vim.helper.SearchHelper; import com.maddyhome.idea.vim.option.BoundStringOption; import com.maddyhome.idea.vim.option.NumberOption; import com.maddyhome.idea.vim.option.Options; import com.maddyhome.idea.vim.ui.ExEntryPanel; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.event.MouseEvent; import java.io.File; /** * This handles all motion related commands and marks */ public class MotionGroup { public static final int LAST_F = 1; public static final int LAST_f = 2; public static final int LAST_T = 3; public static final int LAST_t = 4; public static final int LAST_COLUMN = 9999; /** * Create the group */ public MotionGroup() { EventFacade.getInstance().addEditorFactoryListener(new EditorFactoryAdapter() { public void editorCreated(@NotNull EditorFactoryEvent event) { final Editor editor = event.getEditor(); // This ridiculous code ensures that a lot of events are processed BEFORE we finally start listening // to visible area changes. The primary reason for this change is to fix the cursor position bug // using the gd and gD commands (Goto Declaration). This bug has been around since Idea 6.0.4? // Prior to this change the visible area code was moving the cursor around during file load and messing // with the cursor position of the Goto Declaration processing. ApplicationManager.getApplication().invokeLater(() -> ApplicationManager.getApplication().invokeLater( () -> ApplicationManager.getApplication().invokeLater(() -> { addEditorListener(editor); EditorData.setMotionGroup(editor, true); }))); } public void editorReleased(@NotNull EditorFactoryEvent event) { Editor editor = event.getEditor(); if (EditorData.getMotionGroup(editor)) { removeEditorListener(editor); EditorData.setMotionGroup(editor, false); } } }, ApplicationManager.getApplication()); } public void turnOn() { Editor[] editors = EditorFactory.getInstance().getAllEditors(); for (Editor editor : editors) { if (!EditorData.getMotionGroup(editor)) { addEditorListener(editor); EditorData.setMotionGroup(editor, true); } } } public void turnOff() { Editor[] editors = EditorFactory.getInstance().getAllEditors(); for (Editor editor : editors) { if (EditorData.getMotionGroup(editor)) { removeEditorListener(editor); EditorData.setMotionGroup(editor, false); } } } private void addEditorListener(@NotNull Editor editor) { final EventFacade eventFacade = EventFacade.getInstance(); eventFacade.addEditorMouseListener(editor, mouseHandler); eventFacade.addEditorMouseMotionListener(editor, mouseHandler); eventFacade.addEditorSelectionListener(editor, selectionHandler); } private void removeEditorListener(@NotNull Editor editor) { final EventFacade eventFacade = EventFacade.getInstance(); eventFacade.removeEditorMouseListener(editor, mouseHandler); eventFacade.removeEditorMouseMotionListener(editor, mouseHandler); eventFacade.removeEditorSelectionListener(editor, selectionHandler); } /** * Process mouse clicks by setting/resetting visual mode. There are some strange scenarios to handle. * * @param editor The editor * @param event The mouse event */ private void processMouseClick(@NotNull Editor editor, @NotNull MouseEvent event) { if (ExEntryPanel.getInstance().isActive()) { ExEntryPanel.getInstance().deactivate(false); } ExOutputModel.getInstance(editor).clear(); CommandState.SubMode visualMode = CommandState.SubMode.NONE; switch (event.getClickCount()) { case 2: visualMode = CommandState.SubMode.VISUAL_CHARACTER; break; case 3: visualMode = CommandState.SubMode.VISUAL_LINE; // Pop state of being in Visual Char mode if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) { CommandState.getInstance(editor).popState(); } int start = editor.getSelectionModel().getSelectionStart(); int end = editor.getSelectionModel().getSelectionEnd(); editor.getSelectionModel().setSelection(start, Math.max(start, end - 1)); break; } setVisualMode(editor, visualMode); final CaretModel caretModel = editor.getCaretModel(); if (CommandState.getInstance(editor).getSubMode() != CommandState.SubMode.NONE) { caretModel.removeSecondaryCarets(); } switch (CommandState.getInstance(editor).getSubMode()) { case NONE: VisualPosition vp = caretModel.getVisualPosition(); int col = EditorHelper.normalizeVisualColumn(editor, vp.line, vp.column, CommandState.getInstance(editor).getMode() == CommandState.Mode.INSERT || CommandState.getInstance(editor).getMode() == CommandState.Mode.REPLACE); if (col != vp.column) { caretModel.moveToVisualPosition(new VisualPosition(vp.line, col)); } MotionGroup.scrollCaretIntoView(editor); break; case VISUAL_CHARACTER: caretModel.moveToOffset(CaretData.getVisualEnd(caretModel.getPrimaryCaret())); break; case VISUAL_LINE: caretModel.moveToLogicalPosition(editor.xyToLogicalPosition(event.getPoint())); break; } CaretData.setVisualOffset(caretModel.getPrimaryCaret(), caretModel.getOffset()); CaretData.setLastColumn(editor, caretModel.getPrimaryCaret(), caretModel.getVisualPosition().column); } /** * Handles mouse drags by properly setting up visual mode based on the new selection. * * @param editor The editor the mouse drag occurred in. * @param update True if update, false if not. */ private void processLineSelection(@NotNull Editor editor, boolean update) { if (ExEntryPanel.getInstance().isActive()) { ExEntryPanel.getInstance().deactivate(false); } ExOutputModel.getInstance(editor).clear(); if (update) { if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) { for (@NotNull Caret caret : editor.getCaretModel().getAllCarets()) { updateSelection(editor, caret, caret.getOffset()); } } } else { if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) { CommandState.getInstance(editor).popState(); } int start = editor.getSelectionModel().getSelectionStart(); int end = editor.getSelectionModel().getSelectionEnd(); editor.getSelectionModel().setSelection(start, Math.max(start, end - 1)); setVisualMode(editor, CommandState.SubMode.VISUAL_LINE); VisualChange range = getVisualOperatorRange(editor, Command.FLAG_MOT_LINEWISE); if (range.getLines() > 1) { MotionGroup.moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), moveCaretVertical(editor, editor.getCaretModel().getPrimaryCaret(), -1)); } } } private void processMouseReleased(@NotNull Editor editor, @NotNull CommandState.SubMode mode, int startOff, int endOff) { if (ExEntryPanel.getInstance().isActive()) { ExEntryPanel.getInstance().deactivate(false); } ExOutputModel.getInstance(editor).clear(); if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) { CommandState.getInstance(editor).popState(); } int start = editor.getSelectionModel().getSelectionStart(); int end = editor.getSelectionModel().getSelectionEnd(); if (start == end) return; if (mode == CommandState.SubMode.VISUAL_LINE) { end endOff } if (end == startOff || end == endOff) { int t = start; start = end; end = t; if (mode == CommandState.SubMode.VISUAL_CHARACTER) { start } } MotionGroup.moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), start); toggleVisual(editor, 1, 0, mode); MotionGroup.moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), end); KeyHandler.getInstance().reset(editor); } @NotNull public TextRange getWordRange(@NotNull Editor editor, @NotNull Caret caret, int count, boolean isOuter, boolean isBig) { int dir = 1; boolean selection = false; if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) { if (CaretData.getVisualEnd(caret) < CaretData.getVisualStart(caret)) { dir = -1; } if (CaretData.getVisualStart(caret) != CaretData.getVisualEnd(caret)) { selection = true; } } return SearchHelper.findWordUnderCursor(editor, caret, count, dir, isOuter, isBig, selection); } @Nullable public TextRange getBlockQuoteRange(@NotNull Editor editor, @NotNull Caret caret, char quote, boolean isOuter) { return SearchHelper.findBlockQuoteInLineRange(editor, caret, quote, isOuter); } @Nullable public TextRange getBlockRange(@NotNull Editor editor, @NotNull Caret caret, int count, boolean isOuter, char type) { return SearchHelper.findBlockRange(editor, caret, type, count, isOuter); } @Nullable public TextRange getBlockTagRange(@NotNull Editor editor, @NotNull Caret caret, int count, boolean isOuter) { return SearchHelper.findBlockTagRange(editor, caret, count, isOuter); } @NotNull public TextRange getSentenceRange(@NotNull Editor editor, @NotNull Caret caret, int count, boolean isOuter) { return SearchHelper.findSentenceRange(editor, caret, count, isOuter); } @Nullable public TextRange getParagraphRange(@NotNull Editor editor, @NotNull Caret caret, int count, boolean isOuter) { return SearchHelper.findParagraphRange(editor, caret, count, isOuter); } /** * This helper method calculates the complete range a motion will move over taking into account whether * the motion is FLAG_MOT_LINEWISE or FLAG_MOT_CHARACTERWISE (FLAG_MOT_INCLUSIVE or FLAG_MOT_EXCLUSIVE). * * @param editor The editor the motion takes place in * @param caret The caret the motion takes place on * @param context The data context * @param count The count applied to the motion * @param rawCount The actual count entered by the user * @param argument Any argument needed by the motion * @param incNewline True if to include newline * @return The motion's range */ @Nullable public static TextRange getMotionRange(@NotNull Editor editor, @NotNull Caret caret, DataContext context, int count, int rawCount, @NotNull Argument argument, boolean incNewline) { final Command cmd = argument.getMotion(); if (cmd == null) { return null; } // Normalize the counts between the command and the motion argument int cnt = cmd.getCount() * count; int raw = rawCount == 0 && cmd.getRawCount() == 0 ? 0 : cnt; int start = 0; int end = 0; if (cmd.getAction() instanceof MotionEditorAction) { MotionEditorAction action = (MotionEditorAction) cmd.getAction(); // This is where we are now start = caret.getOffset(); // Execute the motion (without moving the cursor) and get where we end try { end = action.getOffset(editor, caret, context, cnt, raw, cmd.getArgument()); } catch (ExecuteMethodNotOverriddenException e) { // This actually should have fallen even earlier. end = -1; VimPlugin.indicateError(); } // Invalid motion if (end == -1) { return null; } } else if (cmd.getAction() instanceof TextObjectAction) { TextObjectAction action = (TextObjectAction) cmd.getAction(); TextRange range = action.getRange(editor, caret, context, cnt, raw, cmd.getArgument()); if (range == null) { return null; } start = range.getStartOffset(); end = range.getEndOffset(); } // If we are a linewise motion we need to normalize the start and stop then move the start to the beginning // of the line and move the end to the end of the line. int flags = cmd.getFlags(); if ((flags & Command.FLAG_MOT_LINEWISE) != 0) { if (start > end) { int t = start; start = end; end = t; } start = EditorHelper.getLineStartForOffset(editor, start); end = Math .min(EditorHelper.getLineEndForOffset(editor, end) + (incNewline ? 1 : 0), EditorHelper.getFileSize(editor)); } // If characterwise and inclusive, add the last character to the range else if ((flags & Command.FLAG_MOT_INCLUSIVE) != 0) { end++; } // Normalize the range if (start > end) { int t = start; start = end; end = t; } return new TextRange(start, end); } public int moveCaretToNthCharacter(@NotNull Editor editor, int count) { return Math.max(0, Math.min(count, EditorHelper.getFileSize(editor) - 1)); } public int moveCaretToMark(@NotNull Editor editor, @NotNull Caret caret, char ch) { final Mark mark = VimPlugin.getMark().getMark(editor, ch); if (mark == null) { return -1; } final VirtualFile vf = EditorData.getVirtualFile(editor); if (vf == null) { return -1; } final LogicalPosition lp = new LogicalPosition(mark.getLogicalLine(), mark.getCol()); if (!vf.getPath().equals(mark.getFilename())) { final Editor selectedEditor = selectEditor(editor, mark); if (selectedEditor != null) { editor.getCaretModel().removeCaret(caret); final Caret newCaret = selectedEditor.getCaretModel().addCaret(selectedEditor.logicalToVisualPosition(lp), false); if (newCaret != null) { moveCaret(selectedEditor, newCaret, selectedEditor.logicalPositionToOffset(lp)); } } return -2; } else { return editor.logicalPositionToOffset(lp); } } public int moveCaretToMark(@NotNull Editor editor, @NotNull Caret caret, char ch, boolean toLineStart) { final Mark mark = VimPlugin.getMark().getMark(editor, ch); if (mark == null) { return -1; } final VirtualFile vf = EditorData.getVirtualFile(editor); if (vf == null) { return -1; } final LogicalPosition lp = new LogicalPosition(mark.getLogicalLine(), mark.getCol()); if (!vf.getPath().equals(mark.getFilename())) { final Editor selectedEditor = selectEditor(editor, mark); if (selectedEditor != null) { editor.getCaretModel().removeCaret(caret); final Caret newCaret = selectedEditor.getCaretModel().addCaret(selectedEditor.logicalToVisualPosition(lp), false); if (newCaret != null) { final int offset = toLineStart ? moveCaretToLineStartSkipLeading(selectedEditor, lp.line) : selectedEditor.logicalPositionToOffset(lp); moveCaret(selectedEditor, newCaret, offset); } } return -2; } else { return toLineStart ? moveCaretToLineStartSkipLeading(editor, lp.line) : editor.logicalPositionToOffset(lp); } } public int moveCaretToJump(@NotNull Editor editor, @NotNull Caret caret, int count) { final int spot = VimPlugin.getMark().getJumpSpot(); final Jump jump = VimPlugin.getMark().getJump(count); if (jump == null) { return -1; } final VirtualFile vf = EditorData.getVirtualFile(editor); if (vf == null) { return -1; } final LogicalPosition lp = new LogicalPosition(jump.getLogicalLine(), jump.getCol()); final String fileName = jump.getFilename(); if (!vf.getPath().equals(fileName) && fileName != null) { final VirtualFile newFile = LocalFileSystem.getInstance().findFileByPath(fileName.replace(File.separatorChar, '/')); if (newFile == null) { return -2; } final Editor newEditor = selectEditor(editor, newFile); if (newEditor != null) { if (spot == -1) { VimPlugin.getMark().addJump(editor, false); } moveCaret(newEditor, caret, EditorHelper.normalizeOffset(newEditor, newEditor.logicalPositionToOffset(lp), false)); } return -2; } else { if (spot == -1) { VimPlugin.getMark().addJump(editor, false); } return editor.logicalPositionToOffset(lp); } } @Nullable private Editor selectEditor(@NotNull Editor editor, @NotNull Mark mark) { final VirtualFile virtualFile = markToVirtualFile(mark); if (virtualFile != null) { return selectEditor(editor, virtualFile); } else { return null; } } @Nullable private VirtualFile markToVirtualFile(@NotNull Mark mark) { String protocol = mark.getProtocol(); VirtualFileSystem fileSystem = VirtualFileManager.getInstance().getFileSystem(protocol); if (mark.getFilename() == null) { return null; } return fileSystem.findFileByPath(mark.getFilename()); } @Nullable private Editor selectEditor(@NotNull Editor editor, @NotNull VirtualFile file) { return VimPlugin.getFile().selectEditor(editor.getProject(), file); } public int moveCaretToMatchingPair(@NotNull Editor editor, @NotNull Caret caret) { int pos = SearchHelper.findMatchingPairOnCurrentLine(editor, caret); if (pos >= 0) { return pos; } else { return -1; } } /** * This moves the caret to the start of the next/previous camel word. * * @param editor The editor to move in * @param caret The caret to be moved * @param count The number of words to skip * @return position */ public int moveCaretToNextCamel(@NotNull Editor editor, @NotNull Caret caret, int count) { if ((caret.getOffset() == 0 && count < 0) || (caret.getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0)) { return -1; } else { return SearchHelper.findNextCamelStart(editor, caret, count); } } /** * This moves the caret to the start of the next/previous camel word. * * @param editor The editor to move in * @param caret The caret to be moved * @param count The number of words to skip * @return position */ public int moveCaretToNextCamelEnd(@NotNull Editor editor, @NotNull Caret caret, int count) { if ((caret.getOffset() == 0 && count < 0) || (caret.getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0)) { return -1; } else { return SearchHelper.findNextCamelEnd(editor, caret, count); } } /** * This moves the caret to the start of the next/previous word/WORD. * * @param editor The editor to move in * @param caret The caret to be moved * @param count The number of words to skip * @param bigWord If true then find WORD, if false then find word * @return position */ public int moveCaretToNextWord(@NotNull Editor editor, @NotNull Caret caret, int count, boolean bigWord) { final int offset = caret.getOffset(); final int size = EditorHelper.getFileSize(editor); if ((offset == 0 && count < 0) || (offset >= size - 1 && count > 0)) { return -1; } return SearchHelper.findNextWord(editor, caret, count, bigWord); } /** * This moves the caret to the end of the next/previous word/WORD. * * @param editor The editor to move in * @param caret The caret to be moved * @param count The number of words to skip * @param bigWord If true then find WORD, if false then find word * @return position */ public int moveCaretToNextWordEnd(@NotNull Editor editor, @NotNull Caret caret, int count, boolean bigWord) { if ((caret.getOffset() == 0 && count < 0) || (caret.getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0)) { return -1; } // If we are doing this move as part of a change command (e.q. cw), we need to count the current end of // word if the cursor happens to be on the end of a word already. If this is a normal move, we don't count // the current word. int pos = SearchHelper.findNextWordEnd(editor, caret, count, bigWord); if (pos == -1) { if (count < 0) { return moveCaretToLineStart(editor, 0); } else { return moveCaretToLineEnd(editor, EditorHelper.getLineCount(editor) - 1, false); } } else { return pos; } } /** * This moves the caret to the start of the next/previous paragraph. * * @param editor The editor to move in * @param caret The caret to be moved * @param count The number of paragraphs to skip * @return position */ public int moveCaretToNextParagraph(@NotNull Editor editor, @NotNull Caret caret, int count) { int res = SearchHelper.findNextParagraph(editor, caret, count, false); if (res >= 0) { res = EditorHelper.normalizeOffset(editor, res, true); } else { res = -1; } return res; } public int moveCaretToNextSentenceStart(@NotNull Editor editor, @NotNull Caret caret, int count) { int res = SearchHelper.findNextSentenceStart(editor, caret, count, false, true); if (res >= 0) { res = EditorHelper.normalizeOffset(editor, res, true); } else { res = -1; } return res; } public int moveCaretToNextSentenceEnd(@NotNull Editor editor, @NotNull Caret caret, int count) { int res = SearchHelper.findNextSentenceEnd(editor, caret, count, false, true); if (res >= 0) { res = EditorHelper.normalizeOffset(editor, res, false); } else { res = -1; } return res; } public int moveCaretToUnmatchedBlock(@NotNull Editor editor, @NotNull Caret caret, int count, char type) { if ((editor.getCaretModel().getOffset() == 0 && count < 0) || (editor.getCaretModel().getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0)) { return -1; } else { int res = SearchHelper.findUnmatchedBlock(editor, caret, type, count); if (res != -1) { res = EditorHelper.normalizeOffset(editor, res, false); } return res; } } public int moveCaretToSection(@NotNull Editor editor, @NotNull Caret caret, char type, int dir, int count) { if ((caret.getOffset() == 0 && count < 0) || (caret.getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0)) { return -1; } else { int res = SearchHelper.findSection(editor, caret, type, dir, count); if (res != -1) { res = EditorHelper.normalizeOffset(editor, res, false); } return res; } } public int moveCaretToMethodStart(@NotNull Editor editor, @NotNull Caret caret, int count) { return SearchHelper.findMethodStart(editor, caret, count); } public int moveCaretToMethodEnd(@NotNull Editor editor, @NotNull Caret caret, int count) { return SearchHelper.findMethodEnd(editor, caret, count); } public void setLastFTCmd(int lastFTCmd, char lastChar) { this.lastFTCmd = lastFTCmd; this.lastFTChar = lastChar; } public int repeatLastMatchChar(@NotNull Editor editor, @NotNull Caret caret, int count) { int res = -1; int startPos = editor.getCaretModel().getOffset(); switch (lastFTCmd) { case LAST_F: res = moveCaretToNextCharacterOnLine(editor, caret, -count, lastFTChar); break; case LAST_f: res = moveCaretToNextCharacterOnLine(editor, caret, count, lastFTChar); break; case LAST_T: res = moveCaretToBeforeNextCharacterOnLine(editor, caret, -count, lastFTChar); if (res == startPos && Math.abs(count) == 1) { res = moveCaretToBeforeNextCharacterOnLine(editor, caret, 2 * count, lastFTChar); } break; case LAST_t: res = moveCaretToBeforeNextCharacterOnLine(editor, caret, count, lastFTChar); if (res == startPos && Math.abs(count) == 1) { res = moveCaretToBeforeNextCharacterOnLine(editor, caret, 2 * count, lastFTChar); } break; } return res; } /** * This moves the caret to the next/previous matching character on the current line * * @param caret The caret to be moved * @param count The number of occurrences to move to * @param ch The character to search for * @param editor The editor to search in * @return True if [count] character matches were found, false if not */ public int moveCaretToNextCharacterOnLine(@NotNull Editor editor, @NotNull Caret caret, int count, char ch) { int pos = SearchHelper.findNextCharacterOnLine(editor, caret, count, ch); if (pos >= 0) { return pos; } else { return -1; } } /** * This moves the caret next to the next/previous matching character on the current line * * @param caret The caret to be moved * @param count The number of occurrences to move to * @param ch The character to search for * @param editor The editor to search in * @return True if [count] character matches were found, false if not */ public int moveCaretToBeforeNextCharacterOnLine(@NotNull Editor editor, @NotNull Caret caret, int count, char ch) { int pos = SearchHelper.findNextCharacterOnLine(editor, caret, count, ch); if (pos >= 0) { int step = count >= 0 ? 1 : -1; return pos - step; } else { return -1; } } public boolean scrollLineToFirstScreenLine(@NotNull Editor editor, int rawCount, int count, boolean start) { scrollLineToScreenLine(editor, 1, rawCount, count, start); return true; } public boolean scrollLineToMiddleScreenLine(@NotNull Editor editor, int rawCount, int count, boolean start) { scrollLineToScreenLine(editor, EditorHelper.getScreenHeight(editor) / 2 + 1, rawCount, count, start); return true; } public boolean scrollLineToLastScreenLine(@NotNull Editor editor, int rawCount, int count, boolean start) { scrollLineToScreenLine(editor, EditorHelper.getScreenHeight(editor), rawCount, count, start); return true; } public boolean scrollColumnToFirstScreenColumn(@NotNull Editor editor) { scrollColumnToScreenColumn(editor, 0); return true; } public boolean scrollColumnToLastScreenColumn(@NotNull Editor editor) { scrollColumnToScreenColumn(editor, EditorHelper.getScreenWidth(editor)); return true; } private void scrollColumnToScreenColumn(@NotNull Editor editor, int column) { int scrollOffset = ((NumberOption) Options.getInstance().getOption("sidescrolloff")).value(); int width = EditorHelper.getScreenWidth(editor); if (scrollOffset > width / 2) { scrollOffset = width / 2; } if (column <= width / 2) { if (column < scrollOffset + 1) { column = scrollOffset + 1; } } else { if (column > width - scrollOffset) { column = width - scrollOffset; } } int visualColumn = editor.getCaretModel().getVisualPosition().column; scrollColumnToLeftOfScreen(editor, EditorHelper .normalizeVisualColumn(editor, editor.getCaretModel().getVisualPosition().line, visualColumn - column + 1, false)); } private void scrollLineToScreenLine(@NotNull Editor editor, int line, int rawCount, int count, boolean start) { int scrollOffset = ((NumberOption) Options.getInstance().getOption("scrolloff")).value(); int height = EditorHelper.getScreenHeight(editor); if (scrollOffset > height / 2) { scrollOffset = height / 2; } if (line <= height / 2) { if (line < scrollOffset + 1) { line = scrollOffset + 1; } } else { if (line > height - scrollOffset) { line = height - scrollOffset; } } int visualLine = rawCount == 0 ? editor.getCaretModel().getVisualPosition().line : EditorHelper.logicalLineToVisualLine(editor, count - 1); scrollLineToTopOfScreen(editor, EditorHelper.normalizeVisualLine(editor, visualLine - line + 1)); if (visualLine != editor.getCaretModel().getVisualPosition().line || start) { int offset; if (start) { offset = moveCaretToLineStartSkipLeading(editor, EditorHelper.visualLineToLogicalLine(editor, visualLine)); } else { offset = moveCaretVertical(editor, editor.getCaretModel().getPrimaryCaret(), EditorHelper.visualLineToLogicalLine(editor, visualLine) - editor.getCaretModel().getLogicalPosition().line); } moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), offset); } } public int moveCaretToFirstScreenLine(@NotNull Editor editor, int count) { return moveCaretToScreenLine(editor, count); } public int moveCaretToLastScreenLine(@NotNull Editor editor, int count) { return moveCaretToScreenLine(editor, EditorHelper.getScreenHeight(editor) - count + 1); } public int moveCaretToMiddleScreenLine(@NotNull Editor editor) { return moveCaretToScreenLine(editor, EditorHelper.getScreenHeight(editor) / 2 + 1); } private int moveCaretToScreenLine(@NotNull Editor editor, int line) { //saveJumpLocation(editor, context); int scrollOffset = ((NumberOption) Options.getInstance().getOption("scrolloff")).value(); int height = EditorHelper.getScreenHeight(editor); if (scrollOffset > height / 2) { scrollOffset = height / 2; } int top = EditorHelper.getVisualLineAtTopOfScreen(editor); if (line > height - scrollOffset && top < EditorHelper.getLineCount(editor) - height) { line = height - scrollOffset; } else if (line <= scrollOffset && top > 0) { line = scrollOffset + 1; } return moveCaretToLineStartSkipLeading(editor, EditorHelper.visualLineToLogicalLine(editor, top + line - 1)); } public boolean scrollHalfPage(@NotNull Editor editor, int dir, int count) { NumberOption scroll = (NumberOption) Options.getInstance().getOption("scroll"); int height = EditorHelper.getScreenHeight(editor) / 2; if (count == 0) { count = scroll.value(); if (count == 0) { count = height; } } else { scroll.set(count); } return scrollPage(editor, dir, count, EditorHelper.getCurrentVisualScreenLine(editor), true); } public boolean scrollColumn(@NotNull Editor editor, int columns) { int visualColumn = EditorHelper.getVisualColumnAtLeftOfScreen(editor); visualColumn = EditorHelper .normalizeVisualColumn(editor, editor.getCaretModel().getVisualPosition().line, visualColumn + columns, false); scrollColumnToLeftOfScreen(editor, visualColumn); moveCaretToView(editor); return true; } public boolean scrollLine(@NotNull Editor editor, int lines) { int visualLine = EditorHelper.getVisualLineAtTopOfScreen(editor); visualLine = EditorHelper.normalizeVisualLine(editor, visualLine + lines); scrollLineToTopOfScreen(editor, visualLine); moveCaretToView(editor); return true; } public static void moveCaretToView(@NotNull Editor editor) { int scrollOffset = ((NumberOption) Options.getInstance().getOption("scrolloff")).value(); int sideScrollOffset = ((NumberOption) Options.getInstance().getOption("sidescrolloff")).value(); int height = EditorHelper.getScreenHeight(editor); int width = EditorHelper.getScreenWidth(editor); if (scrollOffset > height / 2) { scrollOffset = height / 2; } if (sideScrollOffset > width / 2) { sideScrollOffset = width / 2; } int visualLine = EditorHelper.getVisualLineAtTopOfScreen(editor); int cline = editor.getCaretModel().getVisualPosition().line; int newline = cline; if (cline < visualLine + scrollOffset) { newline = EditorHelper.normalizeVisualLine(editor, visualLine + scrollOffset); } else if (cline >= visualLine + height - scrollOffset) { newline = EditorHelper.normalizeVisualLine(editor, visualLine + height - scrollOffset - 1); } int col = editor.getCaretModel().getVisualPosition().column; int oldColumn = col; if (col >= EditorHelper.getLineLength(editor) - 1) { col = CaretData.getLastColumn(editor.getCaretModel().getPrimaryCaret()); } int visualColumn = EditorHelper.getVisualColumnAtLeftOfScreen(editor); int caretColumn = col; int newColumn = caretColumn; if (caretColumn < visualColumn + sideScrollOffset) { newColumn = visualColumn + sideScrollOffset; } else if (caretColumn >= visualColumn + width - sideScrollOffset) { newColumn = visualColumn + width - sideScrollOffset - 1; } if (newline == cline && newColumn != caretColumn) { col = newColumn; } newColumn = EditorHelper.normalizeVisualColumn(editor, newline, newColumn, CommandState.inInsertMode(editor)); if (newline != cline || newColumn != oldColumn) { int offset = EditorHelper.visualPositionToOffset(editor, new VisualPosition(newline, newColumn)); moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), offset); CaretData.setLastColumn(editor, editor.getCaretModel().getPrimaryCaret(), col); } } public boolean scrollFullPage(@NotNull Editor editor, int pages) { int height = EditorHelper.getScreenHeight(editor); int line = pages > 0 ? 1 : height; return scrollPage(editor, pages, height - 2, line, false); } public boolean scrollPage(@NotNull Editor editor, int pages, int height, int line, boolean partial) { int visualTopLine = EditorHelper.getVisualLineAtTopOfScreen(editor); int newLine = visualTopLine + pages * height; int topLine = EditorHelper.normalizeVisualLine(editor, newLine); boolean moved = scrollLineToTopOfScreen(editor, topLine); visualTopLine = EditorHelper.getVisualLineAtTopOfScreen(editor); if (moved && topLine == newLine && topLine == visualTopLine) { moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), moveCaretToScreenLine(editor, line)); return true; } else if (moved && !partial) { int visualLine = Math.abs(visualTopLine - newLine) % height + 1; if (pages < 0) { visualLine = height - visualLine + 3; } moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), moveCaretToScreenLine(editor, visualLine)); return true; } else if (partial) { int cline = editor.getCaretModel().getVisualPosition().line; int visualLine = cline + pages * height; visualLine = EditorHelper.normalizeVisualLine(editor, visualLine); if (cline == visualLine) { return false; } int logicalLine = editor.visualToLogicalPosition(new VisualPosition(visualLine, 0)).line; moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), moveCaretToLineStartSkipLeading(editor, logicalLine)); return true; } else { moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), moveCaretToLineStartSkipLeading(editor, editor.getCaretModel().getPrimaryCaret())); return false; } } private static boolean scrollLineToTopOfScreen(@NotNull Editor editor, int line) { int pos = line * editor.getLineHeight(); int verticalPos = editor.getScrollingModel().getVerticalScrollOffset(); editor.getScrollingModel().scrollVertically(pos); return verticalPos != editor.getScrollingModel().getVerticalScrollOffset(); } private static void scrollColumnToLeftOfScreen(@NotNull Editor editor, int column) { editor.getScrollingModel().scrollHorizontally(column * EditorHelper.getColumnWidth(editor)); } public int moveCaretToMiddleColumn(@NotNull Editor editor, @NotNull Caret caret) { final int width = EditorHelper.getScreenWidth(editor) / 2; final int len = EditorHelper.getLineLength(editor); return moveCaretToColumn(editor, caret, Math.max(0, Math.min(len - 1, width)), false); } public int moveCaretToColumn(@NotNull Editor editor, @NotNull Caret caret, int count, boolean allowEnd) { int line = caret.getLogicalPosition().line; int pos = EditorHelper.normalizeColumn(editor, line, count, allowEnd); return editor.logicalPositionToOffset(new LogicalPosition(line, pos)); } /** * @deprecated To move the caret, use {@link #moveCaretToColumn(Editor, Caret, int, boolean)} */ public int moveCaretToColumn(@NotNull Editor editor, int count, boolean allowEnd) { return moveCaretToColumn(editor, editor.getCaretModel().getPrimaryCaret(), count, allowEnd); } public int moveCaretToLineStartSkipLeading(@NotNull Editor editor, @NotNull Caret caret) { int logicalLine = caret.getLogicalPosition().line; return moveCaretToLineStartSkipLeading(editor, logicalLine); } public int moveCaretToLineStartSkipLeading(@NotNull Editor editor, int line) { return EditorHelper.getLeadingCharacterOffset(editor, line); } /** * @deprecated To move the caret, use {@link #moveCaretToLineStartSkipLeading(Editor, Caret)} */ public int moveCaretToLineStartSkipLeading(@NotNull Editor editor) { return moveCaretToLineStartSkipLeading(editor, editor.getCaretModel().getPrimaryCaret()); } public int moveCaretToLineStartSkipLeadingOffset(@NotNull Editor editor, @NotNull Caret caret, int linesOffset) { int line = EditorHelper.normalizeVisualLine(editor, caret.getVisualPosition().line + linesOffset); return moveCaretToLineStartSkipLeading(editor, EditorHelper.visualLineToLogicalLine(editor, line)); } /** * @deprecated To move the caret, use {@link #moveCaretToLineStartSkipLeadingOffset(Editor, Caret, int)} */ public int moveCaretToLineStartSkipLeadingOffset(@NotNull Editor editor, int linesOffset) { return moveCaretToLineStartSkipLeadingOffset(editor, editor.getCaretModel().getPrimaryCaret(), linesOffset); } public int moveCaretToLineEndSkipLeadingOffset(@NotNull Editor editor, @NotNull Caret caret, int linesOffset) { int line = EditorHelper.normalizeVisualLine(editor, caret.getVisualPosition().line + linesOffset); return moveCaretToLineEndSkipLeading(editor, EditorHelper.visualLineToLogicalLine(editor, line)); } public int moveCaretToLineEndSkipLeading(@NotNull Editor editor, int line) { int start = EditorHelper.getLineStartOffset(editor, line); int end = EditorHelper.getLineEndOffset(editor, line, true); CharSequence chars = editor.getDocument().getCharsSequence(); int pos = start; for (int offset = end; offset > start; offset if (offset >= chars.length()) { break; } if (!Character.isWhitespace(chars.charAt(offset))) { pos = offset; break; } } return pos; } /** * @deprecated Use {@link #moveCaretToLineEnd(Editor, Caret)} */ public int moveCaretToLineEnd(@NotNull Editor editor) { return moveCaretToLineEnd(editor, editor.getCaretModel().getPrimaryCaret()); } public int moveCaretToLineEnd(@NotNull Editor editor, @NotNull Caret caret) { final VisualPosition visualPosition = caret.getVisualPosition(); final int lastVisualLineColumn = EditorUtil.getLastVisualLineColumnNumber(editor, visualPosition.line); final VisualPosition visualEndOfLine = new VisualPosition(visualPosition.line, lastVisualLineColumn, true); return moveCaretToLineEnd(editor, editor.visualToLogicalPosition(visualEndOfLine).line, true); } public int moveCaretToLineEnd(@NotNull Editor editor, int line, boolean allowPastEnd) { return EditorHelper .normalizeOffset(editor, line, EditorHelper.getLineEndOffset(editor, line, allowPastEnd), allowPastEnd); } public int moveCaretToLineEndOffset(@NotNull Editor editor, @NotNull Caret caret, int cntForward, boolean allowPastEnd) { int line = EditorHelper.normalizeVisualLine(editor, caret.getVisualPosition().line + cntForward); if (line < 0) { return 0; } else { return moveCaretToLineEnd(editor, EditorHelper.visualLineToLogicalLine(editor, line), allowPastEnd); } } /** * @deprecated To move the caret, use {@link #moveCaretToLineEndOffset(Editor, Caret, int, boolean)} */ public int moveCaretToLineEndOffset(@NotNull Editor editor, int cntForward, boolean allowPastEnd) { return moveCaretToLineEndOffset(editor, editor.getCaretModel().getPrimaryCaret(), cntForward, allowPastEnd); } public int moveCaretToLineStart(@NotNull Editor editor, @NotNull Caret caret) { int logicalLine = caret.getLogicalPosition().line; return moveCaretToLineStart(editor, logicalLine); } /** * @deprecated To move the caret, use {@link #moveCaretToLineStart(Editor, Caret)} */ public int moveCaretToLineStart(@NotNull Editor editor) { return moveCaretToLineStart(editor, editor.getCaretModel().getPrimaryCaret()); } public int moveCaretToLineStart(@NotNull Editor editor, int line) { if (line >= EditorHelper.getLineCount(editor)) { return EditorHelper.getFileSize(editor); } return EditorHelper.getLineStartOffset(editor, line); } public int moveCaretToLineScreenStart(@NotNull Editor editor, @NotNull Caret caret) { final int col = EditorHelper.getVisualColumnAtLeftOfScreen(editor); return moveCaretToColumn(editor, caret, col, false); } public int moveCaretToLineScreenStartSkipLeading(@NotNull Editor editor, @NotNull Caret caret) { final int col = EditorHelper.getVisualColumnAtLeftOfScreen(editor); final int logicalLine = caret.getLogicalPosition().line; return EditorHelper.getLeadingCharacterOffset(editor, logicalLine, col); } public int moveCaretToLineScreenEnd(@NotNull Editor editor, @NotNull Caret caret, boolean allowEnd) { final int col = EditorHelper.getVisualColumnAtLeftOfScreen(editor) + EditorHelper.getScreenWidth(editor) - 1; return moveCaretToColumn(editor, caret, col, allowEnd); } public int moveCaretHorizontalWrap(@NotNull Editor editor, @NotNull Caret caret, int count) { // FIX - allows cursor over newlines int oldOffset = caret.getOffset(); int offset = Math.min(Math.max(0, caret.getOffset() + count), EditorHelper.getFileSize(editor)); if (offset == oldOffset) { return -1; } else { return offset; } } /** * @deprecated To move the caret, use {@link #moveCaret(Editor, Caret, int)} */ public int moveCaretHorizontal(@NotNull Editor editor, int count, boolean allowPastEnd) { int oldOffset = editor.getCaretModel().getOffset(); int offset = EditorHelper .normalizeOffset(editor, editor.getCaretModel().getLogicalPosition().line, oldOffset + count, allowPastEnd); if (offset == oldOffset) { return -1; } else { return offset; } } public int moveCaretHorizontal(@NotNull Editor editor, @NotNull Caret caret, int count, boolean allowPastEnd) { int oldOffset = caret.getOffset(); int offset = EditorHelper.normalizeOffset(editor, caret.getLogicalPosition().line, oldOffset + count, allowPastEnd); if (offset == oldOffset) { return -1; } else { return offset; } } public int moveCaretVertical(@NotNull Editor editor, @NotNull Caret caret, int count) { VisualPosition pos = caret.getVisualPosition(); if ((pos.line == 0 && count < 0) || (pos.line >= EditorHelper.getVisualLineCount(editor) - 1 && count > 0)) { return -1; } else { int col = CaretData.getLastColumn(caret); int line = EditorHelper.normalizeVisualLine(editor, pos.line + count); VisualPosition newPos = new VisualPosition(line, EditorHelper .normalizeVisualColumn(editor, line, col, CommandState.inInsertMode(editor))); return EditorHelper.visualPositionToOffset(editor, newPos); } } public int moveCaretToLine(@NotNull Editor editor, int logicalLine) { int col = CaretData.getLastColumn(editor.getCaretModel().getPrimaryCaret()); int line = logicalLine; if (logicalLine < 0) { line = 0; col = 0; } else if (logicalLine >= EditorHelper.getLineCount(editor)) { line = EditorHelper.normalizeLine(editor, EditorHelper.getLineCount(editor) - 1); col = EditorHelper.getLineLength(editor, line); } LogicalPosition newPos = new LogicalPosition(line, EditorHelper.normalizeColumn(editor, line, col, false)); return editor.logicalPositionToOffset(newPos); } public int moveCaretToLinePercent(@NotNull Editor editor, int count) { if (count > 100) count = 100; return moveCaretToLineStartSkipLeading(editor, EditorHelper .normalizeLine(editor, (EditorHelper.getLineCount(editor) * count + 99) / 100 - 1)); } public int moveCaretGotoLineLast(@NotNull Editor editor, int rawCount) { final int line = rawCount == 0 ? EditorHelper.normalizeLine(editor, EditorHelper.getLineCount(editor) - 1) : rawCount - 1; return moveCaretToLineStartSkipLeading(editor, line); } public int moveCaretGotoLineLastEnd(@NotNull Editor editor, int rawCount, int line, boolean pastEnd) { return moveCaretToLineEnd(editor, rawCount == 0 ? EditorHelper.normalizeLine(editor, EditorHelper.getLineCount(editor) - 1) : line, pastEnd); } public int moveCaretGotoLineFirst(@NotNull Editor editor, int line) { return moveCaretToLineStartSkipLeading(editor, line); } public static void moveCaret(@NotNull Editor editor, @NotNull Caret caret, int offset) { moveCaret(editor, caret, offset, false); } /** * @deprecated Use the {@link #moveCaret(Editor, Caret, int) multi-caret version} of this function. */ public static void moveCaret(@NotNull Editor editor, int offset) { moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), offset); } public static void moveCaret(@NotNull Editor editor, @NotNull Caret caret, int offset, boolean forceKeepVisual) { if (offset >= 0 && offset <= editor.getDocument().getTextLength()) { final boolean keepVisual = forceKeepVisual || keepVisual(editor); if (caret.getOffset() != offset) { caret.moveToOffset(offset); CaretData.setLastColumn(editor, caret, caret.getVisualPosition().column); if (caret == editor.getCaretModel().getPrimaryCaret()) { scrollCaretIntoView(editor); } } if (keepVisual) { VimPlugin.getMotion().updateSelection(editor, caret, offset); } else { editor.getSelectionModel().removeSelection(); } } } private static boolean keepVisual(Editor editor) { final CommandState commandState = CommandState.getInstance(editor); if (commandState.getMode() == CommandState.Mode.VISUAL) { final Command command = commandState.getCommand(); return command == null || (command.getFlags() & Command.FLAG_EXIT_VISUAL) == 0; } return false; } /** * If 'absolute' is true, then set tab index to 'value', otherwise add 'value' to tab index with wraparound. */ private void switchEditorTab(@Nullable EditorWindow editorWindow, int value, boolean absolute) { if (editorWindow != null) { final EditorTabbedContainer tabbedPane = editorWindow.getTabbedPane(); if (tabbedPane != null) { if (absolute) { tabbedPane.setSelectedIndex(value); } else { int tabIndex = (value + tabbedPane.getSelectedIndex()) % tabbedPane.getTabCount(); tabbedPane.setSelectedIndex(tabIndex < 0 ? tabIndex + tabbedPane.getTabCount() : tabIndex); } } } } public int moveCaretGotoPreviousTab(@NotNull Editor editor, @NotNull DataContext context, int rawCount) { switchEditorTab(EditorWindow.DATA_KEY.getData(context), rawCount >= 1 ? -rawCount : -1, false); return editor.getCaretModel().getOffset(); } public int moveCaretGotoNextTab(@NotNull Editor editor, @NotNull DataContext context, int rawCount) { final boolean absolute = rawCount >= 1; switchEditorTab(EditorWindow.DATA_KEY.getData(context), absolute ? rawCount - 1 : 1, absolute); return editor.getCaretModel().getOffset(); } public static void scrollCaretIntoView(@NotNull Editor editor) { final boolean scrollJump = (CommandState.getInstance(editor).getFlags() & Command.FLAG_IGNORE_SCROLL_JUMP) == 0; scrollPositionIntoView(editor, editor.getCaretModel().getVisualPosition(), scrollJump); } public static void scrollPositionIntoView(@NotNull Editor editor, @NotNull VisualPosition position, boolean scrollJump) { final int line = position.line; final int column = position.column; final int topLine = EditorHelper.getVisualLineAtTopOfScreen(editor); int scrollOffset = ((NumberOption) Options.getInstance().getOption("scrolloff")).value(); int scrollJumpSize = 0; if (scrollJump) { scrollJumpSize = Math.max(0, ((NumberOption) Options.getInstance().getOption("scrolljump")).value() - 1); } int height = EditorHelper.getScreenHeight(editor); int visualTop = topLine + scrollOffset; int visualBottom = topLine + height - scrollOffset; if (scrollOffset >= height / 2) { scrollOffset = height / 2; visualTop = topLine + scrollOffset; visualBottom = topLine + height - scrollOffset; if (visualTop == visualBottom) { visualBottom++; } } int diff; if (line < visualTop) { diff = line - visualTop; scrollJumpSize = -scrollJumpSize; } else { diff = line - visualBottom + 1; if (diff < 0) { diff = 0; } } if (diff != 0) { int resLine; // If we need to move the top line more than a half screen worth then we just center the cursor line if (Math.abs(diff) > height / 2) { resLine = line - height / 2 - 1; } // Otherwise put the new cursor line "scrolljump" lines from the top/bottom else { resLine = topLine + diff + scrollJumpSize; } resLine = Math.min(resLine, EditorHelper.getVisualLineCount(editor) - height); resLine = Math.max(0, resLine); scrollLineToTopOfScreen(editor, resLine); } int visualColumn = EditorHelper.getVisualColumnAtLeftOfScreen(editor); int width = EditorHelper.getScreenWidth(editor); scrollJump = (CommandState.getInstance(editor).getFlags() & Command.FLAG_IGNORE_SIDE_SCROLL_JUMP) == 0; scrollOffset = ((NumberOption) Options.getInstance().getOption("sidescrolloff")).value(); scrollJumpSize = 0; if (scrollJump) { scrollJumpSize = Math.max(0, ((NumberOption) Options.getInstance().getOption("sidescroll")).value() - 1); if (scrollJumpSize == 0) { scrollJumpSize = width / 2; } } int visualLeft = visualColumn + scrollOffset; int visualRight = visualColumn + width - scrollOffset; if (scrollOffset >= width / 2) { scrollOffset = width / 2; visualLeft = visualColumn + scrollOffset; visualRight = visualColumn + width - scrollOffset; if (visualLeft == visualRight) { visualRight++; } } scrollJumpSize = Math.min(scrollJumpSize, width / 2 - scrollOffset); if (column < visualLeft) { diff = column - visualLeft + 1; scrollJumpSize = -scrollJumpSize; } else { diff = column - visualRight + 1; if (diff < 0) { diff = 0; } } if (diff != 0) { int col; if (Math.abs(diff) > width / 2) { col = column - width / 2 - 1; } else { col = visualColumn + diff + scrollJumpSize; } col = Math.max(0, col); scrollColumnToLeftOfScreen(editor, col); } } public boolean selectPreviousVisualMode(@NotNull Editor editor) { final SelectionType lastSelectionType = EditorData.getLastSelectionType(editor); if (lastSelectionType == null) { return false; } final TextRange visualMarks = VimPlugin.getMark().getVisualSelectionMarks(editor); if (visualMarks == null) { return false; } editor.getCaretModel().removeSecondaryCarets(); CommandState.getInstance(editor) .pushState(CommandState.Mode.VISUAL, lastSelectionType.toSubMode(), MappingMode.VISUAL); Caret primaryCaret = editor.getCaretModel().getPrimaryCaret(); CaretData.setVisualStart(primaryCaret, visualMarks.getStartOffset()); CaretData.setVisualEnd(primaryCaret, visualMarks.getEndOffset()); CaretData.setVisualOffset(primaryCaret, visualMarks.getEndOffset()); updateSelection(editor, primaryCaret, visualMarks.getEndOffset()); primaryCaret.moveToOffset(visualMarks.getEndOffset()); editor.getScrollingModel().scrollToCaret(ScrollType.CENTER); return true; } public boolean swapVisualSelections(@NotNull Editor editor) { final SelectionType lastSelectionType = EditorData.getLastSelectionType(editor); final TextRange lastVisualRange = EditorData.getLastVisualRange(editor); if (lastSelectionType == null || lastVisualRange == null) { return false; } final SelectionType selectionType = SelectionType.fromSubMode(CommandState.getInstance(editor).getSubMode()); EditorData.setLastSelectionType(editor, selectionType); editor.getCaretModel().removeSecondaryCarets(); Caret primaryCaret = editor.getCaretModel().getPrimaryCaret(); CaretData.setVisualStart(primaryCaret, lastVisualRange.getStartOffset()); CaretData.setVisualEnd(primaryCaret, lastVisualRange.getEndOffset()); CaretData.setVisualOffset(primaryCaret, lastVisualRange.getEndOffset()); CommandState.getInstance(editor).setSubMode(lastSelectionType.toSubMode()); updateSelection(editor, primaryCaret, lastVisualRange.getEndOffset()); primaryCaret.moveToOffset(lastVisualRange.getEndOffset()); editor.getScrollingModel().scrollToCaret(ScrollType.CENTER); return true; } public void setVisualMode(@NotNull Editor editor, @NotNull CommandState.SubMode mode) { CommandState.SubMode oldMode = CommandState.getInstance(editor).getSubMode(); if (mode == CommandState.SubMode.NONE) { int start = editor.getSelectionModel().getSelectionStart(); int end = editor.getSelectionModel().getSelectionEnd(); if (start != end) { int line = editor.offsetToLogicalPosition(start).line; int logicalStart = EditorHelper.getLineStartOffset(editor, line); int lend = EditorHelper.getLineEndOffset(editor, line, true); if (logicalStart == start && lend + 1 == end) { mode = CommandState.SubMode.VISUAL_LINE; } else { mode = CommandState.SubMode.VISUAL_CHARACTER; } } } if (oldMode == CommandState.SubMode.NONE && mode == CommandState.SubMode.NONE) { editor.getSelectionModel().removeSelection(); return; } if (mode == CommandState.SubMode.NONE) { exitVisual(editor); } else { CommandState.getInstance(editor).pushState(CommandState.Mode.VISUAL, mode, MappingMode.VISUAL); } KeyHandler.getInstance().reset(editor); for (Caret caret : editor.getCaretModel().getAllCarets()) { CaretData.setVisualStart(caret, caret.getSelectionStart()); int visualEnd = caret.getSelectionEnd(); if (CommandState.getInstance(editor).getSubMode() == CommandState.SubMode.VISUAL_CHARACTER) { BoundStringOption opt = (BoundStringOption) Options.getInstance().getOption("selection"); int adj = 1; if (opt.getValue().equals("exclusive")) { adj = 0; } visualEnd -= adj; } CaretData.setVisualEnd(caret, visualEnd); CaretData.setVisualOffset(caret, caret.getOffset()); } VimPlugin.getMark().setVisualSelectionMarks(editor, getRawVisualRange(editor)); } public boolean toggleVisual(@NotNull Editor editor, int count, int rawCount, @NotNull CommandState.SubMode mode) { CommandState.SubMode currentMode = CommandState.getInstance(editor).getSubMode(); if (CommandState.getInstance(editor).getMode() != CommandState.Mode.VISUAL) { if (rawCount > 0) { if (editor.getCaretModel().getCaretCount() > 1) { return false; } VisualChange range = CaretData.getLastVisualOperatorRange(editor.getCaretModel().getPrimaryCaret()); if (range == null) { return false; } switch (range.getType()) { case CHARACTER_WISE: mode = CommandState.SubMode.VISUAL_CHARACTER; break; case LINE_WISE: mode = CommandState.SubMode.VISUAL_LINE; break; case BLOCK_WISE: mode = CommandState.SubMode.VISUAL_BLOCK; break; } int start = editor.getCaretModel().getOffset(); int end = calculateVisualRange(editor, range, count); Caret primaryCaret = editor.getCaretModel().getPrimaryCaret(); CommandState.getInstance(editor).pushState(CommandState.Mode.VISUAL, mode, MappingMode.VISUAL); CaretData.setVisualStart(primaryCaret, start); updateSelection(editor, primaryCaret, end); MotionGroup.moveCaret(editor, primaryCaret, CaretData.getVisualEnd(primaryCaret), true); } else { CommandState.getInstance(editor).pushState(CommandState.Mode.VISUAL, mode, MappingMode.VISUAL); if (mode == CommandState.SubMode.VISUAL_BLOCK) { EditorData.setVisualBlockStart(editor, editor.getSelectionModel().getSelectionStart()); updateBlockSelection(editor, editor.getSelectionModel().getSelectionEnd()); MotionGroup .moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), EditorData.getVisualBlockEnd(editor), true); } else { for (Caret caret : editor.getCaretModel().getAllCarets()) { CaretData.setVisualStart(caret, caret.getSelectionStart()); updateSelection(editor, caret, caret.getSelectionEnd()); MotionGroup.moveCaret(editor, caret, CaretData.getVisualEnd(caret), true); } } } } else if (mode == currentMode) { exitVisual(editor); } else if (mode == CommandState.SubMode.VISUAL_BLOCK) { CommandState.getInstance(editor).setSubMode(mode); updateBlockSelection(editor, EditorData.getVisualBlockEnd(editor)); } else { CommandState.getInstance(editor).setSubMode(mode); for (Caret caret : editor.getCaretModel().getAllCarets()) { updateSelection(editor, caret, CaretData.getVisualEnd(caret)); } } return true; } private int calculateVisualRange(@NotNull Editor editor, @NotNull VisualChange range, int count) { int lines = range.getLines(); int chars = range.getColumns(); if (range.getType() == SelectionType.LINE_WISE || range.getType() == SelectionType.BLOCK_WISE || lines > 1) { lines *= count; } if ((range.getType() == SelectionType.CHARACTER_WISE && lines == 1) || range.getType() == SelectionType.BLOCK_WISE) { chars *= count; } int start = editor.getCaretModel().getOffset(); LogicalPosition sp = editor.offsetToLogicalPosition(start); int endLine = sp.line + lines - 1; int res; if (range.getType() == SelectionType.LINE_WISE) { res = moveCaretToLine(editor, endLine); } else if (range.getType() == SelectionType.CHARACTER_WISE) { if (lines > 1) { res = moveCaretToLineStart(editor, endLine) + Math.min(EditorHelper.getLineLength(editor, endLine), chars); } else { res = EditorHelper.normalizeOffset(editor, sp.line, start + chars - 1, false); } } else { int endColumn = Math.min(EditorHelper.getLineLength(editor, endLine), sp.column + chars - 1); res = editor.logicalPositionToOffset(new LogicalPosition(endLine, endColumn)); } return res; } public void exitVisual(@NotNull final Editor editor) { resetVisual(editor, true); if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) { CommandState.getInstance(editor).popState(); } } public void resetVisual(@NotNull final Editor editor, final boolean removeSelection) { final boolean wasVisualBlock = CommandState.inVisualBlockMode(editor); final SelectionType selectionType = SelectionType.fromSubMode(CommandState.getInstance(editor).getSubMode()); EditorData.setLastSelectionType(editor, selectionType); final TextRange visualMarks = VimPlugin.getMark().getVisualSelectionMarks(editor); if (visualMarks != null) { EditorData.setLastVisualRange(editor, visualMarks); } if (removeSelection) { if (!EditorData.isKeepingVisualOperatorAction(editor)) { for (Caret caret : editor.getCaretModel().getAllCarets()) { caret.removeSelection(); } } if (wasVisualBlock) { editor.getCaretModel().removeSecondaryCarets(); } } CommandState.getInstance(editor).setSubMode(CommandState.SubMode.NONE); } @NotNull public VisualChange getVisualOperatorRange(@NotNull Editor editor, @NotNull Caret caret, int cmdFlags) { int start = CaretData.getVisualStart(caret); int end = CaretData.getVisualEnd(caret); if (CommandState.inVisualBlockMode(editor)) { start = EditorData.getVisualBlockStart(editor); end = EditorData.getVisualBlockEnd(editor); } if (start > end) { int t = start; start = end; end = t; } start = EditorHelper.normalizeOffset(editor, start, false); end = EditorHelper.normalizeOffset(editor, end, false); LogicalPosition sp = editor.offsetToLogicalPosition(start); LogicalPosition ep = editor.offsetToLogicalPosition(end); int lines = ep.line - sp.line + 1; int chars; SelectionType type; if (CommandState.getInstance(editor).getSubMode() == CommandState.SubMode.VISUAL_LINE || (cmdFlags & Command.FLAG_MOT_LINEWISE) != 0) { chars = ep.column; type = SelectionType.LINE_WISE; } else if (CommandState.getInstance(editor).getSubMode() == CommandState.SubMode.VISUAL_CHARACTER) { type = SelectionType.CHARACTER_WISE; if (lines > 1) { chars = ep.column; } else { chars = ep.column - sp.column + 1; } } else { chars = ep.column - sp.column + 1; if (CaretData.getLastColumn(editor.getCaretModel().getPrimaryCaret()) == MotionGroup.LAST_COLUMN) { chars = MotionGroup.LAST_COLUMN; } type = SelectionType.BLOCK_WISE; } return new VisualChange(lines, chars, type); } @NotNull public VisualChange getVisualOperatorRange(@NotNull Editor editor, int cmdFlags) { return getVisualOperatorRange(editor, editor.getCaretModel().getPrimaryCaret(), cmdFlags); } @NotNull public TextRange getVisualRange(@NotNull Editor editor) { return new TextRange(editor.getSelectionModel().getBlockSelectionStarts(), editor.getSelectionModel().getBlockSelectionEnds()); } @NotNull public TextRange getVisualRange(@NotNull Caret caret) { return new TextRange(caret.getSelectionStart(), caret.getSelectionEnd()); } @NotNull public TextRange getRawVisualRange(@NotNull Editor editor) { return getRawVisualRange(editor.getCaretModel().getPrimaryCaret()); } @NotNull public TextRange getRawVisualRange(@NotNull Caret caret) { return new TextRange(CaretData.getVisualStart(caret), CaretData.getVisualEnd(caret)); } public void updateBlockSelection(@NotNull Editor editor) { updateBlockSelection(editor, EditorData.getVisualBlockEnd(editor)); } private void updateBlockSelection(@NotNull Editor editor, int offset) { EditorData.setVisualBlockEnd(editor, offset); EditorData.setVisualBlockOffset(editor, offset); int start = EditorData.getVisualBlockStart(editor); int end = EditorData.getVisualBlockEnd(editor); LogicalPosition blockStart = editor.offsetToLogicalPosition(start); LogicalPosition blockEnd = editor.offsetToLogicalPosition(end); if (blockStart.column < blockEnd.column) { blockEnd = new LogicalPosition(blockEnd.line, blockEnd.column + 1); } else { blockStart = new LogicalPosition(blockStart.line, blockStart.column + 1); } editor.getSelectionModel().setBlockSelection(blockStart, blockEnd); for (Caret caret : editor.getCaretModel().getAllCarets()) { int line = caret.getLogicalPosition().line; int lineEndOffset = EditorHelper.getLineEndOffset(editor, line, true); if (CaretData.getLastColumn(editor.getCaretModel().getPrimaryCaret()) >= MotionGroup.LAST_COLUMN) { caret.setSelection(caret.getSelectionStart(), lineEndOffset); } if (!EditorHelper.isLineEmpty(editor, line, false)) { caret.moveToOffset(caret.getSelectionEnd() - 1); } } editor.getCaretModel().getPrimaryCaret().moveToOffset(end); VimPlugin.getMark().setVisualSelectionMarks(editor, new TextRange(start, end)); } private void updateSelection(@NotNull Editor editor, @NotNull Caret caret, int offset) { if (CommandState.getInstance(editor).getSubMode() == CommandState.SubMode.VISUAL_BLOCK) { updateBlockSelection(editor, offset); } else { CaretData.setVisualEnd(caret, offset); CaretData.setVisualOffset(caret, offset); int start = CaretData.getVisualStart(caret); int end = offset; final CommandState.SubMode subMode = CommandState.getInstance(editor).getSubMode(); if (subMode == CommandState.SubMode.VISUAL_CHARACTER) { if (start > end) { int t = start; start = end; end = t; } final BoundStringOption opt = (BoundStringOption) Options.getInstance().getOption("selection"); int lineEnd = EditorHelper.getLineEndForOffset(editor, end); final int adj = opt.getValue().equals("exclusive") || end == lineEnd ? 0 : 1; final int adjEnd = Math.min(EditorHelper.getFileSize(editor), end + adj); caret.setSelection(start, adjEnd); } else if (subMode == CommandState.SubMode.VISUAL_LINE) { if (start > end) { int t = start; start = end; end = t; } start = EditorHelper.getLineStartForOffset(editor, start); end = EditorHelper.getLineEndForOffset(editor, end); caret.setSelection(start, end); } VimPlugin.getMark().setVisualSelectionMarks(editor, new TextRange(start, end)); } } public boolean swapVisualBlockEnds(@NotNull Editor editor) { if (!CommandState.inVisualBlockMode(editor)) return false; int t = EditorData.getVisualBlockEnd(editor); EditorData.setVisualBlockEnd(editor, EditorData.getVisualBlockStart(editor)); EditorData.setVisualBlockStart(editor, t); moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), EditorData.getVisualBlockEnd(editor)); return true; } public boolean swapVisualEnds(@NotNull Editor editor, @NotNull Caret caret) { int t = CaretData.getVisualEnd(caret); CaretData.setVisualEnd(caret, CaretData.getVisualStart(caret)); CaretData.setVisualStart(caret, t); moveCaret(editor, caret, CaretData.getVisualEnd(caret)); return true; } public void moveVisualStart(@NotNull Caret caret, int startOffset) { CaretData.setVisualStart(caret, startOffset); } public void processEscape(@NotNull Editor editor) { exitVisual(editor); } public static class MotionEditorChange implements FileEditorManagerListener { public void selectionChanged(@NotNull FileEditorManagerEvent event) { if (ExEntryPanel.getInstance().isActive()) { ExEntryPanel.getInstance().deactivate(false); } final FileEditor fileEditor = event.getOldEditor(); if (fileEditor instanceof TextEditor) { final Editor editor = ((TextEditor) fileEditor).getEditor(); ExOutputModel.getInstance(editor).clear(); if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) { VimPlugin.getMotion().exitVisual(editor); } } } } private static class EditorSelectionHandler implements SelectionListener { private boolean myMakingChanges = false; public void selectionChanged(@NotNull SelectionEvent selectionEvent) { final Editor editor = selectionEvent.getEditor(); final Document document = editor.getDocument(); if (myMakingChanges || (document instanceof DocumentEx && ((DocumentEx) document).isInEventsHandling())) { return; } myMakingChanges = true; try { final com.intellij.openapi.util.TextRange newRange = selectionEvent.getNewRange(); for (Editor e : EditorFactory.getInstance().getEditors(document)) { if (!e.equals(editor)) { e.getSelectionModel().setSelection(newRange.getStartOffset(), newRange.getEndOffset()); } } } finally { myMakingChanges = false; } } } private static class EditorMouseHandler implements EditorMouseListener, EditorMouseMotionListener { public void mouseMoved(EditorMouseEvent event) { } public void mouseDragged(@NotNull EditorMouseEvent event) { if (!VimPlugin.isEnabled()) return; if (event.getArea() == EditorMouseEventArea.EDITING_AREA || event.getArea() != EditorMouseEventArea.ANNOTATIONS_AREA) { if (dragEditor == null) { if (event.getArea() == EditorMouseEventArea.EDITING_AREA) { mode = CommandState.SubMode.VISUAL_CHARACTER; } else if (event.getArea() != EditorMouseEventArea.ANNOTATIONS_AREA) { mode = CommandState.SubMode.VISUAL_LINE; } startOff = event.getEditor().getSelectionModel().getSelectionStart(); endOff = event.getEditor().getSelectionModel().getSelectionEnd(); } dragEditor = event.getEditor(); } } public void mousePressed(EditorMouseEvent event) { } public void mouseClicked(@NotNull EditorMouseEvent event) { if (!VimPlugin.isEnabled()) return; if (event.getArea() == EditorMouseEventArea.EDITING_AREA) { VimPlugin.getMotion().processMouseClick(event.getEditor(), event.getMouseEvent()); } else if (event.getArea() != EditorMouseEventArea.ANNOTATIONS_AREA && event.getArea() != EditorMouseEventArea.FOLDING_OUTLINE_AREA) { VimPlugin.getMotion() .processLineSelection(event.getEditor(), event.getMouseEvent().getButton() == MouseEvent.BUTTON3); } } public void mouseReleased(@NotNull EditorMouseEvent event) { if (!VimPlugin.isEnabled()) return; if (event.getEditor().equals(dragEditor)) { VimPlugin.getMotion().processMouseReleased(event.getEditor(), mode, startOff, endOff); dragEditor = null; } } public void mouseEntered(EditorMouseEvent event) { } public void mouseExited(EditorMouseEvent event) { } @Nullable private Editor dragEditor = null; @NotNull private CommandState.SubMode mode = CommandState.SubMode.NONE; private int startOff; private int endOff; } public int getLastFTCmd() { return lastFTCmd; } public char getLastFTChar() { return lastFTChar; } private int lastFTCmd = 0; private char lastFTChar; @NotNull private final EditorMouseHandler mouseHandler = new EditorMouseHandler(); @NotNull private final EditorSelectionHandler selectionHandler = new EditorSelectionHandler(); }
package com.namelessmc.plugin.common; import java.net.MalformedURLException; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; import com.namelessmc.java_api.ApiError; import com.namelessmc.java_api.NamelessAPI; import com.namelessmc.java_api.NamelessException; import com.namelessmc.java_api.Website; import com.namelessmc.java_api.exception.UnknownNamelessVersionException; import com.namelessmc.java_api.logger.ApiLogger; import com.namelessmc.java_api.logger.JavaLoggerLogger; @SuppressWarnings("OptionalAssignedToNull") public abstract class ApiProvider { private static final String USER_AGENT = "Nameless-Plugin"; private Optional<NamelessAPI> cachedApi; // null if not cached private final Logger logger; public ApiProvider(final Logger logger) { this.logger = logger; } public synchronized Optional<NamelessAPI> getNamelessApi() { if (this.cachedApi != null) { return this.cachedApi; } final ApiLogger debugLogger = this.getDebug() ? new JavaLoggerLogger(this.logger, Level.INFO, "[Nameless-Java-API] ") : null; this.cachedApi = Optional.empty(); try { if (this.getApiUrl().isEmpty()) { this.logger.severe("You have not entered an API URL in the config. Please get your site's API URL from StaffCP > Configuration > API and reload the plugin."); } else { final NamelessAPI api = NamelessAPI.builder() .apiUrl(this.getApiUrl()) .userAgent(USER_AGENT) .withCustomDebugLogger(debugLogger) .build(); final Website info = api.getWebsite(); try { if (GlobalConstants.SUPPORTED_WEBSITE_VERSIONS.contains(info.getParsedVersion())) { this.cachedApi = Optional.of(api); } else { this.logger.severe("Your website runs a version of NamelessMC (" + info.getVersion() + ") that is not supported by this version of the plugin. Note that usually only the newest one or two NamelessMC versions are supported."); } } catch (final UnknownNamelessVersionException e) { this.logger.severe("The plugin doesn't recognize the NamelessMC version you are using. Try updating the plugin to the latest version."); } } } catch (final MalformedURLException e) { this.logger.severe("You have entered an invalid API URL or not entered one at all. Please get an up-to-date API URL from StaffCP > Configuration > API and reload the plugin."); this.logger.severe("Error message: '" + e.getMessage() + "'"); } catch (final ApiError e) { if (e.getError() == ApiError.INVALID_API_KEY) { this.logger.severe("You have entered an invalid API key. Please get an up-to-date API URL from StaffCP > Configuration > API and reload the plugin."); } else { this.logger.severe("Encountered an unexpected error code " + e.getError() + " while trying to connect to your website. Enable api debug mode in the config file for more details. When you think you've fixed the problem, reload the plugin to attempt connecting again."); } } catch (final NamelessException e) { this.logger.warning("Encounted an error when connecting to the website. This message is expected if your site is down temporarily and can be ignored if the plugin works fine otherwise. If the plugin doesn't work as expected, please enable api-debug-mode in the config and run /nlpl reload to get more information."); // Do not cache so it immediately tries again the next time. These types of errors may fix on their // own, so we don't want to break the plugin until the administrator reloads. if (this.getDebug()) { this.logger.warning("Debug is enabled, printing full error message:"); e.printStackTrace(); } this.cachedApi = null; return Optional.empty(); } return this.cachedApi; } protected synchronized void clearCachedApi() { this.cachedApi = null; } protected abstract String getApiUrl(); protected abstract boolean getDebug(); public abstract boolean useUuids(); }
package com.nickhs.testopenxc; import org.achartengine.ChartFactory; import org.achartengine.GraphicalView; import org.achartengine.model.XYMultipleSeriesDataset; import org.achartengine.model.XYSeries; import org.achartengine.renderer.XYMultipleSeriesRenderer; import org.achartengine.renderer.XYSeriesRenderer; import org.achartengine.tools.PanListener; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.graphics.Color; import android.os.Bundle; import android.os.IBinder; import android.preference.PreferenceManager; import android.text.format.Time; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.widget.FrameLayout; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; import com.openxc.VehicleService; import com.openxc.VehicleService.VehicleServiceBinder; import com.openxc.measurements.FineOdometer; import com.openxc.measurements.FuelConsumed; import com.openxc.measurements.IgnitionStatus; import com.openxc.measurements.IgnitionStatus.IgnitionPosition; import com.openxc.measurements.UnrecognizedMeasurementTypeException; import com.openxc.measurements.VehicleMeasurement; import com.openxc.measurements.VehicleSpeed; import com.openxc.remote.NoValueException; import com.openxc.remote.RemoteVehicleServiceException; import com.openxc.remote.sources.trace.TraceVehicleDataSource; import com.openxc.remote.sources.usb.UsbVehicleDataSource; /* TODO: Send the range into a sharedpreferences. * Check on how many points before we die * Broadcast filter for ignition on * Fix getLastData */ public class OpenXCTestActivity extends Activity { VehicleService vehicleService; DbHelper dbHelper; private boolean isBound = false; private boolean isRunning = false; private boolean scrollGraph = true; private static int OPTIMAL_SPEED = 97; private long START_TIME = -1; private int POLL_FREQUENCY = -1; private double lastUsageCount = 0; private int CAN_TIMEOUT = 30; private XYMultipleSeriesRenderer mSpeedRenderer = new XYMultipleSeriesRenderer(); private XYMultipleSeriesRenderer mGasRenderer = new XYMultipleSeriesRenderer(); private XYSeries speedSeries = new XYSeries("Speed"); private XYSeries gasSeries = new XYSeries("Gas Consumed"); // FIXME strings should be hardcoded private GraphicalView mSpeedChartView; private GraphicalView mGasChartView; final static String TAG = "XCTest"; private TextView speed; private TextView mpg; private ToggleButton scroll; private SharedPreferences sharedPrefs; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Log.i(TAG, "onCreated"); speed = (TextView) findViewById(R.id.textSpeed); mpg = (TextView) findViewById(R.id.textMPG); scroll = (ToggleButton) findViewById(R.id.toggleButton1); scroll.setChecked(scrollGraph); scroll.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { scrollGraph = !scrollGraph; scroll.setChecked(scrollGraph); mSpeedRenderer.setYAxisMin(0); mGasRenderer.setYAxisMin(0); } }); sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); sharedPrefs.registerOnSharedPreferenceChangeListener(prefListener); Intent intent = new Intent(this, VehicleService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); dbHelper = new DbHelper(this); XYMultipleSeriesDataset gDataset = initGraph(mGasRenderer, gasSeries); XYMultipleSeriesDataset sDataset = initGraph(mSpeedRenderer, speedSeries); START_TIME = getTime(); if (savedInstanceState != null) { double[] speedX = savedInstanceState.getDoubleArray("speedX"); double[] speedY = savedInstanceState.getDoubleArray("speedY"); for (int i = 0; i < speedX.length; i++) { speedSeries.add(speedX[i], speedY[i]); } double[] gasX = savedInstanceState.getDoubleArray("gasX"); double[] gasY = savedInstanceState.getDoubleArray("gasY"); for (int i = 0; i < gasX.length; i++) { gasSeries.add(gasX[i], gasY[i]); } Log.i(TAG, "Recreated graph"); START_TIME = savedInstanceState.getLong("time"); } mSpeedRenderer.setXTitle("Time (ms)"); mSpeedRenderer.setYTitle("Speed (km/h)"); mGasRenderer.setXTitle("Time (ms)"); mGasRenderer.setYTitle("Fuel Usage (litres)"); XYSeries optimalSpeed = new XYSeries("Optimal Speed"); //TODO String should be referenced from strings.xml optimalSpeed.add(0, OPTIMAL_SPEED); optimalSpeed.add(Integer.MAX_VALUE, OPTIMAL_SPEED); sDataset.addSeries(optimalSpeed); mSpeedRenderer.addSeriesRenderer(1, new XYSeriesRenderer()); mSpeedRenderer.setRange(new double[] {0, 50000, 0, 100}); // FIXME mGasRenderer.setRange(new double[] {0, 50000, 0, 0.03}); FrameLayout topLayout = (FrameLayout) findViewById(R.id.topChart); FrameLayout botLayout = (FrameLayout) findViewById(R.id.botChart); mSpeedChartView = ChartFactory.getTimeChartView(this, sDataset, mSpeedRenderer, null); mSpeedChartView.addPanListener(panListener); topLayout.addView(mSpeedChartView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); mGasChartView = ChartFactory.getTimeChartView(this, gDataset, mGasRenderer, null); mGasChartView.addPanListener(panListener); botLayout.addView(mGasChartView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); Log.i(TAG, "onSaveInstanceState"); outState.putInt("count", speedSeries.getItemCount()); double[] speedX = convertToArray(speedSeries, "x"); double[] speedY = convertToArray(speedSeries, "y"); double[] gasX = convertToArray(gasSeries, "x"); double[] gasY = convertToArray(gasSeries, "y"); outState.putDoubleArray("speedX", speedX); outState.putDoubleArray("speedY", speedY); outState.putDoubleArray("gasX", gasX); outState.putDoubleArray("gasY", gasY); outState.putLong("time", START_TIME); } private double[] convertToArray(XYSeries series, String type) { int count = series.getItemCount(); double[] array = new double[count]; for (int i=0; i < count; i++) { if (type.equalsIgnoreCase("x")) { array[i] = series.getX(i); } else if (type.equalsIgnoreCase("y")) { array[i] = series.getY(i); } else { Log.e(TAG, "Invalid call to convertToArray"); Log.e(TAG, "Type is invalid: "+type); break; } } return array; } @Override protected void onDestroy() { super.onDestroy(); Log.i(TAG, "onDestroy called"); POLL_FREQUENCY = -1; } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { Log.i(TAG, "Option Selected "+item.getItemId()); switch (item.getItemId()) { case R.id.settings: startActivity(new Intent(this, ShowSettingsActivity.class)); break; case R.id.close: System.exit(0); break; case R.id.stopRecording: stopRecording(); break; case R.id.pauseRecording: if (isRunning) { POLL_FREQUENCY = -1; item.setIcon(android.R.drawable.ic_media_play); } else { pollManager(); item.setIcon(android.R.drawable.ic_media_pause); } break; case R.id.viewOverview: startActivity(new Intent(this, MileageActivity.class)); break; case R.id.createData: dbHelper.createTestData(1); break; case R.id.viewGraphs: startActivity(new Intent(this, OverviewActivity.class)); } return super.onOptionsItemSelected(item); } public ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { vehicleService = null; Log.i(TAG, "Service unbound"); isBound = false; } @Override public void onServiceConnected(ComponentName name, IBinder service) { VehicleServiceBinder binder = (VehicleServiceBinder) service; vehicleService = binder.getService(); Log.i(TAG, "Remote Vehicle Service bound"); Log.i(TAG, "Trace file is: "+sharedPrefs.getBoolean("use_trace_file", true)); if (sharedPrefs.getBoolean("use_trace_file", false)) { Log.i(TAG, "Using trace file"); try { vehicleService.setDataSource(TraceVehicleDataSource.class.getName(), "file:///sdcard/drivingnew"); } catch (RemoteVehicleServiceException e) { Log.e(TAG, e.getMessage()); e.printStackTrace(); } } else { try { vehicleService.setDataSource(UsbVehicleDataSource.class.getName(), null); } catch (RemoteVehicleServiceException e) { Log.e(TAG, e.getMessage()); e.printStackTrace(); } } try { vehicleService.addListener(IgnitionStatus.class, ignitionListener); } catch (RemoteVehicleServiceException e) { e.printStackTrace(); } catch (UnrecognizedMeasurementTypeException e) { e.printStackTrace(); } isBound = true; pollManager(); } }; OnSharedPreferenceChangeListener prefListener = new OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Log.i(TAG, "Preference changed: "+key); if (key.equalsIgnoreCase("use_trace_file")) { Log.i(TAG, "finishing"); finish(); startActivity(new Intent(getApplicationContext(), OpenXCTestActivity.class)); } else { pollManager(); } } }; PanListener panListener = new PanListener() { @Override public void panApplied() { scrollGraph = false; scroll.setChecked(false); } }; IgnitionStatus.Listener ignitionListener = new IgnitionStatus.Listener() { @Override public void receive(VehicleMeasurement arg0) { IgnitionPosition ignitionPosition = ((IgnitionStatus) arg0).getValue().enumValue(); Log.i(TAG, "Ignition is "+ignitionPosition.toString()); if (ignitionPosition == IgnitionPosition.OFF) { Log.i(TAG, "Ignition is off. Halting recording"); stopRecording(); } } }; private void drawGraph(double time, double speed, double gas) { speedSeries.add(time, speed); gasSeries.add(time, gas); if (scrollGraph) { if (time > 50000) { // FIXME should be a preference double max = speedSeries.getMaxX(); mSpeedRenderer.setXAxisMax(max+POLL_FREQUENCY); mSpeedRenderer.setXAxisMin(max-50000); //FIXME mGasRenderer.setXAxisMax(max+POLL_FREQUENCY); mGasRenderer.setXAxisMin(max-50000); } } if (mSpeedChartView != null) { mSpeedChartView.repaint(); mGasChartView.repaint(); } } private void updateMeasurements() { if(isBound) { isRunning = true; new Thread(new Runnable () { @Override public void run() { while(true) { if (checkForCANFresh()) getMeasurements(); else stopRecording(); try { Thread.sleep(POLL_FREQUENCY); } catch (InterruptedException e) { Log.e(TAG, "InterruptedException"); } catch (IllegalArgumentException e) { Log.i(TAG, "Breaking out of measurement loop"); isRunning = false; break; } } } }).start(); } else { Log.e(TAG, "No Service Bound - this should not happen"); } } private double getSpeed() { VehicleSpeed speed; double temp = -1; try { speed = (VehicleSpeed) vehicleService.get(VehicleSpeed.class); temp = speed.getValue().doubleValue(); } catch (UnrecognizedMeasurementTypeException e) { e.printStackTrace(); } catch (NoValueException e) { Log.w(TAG, "Failed to get speed measurement"); } return temp; } private double getGasConsumed() { FuelConsumed fuel; double temp = 0; try { fuel = (FuelConsumed) vehicleService.get(FuelConsumed.class); temp = fuel.getValue().doubleValue(); } catch (UnrecognizedMeasurementTypeException e) { e.printStackTrace(); } catch (NoValueException e) { Log.w(TAG, "Failed to get fuel measurement"); } double diff = temp - lastUsageCount; lastUsageCount = temp; if (diff > 1) { // catch bogus values FIXME diff = 0; } return diff; } private boolean checkForCANFresh() { boolean ret = false; try { VehicleSpeed measurement = (VehicleSpeed) vehicleService.get(VehicleSpeed.class); if (measurement.getAge() < CAN_TIMEOUT) ret = true; } catch (UnrecognizedMeasurementTypeException e) { e.printStackTrace(); } catch (NoValueException e) { Log.e(TAG, "NoValueException thrown, ret is "+ret); } return ret; } private void getMeasurements() { double speedm = getSpeed(); double gas = getGasConsumed(); final String temp = Double.toString(speedm); speed.post(new Runnable() { public void run() { speed.setText(temp); } }); final double usage = gas; mpg.post(new Runnable() { public void run() { mpg.setText(Double.toString(usage)); } }); double time = getTime(); drawGraph((time-START_TIME), speedm, gas); } private void pollManager() { String choice = sharedPrefs.getString("update_interval", "1000"); POLL_FREQUENCY = Integer.parseInt(choice); if (!isRunning) updateMeasurements(); } private long getTime() { Time curTime = new Time(); curTime.setToNow(); long time = curTime.toMillis(false); return time; } private void makeToast(String say) { Context context = getApplicationContext(); int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, say, duration); toast.show(); } private void stopRecording() { FineOdometer oMeas; try { oMeas = (FineOdometer) vehicleService.get(FineOdometer.class); final double distanceTravelled = oMeas.getValue().doubleValue(); FuelConsumed fMeas = (FuelConsumed) vehicleService.get(FuelConsumed.class); final double fuelConsumed = fMeas.getValue().doubleValue(); final double gasMileage = distanceTravelled/fuelConsumed; double endTime = getTime(); dbHelper.saveResults(distanceTravelled, fuelConsumed, gasMileage, START_TIME, endTime); startActivity(new Intent(this, OverviewActivity.class)); POLL_FREQUENCY = -1; runOnUiThread(new Runnable() { @Override public void run() { makeToast("Distance moved: "+distanceTravelled+". Fuel Consumed is: "+fuelConsumed+" Last trip gas mileage was: "+gasMileage); } }); vehicleService.removeListener(IgnitionStatus.class, ignitionListener); } catch (UnrecognizedMeasurementTypeException e) { e.printStackTrace(); } catch (NoValueException e) { e.printStackTrace(); } catch (RemoteVehicleServiceException e) { e.printStackTrace(); } } private XYMultipleSeriesDataset initGraph(XYMultipleSeriesRenderer rend, XYSeries series) { rend.setApplyBackgroundColor(true); rend.setBackgroundColor(Color.argb(100, 50, 50, 50)); rend.setAxisTitleTextSize(16); rend.setChartTitleTextSize(20); rend.setLabelsTextSize(15); rend.setLegendTextSize(15); rend.setShowGrid(true); rend.setYAxisMax(100); rend.setYAxisMin(0); rend.setPanLimits(new double[] {0, Integer.MAX_VALUE, 0, 400}); XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset(); dataset.addSeries(series); XYSeriesRenderer tempRend = new XYSeriesRenderer(); tempRend.setLineWidth(2); tempRend.setColor(Color.parseColor("#FFBB33")); rend.addSeriesRenderer(tempRend); return dataset; } }
package com.tech.frontier.network; import com.android.volley.Response.Listener; import com.android.volley.toolbox.JsonArrayRequest; import com.tech.frontier.entities.Article; import com.tech.frontier.listeners.DataListener; import com.tech.frontier.network.handler.ArticleJsonArrayHandler; import com.tech.frontier.network.mgr.RequestQueueMgr; import org.json.JSONArray; import java.util.List; public class ArticleAPIImpl implements ArticleAPI { @Override public void fetchArticles(final DataListener<List<Article>> listener) { JsonArrayRequest request = new JsonArrayRequest( "http: @Override public void onResponse(JSONArray jsonArray) { if (listener != null) { ArticleJsonArrayHandler handler = new ArticleJsonArrayHandler(); listener.onComplete(handler.parse(jsonArray)); } } }, null); RequestQueueMgr.getRequestQueue().add(request); } }
package com.toscana.model.reports; import com.toscana.model.sessions.Session; import com.toscana.model.reports.templates.ReceiptTemplate; import javax.persistence.*; @Entity @Table (name = "cashout") public class ReceiptCashOut { /* * Class methods */ /* * Getters and Setters */ public int getID() { return ID; } public void setID(int ID) { this.ID = ID; } public Session getSession() { return session; } public void setSession(Session session) { this.session = session; } public double getRetirementAmount() { return retirementAmount; } public void setRetirementAmount(double retirementAmount) { this.retirementAmount = retirementAmount; } public String getCurrencyType() { return currencyType; } public void setCurrencyType(String currencyType) { this.currencyType = currencyType; } public ReceiptTemplate getReceiptTempleate() { return receiptTempleate; } public void setReceiptTempleate(ReceiptTemplate receiptTempleate) { this.receiptTempleate = receiptTempleate; } /* * Inner methods */ /* * Attributes */ @Id @Column (name = "ID") @GeneratedValue private int ID; @Column (name = "session") @OneToOne private Session session; @Column (name = "amount") private double retirementAmount; @Column (name = "curencytype") private String currencyType; private ReceiptTemplate receiptTempleate; }
package com.trypto.android.xbettercam; import static com.trypto.android.xbettercam.Constants.*; import static de.robv.android.xposed.XposedHelpers.callMethod; import static de.robv.android.xposed.XposedHelpers.callStaticMethod; import static de.robv.android.xposed.XposedHelpers.findAndHookMethod; import static de.robv.android.xposed.XposedHelpers.findClass; import java.io.File; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.provider.MediaStore; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.XC_MethodHook.MethodHookParam; import de.robv.android.xposed.XSharedPreferences; import de.robv.android.xposed.XposedBridge; import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam; public class XBetterCam implements IXposedHookLoadPackage { private static final String PACKAGE_NAME = XBetterCam.class.getPackage().getName(); final XSharedPreferences prefs = new XSharedPreferences(PACKAGE_NAME); @Override public void handleLoadPackage(final LoadPackageParam lpparam) throws Throwable { if (lpparam.packageName.equals(APP_PACKAGE_CAMERA) || lpparam.packageName.equals(APP_PACKAGE_CAMERA_3D) || lpparam.packageName.equals(APP_PACKAGE_ART_CAMERA) || lpparam.packageName.equals(APP_PACKAGE_SOUND_PHOTO) || lpparam.packageName.equals(APP_PACKAGE_TIMESHIFT)) { final Class<?> AlbumLauncher = findClass(PATH_ALBUM_LAUNCHER, lpparam.classLoader); @SuppressWarnings({ "unchecked", "rawtypes" }) final Class<? extends Enum> CapturingMode = (Class<? extends Enum>) findClass(PATH_CAPTURING_MODE, lpparam.classLoader); @SuppressWarnings("unchecked") final Enum<?> enumPhoto = Enum.valueOf(CapturingMode, "NORMAL"); hookOnResume(lpparam); modLastCapturingMode(lpparam, CapturingMode, enumPhoto); findAndHookMethod(PATH_ALBUM_LAUNCHER, lpparam.classLoader, "launchAlbum", Activity.class, Uri.class, String.class, int.class, boolean.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { if (!prefs.getBoolean("launcher_preference", true)) return; final Activity activity = (Activity) param.args[0]; final Uri uri = (Uri) param.args[1]; final String s = (String) param.args[2]; final boolean b = (Boolean) param.args[4]; if (needsSonyGallery(activity, uri, s, b)) { return; } XposedBridge.log("XBetterCam: Starting user gallery..."); callStaticMethod(AlbumLauncher, "launchPlayer", activity, uri, s); param.setResult(null); } }); findAndHookMethod(PATH_LOCATION_SETTINGS_READER, lpparam.classLoader, "getIsGpsLocationAllowed", new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { if (!prefs.getBoolean("geotag_preference", true)) return; param.setResult(true); } }); } else if (lpparam.packageName.equals(APP_PACKAGE_AR_EFFECT)) { hookOnResume(lpparam); findAndHookMethod(PATH_AR_EFFECT_MAIN_UI, lpparam.classLoader, "launchAlbum", Uri.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { if (!prefs.getBoolean("launcher_preference", true)) return; XposedBridge.log("XBetterCam: Hooking Method launchAlbum in MainUi of AR Effect addon..."); final Uri uri = (Uri) param.args[0]; Activity activity = (Activity) callMethod(param.thisObject, "getActivity"); if (needsSonyGallery(activity, uri, "", false)) { return; } startUserGallery(uri, param, activity); } }); } else if (lpparam.packageName.equals(APP_PACKAGE_BACKGROUND_DEFOCUS)) { hookOnResume(lpparam); findAndHookMethod(PATH_ANDROID_APP_ACTIVITY, lpparam.classLoader, "startActivityForResult", Intent.class, int.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { if (!prefs.getBoolean("launcher_preference", true)) return; XposedBridge.log( "XBetterCam: Hooking Method startActivityForResult in superclass Activity from ViewFinderActivity of Background Defocus addon..."); final Intent intent = (Intent) param.args[0]; if (intent.getAction().equals("android.intent.action.VIEW") || !intent.getPackage().equals("com.sonyericsson.album")) { return; } final Uri uri = intent.getData(); if (needsSonyGallery((Activity) param.thisObject, uri, "", false)) { return; } startUserGallery(uri, param, (Activity) param.thisObject); param.setResult(null); } }); } } private void modLastCapturingMode(final LoadPackageParam lpparam, final Class<? extends Enum> CapturingMode, final Enum<?> enumPhoto) { findAndHookMethod(PATH_CAMERA_ACTIVITY, lpparam.classLoader, "getLastCapturingMode", CapturingMode, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { prefs.reload(); if (!prefs.getBoolean("capture_mode_preference", false)) return; XposedBridge.log("XBetterCam: hooking getLastCapturingMode()"); param.setResult(enumPhoto); } }); findAndHookMethod(PATH_CAMERA_ACTIVITY, lpparam.classLoader, "getLastPreviousCapturingMode", CapturingMode, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { if (!prefs.getBoolean("capture_mode_preference", false)) return; XposedBridge.log("XBetterCam: hooking getLastPreviousCapturingMode()"); param.setResult(enumPhoto); } }); findAndHookMethod(PATH_CAMERA_ACTIVITY, lpparam.classLoader, "getLastPreviousManualMode", CapturingMode, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { if (!prefs.getBoolean("capture_mode_preference", false)) return; XposedBridge.log("XBetterCam: hooking getLastPreviousManualMode()"); param.setResult(enumPhoto); } }); } private void hookOnResume(final LoadPackageParam lpparam) { findAndHookMethod("android.app.Activity", lpparam.classLoader, "onResume", new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { XposedBridge.log("XBetterCam: Entering Activity.performResume()..."); prefs.reload(); } }); } private void startUserGallery(Uri uri, MethodHookParam param, Activity activity) { final Intent intent = new Intent("android.intent.action.VIEW"); intent.addCategory("android.intent.category.DEFAULT"); intent.putExtra("android.intent.extra.finishOnCompletion", true); intent.setDataAndType(uri, MimeType.PHOTO.getText()); if (intent.resolveActivity(activity.getPackageManager()) != null) { XposedBridge.log("XBetterCam: Starting user gallery..."); activity.startActivity(intent); param.setResult(null); } } private boolean needsSonyGallery(final Activity activity, final Uri uri, final String s, final boolean b) { final String realPath = getRealPathFromURI(activity, uri); XposedBridge.log("XBetterCam: Path to medium: " + realPath); boolean mpoPresent = false; if (realPath.toUpperCase().endsWith(".JPG") && (new File(realPath.replaceAll("(?i)\\.JPG$", ".MPO")).exists() || new File(realPath.replaceAll("(?i)\\.JPG$", ".mpo")).exists())) { mpoPresent = true; } if (MimeType.fromText(s) == MimeType.MPO || b || realPath.contains(TIMESHIFT_IDENT) || mpoPresent) { XposedBridge.log("XBetterCam: Fallback to original method"); return true; } return false; } public String getRealPathFromURI(Context context, Uri contentUri) { Cursor cursor = null; try { final String[] proj = { MediaStore.Images.Media.DATA }; cursor = context.getContentResolver().query(contentUri, proj, null, null, null); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } finally { if (cursor != null) { cursor.close(); } } } private enum MimeType { MP4("video/mp4"), MPO("image/mpo"), PHOTO("image/jpeg"), THREEGPP("video/3gpp"), UNKOWN(""); final String mText; private MimeType(final String mText) { this.mText = mText; } static MimeType fromText(final String s) { final MimeType[] values = values(); for (int length = values.length, i = 0; i < length; ++i) { final MimeType mimeType = values[i]; if (mimeType.mText.equals(s)) { return mimeType; } } return MimeType.UNKOWN; } public String getText() { return mText; } } }
package game.control; import game.control.packets.Packet; import game.control.packets.Packet00Login; import game.control.packets.Packet03Engage; import game.control.packets.Packet04Damage; import game.control.packets.Packet05Heal; import game.control.packets.Packet06Interact; import game.control.packets.Packet07Equip; import game.control.packets.Packet.PacketType; import game.control.packets.Packet01Disconnect; import game.control.packets.Packet02Move; import game.control.packets.Packet20GameStart; import game.control.packets.Packet22LoadLevel; import game.model.StealthGame; import gameworld.TestPush; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException; /** * Represents a client in a multiplayer game. * * @author Bieleski, Bryers, Gill & Thompson MMXV. * */ public class GameClient extends Thread { private static final boolean DEBUG = StealthGame.DEBUG; private InetAddress ipAddress; private DatagramSocket socket; private StealthGame game; // TODO this constructor needs to take in a Game paramter public GameClient(String ipAddress, StealthGame game) { this.game = game; // Setup socket try { this.socket = new DatagramSocket(); } catch (SocketException e) { e.printStackTrace(); } // Setup ipAddress try { this.ipAddress = InetAddress.getByName(ipAddress); } catch (UnknownHostException e) { e.printStackTrace(); } } /** * Run the client */ public void run() { while (true) { // Packet and data to be send to server byte[] data = new byte[1024]; DatagramPacket packet = new DatagramPacket(data, data.length); try { socket.receive(packet); } catch (IOException e) { e.printStackTrace(); } this.parsePacket(packet.getData(), packet.getAddress(), packet.getPort()); } } /** * Parse a packet type * * @param data * @param address * @param port */ private void parsePacket(byte[] data, InetAddress address, int port) { String message = new String(data).trim(); PacketType type = Packet.lookupPacket(message.substring(0, 2)); Packet packet = null; if (StealthGame.DEBUG) System.out.println("Client TYPE: " + type.toString()); switch (type) { case INVALID: break; case LOGIN: packet = new Packet00Login(data); handleLogin((Packet00Login) packet, address, port); break; case DISCONNECT: packet = new Packet01Disconnect(data); System.out.println("[" + address.getHostAddress() + ":" + port + "] " + ((Packet01Disconnect) packet).getUsername() + " has left the world..."); game.removePlayer(((Packet01Disconnect) packet).getUsername()); break; case MOVE: packet = new Packet02Move(data); handleMove((Packet02Move) packet); break; case ENGAGE: packet = new Packet03Engage(data); handleEngage((Packet03Engage) packet); break; case DAMAGE: packet = new Packet04Damage(data); handleDamage((Packet04Damage) packet); break; case HEAL: packet = new Packet05Heal(data); handleHeal((Packet05Heal) packet); break; case INTERACT: packet = new Packet06Interact(data); handleInteract((Packet06Interact) packet); break; case EQUIP: packet = new Packet07Equip(data); handleEquip((Packet07Equip) packet); break; case GAME_START: game.run(); break; case GAME_OVER: game.stop(); break; case LOAD_LEVEL: packet = new Packet22LoadLevel(data); handleLoadLevel((Packet22LoadLevel) packet); break; default: break; } } /** * Add a new player to the game * * @param packet * @param address * @param port */ private void handleLogin(Packet00Login packet, InetAddress address, int port) { System.out.println("[ " + address.getHostAddress() + " " + port + " ] " + ((Packet00Login) packet).getUsername() + " has joined the game..."); PlayerMP player = new PlayerMP(packet.getUsername(), address, port); game.addPlayer(player); } /** * Handles a move from the server * * @param packet */ private void handleMove(Packet02Move packet) { game.movePlayer(packet.getUsername(), packet.getX(), packet.getZ(), packet.getDirection()); } private void handleEngage(Packet03Engage packet) { // TODO If guard, the guard should fire his/ her gun. } private void handleDamage(Packet04Damage packet) { // TODO Decrease the health of the player } private void handleHeal(Packet05Heal packet) { // TODO Increase the health of the player } private void handleInteract(Packet06Interact packet) { } private void handleEquip(Packet07Equip packet) { } private void handleLoadLevel(Packet22LoadLevel packet) { System.out.println(packet.getFilename()); game.loadLevel(packet.getFilename()); } /** * Send data to the server * * @param data */ public void sendData(byte[] data) { /* port 1331 might have to be changed */ DatagramPacket packet = new DatagramPacket(data, data.length, ipAddress, 1331); // Send packet try { socket.send(packet); } catch (IOException e) { e.printStackTrace(); } } }
package test; public class Demo { public static void main(String[] args) { System.out.println("ccc1546"); System.out.println("ksajdhas"); System.out.println("aaaa"); System.out.println("jhj"); System.out.println(""); System.out.println("aaaaaaaaaaaa"); System.out.println("sssssssssddaddada"); System.out.println(); for(int i=0;i<10;i++) { } } }
package com.evolveum.midpoint.provisioning.test.ucf; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.assertEquals; import static com.evolveum.midpoint.test.IntegrationTestTools.*; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import javax.xml.bind.JAXBException; import javax.xml.namespace.QName; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.Assert; import org.testng.AssertJUnit; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.w3c.dom.Document; import org.xml.sax.SAXException; import com.evolveum.icf.dummy.resource.DummyAccount; import com.evolveum.icf.dummy.resource.DummyResource; import com.evolveum.icf.dummy.resource.DummySyncStyle; import com.evolveum.midpoint.common.refinery.RefinedResourceSchema; import com.evolveum.midpoint.prism.Containerable; import com.evolveum.midpoint.prism.Item; import com.evolveum.midpoint.prism.PrismContainer; import com.evolveum.midpoint.prism.PrismContainerDefinition; import com.evolveum.midpoint.prism.PrismContainerValue; import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismObjectDefinition; import com.evolveum.midpoint.prism.PrismProperty; import com.evolveum.midpoint.prism.PrismPropertyDefinition; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.schema.PrismSchema; import com.evolveum.midpoint.prism.schema.SchemaRegistry; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.provisioning.ProvisioningTestUtil; import com.evolveum.midpoint.provisioning.ucf.api.Change; import com.evolveum.midpoint.provisioning.ucf.api.ConnectorFactory; import com.evolveum.midpoint.provisioning.ucf.api.ConnectorInstance; import com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException; import com.evolveum.midpoint.provisioning.ucf.api.ResultHandler; import com.evolveum.midpoint.provisioning.ucf.api.UcfException; import com.evolveum.midpoint.provisioning.ucf.impl.ConnectorFactoryIcfImpl; import com.evolveum.midpoint.schema.MidPointPrismContextFactory; import com.evolveum.midpoint.schema.SchemaConstantsGenerated; import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition; import com.evolveum.midpoint.schema.processor.ResourceAttribute; import com.evolveum.midpoint.schema.processor.ResourceAttributeContainer; import com.evolveum.midpoint.schema.processor.ResourceSchema; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.ObjectTypeUtil; import com.evolveum.midpoint.schema.util.ResourceObjectShadowUtil; import com.evolveum.midpoint.schema.util.ResourceTypeUtil; import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.DebugUtil; import com.evolveum.midpoint.util.exception.CommunicationException; import com.evolveum.midpoint.util.exception.ConfigurationException; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_2.AccountShadowType; import com.evolveum.midpoint.xml.ns._public.common.common_2.ConnectorType; import com.evolveum.midpoint.xml.ns._public.common.common_2.ObjectReferenceType; import com.evolveum.midpoint.xml.ns._public.common.common_2.ConnectorConfigurationType; import com.evolveum.midpoint.xml.ns._public.common.common_2.ResourceObjectShadowType; import com.evolveum.midpoint.xml.ns._public.common.common_2.ResourceType; import com.evolveum.prism.xml.ns._public.types_2.PolyStringType; /** * Simple UCF tests. No real resource, just basic setup and sanity. * * @author Radovan Semancik * * This is an UCF test. It shold not need repository or other things from the midPoint spring context * except from the provisioning beans. But due to a general issue with spring context initialization * this is a lesser evil for now (MID-392) */ @ContextConfiguration(locations = { "classpath:application-context-provisioning-test.xml", "classpath:application-context-audit.xml", "classpath:application-context-configuration-test-no-repo.xml" }) public class TestUcfDummy extends AbstractTestNGSpringContextTests { private static final String FILENAME_RESOURCE_DUMMY = "src/test/resources/object/resource-dummy.xml"; private static final String FILENAME_CONNECTOR_DUMMY = "src/test/resources/ucf/connector-dummy.xml"; private static final String ACCOUNT_JACK_USERNAME = "jack"; private static final String ACCOUNT_JACK_FULLNAME = "Jack Sparrow"; private ConnectorFactory manager; private PrismObject<ResourceType> resource; private ResourceType resourceType; private ConnectorType connectorType; private ConnectorInstance cc; private ResourceSchema resourceSchema; private static DummyResource dummyResource; @Autowired(required = true) private ConnectorFactory connectorFactoryIcfImpl; @Autowired(required = true) private PrismContext prismContext; private static Trace LOGGER = TraceManager.getTrace(TestUcfDummy.class); @BeforeClass public void setup() throws SchemaException, SAXException, IOException { displayTestTile("setup"); System.setProperty("midpoint.home", "target/midPointHome/"); DebugUtil.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); dummyResource = DummyResource.getInstance(); dummyResource.reset(); dummyResource.populateWithDefaultSchema(); manager = connectorFactoryIcfImpl; resource = PrismTestUtil.parseObject(new File(FILENAME_RESOURCE_DUMMY)); resourceType = resource.asObjectable(); PrismObject<ConnectorType> connector = PrismTestUtil.parseObject(new File (FILENAME_CONNECTOR_DUMMY)); connectorType = connector.asObjectable(); } @Test public void test000PrismContextSanity() throws ObjectNotFoundException, SchemaException { displayTestTile("test000PrismContextSanity"); SchemaRegistry schemaRegistry = PrismTestUtil.getPrismContext().getSchemaRegistry(); PrismSchema schemaIcfc = schemaRegistry.findSchemaByNamespace(ConnectorFactoryIcfImpl.NS_ICF_CONFIGURATION); assertNotNull("ICFC schema not found in the context ("+ConnectorFactoryIcfImpl.NS_ICF_CONFIGURATION+")", schemaIcfc); PrismContainerDefinition configurationPropertiesDef = schemaIcfc.findContainerDefinitionByElementName(ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_ELEMENT_QNAME); assertNotNull("icfc:configurationProperties not found in icfc schema ("+ ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_ELEMENT_QNAME+")", configurationPropertiesDef); PrismSchema schemaIcfs = schemaRegistry.findSchemaByNamespace(ConnectorFactoryIcfImpl.NS_ICF_SCHEMA); assertNotNull("ICFS schema not found in the context ("+ConnectorFactoryIcfImpl.NS_ICF_SCHEMA+")", schemaIcfs); } @Test public void test001ResourceSanity() throws ObjectNotFoundException, SchemaException { displayTestTile("test001ResourceSanity"); display("Resource", resource); assertEquals("Wrong oid", "ef2bc95b-76e0-59e2-86d6-9999dddddddd", resource.getOid()); // assertEquals("Wrong version", "42", resource.getVersion()); PrismObjectDefinition<ResourceType> resourceDefinition = resource.getDefinition(); assertNotNull("No resource definition", resourceDefinition); PrismAsserts.assertObjectDefinition(resourceDefinition, new QName(SchemaConstantsGenerated.NS_COMMON, "resource"), ResourceType.COMPLEX_TYPE, ResourceType.class); assertEquals("Wrong class in resource", ResourceType.class, resource.getCompileTimeClass()); ResourceType resourceType = resource.asObjectable(); assertNotNull("asObjectable resulted in null", resourceType); assertPropertyValue(resource, "name", PrismTestUtil.createPolyString("Dummy Resource")); assertPropertyDefinition(resource, "name", PolyStringType.COMPLEX_TYPE, 0, 1); PrismContainer<?> configurationContainer = resource.findContainer(ResourceType.F_CONNECTOR_CONFIGURATION); assertContainerDefinition(configurationContainer, "configuration", ConnectorConfigurationType.COMPLEX_TYPE, 1, 1); PrismContainerValue<?> configContainerValue = configurationContainer.getValue(); List<Item<?>> configItems = configContainerValue.getItems(); assertEquals("Wrong number of config items", 1, configItems.size()); PrismContainer<?> dummyConfigPropertiesContainer = configurationContainer.findContainer( ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_ELEMENT_QNAME); assertNotNull("No icfc:configurationProperties container", dummyConfigPropertiesContainer); List<Item<?>> dummyConfigPropItems = dummyConfigPropertiesContainer.getValue().getItems(); assertEquals("Wrong number of dummy ConfigPropItems items", 3, dummyConfigPropItems.size()); } @Test public void test002ConnectorSchema() throws ObjectNotFoundException, SchemaException { displayTestTile("test002ConnectorSchema"); ConnectorInstance cc = manager.createConnectorInstance(connectorType, ResourceTypeUtil.getResourceNamespace(resourceType)); assertNotNull("Failed to instantiate connector", cc); PrismSchema connectorSchema = cc.generateConnectorSchema(); ProvisioningTestUtil.assertConnectorSchemaSanity(connectorSchema, "generated"); assertEquals("Unexpected number of definitions", 3, connectorSchema.getDefinitions().size()); Document xsdSchemaDom = connectorSchema.serializeToXsd(); assertNotNull("No serialized connector schema", xsdSchemaDom); display("Serialized XSD connector schema", DOMUtil.serializeDOMToString(xsdSchemaDom)); // Try to re-parse PrismSchema reparsedConnectorSchema = PrismSchema.parse(DOMUtil.getFirstChildElement(xsdSchemaDom), "schema fetched from "+cc, PrismTestUtil.getPrismContext()); ProvisioningTestUtil.assertConnectorSchemaSanity(reparsedConnectorSchema, "re-parsed"); assertEquals("Unexpected number of definitions in re-parsed schema", 3, reparsedConnectorSchema.getDefinitions().size()); } /** * Test listing connectors. Very simple. Just test that the list is * non-empty and that there are mandatory values filled in. * @throws CommunicationException */ @Test public void test010ListConnectors() throws CommunicationException { displayTestTile("test004ListConnectors"); OperationResult result = new OperationResult(TestUcfDummy.class+".testListConnectors"); Set<ConnectorType> listConnectors = manager.listConnectors(null, result); System.out.println(" assertNotNull(listConnectors); assertFalse(listConnectors.isEmpty()); for (ConnectorType connector : listConnectors) { assertNotNull(connector.getName()); System.out.println("CONNECTOR OID=" + connector.getOid() + ", name=" + connector.getName() + ", version=" + connector.getConnectorVersion()); System.out.println(" System.out.println(ObjectTypeUtil.dump(connector)); System.out.println(" } System.out.println(" } @Test public void test020CreateConfiguredConnector() throws FileNotFoundException, JAXBException, ObjectNotFoundException, CommunicationException, GenericFrameworkException, SchemaException, ConfigurationException { displayTestTile("test004CreateConfiguredConnector"); ConnectorInstance cc = manager.createConnectorInstance(connectorType, ResourceTypeUtil.getResourceNamespace(resourceType)); assertNotNull("Failed to instantiate connector", cc); OperationResult result = new OperationResult(TestUcfDummy.class.getName() + ".testCreateConfiguredConnector"); PrismContainerValue configContainer = resourceType.getConnectorConfiguration().asPrismContainerValue(); display("Configuration container", configContainer); // WHEN cc.configure(configContainer, result); // THEN result.computeStatus("test failed"); assertSuccess("Connector configuration failed", result); // TODO: assert something } @Test public void test030ResourceSchema() throws ObjectNotFoundException, SchemaException, CommunicationException, GenericFrameworkException, ConfigurationException { displayTestTile("test030ResourceSchema"); OperationResult result = new OperationResult(TestUcfDummy.class+".test030ResourceSchema"); cc = manager.createConnectorInstance(connectorType, ResourceTypeUtil.getResourceNamespace(resourceType)); assertNotNull("Failed to instantiate connector", cc); PrismContainerValue configContainer = resourceType.getConnectorConfiguration().asPrismContainerValue(); display("Configuration container", configContainer); cc.configure(configContainer, result); // WHEN resourceSchema = cc.getResourceSchema(result); // THEN display("Generated resource schema", resourceSchema); assertEquals("Unexpected number of definitions", 1, resourceSchema.getDefinitions().size()); ProvisioningTestUtil.assertDummyResourceSchemaSanity(resourceSchema, resourceType); Document xsdSchemaDom = resourceSchema.serializeToXsd(); assertNotNull("No serialized resource schema", xsdSchemaDom); display("Serialized XSD resource schema", DOMUtil.serializeDOMToString(xsdSchemaDom)); // Try to re-parse ResourceSchema reparsedResourceSchema = ResourceSchema.parse(DOMUtil.getFirstChildElement(xsdSchemaDom), "serialized schema", PrismTestUtil.getPrismContext()); assertEquals("Unexpected number of definitions in re-parsed schema", 1, reparsedResourceSchema.getDefinitions().size()); ProvisioningTestUtil.assertDummyResourceSchemaSanity(reparsedResourceSchema, resourceType); } @Test public void test040AddAccount() throws Exception { displayTestTile(this, "test040AddAccount"); OperationResult result = new OperationResult(this.getClass().getName() + ".test040AddAccount"); ObjectClassComplexTypeDefinition defaultAccountDefinition = resourceSchema.findDefaultAccountDefinition(); AccountShadowType shadowType = new AccountShadowType(); PrismTestUtil.getPrismContext().adopt(shadowType); shadowType.setName(PrismTestUtil.createPolyStringType(ACCOUNT_JACK_USERNAME)); ObjectReferenceType resourceRef = new ObjectReferenceType(); resourceRef.setOid(resource.getOid()); shadowType.setResourceRef(resourceRef); shadowType.setObjectClass(defaultAccountDefinition.getTypeName()); PrismObject<AccountShadowType> shadow = shadowType.asPrismObject(); ResourceAttributeContainer attributesContainer = ResourceObjectShadowUtil.getOrCreateAttributesContainer(shadow, defaultAccountDefinition); ResourceAttribute<String> icfsNameProp = attributesContainer.findOrCreateAttribute(ConnectorFactoryIcfImpl.ICFS_NAME); icfsNameProp.setRealValue(ACCOUNT_JACK_USERNAME); // WHEN cc.addObject(shadow, null, result); // THEN DummyAccount dummyAccount = dummyResource.getAccountByUsername(ACCOUNT_JACK_USERNAME); assertNotNull("Account "+ACCOUNT_JACK_USERNAME+" was not created", dummyAccount); assertNotNull("Account "+ACCOUNT_JACK_USERNAME+" has no username", dummyAccount.getUsername()); } @Test public void test050Search() throws UcfException, SchemaException, CommunicationException { displayTestTile("test050Search"); // GIVEN final ObjectClassComplexTypeDefinition accountDefinition = resourceSchema.findDefaultAccountDefinition(); // Determine object class from the schema final List<PrismObject<AccountShadowType>> searchResults = new ArrayList<PrismObject<AccountShadowType>>(); ResultHandler<AccountShadowType> handler = new ResultHandler<AccountShadowType>() { @Override public boolean handle(PrismObject<AccountShadowType> shadow) { System.out.println("Search: found: " + shadow); checkUcfShadow(shadow, accountDefinition); searchResults.add(shadow); return true; } }; OperationResult result = new OperationResult(this.getClass().getName() + ".testSearch"); // WHEN cc.search(AccountShadowType.class, accountDefinition, new ObjectQuery(), handler, result); // THEN assertEquals("Unexpected number of search results", 1, searchResults.size()); } private void checkUcfShadow(PrismObject<AccountShadowType> shadow, ObjectClassComplexTypeDefinition objectClassDefinition) { assertNotNull("No objectClass in shadow "+shadow, shadow.asObjectable().getObjectClass()); assertEquals("Wrong objectClass in shadow "+shadow, objectClassDefinition.getTypeName(), shadow.asObjectable().getObjectClass()); Collection<ResourceAttribute<?>> attributes = ResourceObjectShadowUtil.getAttributes(shadow); assertNotNull("No attributes in shadow "+shadow, attributes); assertFalse("Empty attributes in shadow "+shadow, attributes.isEmpty()); } @Test public void test100FetchEmptyChanges() throws Exception { displayTestTile(this, "test100FetchEmptyChanges"); OperationResult result = new OperationResult(this.getClass().getName() + ".test100FetchEmptyChanges"); ObjectClassComplexTypeDefinition accountDefinition = resourceSchema.findDefaultAccountDefinition(); // WHEN PrismProperty<?> lastToken = cc.fetchCurrentToken(accountDefinition, result); assertNotNull("No last sync token", lastToken); System.out.println("Property:"); System.out.println(lastToken.dump()); PrismPropertyDefinition lastTokenDef = lastToken.getDefinition(); assertNotNull("No last sync token definition", lastTokenDef); assertEquals("Last sync token definition has wrong type", DOMUtil.XSD_INT, lastTokenDef.getTypeName()); assertTrue("Last sync token definition is NOT dynamic", lastTokenDef.isDynamic()); // WHEN List<Change> changes = cc.fetchChanges(accountDefinition, lastToken, result); AssertJUnit.assertEquals(0, changes.size()); } @Test public void test101FetchAddChange() throws Exception { displayTestTile(this, "test101FetchAddChange"); OperationResult result = new OperationResult(this.getClass().getName() + ".test101FetchAddChange"); ObjectClassComplexTypeDefinition accountDefinition = resourceSchema.findDefaultAccountDefinition(); PrismProperty<?> lastToken = cc.fetchCurrentToken(accountDefinition, result); assertNotNull("No last sync token", lastToken); // Add account to the resource dummyResource.setSyncStyle(DummySyncStyle.DUMB); DummyAccount newAccount = new DummyAccount("blackbeard"); newAccount.addAttributeValues("fullname", "Edward Teach"); newAccount.setEnabled(true); newAccount.setPassword("shiverMEtimbers"); dummyResource.addAccount(newAccount); // WHEN List<Change> changes = cc.fetchChanges(accountDefinition, lastToken, result); AssertJUnit.assertEquals(1, changes.size()); Change change = changes.get(0); assertNotNull("null change", change); PrismObject<? extends ResourceObjectShadowType> currentShadow = change.getCurrentShadow(); assertNotNull("null current shadow", currentShadow); PrismAsserts.assertParentConsistency(currentShadow); Collection<ResourceAttribute<?>> identifiers = change.getIdentifiers(); assertNotNull("null identifiers", identifiers); assertFalse("empty identifiers", identifiers.isEmpty()); } private void assertPropertyDefinition(PrismContainer<?> container, String propName, QName xsdType, int minOccurs, int maxOccurs) { QName propQName = new QName(SchemaConstantsGenerated.NS_COMMON, propName); PrismAsserts.assertPropertyDefinition(container, propQName, xsdType, minOccurs, maxOccurs); } public static void assertPropertyValue(PrismContainer<?> container, String propName, Object propValue) { QName propQName = new QName(SchemaConstantsGenerated.NS_COMMON, propName); PrismAsserts.assertPropertyValue(container, propQName, propValue); } private void assertContainerDefinition(PrismContainer container, String contName, QName xsdType, int minOccurs, int maxOccurs) { QName qName = new QName(SchemaConstantsGenerated.NS_COMMON, contName); PrismAsserts.assertDefinition(container.getDefinition(), qName, xsdType, minOccurs, maxOccurs); } }
package nl.idgis.publisher.provider.database; import java.sql.Connection; import akka.event.Logging; import akka.event.LoggingAdapter; import com.typesafe.config.ConfigException; import nl.idgis.publisher.database.JdbcDatabase; import akka.actor.Props; import com.typesafe.config.Config; public class Database extends JdbcDatabase { private final LoggingAdapter log = Logging.getLogger(getContext().system(), this); public Database(Config config, String name) { super(config, name + "-database"); } public static Props props(Config config, String name) { return Props.create(Database.class, config, name); } @Override protected Props createTransaction(Connection connection) throws ConfigException { DatabaseType databaseVendor; if (config.hasPath("vendor")) { try { databaseVendor = DatabaseType.valueOf(config.getString("vendor").toUpperCase()); } catch(IllegalArgumentException iae) { throw new ConfigException.BadValue("vendor", "Invalid vendor supplied in config"); } } else { databaseVendor = DatabaseType.ORACLE; } log.debug(String.format("Using database: %s", databaseVendor.toString())); /* Return props from Oracle or postgres */ switch(databaseVendor) { case ORACLE: return OracleDatabaseTransaction.props(config, connection); case POSTGRES: return PostgresDatabaseTransaction.props(config, connection); default: log.error("Vendor is not supported"); throw new ConfigException.BadValue("database {vendor}", "Invalid vendor supplied in config"); } } }
import uk.co.uwcs.choob.*; import uk.co.uwcs.choob.modules.*; import uk.co.uwcs.choob.support.*; import uk.co.uwcs.choob.support.events.*; import java.util.*; import java.util.regex.*; import java.io.*; import java.net.*; /** * Plugin to retrieve the release date of a particular game from Gameplay.co.uk * @author Chris Hawley (Blood_God) */ public class ReleaseDate { Modules mods; private IRCInterface irc; //ReleaseDate help public String[] helpCommandReleaseDate = { "Attempts to look up a item's release date on Play.com or, if no results are found, Gameplay.co.uk. Results include date or stock information, title, platform and price.", "<TITLE>", "<TITLE> the title of an item that you wish to get information for. This may only contain A-Z0-9.,;:_- and spaces." }; /** * Creates a new instance of ReleaseDate * @param mods The modules available. * @param irc The IRCInterface. */ public ReleaseDate(Modules mods, IRCInterface irc) { this.mods = mods; this.irc = irc; } /** * Get the information for the plugin. * @return The information strings. */ public String[] info() { return new String[] { "Plugin to retrieve the release date of a particular item from Play.com Gameplay.co.uk", "The Choob Team", "choob@uwcs.co.uk", "$Rev$$Date$" }; } //TODO: Return multiple results, and filter out "guide" results - as per the JB version this is re-implementing //FIXME: Occaisionally gameplay add 'style="color: #aabbcc"' to some of the tags currently used for parsing. // These need taking into consideration as they are currently ignored by the regular expressions. /** * The command provided by this plugin. * @param mes The command input from which parameters will be extracted. */ public void commandReleaseDate(Message mes) { String param = mods.util.getParamString(mes); try { //Check for only sensible input with at least one alpha-numeric character. Pattern dodgyCharPattern = Pattern.compile("^[\\s\\w\\-\\:\\;\\.\\,]*[a-zA-Z0-9]+[\\s\\w\\-\\:\\;\\.\\,]*$"); Matcher dodgyCharMatcher = dodgyCharPattern.matcher(param); if (dodgyCharMatcher.matches()) { String playResults = playSearch(param); //Check if we got a viable result from play.com, if so return this - otherwise return whatever gameplay gives us. if ((!playResults.equals("Error looking up results.")) && (!playResults.equals("Sorry, no information was found for \"" + param + "\"."))) { irc.sendContextReply(mes, playResults); } else { String gameplayResults = gameplaySearch(param); irc.sendContextReply(mes, gameplayResults); } } else { irc.sendContextReply(mes, "Sorry, I'm limited to A-Z0-9,._;: hyphen and space characters. At least one alpha-numeric character must be provided."); } } catch (NullPointerException e) { irc.sendContextReply(mes, "Error looking up results."); } catch (IllegalStateException e) { irc.sendContextReply(mes, "Error looking up results."); } } /** * Search Gameplay.co.uk * @param param The parameter to search for on the website. * @returns A message string to display. */ private String gameplaySearch(String param) { try { URL url = generateURL("http://shop.gameplay.co.uk/webstore/advanced_search.asp?keyword=", param); //Info from the following regepx: Title - group 1 Matcher gameplayNoResultMatcher = getMatcher(url, "(?s)" + "Sorry, your search for" + "(.*?)" + "returned no results."); //Info from the following regepx: Title - group 3, Category - group 5, Release date + price - Group 7 Matcher gameplayGotResultMatcher = getMatcher(url, "(?s)" + "<h2 class=\"vlgWhite\">" + "(.*?)" + "<a href=\"productpage.asp?" + "(.*?)" + "class=\"vlgWhite\">" + "(.*?)" + "</a></td></h2>" + "(.*?)" + "<div class=\"vsmorange10\">" + "(.*?)" + "</div>" + "(.*?)" + "<td valign=\"bottom\">" + "(.*?)" + "((RRP)|(<a href=\"add_to_basket))"); //Info from the following regepx: Title - group 1, releasedate - group 5, price - group 3 Matcher gameplaySingleResultMatcher = getMatcher(url, "(?s)" + "<h1 class=\"bbHeader\">" + "(.*?)" + "</h1>" + "(.*?)" + "<td style=\"padding: 6px;\">" + "(.*?)" + "<img src=\"http://shop" + "(.*?)" + "<td valign=\"bottom\" colspan=\"2\">" + "(.*?)" + "<b>Category:</b><a href="); if (gameplayNoResultMatcher.find()) { return "Sorry, no information was found for \"" + param + "\"."; } else if (gameplayGotResultMatcher.find()) { return prettyReply(mods.scrape.readyForIrc(gameplayGotResultMatcher.group(3) + " (" + gameplayGotResultMatcher.group(5) + ")" + gameplayGotResultMatcher.group(7)), url.toString(), 1); } else if (gameplaySingleResultMatcher.find()) { return prettyReply(mods.scrape.readyForIrc(gameplaySingleResultMatcher.group(1) + gameplaySingleResultMatcher.group(5) + gameplaySingleResultMatcher.group(3)), url.toString(), 1); } else { return "There was an error parsing the results. See " + url.toString(); } } catch (LookupException e) { return "Error looking up results."; } catch (NullPointerException e) { return "Error looking up results."; } catch (IllegalStateException e) { return "Error looking up results."; } } /** * Search Play.com * @param param The parameter to search for on the website. * @returns A message string to display. */ private String playSearch(String param) { try { URL url = generateURL("http: Matcher playNoResultMatcher = getMatcher(url, "(?s)" + "<td class=\"textblack\" align=\"center\">There were no results for your search"); Matcher playNoExactResultMatcher = getMatcher(url, "(?s)" + "<p class=\"searchterms\"><span>We could not find an exact match"); //Info from the following regepx: Title - group 4, category - group 1, releasedate - group 5, price - group 6 Matcher playGotResultMatcher = getMatcher(url, "(?s)" + "View results in " + "(.*?)" + " »" + "(.*?)" + "<div class=\"info\"><h5><a href=\"" + "(.*?)" + "Product.html\">" + "(.*?)" + "</a></h5><p class=\"stock\"><span></span>" + "(.*?)" + "</p><h6><span>our price: </span>" + "(.*?)" + " ((Delivered</h6><p class=\"saving\">RRP)|(Delivered</h6><div class=\"buy\">))"); //Info from the following regepx: title - group 2, releasedate - group 3, price - group 4 Matcher playAlternativeResultMatcher = getMatcher(url, "(?s)" + "<div class=\"info\"><h5><a href=\"" + "(.*?)" + "Product.html\">" + "(.*?)" + "</a></h5><p class=\"stock\"><span></span>" + "(.*?)" + "</p><h6><span>our price: </span>" + "(.*?)" + " Delivered</h6><p class=\"saving\">RRP"); //Info from the following regexp: title - group 6, category - group 1, releasedate - group 7, price - group 8 Matcher playResultMatcherThree = getMatcher(url, "(?s)<span>Searching for (.*?) titles containing(.*?)</span></p><p class=\"results\"><span>Results </span><STRONG>(.*?)</STRONG></p></div><div class=\"slice\"><table cellspacing=\"0\"><tr><td><div class=\"image\">(.*?)</div></td><td class=\"wide\"><div class=\"info\"><h5><a href=\"(.*?)\">(.*?)</a></h5><p class=\"stock\"><span></span>(.*?)</p><h6><span>our price: </span>(.*?) Delivered</h6><div class=\"buy\">"); //Info from the following regexp: title - group 1, releasedate - group 4, price - group 3 Matcher playProductPageMatcher = getMatcher(url, "(?s)" + "<div class=\"texthead\"><div><div><h2>" + "(.*?)" + "</h2></div></div></div><div class=\"box\">" + "(.*?)" + "<div class=\"info\"><h6><span><span>our price:</span> </span>" + "(.*?)" + " Delivered</h6><p class=\"stock\"><span>availability: </span>" + "(.*?)" + "</p><p class=\"note\">"); if (playNoResultMatcher.find()) { return "Sorry, no information was found for \"" + param + "\"."; } else if (playNoExactResultMatcher.find()) { return "Sorry, no information was found for \"" + param + "\"."; } else if (playGotResultMatcher.find()) { return prettyReply(mods.scrape.readyForIrc("<b>" + playGotResultMatcher.group(4) + "</b> (" + playGotResultMatcher.group(1) + ") " + playGotResultMatcher.group(5).replaceAll("<br/>", "<b> ") + "</b> Play.com price:" + playGotResultMatcher.group(6)), url.toString(), 1); } else if (playAlternativeResultMatcher.find()) { return prettyReply(mods.scrape.readyForIrc("<b>" + playAlternativeResultMatcher.group(2) + "</b> " + playAlternativeResultMatcher.group(3).replaceAll("<br/>", "<b> ") + "</b> Play.com price:" + playAlternativeResultMatcher.group(4)), url.toString(), 1); } else if (playResultMatcherThree.find()) { return prettyReply(mods.scrape.readyForIrc("<b>" + playResultMatcherThree.group(6) + "</b> (" + playResultMatcherThree.group(1) + ") " + playResultMatcherThree.group(7).replaceAll("<br/>", "<b> ") + "</b> Play.com price:" + playResultMatcherThree.group(8)), url.toString(), 1); } else if (playProductPageMatcher.find()) { return prettyReply(mods.scrape.readyForIrc("<b>" + playProductPageMatcher.group(1) + "</b> " + playProductPageMatcher.group(4).replaceAll("<br/>", "<b> ") + "</b> Play.com price: " + playProductPageMatcher.group(3)), url.toString(), 1); } else { return "There was an error parsing the results. See " + url.toString(); } } catch (LookupException e) { return "Error looking up results."; } catch (NullPointerException e) { return "Error looking up results."; } catch (IllegalStateException e) { return "Error looking up results."; } } /* -- Start of code stolen from Dict.java -- */ private String prettyReply(String text, String url, int lines) { int maxlen=((irc.MAX_MESSAGE_LENGTH-15)*lines) - url.length(); text=text.replaceAll("\\s+"," "); if (text.length()>maxlen) { return text.substring(0, maxlen) + "..., see " + url; } else { return text + " See " + url; } } private URL generateURL(String base, String url) throws LookupException { try { return new URL(base + URLEncoder.encode(url, "UTF-8")); } catch (UnsupportedEncodingException e) { throw new LookupException("Unexpected exception generating url.", e); } catch (MalformedURLException e) { throw new LookupException("Error, malformed url generated.", e); } } private Matcher getMatcher(URL url, String pat) throws LookupException { try { return mods.scrape.getMatcher(url, pat); } catch (FileNotFoundException e) { throw new LookupException("No article found (404).", e); } catch (IOException e) { throw new LookupException("Error reading from site. " + e, e); } } /* -- End of stolen code -- */ } public class LookupException extends ChoobException { public LookupException(String text) { super(text); } public LookupException(String text, Throwable e) { super(text, e); } public String toString() { return getMessage(); } }
package com.neverwinterdp.scribengin.dataflow.operator; import com.neverwinterdp.registry.task.TaskStatus; import com.neverwinterdp.registry.task.dedicated.DedicatedTaskContext; import com.neverwinterdp.registry.task.dedicated.TaskSlotExecutor; import com.neverwinterdp.scribengin.dataflow.registry.DataflowRegistry; import com.neverwinterdp.scribengin.dataflow.worker.WorkerService; import com.neverwinterdp.scribengin.storage.Record; public class OperatorTaskSlotExecutor extends TaskSlotExecutor<OperatorTaskConfig>{ private WorkerService workerService; private DedicatedTaskContext<OperatorTaskConfig> taskContext; private OperatorTaskConfig operatorTaskConfig; private Operator operator; private OperatorContext context; private long startTime = 0; private long lastFlushTime = System.currentTimeMillis(); private long lastNoMessageTime ; public OperatorTaskSlotExecutor(WorkerService service, DedicatedTaskContext<OperatorTaskConfig> taskContext) throws Exception { super(taskContext); this.workerService = service; this.taskContext = taskContext; this.operatorTaskConfig = taskContext.getTaskDescriptor(false); Class<Operator> opType = (Class<Operator>) Class.forName(operatorTaskConfig.getOperator()); operator = opType.newInstance(); startTime = System.currentTimeMillis(); DataflowRegistry dRegistry = workerService.getDataflowRegistry(); OperatorTaskReport report = dRegistry.getTaskRegistry().getTaskReport(operatorTaskConfig); report.incrAssignedCount(); dRegistry.getTaskRegistry().save(operatorTaskConfig, report); context = new OperatorContext(workerService, operatorTaskConfig, report); dRegistry.getTaskRegistry().save(operatorTaskConfig, report); } public DedicatedTaskContext<OperatorTaskConfig> getTaskContext() { return this.taskContext; } public OperatorTaskConfig getDescriptor() { return operatorTaskConfig ; } public boolean isComplete() { return context.isComplete() ; } @Override public void executeSlot() throws Exception { startTime = System.currentTimeMillis(); OperatorTaskReport report = context.getTaskReport(); int recCount = 0; try { while(!isInterrupted()) { Record record = context.nextRecord(1000); if(record == null) break ; recCount++; report.incrProcessCount(); operator.process(context, record); } //end while long currentTime = System.currentTimeMillis(); if(recCount == 0) { if(lastNoMessageTime < 0) lastNoMessageTime = currentTime; report.setAssignedWithNoMessageProcess(report.getAssignedWithNoMessageProcess() + 1); report.setLastAssignedWithNoMessageProcess(report.getLastAssignedWithNoMessageProcess() + 1); if(lastNoMessageTime + 30000 < currentTime) { getTaskContext().setComplete(); context.setComplete(); } } else { report.setLastAssignedWithNoMessageProcess(0); lastNoMessageTime = -1; } report.addAccRuntime(currentTime - startTime); if(context.isComplete() || report.getProcessCount() > 200000 || lastFlushTime + 30000 < currentTime) { updateContext(); } } catch(InterruptedException ex) { //kill simulation throw ex ; } catch(Throwable t) { report.setAssignedHasErrorCount(report.getAssignedHasErrorCount() + 1); workerService.getLogger().error("DataflowTask Error", t); t.printStackTrace(); } } public void suspend() throws Exception { saveContext(); DataflowRegistry dflRegistry = workerService.getDataflowRegistry(); dflRegistry.getTaskRegistry().suspend(taskContext); } public void finish() throws Exception { OperatorTaskReport report = context.getTaskReport(); report.setFinishTime(System.currentTimeMillis()); saveContext(); DataflowRegistry dflRegistry = workerService.getDataflowRegistry(); dflRegistry.getTaskRegistry().finish(taskContext, TaskStatus.TERMINATED); } void saveContext() { try { OperatorTaskReport report = context.getTaskReport(); report.addAccRuntime(System.currentTimeMillis() - startTime); context.commit(); context.close(); } catch(Exception ex) { workerService.getLogger().error("Cannot save the executor context due to the error: " + ex); } } void updateContext() throws Exception { OperatorTaskReport report = context.getTaskReport(); context.commit(); } }
package no.steria.skuldsku.recorder.dbrecorder.impl.oracle; import no.steria.skuldsku.recorder.dbrecorder.DatabaseRecorder; import no.steria.skuldsku.recorder.logging.RecorderLog; import no.steria.skuldsku.utils.*; import javax.sql.DataSource; import java.io.PrintWriter; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import static no.steria.skuldsku.DatabaseTableNames.SKULDSKU_DATABASE_TABLE_PREFIX; import static no.steria.skuldsku.DatabaseTableNames.DATABASE_RECORDINGS_TABLE; public class OracleDatabaseRecorder implements DatabaseRecorder { private static final int MAX_TRIGGER_NAME_LENGTH = 30; private List<String> ignoredTables = new ArrayList<>(); private final TransactionManager transactionManager; public OracleDatabaseRecorder(DataSource dataSource) { this(new SimpleTransactionManager(dataSource), new ArrayList<String>(0)); } public OracleDatabaseRecorder(DataSource dataSource, List<String> ignoredTables) { this(new SimpleTransactionManager(dataSource), ignoredTables); } OracleDatabaseRecorder(TransactionManager transactionManager, List<String> ignoredTables) { this.transactionManager = transactionManager; this.ignoredTables = ignoredTables; } @Override public void initialize() { transactionManager.doInTransaction(new TransactionCallback<Object>() { @Override public Object callback(Jdbc jdbc) { createRecorderTableIfNotExists(jdbc); createDbSequenceIfNotExists(jdbc); return null; } }); } @Override public void start() { createTriggersInTransaction(); } @Override public void stop() { dropRecorderTriggers(); } @Override public void tearDown() { dropRecorderTriggers(); dropRecorderTable(); } @Override public void exportTo(final PrintWriter out) { transactionManager.doInTransaction(new TransactionCallback<Object>() { @Override public Object callback(Jdbc jdbc) { jdbc.query("SELECT 'CLIENT_IDENTIFIER='||CLIENT_IDENTIFIER||';SESSION_USER='||SESSION_USER||';SESSIONID='|" + "|SESSIONID||';TABLE_NAME='||TABLE_NAME||';ACTION='||ACTION||';'||DATAROW AS DATA FROM " + DATABASE_RECORDINGS_TABLE + " ORDER BY SKS_ID", new ResultSetCallback() { @Override public void extractData(ResultSet rs) throws SQLException { while (rs.next()) { out.println(rs.getString(1)); } } }); return null; } }); } /** * * @param out Exports all database recordings, but without the field session ID, so that results from different * executions can be easily compared (for unit-test level integration tests). */ public void exportWithoutSessionIdTo(final PrintWriter out) { transactionManager.doInTransaction(new TransactionCallback<Object>() { @Override public Object callback(Jdbc jdbc) { jdbc.query("SELECT 'CLIENT_IDENTIFIER='||CLIENT_IDENTIFIER||';SESSION_USER='||SESSION_USER||'" + ";TABLE_NAME='||TABLE_NAME||';ACTION='||ACTION||';'||DATAROW AS DATA FROM " + DATABASE_RECORDINGS_TABLE + " ORDER BY SKS_ID", new ResultSetCallback() { @Override public void extractData(ResultSet rs) throws SQLException { while (rs.next()) { out.println(rs.getString(1)); } } }); return null; } }); } public void exportAndRemove(final PrintWriter out) { final List<String> retrievedDataIds = new ArrayList<>(); transactionManager.doInTransaction(new TransactionCallback<Object>() { @Override public Object callback(Jdbc jdbc) { jdbc.query("SELECT " + SKULDSKU_DATABASE_TABLE_PREFIX + "ID, 'CLIENT_IDENTIFIER='||CLIENT_IDENTIFIER||';SESSION_USER='||SESSION_USER||';SESSIONID='||SESSIONID||';TABLE_NAME='||TABLE_NAME||';ACTION='||ACTION||';'||DATAROW AS DATA FROM " + DATABASE_RECORDINGS_TABLE + " ORDER BY SKS_ID", new ResultSetCallback() { @Override public void extractData(ResultSet rs) throws SQLException { while (rs.next()) { retrievedDataIds.add(rs.getString(1)); out.println(rs.getString(2)); } } }); return null; } }); out.flush(); /* * Deleting after select in order to avoid forcing the database to maintain * two different versions of the data while the select is running. */ transactionManager.doInTransaction(new TransactionCallback<Object>() { @Override public Object callback(Jdbc jdbc) { for (String id : retrievedDataIds) { jdbc.execute("DELETE FROM " + DATABASE_RECORDINGS_TABLE + " WHERE " + SKULDSKU_DATABASE_TABLE_PREFIX + "ID = " + id); } return null; } }); } void dropRecorderTable() { transactionManager.doInTransaction(new TransactionCallback<Object>() { @Override public Object callback(Jdbc jdbc) { try { jdbc.execute("DROP TABLE " + DATABASE_RECORDINGS_TABLE); } catch (JdbcException e) { RecorderLog.error("Could not drop table " + DATABASE_RECORDINGS_TABLE, e); } try { jdbc.execute("DROP SEQUENCE " + SKULDSKU_DATABASE_TABLE_PREFIX + "RECORDER_ID_SEQ"); } catch (JdbcException e) { RecorderLog.error("Could not drop sequence " + SKULDSKU_DATABASE_TABLE_PREFIX + "RECORDER_ID_SEQ", e); } return null; } }); } private void dropRecorderTriggers() { transactionManager.doInTransaction(new TransactionCallback<Object>() { @Override public Object callback(Jdbc jdbc) { for (String triggerName : getTriggerNames(jdbc)) { if (isSkuldskuTrigger(triggerName)) { jdbc.execute("DROP TRIGGER " + triggerName); } } return null; } }); } List<String> getTriggerNames(Jdbc jdbc) { return jdbc.queryForList("SELECT TRIGGER_NAME FROM USER_TRIGGERS", String.class); } private void createRecorderTableIfNotExists(Jdbc jdbc) { List<String> recorderTable = jdbc.queryForList( "select table_name from all_tables where table_name='" + DATABASE_RECORDINGS_TABLE + "'", String.class); if (recorderTable.isEmpty()) { jdbc.execute("CREATE TABLE " + DATABASE_RECORDINGS_TABLE + " (\n" + " " + SKULDSKU_DATABASE_TABLE_PREFIX + "ID NUMBER,\n" + " CLIENT_IDENTIFIER VARCHAR2(256),\n" + " SESSION_USER VARCHAR2(256),\n" + " SESSIONID VARCHAR2(256),\n" + " TABLE_NAME VARCHAR2(30),\n" + " ACTION VARCHAR2(6),\n" + " DATAROW CLOB \n" + ")"); } } private void createDbSequenceIfNotExists(Jdbc jdbc) { List<String> recorderTrigger = jdbc.queryForList( "select sequence_name from all_sequences where sequence_name='" + SKULDSKU_DATABASE_TABLE_PREFIX + "RECORDER_ID_SEQ'", String.class); if (recorderTrigger.isEmpty()) { jdbc.execute("CREATE SEQUENCE " + SKULDSKU_DATABASE_TABLE_PREFIX + "RECORDER_ID_SEQ"); } } void createTriggersInTransaction() { transactionManager.doInTransaction(new TransactionCallback<Object>() { @Override public Object callback(Jdbc jdbc) { createTriggers(jdbc); return null; } }); } void createTriggers(Jdbc jdbc) { for (String tableName : getTableNames(jdbc)) { if (isSkuldskuTrigger(tableName) || isIgnoredTable(tableName)) { continue; } final List<String> columnNames = getColumnNames(jdbc, tableName); if (columnNames.isEmpty()) { RecorderLog.debug("Ignoring table with no columns: " + tableName); continue; } try { createTrigger(jdbc, tableName, columnNames); } catch (JdbcException e) { RecorderLog.debug("Ignoring table: " + tableName + " (" + e.getMessage() + ")"); } } } private void createTrigger(Jdbc jdbc, String tableName, final List<String> columnNames) { final String triggerSql = TriggerSqlGenerator.generateTriggerSql( reduceToMaxLength(SKULDSKU_DATABASE_TABLE_PREFIX + tableName, MAX_TRIGGER_NAME_LENGTH), tableName, columnNames); jdbc.execute(triggerSql); } List<String> getTableNames(Jdbc jdbc) { return jdbc.queryForList("SELECT TABLE_NAME FROM USER_TABLES", String.class); } List<String> getColumnNames(Jdbc jdbc, String tableName) { return jdbc.queryForList("SELECT COLUMN_NAME FROM USER_TAB_COLS WHERE TABLE_NAME = ? ORDER BY COLUMN_NAME", String.class, tableName); } private boolean isSkuldskuTrigger(String resourceName) { return resourceName.toUpperCase().startsWith(SKULDSKU_DATABASE_TABLE_PREFIX); } private boolean isIgnoredTable(String tableName) { for (String ignoredTable : ignoredTables) { if (tableName.equalsIgnoreCase(ignoredTable)) { return true; } } return false; } String reduceToMaxLength(String s, int length) { return (s.length() <= length) ? s : s.substring(0, length); } }
package com.splicemachine.derby.impl.sql.execute.operations.joins; import com.splicemachine.derby.test.framework.SpliceSchemaWatcher; import com.splicemachine.derby.test.framework.SpliceWatcher; import com.splicemachine.test_tools.TableCreator; import org.junit.*; import org.junit.rules.RuleChain; import org.junit.rules.TestRule; import java.sql.Connection; import java.util.List; import static com.splicemachine.test_tools.Rows.row; import static com.splicemachine.test_tools.Rows.rows; import static org.junit.Assert.assertEquals; /** * Tests various permutations of join strategy and inclusion of RTRIM function * in predicate. */ public class JoinWithTrimIT { // These tests were derived from some Wells Fargo POC defects, // for example DB-4921, DB-4922, DB-4883. private static final String SCHEMA = JoinWithTrimIT.class.getSimpleName().toUpperCase(); private static final SpliceWatcher spliceClassWatcher = new SpliceWatcher(SCHEMA); private static final SpliceSchemaWatcher spliceSchemaWatcher = new SpliceSchemaWatcher(SCHEMA); private static final String NESTED_LOOP = "--SPLICE-PROPERTIES joinStrategy=NESTEDLOOP"; private static final String BROADCAST = "--SPLICE-PROPERTIES joinStrategy=BROADCAST"; private static final String MERGE_SORT = "--SPLICE-PROPERTIES joinStrategy=SORTMERGE"; private static final String RTRIM = "RTRIM"; private static final String TRIM = "TRIM"; @ClassRule public static TestRule chain = RuleChain.outerRule(spliceClassWatcher) .around(spliceSchemaWatcher); @Rule public final SpliceWatcher methodWatcher = new SpliceWatcher(SCHEMA); @BeforeClass public static void createSharedTables() throws Exception { Connection conn = spliceClassWatcher.getOrCreateConnection(); // There is a method to the madness with the following column widths. // They correspond to what Wells Fargo has in their production schema. // Having the id be varchar(6) in one table and varchar(16) in the other // is also good in that exposes potential edge cases to test. // t1 - pad/nopad/nopad/pad // padded to 6 chars within varchar(6) TableCreator tableCreator = new TableCreator(conn) .withCreate("CREATE TABLE %s (id varchar(6), info varchar(32))") .withInsert("insert into %s values (?,?)") .withRows(rows( row("1 ", "small info 1"), row("2", "small info 2"), row("3", "small info e"), row("4 ", "small info 4"))); tableCreator.withTableName("t1").create(); // t2 - pad/nopad/pad/nopad // padded to 12 chars (not 6) within varchar(16) (not 6, not 12) TableCreator tableCreator2 = new TableCreator(conn) .withCreate("CREATE TABLE %s (id varchar(16), info varchar(32))") .withInsert("insert into %s values (?,?)") .withRows(rows( row("1 ", "info 1"), row("2", "info 2"), row("3 ", "info 3"), row("4", "info 4"))); tableCreator2.withTableName("t2").create(); } String ROWS_MSG = "Incorrect number of rows returned"; String SQL_NO_TRIM = "select t1.id, t2.id from --SPLICE-PROPERTIES joinOrder=fixed\n" + "t1 inner join t2 %s\n" + "on t1.id = t2.id order by t1.id"; String SQL_TRIM_LEFT_OP = "select t1.id, t2.id from --SPLICE-PROPERTIES joinOrder=fixed\n" + "t1 inner join t2 %s\n" + "on %s(t1.id) = t2.id order by t1.id"; String SQL_TRIM_RIGHT_OP = "select t1.id, t2.id from --SPLICE-PROPERTIES joinOrder=fixed\n" + "t1 inner join t2 %s\n" + "on t1.id = %s(t2.id) order by t1.id"; String SQL_TRIM_BOTH = "select t1.id, t2.id from --SPLICE-PROPERTIES joinOrder=fixed\n" + "t1 inner join t2 %s\n" + "on %s(t1.id) = %s(t2.id) order by t1.id"; String SQL_TRIM_BOTH_REVERSE_TABLE_ORDER = "select t1.id, t2.id from --SPLICE-PROPERTIES joinOrder=fixed\n" + "t2 inner join t1 %s\n" + "on %s(t1.id) = %s(t2.id) order by t1.id"; @Test public void testNoTrimNoHint() throws Exception { // Needed because occasionally an explicit join hint will cause infeasible plan error, // but if we remove hint, optimizer picks that join strategy anyway. assertNoTrimResult(methodWatcher.queryListMulti(String.format(SQL_NO_TRIM, ""), 2)); } @Test public void testNoTrimNestedLoop() throws Exception { assertNoTrimResult(methodWatcher.queryListMulti(String.format(SQL_NO_TRIM, NESTED_LOOP), 2)); } @Test public void testNoTrimBroadcast() throws Exception { assertNoTrimResult(methodWatcher.queryListMulti(String.format(SQL_NO_TRIM, BROADCAST), 2)); } @Test public void testNoTrimMergeSort() throws Exception { assertNoTrimResult(methodWatcher.queryListMulti(String.format(SQL_NO_TRIM, MERGE_SORT), 2)); } @Test public void testLeftOpTrimNoHint() throws Exception { // Needed because occasionally an explicit join hint will cause infeasible plan error, // but if we remove hint, optimizer picks that join strategy anyway. assertLeftOpTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_LEFT_OP, "", RTRIM), 2)); assertLeftOpTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_LEFT_OP, "", TRIM), 2)); } @Test public void testLeftOpTrimNestedLoop() throws Exception { assertLeftOpTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_LEFT_OP, NESTED_LOOP, RTRIM), 2)); assertLeftOpTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_LEFT_OP, NESTED_LOOP, TRIM), 2)); } @Test public void testLeftOpTrimBroadcast() throws Exception { assertLeftOpTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_LEFT_OP, BROADCAST, RTRIM), 2)); assertLeftOpTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_LEFT_OP, BROADCAST, TRIM), 2)); } @Test public void testLeftOpTrimMergeSort() throws Exception { assertLeftOpTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_LEFT_OP, MERGE_SORT, RTRIM), 2)); assertLeftOpTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_LEFT_OP, MERGE_SORT, TRIM), 2)); } @Test public void testRightOpTrimNoHint() throws Exception { // Needed because occasionally an explicit join hint will cause infeasible plan error, // but if we remove hint, optimizer picks that join strategy anyway. assertRightOpTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_RIGHT_OP, "", RTRIM), 2)); assertRightOpTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_RIGHT_OP, "", TRIM), 2)); } @Test public void testRightOpTrimNestedLoop() throws Exception { assertRightOpTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_RIGHT_OP, NESTED_LOOP, RTRIM), 2)); assertRightOpTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_RIGHT_OP, NESTED_LOOP, TRIM), 2)); } // Commented out rather then skipped because plan is not valid. Keep here for reference. // @Test // public void testRightOpTrimBroadcast() throws Exception { // assertRightOpTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_RIGHT_OP, BROADCAST, RTRIM), 2)); // Commented out rather then skipped because plan is not valid. Keep here for reference. // @Test // public void testRightOpTrimSortMerge() throws Exception { // assertRightOpTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_RIGHT_OP, MERGE_SORT, RTRIM), 2)); @Test public void testBothTrimNoHint() throws Exception { // Needed because occasionally an explicit join hint will cause infeasible plan error, // but if we remove hint, optimizer picks that join strategy anyway. assertBothTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_BOTH, "", RTRIM, RTRIM), 2)); assertBothTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_BOTH, "", TRIM, RTRIM), 2)); assertBothTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_BOTH, "", RTRIM, TRIM), 2)); assertBothTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_BOTH, "", TRIM, TRIM), 2)); } @Test public void testBothTrimNestedLoop() throws Exception { assertBothTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_BOTH, NESTED_LOOP, RTRIM, RTRIM), 2)); assertBothTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_BOTH, NESTED_LOOP, RTRIM, TRIM), 2)); assertBothTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_BOTH, NESTED_LOOP, TRIM, RTRIM), 2)); assertBothTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_BOTH, NESTED_LOOP, TRIM, TRIM), 2)); } // Commented out rather then skipped because plan is not valid. Keep here for reference. // @Test // public void testBothTrimBroadcast() throws Exception { // assertBothTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_BOTH, BROADCAST, RTRIM, RTRIM), 2)); // Commented out rather then skipped because plan is not valid. Keep here for reference. // @Test // public void testBothTrimMergeSort() throws Exception { // assertBothTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_BOTH, MERGE_SORT, RTRIM, RTRIM), 2)); @Test public void testBothTrimNoHintReverse() throws Exception { assertBothTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_BOTH_REVERSE_TABLE_ORDER, "", RTRIM, RTRIM), 2)); assertBothTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_BOTH_REVERSE_TABLE_ORDER, "", RTRIM, TRIM), 2)); assertBothTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_BOTH_REVERSE_TABLE_ORDER, "", TRIM, RTRIM), 2)); assertBothTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_BOTH_REVERSE_TABLE_ORDER, "", TRIM, TRIM), 2)); } @Test public void testBothTrimNestedLoopReverse() throws Exception { assertBothTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_BOTH_REVERSE_TABLE_ORDER, NESTED_LOOP, RTRIM, RTRIM), 2)); assertBothTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_BOTH_REVERSE_TABLE_ORDER, NESTED_LOOP, RTRIM, TRIM), 2)); assertBothTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_BOTH_REVERSE_TABLE_ORDER, NESTED_LOOP, TRIM, RTRIM), 2)); assertBothTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_BOTH_REVERSE_TABLE_ORDER, NESTED_LOOP, TRIM, TRIM), 2)); } // Commented out rather then skipped because plan is not valid. Keep here for reference. // @Test // public void testBothTrimBroadcastReverse() throws Exception { // assertBothTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_BOTH_REVERSE_TABLE_ORDER, BROADCAST, RTRIM), 2)); // Commented out rather then skipped because plan is not valid. Keep here for reference. // @Test // public void testBothTrimMergeSortReverse() throws Exception { // assertBothTrimResult(methodWatcher.queryListMulti(String.format(SQL_TRIM_BOTH_REVERSE_TABLE_ORDER, MERGE_SORT, RTRIM), 2)); private void assertNoTrimResult(List<Object[]> result) throws Exception { assertEquals(ROWS_MSG, 1, result.size()); assertRow(1, result, "2", "2"); } private void assertLeftOpTrimResult(List<Object[]> result) throws Exception { assertEquals(ROWS_MSG, 2, result.size()); assertRow(1, result, "2", "2"); assertRow(2, result, "4 ", "4"); } private void assertRightOpTrimResult(List<Object[]> result) throws Exception { assertEquals(ROWS_MSG, 2, result.size()); assertRow(1, result, "2", "2"); assertRow(2, result, "3", "3 "); } private void assertBothTrimResult(List<Object[]> result) throws Exception { assertEquals(ROWS_MSG, 4, result.size()); assertRow(1, result, "1 ", "1 "); assertRow(2, result, "2", "2"); assertRow(3, result, "3", "3 "); assertRow(4, result, "4 ", "4"); } private void assertRow(int rowNum, List<Object[]> result, String v1, String v2) { assertEquals(String.format("Wrong result row %d, col 1", rowNum), v1, result.get(rowNum - 1)[0].toString()); assertEquals(String.format("Wrong result row %d, col 2", rowNum), v2, result.get(rowNum - 1)[1].toString()); } }
package imj2.tools; import static imj.IMJTools.loadAndTryToCache; import static imj.database.IMJDatabaseTools.RGB; import static imj.database.IMJDatabaseTools.getPreferredMetric; import static imj.database.IMJDatabaseTools.newBKDatabase; import static imj.database.IMJDatabaseTools.newSampler; import static java.lang.Integer.parseInt; import static net.sourceforge.aprog.tools.Tools.debugPrint; import static net.sourceforge.aprog.tools.Tools.gc; import static net.sourceforge.aprog.xml.XMLTools.getNode; import static net.sourceforge.aprog.xml.XMLTools.getNodes; import static net.sourceforge.aprog.xml.XMLTools.parse; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.imageio.ImageIO; import jgencode.primitivelists.IntList; import jgencode.primitivelists.IntList.Processor; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import imj.IMJTools.PixelProcessor; import imj.Image; import imj.apps.GenerateSampleDatabase.Configuration; import imj.apps.modules.RegionOfInterest; import imj.apps.modules.ViewFilter.Channel; import imj.database.BinningQuantizer; import imj.database.PatchDatabase; import imj.database.Quantizer; import imj.database.Sample; import imj.database.Sampler; import imj.database.BKSearch.BKDatabase; import imj.database.Segmenter; import net.sourceforge.aprog.tools.CommandLineArgumentsParser; import net.sourceforge.aprog.tools.IllegalInstantiationException; import net.sourceforge.aprog.tools.TicToc; /** * @author codistmonk (creation 2014-06-15) */ public final class SimplifiedSuperpixels { private SimplifiedSuperpixels() { throw new IllegalInstantiationException(); } /** * @param commandLineArguments * <br>Must not be null */ public static final void main(final String[] commandLineArguments) throws Exception { final TicToc timer = new TicToc(); final CommandLineArgumentsParser arguments = new CommandLineArgumentsParser(commandLineArguments); final String imagePath = arguments.get("file", ""); final Matcher tmMatcher = PragueTextureSegmentation.TM_FILE_PATH.matcher(imagePath); if (!tmMatcher.matches()) { return; } final int setIndex = parseInt(tmMatcher.group(1)); final int maskIndex = parseInt(tmMatcher.group(2)); final int mosaicIndex = parseInt(tmMatcher.group(3)); final String root = new File(imagePath).getParent(); final String metadataPath = arguments.get("metadata", new File(root, "data.xml").getPath()); final Map<String, String> textureMap = PragueTextureSegmentation.getTextureMap(metadataPath, maskIndex, mosaicIndex); debugPrint(textureMap); final Configuration configuration = new Configuration(commandLineArguments); final Image image = loadAndTryToCache(imagePath, configuration.getLod()); final Channel[] channels = RGB; final PatchDatabase<Sample> sampleDatabase = new PatchDatabase<Sample>(Sample.class); final Class<? extends Sampler> samplerFactory = configuration.getSamplerClass(); final Quantizer quantizer = new BinningQuantizer(); quantizer.initialize(image, null, channels, configuration.getQuantizationLevel()); final Segmenter segmenter = configuration.newSegmenter(); { for (final Map.Entry<String, String> entry : textureMap.entrySet()) { final String texturePath = new File(root, entry.getValue()).getPath(); debugPrint(texturePath); final Map<String, RegionOfInterest> classes = new HashMap<String, RegionOfInterest>(); final Image texture = loadAndTryToCache(texturePath, configuration.getLod()); classes.put(entry.getKey(), new RegionOfInterest.UsingBitSet( texture.getRowCount(), texture.getColumnCount(), true)); final Sampler collectorSampler = newSampler(samplerFactory, channels, quantizer, texture , new Sample.ClassSetter(classes, sampleDatabase)); segmenter.process(texture, collectorSampler); debugPrint(sampleDatabase.getEntryCount()); } } final Sample.Collector collector = new Sample.Collector(); final Sampler sampler = newSampler(configuration.getSamplerClass(), channels, quantizer, image, collector); final BKDatabase<Sample> bkDatabase = newBKDatabase(sampleDatabase, getPreferredMetric(sampler)); final BufferedImage result = new BufferedImage(image.getColumnCount(), image.getRowCount(), BufferedImage.TYPE_BYTE_GRAY); final byte[] prediction = new byte[1]; timer.tic(); segmenter.process(image, new PixelProcessor() { private final IntList pixels = new IntList(); @Override public final void process(final int pixel) { sampler.process(pixel); this.pixels.add(pixel); } @Override public void finishPatch() { sampler.finishPatch(); final Sample sample = bkDatabase.findClosest(collector.getSample()); if (1 != sample.getClasses().size()) { throw new IllegalArgumentException("Invalid group: " + sample.getClasses()); } prediction[0] = (byte) parseInt(sample.getClasses().iterator().next()); this.pixels.forEach(new Processor() { @Override public final boolean process(final int pixel) { final int x = pixel % image.getColumnCount(); final int y = pixel / image.getColumnCount(); result.getRaster().setDataElements(x, y, prediction); return true; } /** * {@value}. */ private static final long serialVersionUID = -4667208741018178698L; }); this.pixels.clear(); } /** * {@value}. */ private static final long serialVersionUID = 4448450281104902695L; }); gc(); final String outputPath = new File(imagePath).getName().replace("tm" + setIndex, "seg" + setIndex); debugPrint(outputPath); try (final OutputStream output = new FileOutputStream(outputPath)) { ImageIO.write(result, "png", output); } debugPrint("time:", timer.toc()); } /** * @author codistmonk (creation 2014-06-15) */ public static final class PragueTextureSegmentation { private PragueTextureSegmentation() { throw new IllegalInstantiationException(); } public static final Pattern TM_FILE_PATH = Pattern.compile(".*tm([0-9]+)_([0-9]+)_([0-9]+)\\.png"); public static final Map<String, String> getTextureMap(final String metadataPath, final int maskIndex, final int mosaicIndex) throws FileNotFoundException { final Document metadata = parse(new FileInputStream(metadataPath)); final Node textureMaps = getNode(metadata, "//section[@name='TMMap_" + maskIndex + "_" + mosaicIndex + "']"); final Element textures = (Element) getNode(textureMaps, "var[contains(@name, 'Textures')]"); final String[] textureIds = textures.getTextContent().replaceAll("[^0-9]", " ").trim().split(" +"); final Map<String, String> result = new LinkedHashMap<>(); { final List<Node> texturePaths = getNodes(textureMaps, "var[contains(@name, 'Train')]"); for (int i = 0; i < textureIds.length; ++i) { result.put(textureIds[i], texturePaths.get(i).getTextContent().replaceAll("\"", "")); } } return result; } } }
//package carrito.server.serial; /* @(#)SerialConnection.java 1.6 98/07/17 SMI * * Clase de Control del vehculo Guistub */ package sibtra.controlcarro; import gnu.io.CommPortIdentifier; import gnu.io.NoSuchPortException; import gnu.io.PortInUseException; import gnu.io.SerialPort; import gnu.io.SerialPortEvent; import gnu.io.SerialPortEventListener; import gnu.io.UnsupportedCommOperationException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.TooManyListenersException; import sibtra.log.LoggerArrayDoubles; import sibtra.log.LoggerArrayInts; import sibtra.log.LoggerFactory; import sibtra.util.UtilCalculos; public class ControlCarro implements SerialPortEventListener { /* * En el freno existen 3 variables a modificar Sentido_freno = indica si se * debe frenar o desfrenar Valor_Freno = indica la fuerza, la amplitud con * la que se abre la valvula que abre el circuito de frenado. Tiempo_freno = * Tiempo en el que esta actuando el freno, funciona a la inversa donde el * tiempo que se pone tiene que saturar a MaxpasosFreno,FFh para parar el * frenado. MaxpasosFreno = 10 decimal, EN REALIDAD SE FIJA EN EL MICRO LA * PARTE ALTA DE LA PALABRA A MAXPASOSFRENO -1 POR LO QUE SE HACE SOLO LA * CUENTA BAJA. Hay que ajustar los parametros de tiempo para conseguir que * funcione correctamente / */ private boolean open; /** Punto central del volante del vehiculo */ public final static int CARRO_CENTRO = 5280; /** Maximo comando en el avance */ public final static int MINAVANCE = 100; /** Minimo comando en el avance */ public final static int MAXAVANCE = 255; /** Numero de cuentas necesarias para alcanzar un metro */ public final static double PULSOS_METRO = 74; // public static final double RADIANES_POR_CUENTA = // 2*Math.PI/MAX_CUENTA_VOLANTE; /** Radianes que suponen cada cuenta del sensor del volante */ public static final double RADIANES_POR_CUENTA = 0.25904573048913979374 / (5280 - 3300); static double T = 0.096; // Version anterior 0.087 static private int freqVel = 8; int Cuentas[] = new int[freqVel]; long tiempos[] = new long[freqVel]; int indiceCuentas = 0; /** Error del controlador PID de la velocidad en {@link #controlVel()}*/ double errorAnt = 0; /** Derivada del controlador PID de la velocidad en {@link #controlVel()}*/ double derivativoAnt = 0; /** Comando calculado por el controlador PID de la velocidad en {@link #controlVel()}*/ double comando = CARRO_CENTRO; /** comando anterior calculado por el PID de control de la velocidad en {@link #controlVel()}*/ private double comandoAnt = MINAVANCE; /** Integral del controlador PID de la velocidad en {@link #controlVel()}*/ double integral = 0; private ControlCarroSerialParameters parameters; private OutputStream os; private InputStream is; private CommPortIdentifier portId; private SerialPort sPort; /** Ultima velocidad de avance calculada en cuentas por segundo */ private double velocidadCS = 0; /** Ultima velocidad de avance calculada en metros por segundo */ private double velocidadMS = 0; /** Total de bytes recibidos desde el PIC por la serial */ private int TotalBytes = 0; private int volante = 32768; private int avance = 0; private int avanceant = 0; /** Contiene byte, recibido del PIC, con los bits correspondientes a las distintas alarmas */ private int alarma = 0; private int ConsignaVolante = 32767; /* Comandos enviados hacia el coche para el microcontrolador */ private int ConsignaFreno = 0; private int ConsignaSentidoFreno = PARAR_FRENO; static public int PARAR_FRENO=0; static public int ABRIR_DESFRENAR=1; static public int ABRIR_FRENAR=2; static public int DESFRENAR=3; static public int NOCAMBIAR_FRENO=4; private int ComandoVelocidad = 0; private int ConsignaSentidoVelocidad = 0; private int ConsignaNumPasosFreno = 0; /** Numero de pasos de freno que se han dado */ private int NumPasosFreno = 0; /** Logger para registrar mensaje recibidos */ private LoggerArrayInts logMenRecibidos; /** Logger para registrar los mensajece enviados */ private LoggerArrayInts logMenEnviados; // private int RVolante; // private int refresco = 300; // /** Ganancia proporcional del PID de freno */ // private double kPFreno = 0.5; // /** Ganancia derivativa del PID de freno */ // private double kPDesfreno = 1.5; /** Ganancia proporcional del PID de avance */ private double kPAvance = 2.5; /** Ganancia defivativa del PID de avance */ private double kDAvance = 0.2; /** Ganancia integral del PID de avance */ private double kIAvance = 0.1; private boolean controlando = false; /** Consigna de velocidad a aplicar en cuentas por segundo */ private double consignaVel = 0; /** Maximo incremento permitido en el comando para evitar aceleraciones bruscas */ private int maxInc = 10; /** Zona Muerta donde el motor empieza a actuar realmente */ static final int ZonaMuerta = 80; /** Numero de paquetes recibidos validos */ private int NumPaquetes = 0; /** Milisegundos al crearse el objeto. Se usa para tener tiempos relativos */ // private long TiempoInicial = System.currentTimeMillis(); // private int contadorFreno = 0; /** Registrador del angulo y velocidad medidos al recivir cada paquete */ private LoggerArrayDoubles logAngVel; /** Registrador de todos los datos del PID de avance*/ private LoggerArrayDoubles logControl; double FactorFreno=20; public ControlCarro(String portName) { parameters = new ControlCarroSerialParameters(portName, 9600, 0, 0, 8, 1, 0); try { openConnection(); } catch (ControlCarroConnectionException e2) { System.out.println("Error al abrir el puerto " + portName); System.out.flush(); } if (isOpen()) System.out.println("Puerto Abierto " + portName); logAngVel=LoggerFactory.nuevoLoggerArrayDoubles(this, "carroAngVel",12); logAngVel.setDescripcion("Carro [Ang en Rad,Vel en m/s]"); logMenRecibidos= LoggerFactory.nuevoLoggerArrayInts(this, "mensajesRecibidos",(int)(1/T)+1); logMenRecibidos.setDescripcion("volante,avance,(int)velocidadCS,alarma,incCuentas,incTiempo"); logMenEnviados= LoggerFactory.nuevoLoggerArrayInts(this, "mensajesEnviados",(int)(1/T)+1); logMenEnviados.setDescripcion("ConsignaVolante,ComandoVelocidad,ConsignaFreno,ConsignaNumPasosFreno"); logControl=LoggerFactory.nuevoLoggerArrayDoubles(this, "controlPID",(int)(1/T)+1); logControl.setDescripcion("error,derivativo,integral,comandotemp,comando,kPAvance,kIAvance,kDAvance,maxInc"); } /** * Attempts to open a serial connection and streams using the parameters in * the SerialParameters object. If it is unsuccesfull at any step it returns * the port to a closed state, throws a * <code>SerialConnectionException</code>, and returns. * * Gives a timeout of 30 seconds on the portOpen to allow other applications * to reliquish the port if have it open and no longer need it. */ private void openConnection() throws ControlCarroConnectionException { // Obtain a CommPortIdentifier object for the port you want to open. try { portId = CommPortIdentifier.getPortIdentifier(parameters .getPortName()); } catch (NoSuchPortException e) { throw new ControlCarroConnectionException(e.getMessage()); } // Open the port represented by the CommPortIdentifier object. Give // the open call a relatively long timeout of 30 seconds to allow // a different application to reliquish the port if the user // wants to. try { sPort = (SerialPort) portId.open("SerialDemo", 30000); } catch (PortInUseException e) { throw new ControlCarroConnectionException(e.getMessage()); } // Set the parameters of the connection. If they won't set, close the // port before throwing an exception. try { setConnectionParameters(); } catch (ControlCarroConnectionException e) { sPort.close(); throw e; } // Open the input and output streams for the connection. If they won't // open, close the port before throwing an exception. try { os = sPort.getOutputStream(); is = sPort.getInputStream(); } catch (IOException e) { sPort.close(); throw new ControlCarroConnectionException( "Error opening i/o streams"); } // Add this object as an event listener for the serial port. try { sPort.addEventListener(this); } catch (TooManyListenersException e) { sPort.close(); throw new ControlCarroConnectionException( "too many listeners added"); } // Set notifyOnDataAvailable to true to allow event driven input. sPort.notifyOnDataAvailable(true); // Set notifyOnBreakInterrup to allow event driven break handling. // sPort.notifyOnBreakInterrupt(true); // Set receive timeout to allow breaking out of polling loop during // input handling. // try { // sPort.enableReceiveTimeout(30); // } catch (UnsupportedCommOperationException e) { open = true; sPort.disableReceiveTimeout(); } /** * Sets the connection parameters to the setting in the parameters object. * If set fails return the parameters object to origional settings and throw * exception. */ private void setConnectionParameters() throws ControlCarroConnectionException { // Save state of parameters before trying a set. int oldBaudRate = sPort.getBaudRate(); int oldDatabits = sPort.getDataBits(); int oldStopbits = sPort.getStopBits(); int oldParity = sPort.getParity(); int oldFlowControl = sPort.getFlowControlMode(); // Set connection parameters, if set fails return parameters object // to original state. try { sPort.setSerialPortParams(parameters.getBaudRate(), parameters .getDatabits(), parameters.getStopbits(), parameters .getParity()); } catch (UnsupportedCommOperationException e) { parameters.setBaudRate(oldBaudRate); parameters.setDatabits(oldDatabits); parameters.setStopbits(oldStopbits); parameters.setParity(oldParity); throw new ControlCarroConnectionException("Unsupported parameter"); } // Set flow control. try { sPort.setFlowControlMode(parameters.getFlowControlIn() | parameters.getFlowControlOut()); } catch (UnsupportedCommOperationException e) { throw new ControlCarroConnectionException( "Unsupported flow control"); } } /** Cierra el puerto y libera los elementos asociados */ public void closeConnection() { // If port is alread closed just return. if (!open) { return; } // Check to make sure sPort has reference to avoid a NPE. if (sPort != null) { try { // close the i/o streams. os.close(); is.close(); } catch (IOException e) { System.err.println(e); } // Close the port. sPort.close(); } open = false; } /** Send a one second break signal. */ private void sendBreak() { sPort.sendBreak(1000); } /** @return true if port is open, false if port is closed.*/ public boolean isOpen() { return open; } /** * Maneja la llegada de datos por la serial */ public void serialEvent(SerialPortEvent e) { int buffer[] = new int[6]; //porque el 0 no se usa :-( int newData = 0; if (e.getEventType() != SerialPortEvent.DATA_AVAILABLE) return; while (newData != -1) { try { newData = is.read(); TotalBytes++; if (newData == -1) { break; } if (newData!=250) continue; //newdata vale 250 newData = is.read(); if (newData != 251) continue; //newdata vale 251 //leemos los datos del mensaje en buffer buffer[1] = is.read(); buffer[2] = is.read(); buffer[3] = is.read(); buffer[4] = is.read(); buffer[5] = is.read(); newData = is.read(); if (newData != 255) continue; //no lo consideramos //Ya tenemos paquete valido en buffer trataMensaje(buffer); } catch (IOException ex) { System.err.println(ex); return; } } } private void trataMensaje(int buffer[]) { volante = UtilCalculos.byte2entero(buffer[1], buffer[2]); if (ConsignaVolante == -1) { ConsignaVolante = volante; } //controlamos desbordamiento contador de avance en el PIC if (avanceant <= buffer[3]) //no se ha producido avance = avance + (buffer[3] - avanceant); else //se ha producido avance = avance + (buffer[3] + (255 - avanceant) + 1); avanceant = buffer[3]; // Calculamos la velocidad usando ventana de freqVel mensajes. Cuentas[indiceCuentas] = avance; tiempos[indiceCuentas] = System.currentTimeMillis(); int incCuentas=Cuentas[indiceCuentas] - Cuentas[(indiceCuentas + 1) % freqVel]; long incTiempo=tiempos[indiceCuentas] - tiempos[(indiceCuentas + 1) % freqVel]; velocidadCS=1000.0 *(double) incCuentas / (double)incTiempo; indiceCuentas = (indiceCuentas + 1) % freqVel; velocidadMS = velocidadCS / PULSOS_METRO; //apuntamos angulo volante en radianes y velocidad en m/sg logAngVel.add((volante - CARRO_CENTRO) * RADIANES_POR_CUENTA,velocidadMS); // System.out.println("T: " + // (System.currentTimeMillis() - lastPaquete) + // " Tmedio: " + (TiempoTotal/Recibidos)); controlVel(); alarma = buffer[4]; NumPasosFreno = buffer[5]; // if (ConsignaSentidoFreno != 0) // System.out.println("NumPasosFreno = "+ NumPasosFreno); // if (NumPasosFreno == 255) { // if (ConsignaSentidoFreno == 2) { // System.out.println("Frenando"); // if (contadorFreno > 0) { // System.out.println("ContadorFreno1 = "+ contadorFreno); // if (getFreno() == 1) { // contadorFreno = 0; // } else { // NumPasosFreno = 0; // contadorFreno--; // System.out.println("ContadorFreno2 = "+ contadorFreno); // } else if (ConsignaSentidoFreno == 1) { // System.out.println("DesFrenando"); // if (contadorFreno > 0) { // System.out.println("ContadorFreno1 = "+ contadorFreno); // if (getDesfreno() == 1) { // contadorFreno = 0; // } else { // NumPasosFreno = 0; // contadorFreno--; // System.out.println("ContadorFreno2 = "+ contadorFreno); NumPaquetes++; logMenRecibidos.add(volante,avance,(int)velocidadCS,alarma,incCuentas,(int)incTiempo); } /** @return Objeto de escritura del puerto serie */ public OutputStream getOutputStream() { return os; } /** * Devuelve el numero de Bytes que hemos recibido del coche * */ public int getBytes() { return TotalBytes; } /** * Devuelve el numero de Cuentas del encoder de la tracci?n, lo que se ha * desplazado el coche * */ public int getAvance() { return avance; } /** * Devuelve la posicion actual del volante * */ public int getVolante() { return volante; } /** * @return Devuelve el angulo del volante en radianes respecto al centro (+ * izquierda, - derecha). */ public double getAnguloVolante() { return (volante - CARRO_CENTRO) * RADIANES_POR_CUENTA; } /** * @return Devuelve el angulo del volante en grados respecto al centro (+ * izquierda, - derecha). */ public double getAnguloVolanteGrados() { return Math.toDegrees(getAnguloVolante()); } /** * Devuelve si esta pulsada la alarma de desfrenado * */ public int getDesfreno() { if ((alarma & 16) == 16) return 1; return 0; } /** * Devuelve si esta pulsada la alarma de frenado * */ public int getFreno() { if ((alarma & 8) == 8) return 1; return 0; } /** * Devuelve si esta pulsada la alarma del fin de carrera izquierdo * */ public int getIzq() { if ((alarma & 4) == 4) return 1; return 0; } /** * Devuelve si esta pulsada la alarma del fin de carrera derecho * */ public int getDer() { if ((alarma & 2) == 2) return 1; return 0; } /** * Devuelve si esta pulsada la alarma global del coche, en este caso el * sistema bloquea todas las posibles opciones * */ public int getAlarma() { if ((alarma & 1) == 1) return 1; return 0; } /** * Obtiene la consigna del volante * * @return Devuelve la consigna del volante */ public int getConsignaVolante() { return ConsignaVolante; } public double getConsignaAnguloVolante() { return (ConsignaVolante - CARRO_CENTRO) * RADIANES_POR_CUENTA; } /** * @return Devuelve la consigna del volante en grados */ public double getConsignaAnguloVolanteGrados() { return Math.toDegrees(getConsignaAnguloVolante()); } /** * @return Devuelve el comando de la velocidad */ public int getComandoVelocidad() { return ComandoVelocidad; } /** * Fija consigna del volante * * @param comandoVolante * angulo deseado en radianes desde el centro (+izquierda, - * derecha) */ public void setAnguloVolante(double comandoVolante) { setVolante((int) Math.floor(comandoVolante / RADIANES_POR_CUENTA) + CARRO_CENTRO); } /** * Fija la posicion del volante a las cuentas indicadas * * @param Angulo * Numero de cuentas a las que fijar el volante */ public void setVolante(int Angulo) { ConsignaVolante=UtilCalculos.limita(Angulo, 0, 65535); ConsignaSentidoFreno=NOCAMBIAR_FRENO; //No modifica el freno ConsignaNumPasosFreno = NumPasosFreno; //TODO sobra Envia(); } /** * Fija la posicion del volante a n cuentas a partir de la posicion actual * * @param deltaAngulo * Numero de cuentas a desplazar a partir de la posicion actual */ public void setRVolante(int deltaAngulo) { ConsignaVolante = UtilCalculos.limita(ConsignaVolante + deltaAngulo, 0, 65535); ConsignaSentidoFreno=NOCAMBIAR_FRENO; ConsignaNumPasosFreno = NumPasosFreno; //TODO sobra Envia(); } /** * Fija la velocidad hacia delante con una Fuerza dada entre 0-255 */ public void Avanza(int Fuerza) { Fuerza=UtilCalculos.limita(Fuerza,0,255); /*if (getDesfreno() != 1) { DesFrena(255); return; }*/ ComandoVelocidad = Fuerza; ConsignaSentidoVelocidad = 2; //para alante ConsignaSentidoFreno = NOCAMBIAR_FRENO; ConsignaNumPasosFreno = 0; //TODO sobra Envia(); } /** * Fija la velocidad hacia delante con una Fuerza dada entre 0-255 */ public void Retrocede(int Fuerza) { Fuerza=UtilCalculos.limita(Fuerza,0,255); if (getDesfreno() != 1) { DesFrena(255); return; } ConsignaSentidoFreno=NOCAMBIAR_FRENO; ConsignaNumPasosFreno = 0; //TODO sobra ComandoVelocidad = Fuerza; ConsignaSentidoVelocidad = 1; Envia(); } /** * @param tiempo 255 maximo, 0 minimo tiempo */ public void DesFrena(int tiempo) { tiempo=UtilCalculos.limita(tiempo, 0, 255); tiempo = 255 - tiempo; ConsignaFreno = 255; ConsignaSentidoFreno = DESFRENAR; ConsignaNumPasosFreno = tiempo; ComandoVelocidad = 0; ConsignaSentidoVelocidad = 0; Envia(); ConsignaFreno = 0; ConsignaNumPasosFreno = 0; ConsignaSentidoFreno = PARAR_FRENO; } /** * Aumenta el frenado del sistema * @param valor apertura de la valvula * @param tiempo tiempo de esta apertura */ public void masFrena(int valor, int tiempo) { valor=UtilCalculos.limita(valor,0,255); tiempo=UtilCalculos.limita(tiempo, 0, 255); tiempo = 255 - tiempo; ConsignaSentidoFreno = ABRIR_FRENAR; //Abrir valvula de frenar ConsignaNumPasosFreno = tiempo; ConsignaFreno = valor; ComandoVelocidad = 0; ConsignaSentidoVelocidad = 0; Envia(); ConsignaFreno = 0; ConsignaNumPasosFreno = 0; ConsignaSentidoFreno = PARAR_FRENO; } /** * Disminuye la presion del frenado * @param valor Apertura de la electrovalvula * @param tiempo tiempo de apertura */ public void menosFrena(int valor, int tiempo) { valor=UtilCalculos.limita(valor,0,255); tiempo=UtilCalculos.limita(tiempo, 0, 255); tiempo = 255 - tiempo; ConsignaSentidoFreno = ABRIR_DESFRENAR; //abrir la valvula de desfrenar ConsignaFreno = valor; ConsignaNumPasosFreno = tiempo; ComandoVelocidad = 0; ConsignaSentidoVelocidad = 0; Envia(); ConsignaFreno = 0; ConsignaNumPasosFreno = 0; ConsignaSentidoFreno = PARAR_FRENO; } private void Envia() { logMenEnviados.add(ConsignaVolante,ComandoVelocidad,ConsignaFreno,ConsignaNumPasosFreno); int a[] = new int[10]; a[0] = 250; a[1] = 251; a[2] = ConsignaVolante & 255; a[3] = (ConsignaVolante & 65280) >> 8; a[4] = ConsignaFreno; a[5] = ConsignaSentidoFreno; a[6] = ComandoVelocidad; a[7] = ConsignaSentidoVelocidad; a[8] = ConsignaNumPasosFreno; a[9] = 255; for (int i = 0; i < 10; i++) try { os.write(a[i]); } catch (Exception e) { System.out.println("Error al enviar, " + e.getMessage()); System.out.println(e.getStackTrace()); try { System.out.println("Se va a proceder a vaciar el buffer"); os.flush(); } catch (Exception e2) { System.out.println("Error al vaciar el buffer, " + e2.getMessage()); } } } public void controlVel() { if (!controlando) return; if (consignaVel == 0) stopControlVel(); double error = consignaVel - velocidadCS; //derivativo como y(k)-y(k-2) double derivativo = error - errorAnt + derivativoAnt; if ((comandoAnt > 0 )&& (comandoAnt < 254 )) integral += errorAnt; double comandotemp = kPAvance * error + kDAvance * derivativo + kIAvance * integral; double IncComando = comandotemp - comandoAnt; //Limitamos el incremento de comando IncComando=UtilCalculos.limita(IncComando,-maxInc,maxInc); comando=comandoAnt+IncComando; //Limitamos el comando maximo a aplicar comando=UtilCalculos.limita(comando, -255, 255); //umbralizamos la zona muerta comando=UtilCalculos.zonaMuertaCon0(comando, comandoAnt, 80 , 90/FactorFreno+comandoAnt); if (comando >= 0) { if(comandoAnt<=0) { menosFrena(255, 255); // DesFrena(255); System.err.println("========== Abrimos :"+comandoAnt+" > "+comando); } Avanza((int)comando); } else { double IncCom=comando-comandoAnt; if(IncCom<=0) { int apertura=-(int)(IncCom*FactorFreno); apertura=UtilCalculos.limita(apertura, 90, 150); masFrena( apertura,20); /** Es un comando negativo, por lo que hay que frenar */ System.err.println("Mas frena "+apertura); } else { int apertura=(int)(IncCom*FactorFreno); if(apertura>150) apertura=150; menosFrena(apertura,20); System.err.println("menos frena "+apertura); } } errorAnt = error; derivativoAnt = derivativo; comandoAnt = comando; logControl.add(error,derivativo,integral,comandotemp,comando,kPAvance,kIAvance,kDAvance,maxInc); } public double getComando() { return comando; } /* * public void setConsigna(double valor) { boolean retroceso = false; * * if (valor < 0) { retroceso = true; valor *= -1; } double error = valor - * velocidad; System.out.println("Error: " + error); * * if (error >= 0) { if (getDesfreno() == 0) { comando += (int)(kPDesfreno * * error); * * DesFrenaPasos(comando); System.out.println("Desfrenando: " + comando); } * else { comando += (int)(kPAvance * error); * * if (retroceso == true) { System.out.println("Retrocediendo: " + comando); * Retrocede(comando); } else { //System.out.println("Avanzando: " + * comando); Avanza(comando); } } } else { comando += (int)(kPFreno * * error); * * Avanza(0); FrenaPasos(comando); } } */ /** * Fija el valor de la velocidad de avance en cuentas Segundo y activa el * control * * @param valor * consigna en cuentas/Seg */ public void setConsignaAvanceCS(double valor) { consignaVel = valor; controlando = true; } /** @return la consigna fijada en cuentas por segundo */ public double getConsignaAvanceCS() { return consignaVel; } /** * Fija el valor de la velocidad de avance en Metros Segundo y activa el * control * * @param valor * consigna en metros/seg */ public void setConsignaAvanceMS(double valor) { consignaVel = valor * PULSOS_METRO; System.out.println("Consigna Avance " + consignaVel); controlando = true; } /** @return la consigna fijada en metros por segundo */ public double getConsignaAvanceMS() { return consignaVel/PULSOS_METRO; } /** * Fija el valor de la velocidad de avance en Kilometros hora y activa el * control * * @param valor * consigna en Kilometros hora */ public void setConsignaAvanceKH(double valor) { consignaVel = valor * PULSOS_METRO * 1000 / 3600; controlando = true; } /** @return la consigna fijada en Kilometros por hora */ public double getConsignaAvanceKH() { return consignaVel/PULSOS_METRO*3600.0/1000.0; } /** * Velocidad actual en el vehiculo en Cuentas Segundo * * @return */ public double getVelocidadCS() { return velocidadCS; } /** * Velocidad actual en el vehiculo en Metros Segundo * * @return */ public double getVelocidadMS() { return velocidadMS; } /** * Velocidad actual en el vehiculo en Kilometros Hora * * @return */ public double getVelocidadKH() { return velocidadMS * 3600 / 1000; } /** * Fija los parametros del controlador PID de la velocidad * * @param kp * Constante proporcional * @param kd * Constante derivativa * @param ki * Constante integral */ public void setKVel(double kp, double kd, double ki) { kPAvance = kp; kDAvance = kd; kIAvance = ki; } /** * Detiene el control de la velocidad */ public void stopControlVel() { controlando = false; comandoAnt = MINAVANCE; Avanza(0); } public void setMaxIncremento(int incremento) { maxInc = incremento; } public int getMaxIncremento() { return maxInc; } public int getPaquetes() { return NumPaquetes; } /** * @return el factorFreno */ public double getFactorFreno() { return FactorFreno; } /** * @param factorFreno el factorFreno a establecer */ public void setFactorFreno(double factorFreno) { FactorFreno = factorFreno; } /** * @return el kDAvance */ public double getKDAvance() { return kDAvance; } /** * @param avance el kDAvance a establecer */ public void setKDAvance(double avance) { kDAvance = avance; } /** * @return el kIAvance */ public double getKIAvance() { return kIAvance; } /** * @param avance el kIAvance a establecer */ public void setKIAvance(double avance) { kIAvance = avance; } /** * @return el kPAvance */ public double getKPAvance() { return kPAvance; } /** * @param avance el kPAvance a establecer */ public void setKPAvance(double avance) { kPAvance = avance; } /** * @return the controlando */ public boolean isControlando() { return controlando; } }
package com.jvm_bloggers.domain.query.blog_statistics_for_listing; import com.jvm_bloggers.entities.blog.BlogRepository; import com.jvm_bloggers.entities.blog.BlogType; import io.vavr.collection.List; import com.jvm_bloggers.utils.NowProvider; import lombok.AllArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional(readOnly = true) @AllArgsConstructor(onConstructor = @__(@Autowired)) public class BlogStatisticsForListingQuery { public static final String BLOG_STATISTICS_CACHE = "Blog posts statistics cache"; private final BlogRepository blogRepository; private final NowProvider nowProvider; @Cacheable(BLOG_STATISTICS_CACHE) public List<BlogStatisticsForListing> findBlogPostStatistics(BlogType blogType, int page, int size) { return blogRepository.findBlogStatistics( nowProvider.today().minusMonths(3).atStartOfDay(), nowProvider.today().minusMonths(12).atStartOfDay(), blogType, new PageRequest(page, size)) .map(BlogStatisticsForListing::fromBlogPostStatisticProjection); } public long countByBlogType(BlogType blogType) { return blogRepository.countByBlogType(blogType); } }
package tv.floe.metronome.deeplearning.neuralnetwork.core; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.math3.distribution.RealDistribution; import org.apache.commons.math3.random.MersenneTwister; import org.apache.commons.math3.random.RandomGenerator; import org.apache.mahout.math.Matrix; import org.apache.mahout.math.MatrixWritable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import tv.floe.metronome.deeplearning.math.transforms.MatrixTransform; import tv.floe.metronome.deeplearning.neuralnetwork.activation.ActivationFunction; import tv.floe.metronome.deeplearning.neuralnetwork.layer.HiddenLayer; import tv.floe.metronome.deeplearning.neuralnetwork.optimize.MultiLayerNetworkOptimizer; import tv.floe.metronome.deeplearning.neuralnetwork.serde.Persistable; import tv.floe.metronome.math.MatrixUtils; import tv.floe.metronome.types.Pair; public abstract class BaseMultiLayerNeuralNetworkVectorized implements Serializable,Persistable { private static final long serialVersionUID = 4066891298715416874L; private static Logger log = LoggerFactory.getLogger( BaseMultiLayerNeuralNetworkVectorized.class ); public int inputNeuronCount; public int outputNeuronCount; //the hidden layer sizes at each layer public int[] hiddenLayerSizes; public int numberLayers; //the hidden layers public HiddenLayer[] hiddenLayers; public LogisticRegression logisticRegressionLayer; // DA / RBM Layers public NeuralNetworkVectorized[] preTrainingLayers; public RandomGenerator randomGenerator; public RealDistribution distribution; // how was it handled with the OOP-MLPN version? public Matrix inputTrainingData = null; public Matrix outputTrainingLabels = null; public double learningRateUpdate = 0.95; public boolean useRegularization = true; public double l2 = 0.01; private double momentum = 0.1; //don't use sparsity by default private double sparsity = 0; public MultiLayerNetworkOptimizer optimizer; protected Map<Integer,MatrixTransform> weightTransforms = new HashMap<Integer,MatrixTransform>(); //hidden bias transforms; for initialization private Map<Integer,MatrixTransform> hiddenBiasTransforms = new HashMap<Integer,MatrixTransform>(); //visible bias transforms for initialization private Map<Integer,MatrixTransform> visibleBiasTransforms = new HashMap<Integer,MatrixTransform>(); private boolean useAdaGrad = false; /** * CTOR * */ public BaseMultiLayerNeuralNetworkVectorized() { } public BaseMultiLayerNeuralNetworkVectorized(int n_ins, int[] hidden_layer_sizes, int n_outs, int n_layers, RandomGenerator rng) { this(n_ins,hidden_layer_sizes,n_outs,n_layers,rng,null,null); } public BaseMultiLayerNeuralNetworkVectorized(int n_ins, int[] hidden_layer_sizes, int n_outs, int n_layers, RandomGenerator rng, Matrix input, Matrix labels) { this.inputNeuronCount = n_ins; this.hiddenLayerSizes = hidden_layer_sizes; this.inputTrainingData = input; this.outputTrainingLabels = labels; if(hidden_layer_sizes.length != n_layers) { throw new IllegalArgumentException("The number of hidden layer sizes must be equivalent to the nLayers argument which is a value of " + n_layers); } this.outputNeuronCount = n_outs; this.numberLayers = n_layers; this.hiddenLayers = new HiddenLayer[n_layers]; this.preTrainingLayers = createNetworkLayers( this.numberLayers ); if (rng == null) { this.randomGenerator = new MersenneTwister(123); } else { this.randomGenerator = rng; } if (input != null) { initializeLayers(input); } } /** * Base class for initializing the layers based on the input. * This is meant for capturing numbers such as input columns or other things. * * This method sets up two types of layers: * - normal ML-NN layers * - RBM / DA layers * * @param input the input matrix for training */ protected void initializeLayers(Matrix input) { Matrix layer_input = input; int input_size; // construct multi-layer for (int i = 0; i < this.numberLayers; i++) { if (i == 0) { //input_size = this.nIns; input_size = this.inputNeuronCount; // construct sigmoid_layer //this.sigmoidLayers[i] = new HiddenLayer(input_size, this.hiddenLayerSizes[i], null, null, rng,layer_input); this.hiddenLayers[ i ] = new HiddenLayer(input_size, this.hiddenLayerSizes[i], this.randomGenerator ); this.hiddenLayers[ i ].setInput( layer_input ); } else { input_size = this.hiddenLayerSizes[ i - 1 ]; layer_input = this.hiddenLayers[i - 1].sampleHiddenGivenLastVisible(); // construct sigmoid_layer this.hiddenLayers[ i ] = new HiddenLayer(input_size, this.hiddenLayerSizes[i], this.randomGenerator); this.hiddenLayers[ i ].setInput( layer_input ); } // System.out.println("Layer [" + i + "] " ); // System.out.println("\tCreated Hidden Layer [" + i + "]: Neuron Count: " + this.hiddenLayerSizes[i] ); // System.out.println("\tCreated RBM PreTrain Layer [" + i + "]: Num Visible: " + input_size + ", Num Hidden: " + this.hiddenLayerSizes[i] ); // construct DL appropriate class for pre training layer this.preTrainingLayers[ i ] = createPreTrainingLayer( layer_input,input_size, this.hiddenLayerSizes[i], this.hiddenLayers[i].connectionWeights, this.hiddenLayers[i].biasTerms, null, this.randomGenerator, i ); } System.out.println("Logistic Output Layer: Inputs: " + this.hiddenLayerSizes[this.numberLayers-1] + ", Output Classes: " + this.outputNeuronCount ); this.logisticRegressionLayer = new LogisticRegression(layer_input, this.hiddenLayerSizes[this.numberLayers-1], this.outputNeuronCount ); // System.out.println( "DBN Network Stats:\n" + this.generateNetworkSizeReport() ); } public synchronized Map<Integer, MatrixTransform> getHiddenBiasTransforms() { return hiddenBiasTransforms; } public synchronized Map<Integer, MatrixTransform> getVisibleBiasTransforms() { return visibleBiasTransforms; } /** * Resets adagrad with the given learning rate. * This is used for switching from the pretrain to finetune phase. * @param lr the new master learning rate to use */ /* public void resetAdaGrad(double lr) { for (int i = 0; i < this.numberLayers; i++) { //layers[i].resetAdaGrad(lr); //this.preTrainingLayers } //logLayer.resetAdaGrad(lr); } */ /** * Returns the -fanIn to fanIn * coefficient used for initializing the * weights. * The default is 1 / nIns * @return the fan in coefficient */ /* public double fanIn() { if(this.in < 0) return 1.0 / nIns; return fanIn; } */ public double getReconstructionCrossEntropy() { double sum = 0; for(int i = 0; i < this.numberLayers; i++) { sum += this.preTrainingLayers[i].getReConstructionCrossEntropy(); } sum /= (double) this.numberLayers; return sum; } public List<Matrix> feedForward() { if (this.inputTrainingData == null) { throw new IllegalStateException("Unable to perform feed forward; no input found"); } List<Matrix> activations = new ArrayList<Matrix>(); Matrix input = this.inputTrainingData; activations.add(input); for (int i = 0; i < this.numberLayers; i++) { HiddenLayer layer = this.hiddenLayers[ i ]; //layers[i].setInput(input); this.preTrainingLayers[i].setInput(input); input = layer.computeOutputActivation(input); activations.add(input); } activations.add( this.logisticRegressionLayer.predict(input) ); return activations; } /** * TODO: make sure our concept of an activation function can deliver functionality * * @param activations * @param deltaRet */ private void computeDeltas(List<Matrix> activations,List<Pair<Matrix,Matrix>> deltaRet) { Matrix[] gradients = new Matrix[ this.numberLayers + 2 ]; Matrix[] deltas = new Matrix[ this.numberLayers + 2 ]; ActivationFunction derivative = this.hiddenLayers[ 0 ].activationFunction; //- y - h Matrix delta = null; /* * Precompute activations and z's (pre activation network outputs) */ List<Matrix> weights = new ArrayList<Matrix>(); /* for (int j = 0; j < layers.length; j++) { weights.add(layers[j].getW()); } */ for (int j = 0; j < this.preTrainingLayers.length; j++) { weights.add( this.preTrainingLayers[j].getConnectionWeights() ); } weights.add( this.logisticRegressionLayer.connectionWeights ); List<Matrix> zs = new ArrayList<Matrix>(); zs.add( this.inputTrainingData ); for (int i = 0; i < this.preTrainingLayers.length; i++) { if (this.preTrainingLayers[i].getInput() == null && i == 0) { this.preTrainingLayers[i].setInput( this.inputTrainingData ); } else if (this.preTrainingLayers[i].getInput() == null) { this.feedForward(); } //zs.add(MatrixUtil.sigmoid(layers[i].getInput().mmul(weights.get(i)).addRowVector(layers[i].gethBias()))); //zs.add(MatrixUtils.sigmoid( this.preTrainingLayers[ i ].getInput().times( weights.get( i ) ).addRowVector( this.preTrainingLayers[i].getHiddenBias() ))); zs.add(MatrixUtils.sigmoid( MatrixUtils.addRowVector( this.preTrainingLayers[ i ].getInput().times( weights.get( i ) ), this.preTrainingLayers[i].getHiddenBias().viewRow(0) ))); } //zs.add(logLayer.input.mmul(logLayer.W).addRowVector(logLayer.b)); //zs.add( this.logisticRegressionLayer.input.times( this.logisticRegressionLayer.connectionWeights ).addRowVector( this.logisticRegressionLayer.biasTerms )); zs.add( MatrixUtils.addRowVector( this.logisticRegressionLayer.input.times( this.logisticRegressionLayer.connectionWeights ), this.logisticRegressionLayer.biasTerms.viewRow(0) ) ); //errors for (int i = this.numberLayers + 1; i >= 0; i if (i >= this.numberLayers + 1) { Matrix z = zs.get(i); //- y - h //delta = labels.sub(activations.get(i)).neg(); delta = MatrixUtils.neg( this.outputTrainingLabels.minus( activations.get( i ) ) ); //(- y - h) .* f'(z^l) where l is the output layer //Matrix initialDelta = delta.times( derivative.applyDerivative( z ) ); Matrix initialDelta = MatrixUtils.elementWiseMultiplication( delta, derivative.applyDerivative( z ) ); deltas[ i ] = initialDelta; } else { delta = deltas[ i + 1 ]; Matrix w = weights.get( i ).transpose(); Matrix z = zs.get( i ); Matrix a = activations.get( i + 1 ); //W^t * error^l + 1 Matrix error = delta.times( w ); deltas[ i ] = error; // MatrixUtils.debug_print_matrix_stats(error, "error matrix"); // MatrixUtils.debug_print_matrix_stats(z, "z matrix"); //error = error.times(derivative.applyDerivative(z)); error = MatrixUtils.elementWiseMultiplication( error, derivative.applyDerivative(z) ); deltas[ i ] = error; // gradients[ i ] = a.transpose().times(error).transpose().div( this.inputTrainingData.numRows() ); gradients[ i ] = a.transpose().times(error).transpose().divide( this.inputTrainingData.numRows() ); } } for (int i = 0; i < gradients.length; i++) { deltaRet.add(new Pair<Matrix, Matrix>(gradients[i],deltas[i])); } } /** * Backpropagation of errors for weights * @param lr the learning rate to use * @param epochs the number of epochs to iterate (this is already called in finetune) */ public void backProp(double lr,int epochs) { for (int i = 0; i < epochs; i++) { List<Matrix> activations = feedForward(); //precompute deltas List<Pair<Matrix,Matrix>> deltas = new ArrayList<Pair<Matrix, Matrix>>(); computeDeltas(activations, deltas); for (int l = 0; l < this.numberLayers; l++) { Matrix add = deltas.get( l ).getFirst().divide( this.inputTrainingData.numRows() ).times( lr ); add = add.divide( this.inputTrainingData.numRows() ); if (useRegularization) { //add = add.times( this.preTrainingLayers[ l ].getConnectionWeights().times( l2 ) ); add = MatrixUtils.elementWiseMultiplication(add, this.preTrainingLayers[ l ].getConnectionWeights().times( l2 )); } this.preTrainingLayers[ l ].setConnectionWeights( this.preTrainingLayers[ l ].getConnectionWeights().minus( add.times( lr ) ) ); this.hiddenLayers[ l ].connectionWeights = this.preTrainingLayers[l].getConnectionWeights(); Matrix deltaColumnSums = MatrixUtils.columnSums( deltas.get( l + 1 ).getSecond() ); // TODO: check this, needs to happen in place? deltaColumnSums = deltaColumnSums.divide( this.inputTrainingData.numRows() ); // TODO: check this, needs to happen in place? //this.preTrainingLayers[ l ].getHiddenBias().subi( deltaColumnSums.times( lr ) ); Matrix hbiasMinus = this.preTrainingLayers[ l ].getHiddenBias().minus( deltaColumnSums.times( lr ) ); this.preTrainingLayers[ l ].sethBias(hbiasMinus); this.hiddenLayers[ l ].biasTerms = this.preTrainingLayers[l].getHiddenBias(); } this.logisticRegressionLayer.connectionWeights = this.logisticRegressionLayer.connectionWeights.plus(deltas.get( this.numberLayers ).getFirst()); } } /** * Creates a layer depending on the index. * The main reason this matters is for continuous variations such as the {@link CDBN} * where the first layer needs to be an {@link CRBM} for continuous inputs * */ public abstract NeuralNetworkVectorized createPreTrainingLayer(Matrix input, int nVisible, int nHidden, Matrix weights, Matrix hbias, Matrix vBias, RandomGenerator rng, int index); public void finetune(double learningRate, int epochs) { finetune( this.outputTrainingLabels, learningRate, epochs ); } /** * Run SGD based on the given output vectors * * * @param labels the labels to use * @param lr the learning rate during training * @param epochs the number of times to iterate */ public void finetune(Matrix outputLabels, double learningRate, int epochs) { if (null != outputLabels) { this.outputTrainingLabels = outputLabels; } optimizer = new MultiLayerNetworkOptimizer(this,learningRate); optimizer.optimize( outputLabels, learningRate, epochs ); //optimizer.optimizeWSGD( outputLabels, learningRate, epochs ); } /** * Label the probabilities of the input * @param x the input to label * @return a vector of probabilities * given each label. * * This is typically of the form: * [0.5, 0.5] or some other probability distribution summing to one * * */ public Matrix predict(Matrix x) { Matrix input = x; for(int i = 0; i < this.numberLayers; i++) { HiddenLayer layer = this.hiddenLayers[i]; input = layer.computeOutputActivation(input); } return this.logisticRegressionLayer.predict(input); } /** * Serializes this to the output stream. * @param os the output stream to write to */ public void write(OutputStream os) { try { // ObjectOutputStream oos = new ObjectOutputStream(os); // oos.writeObject(this); // MatrixWritable.writeMatrix(arg0, arg1)this.hiddenLayers[ 0 ].biasTerms // ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutput d = new DataOutputStream(os); MatrixWritable.writeMatrix(d, inputTrainingData); // d.writeUTF(src_host); /* //d.writeInt(this.SrcWorkerPassCount); d.writeInt(this.GlobalPassCount); d.writeInt(this.IterationComplete); d.writeInt(this.CurrentIteration); d.writeInt(this.TrainedRecords); //d.writeFloat(this.AvgLogLikelihood); d.writeFloat(this.PercentCorrect); d.writeDouble(this.RMSE); */ //d.write // buf.write // MatrixWritable.writeMatrix(d, this.worker_gradient.getMatrix()); //MatrixWritable.writeMatrix(d, this.parameter_vector); // MatrixWritable. // ObjectOutputStream oos = new ObjectOutputStream(out); } catch (IOException e) { throw new RuntimeException(e); } } public void write( String filename ) throws IOException { File file = new File( filename ); if (!file.exists()) { try { file.getParentFile().mkdirs(); } catch (Exception e) { } file.createNewFile(); } FileOutputStream oFile = new FileOutputStream(filename, false); this.write(oFile); oFile.close(); } /** * Load (using {@link ObjectInputStream} * @param is the input stream to load from (usually a file) */ public void load(InputStream is) { try { ObjectInputStream ois = new ObjectInputStream(is); BaseMultiLayerNeuralNetworkVectorized loaded = (BaseMultiLayerNeuralNetworkVectorized) ois.readObject(); update(loaded); } catch (Exception e) { throw new RuntimeException(e); } } /** * Load (using {@link ObjectInputStream} * @param is the input stream to load from (usually a file) */ public static BaseMultiLayerNeuralNetworkVectorized loadFromFile(InputStream is) { try { ObjectInputStream ois = new ObjectInputStream(is); log.info("Loading network model..."); BaseMultiLayerNeuralNetworkVectorized loaded = (BaseMultiLayerNeuralNetworkVectorized) ois.readObject(); return loaded; } catch (Exception e) { throw new RuntimeException(e); } } /** * Helper method for loading the model file from disk by path name * * @param filename * @return * @throws Exception */ public static BaseMultiLayerNeuralNetworkVectorized loadFromFile(String filename ) throws Exception { BaseMultiLayerNeuralNetworkVectorized nn = null; File file = new File( filename ); if(!file.exists()) { //file.createNewFile(); throw new Exception("Model File Path does not exist!"); } //FileOutputStream oFile = new FileOutputStream(filename, false); try { DataInputStream dis = new DataInputStream( new FileInputStream( filename )); nn = BaseMultiLayerNeuralNetworkVectorized.loadFromFile( dis ); //dataOutputStream.flush(); dis.close(); } catch (IOException e) { log.error("Unable to load model",e); } return nn; } /** * Assigns the parameters of this model to the ones specified by this * network. This is used in loading from input streams, factory methods, etc * @param network the network to get parameters from */ protected void update(BaseMultiLayerNeuralNetworkVectorized network) { this.preTrainingLayers = new NeuralNetworkVectorized[ network.preTrainingLayers.length ]; for (int i = 0; i < preTrainingLayers.length; i++) { this.preTrainingLayers[i] = network.preTrainingLayers[ i ].clone(); } this.hiddenLayerSizes = network.hiddenLayerSizes; this.logisticRegressionLayer = network.logisticRegressionLayer.clone(); this.inputNeuronCount = network.inputNeuronCount; this.numberLayers = network.numberLayers; this.outputNeuronCount = network.outputNeuronCount; this.randomGenerator = network.randomGenerator; this.distribution = network.distribution; this.hiddenLayers = new HiddenLayer[network.hiddenLayers.length]; for (int i = 0; i < hiddenLayers.length; i++) { this.hiddenLayers[ i ] = network.hiddenLayers[ i ].clone(); } this.weightTransforms = network.weightTransforms; this.visibleBiasTransforms = network.visibleBiasTransforms; this.hiddenBiasTransforms = network.hiddenBiasTransforms; } public void initBasedOn(BaseMultiLayerNeuralNetworkVectorized network) { this.update(network); // now clear all connections. for (int i = 0; i < preTrainingLayers.length; i++) { this.preTrainingLayers[i].clearWeights(); } this.logisticRegressionLayer.clearWeights(); for (int i = 0; i < hiddenLayers.length; i++) { this.hiddenLayers[ i ].clearWeights(); } } /** * @return the negative log likelihood of the model */ public double negativeLogLikelihood() { return this.logisticRegressionLayer.negativeLogLikelihood(); } /** * Train the network running some unsupervised * pretraining followed by SGD/finetune * @param input the input to train on * @param labels the labels for the training examples(a matrix of the following format: * [0,1,0] where 0 represents the labels its not and 1 represents labels for the positive outcomes * @param otherParams the other parameters for child classes (algorithm specific parameters such as corruption level for SDA) */ public abstract void trainNetwork(Matrix input,Matrix labels,Object[] otherParams); /** * Creates a layer depending on the index. * The main reason this matters is for continuous variations such as the {@link CDBN} * where the first layer needs to be an {@link CRBM} for continuous inputs * @param input the input to the layer * @param nVisible the number of visible inputs * @param nHidden the number of hidden units * @param W the weight vector * @param hbias the hidden bias * @param vBias the visible bias * @param rng the rng to use (THiS IS IMPORTANT; YOU DO NOT WANT TO HAVE A MIS REFERENCED RNG OTHERWISE NUMBERS WILL BE MEANINGLESS) * @param index the index of the layer * @return a neural network layer such as {@link RBM} */ // public abstract NeuralNetwork createLayer(Matrix input,int nVisible,int nHidden, Matrix W,Matrix hbias,Matrix vBias,RandomGenerator rng,int index); public abstract NeuralNetworkVectorized[] createNetworkLayers(int numLayers); /** * Apply transforms to RBMs before we train * * * */ protected void applyTransforms() { // do we have RBMs at all if(this.preTrainingLayers == null || this.preTrainingLayers.length < 1) { throw new IllegalStateException("Layers not initialized"); } for (int i = 0; i < this.preTrainingLayers.length; i++) { if (weightTransforms.containsKey(i)) { // layers[i].setW(weightTransforms.get(i).apply(layers[i].getW())); this.preTrainingLayers[i].setConnectionWeights( weightTransforms.get(i).apply( this.preTrainingLayers[i].getConnectionWeights() ) ); } if (hiddenBiasTransforms.containsKey(i)) { preTrainingLayers[i].sethBias(getHiddenBiasTransforms().get(i).apply(preTrainingLayers[i].getHiddenBias())); } if (this.visibleBiasTransforms.containsKey(i)) { preTrainingLayers[i].setVisibleBias(getVisibleBiasTransforms().get(i).apply(preTrainingLayers[i].getVisibleBias())); } } } public synchronized double getMomentum() { return momentum; } public synchronized void setMomentum(double momentum) { this.momentum = momentum; } public synchronized Map<Integer, MatrixTransform> getWeightTransforms() { return weightTransforms; } public synchronized void setWeightTransforms( Map<Integer, MatrixTransform> weightTransforms) { this.weightTransforms = weightTransforms; } public synchronized void addWeightTransform( int layer,MatrixTransform transform) { this.weightTransforms.put(layer,transform); } public synchronized double getSparsity() { return sparsity; } public synchronized void setSparsity(double sparsity) { this.sparsity = sparsity; } public String generateNetworkSizeReport() { String out = ""; long hiddenLayerConnectionCount = 0; long preTrainLayerConnectionCount = 0; for ( int x = 0; x < this.numberLayers; x++ ) { hiddenLayerConnectionCount += MatrixUtils.length( this.hiddenLayers[ x ].connectionWeights ); } for ( int x = 0; x < this.numberLayers; x++ ) { preTrainLayerConnectionCount += MatrixUtils.length( this.preTrainingLayers[ x ].getConnectionWeights() ); } out += "Number of Hidden / RBM Layers: " + this.numberLayers + "\n"; out += "Total Hidden Layer Connection Count: " + hiddenLayerConnectionCount + "\n"; out += "Total PreTrain (RBM) Layer Connection Count: " + preTrainLayerConnectionCount + "\n"; return out; } public String generateNetworkStateReport() { String out = ""; out += "Number of Hidden / RBM Layers: " + this.numberLayers + "\n"; out += "inputNeuronCount: " + this.inputNeuronCount + "\n"; out += "l2: " + this.l2 + "\n"; out += "learningRateUpdate: " + this.learningRateUpdate + "\n"; out += "momentum: " + this.momentum + "\n"; out += "outputNeuronCount: " + this.outputNeuronCount + "\n"; out += "sparsity: " + this.sparsity + "\n"; out += "this.hiddenLayers.length: " + this.hiddenLayers.length + "\n"; out += "this.logisticRegressionLayer.l2: " + this.logisticRegressionLayer.l2 + "\n"; out += "this.logisticRegressionLayer.nIn: " + this.logisticRegressionLayer.nIn + "\n"; out += "this.logisticRegressionLayer.nOut: " + this.logisticRegressionLayer.nOut + "\n"; out += "this.logisticRegressionLayer.useRegularization: " + this.logisticRegressionLayer.useRegularization + "\n"; out += "this.useRegularization: " + this.useRegularization + "\n"; //out += "this.useRegularization: " + this. + "\n"; return out; } /** * Merges this network with the other one. * This is a weight averaging with the update of: * a += b - a / n * where a is a matrix on the network * b is the incoming matrix and n * is the batch size. * This update is performed across the network layers * as well as hidden layers and logistic layers * * @param network the network to merge with * @param batchSize the batch size (number of training examples) * to average by */ public void merge(BaseMultiLayerNeuralNetworkVectorized network, int batchSize) { if (network.numberLayers != this.numberLayers) { throw new IllegalArgumentException("Unable to merge networks that are not of equal length"); } for (int i = 0; i < this.numberLayers; i++) { // pretrain layers NeuralNetworkVectorized n = this.preTrainingLayers[i]; NeuralNetworkVectorized otherNetwork = network.preTrainingLayers[i]; n.merge(otherNetwork, batchSize); //tied weights: must be updated at the same time //getSigmoidLayers()[i].setB(n.gethBias()); this.hiddenLayers[i].biasTerms = n.getHiddenBias(); //getSigmoidLayers()[i].setW(n.getW()); this.hiddenLayers[i].connectionWeights = n.getConnectionWeights(); } //getLogLayer().merge(network.logLayer, batchSize); this.logisticRegressionLayer.merge(network.logisticRegressionLayer, batchSize); } }
package com.puppycrawl.tools.checkstyle.grammars; import java.lang.reflect.GenericArrayType; import java.lang.reflect.GenericDeclaration; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class MultiDimensionalArraysInGenericsTestInput { @SuppressWarnings("unused") void withUpperBound(List<? extends int[][]> list) {} @SuppressWarnings("unused") void withLowerBound(List<? super String[][]> list) {} @SuppressWarnings("unused") void withLowerBound2(List<? super String[][][]> list) {} static WildcardType getWildcardType(String methodName) throws Exception { ParameterizedType parameterType = (ParameterizedType) WildcardType.class .getDeclaredMethod(methodName, List.class) .getGenericParameterTypes()[0]; return (WildcardType) parameterType.getActualTypeArguments()[0]; } }
package edu.cornell.mannlib.vitro.webapp.web.templatemodels.individual; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestActionConstants; import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAction; import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.AddObjectPropStmt; import edu.cornell.mannlib.vitro.webapp.beans.Individual; import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty; import edu.cornell.mannlib.vitro.webapp.beans.Property; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder.ParamMap; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder.Route; import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyStatementDao; import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import freemarker.cache.TemplateLoader; import freemarker.template.Configuration; public abstract class ObjectPropertyTemplateModel extends PropertyTemplateModel { private static final Log log = LogFactory.getLog(ObjectPropertyTemplateModel.class); private static final String TYPE = "object"; private static final String EDIT_PATH = "edit/editRequestDispatch.jsp"; private static final String IMAGE_UPLOAD_PATH = "/uploadImages"; private static final String END_DATE_TIME_VARIABLE = "dateTimeEnd"; private static final Pattern ORDER_BY_END_DATE_TIME_PATTERN = /* ORDER BY DESC(?dateTimeEnd) * ORDER BY ?subclass ?dateTimeEnd * ORDER BY DESC(?subclass) DESC(?dateTimeEnd) */ Pattern.compile("ORDER\\s+BY\\s+((DESC\\()?\\?subclass\\)?\\s+)?DESC\\s*\\(\\s*\\?" + END_DATE_TIME_VARIABLE + "\\)", Pattern.CASE_INSENSITIVE); private static final String KEY_SUBJECT = "subject"; private static final String KEY_PROPERTY = "property"; private static final String DEFAULT_LIST_VIEW_QUERY_OBJECT_VARIABLE_NAME = "object"; private static final Pattern SUBJECT_PROPERTY_OBJECT_PATTERN = // ?subject ?property ?\w+ Pattern.compile("\\?" + KEY_SUBJECT + "\\s+\\?" + KEY_PROPERTY + "\\s+\\?(\\w+)"); protected static enum ConfigError { NO_SELECT_QUERY("Missing select query specification"), NO_SUBCLASS_SELECT("Query does not select a subclass variable"), NO_SUBCLASS_ORDER_BY("Query does not sort first by subclass variable"), NO_TEMPLATE("Missing template specification"), TEMPLATE_NOT_FOUND("Specified template does not exist"); String message; ConfigError(String message) { this.message = message; } public String getMessage() { return message; } public String toString() { return getMessage(); } } private PropertyListConfig config; private String objectKey; // Used for editing private boolean addAccess = false; //To allow for checking of special parameters private VitroRequest vitroRequest = null; ObjectPropertyTemplateModel(ObjectProperty op, Individual subject, VitroRequest vreq, EditingPolicyHelper policyHelper) throws InvalidConfigurationException { super(op, subject, policyHelper, vreq); this.vitroRequest = vreq; setName(op.getDomainPublic()); // Get the config for this object property try { config = new PropertyListConfig(op, policyHelper); } catch (InvalidConfigurationException e) { throw e; } catch (Exception e) { log.error(e, e); } objectKey = getQueryObjectVariableName(); // Determine whether a new statement can be added if (policyHelper != null) { RequestedAction action = new AddObjectPropStmt(subjectUri, propertyUri, RequestActionConstants.SOME_URI); if (policyHelper.isAuthorizedAction(action)) { addAccess = true; } } } protected List<Map<String, String>> getStatementData() { ObjectPropertyStatementDao opDao = vreq.getWebappDaoFactory().getObjectPropertyStatementDao(); return opDao.getObjectPropertyStatementsForIndividualByProperty(subjectUri, propertyUri, objectKey, getSelectQuery(), getConstructQueries()); } protected abstract boolean isEmpty(); @Override protected int getPropertyDisplayTier(Property p) { // For some reason ObjectProperty.getDomainDisplayTier() returns a String // rather than an int. That should probably be fixed. return Integer.parseInt(((ObjectProperty)p).getDomainDisplayTier()); } @Override protected Route getPropertyEditRoute() { return Route.OBJECT_PROPERTY_EDIT; } protected ConfigError checkQuery(String queryString) { if (StringUtils.isBlank(queryString)) { return ConfigError.NO_SELECT_QUERY; } return null; } private String getSelectQuery() { return config.selectQuery; } private Set<String> getConstructQueries() { return config.constructQueries; } protected String getTemplateName() { return config.templateName; } protected boolean hasDefaultListView() { return config.isDefaultConfig; } public static String getImageUploadUrl(String subjectUri, String action) { ParamMap params = new ParamMap( "entityUri", subjectUri, "action", action); return UrlBuilder.getUrl(IMAGE_UPLOAD_PATH, params); } /** Return the name of the primary object variable of the query by inspecting the query string. * The primary object is the X in the assertion "?subject ?property ?X". */ private String getQueryObjectVariableName() { String object = null; if (hasDefaultListView()) { object = DEFAULT_LIST_VIEW_QUERY_OBJECT_VARIABLE_NAME; log.debug("Using default list view for property " + propertyUri + ", so query object = '" + object + "'"); } else { String queryString = getSelectQuery(); Matcher m = SUBJECT_PROPERTY_OBJECT_PATTERN.matcher(queryString); if (m.find()) { object = m.group(1); log.debug("Query object for property " + propertyUri + " = '" + object + "'"); } } return object; } protected static ObjectPropertyTemplateModel getObjectPropertyTemplateModel(ObjectProperty op, Individual subject, VitroRequest vreq, EditingPolicyHelper policyHelper, List<ObjectProperty> populatedObjectPropertyList) { if (op.getCollateBySubclass()) { try { return new CollatedObjectPropertyTemplateModel(op, subject, vreq, policyHelper, populatedObjectPropertyList); } catch (InvalidConfigurationException e) { log.warn(e.getMessage()); // If the collated config is invalid, instantiate an UncollatedObjectPropertyTemplateModel instead. } } try { return new UncollatedObjectPropertyTemplateModel(op, subject, vreq, policyHelper, populatedObjectPropertyList); } catch (InvalidConfigurationException e) { log.error(e.getMessage()); return null; } } /** Apply post-processing to query results to prepare for template */ protected void postprocess(List<Map<String, String>> data) { if (log.isDebugEnabled()) { log.debug("Data for property " + getUri() + " before postprocessing"); logData(data); } ObjectPropertyDataPostProcessor postprocessor = config.postprocessor; if (postprocessor == null) { log.debug("No postprocessor for property " + getUri()); return; } else { log.debug("Using postprocessor " + postprocessor.getClass().getName() + " for property " + getUri()); } postprocessor.process(data); if (log.isDebugEnabled()) { log.debug("Data for property " + getUri() + " after postprocessing"); logData(data); } } protected void logData(List<Map<String, String>> data) { if (log.isDebugEnabled()) { int count = 1; for (Map<String, String> map : data) { log.debug("List item " + count); count++; for (String key : map.keySet()) { log.debug(key + ": " + map.get(key)); } } } } /** The SPARQL query results may contain duplicate rows for a single object, if there are multiple solutions * to the entire query. Remove duplicates here by arbitrarily selecting only the first row returned. * @param List<Map<String, String>> data */ protected void removeDuplicates(List<Map<String, String>> data) { String objectVariableName = getObjectKey(); if (objectVariableName == null) { log.error("Cannot remove duplicate statements for property " + getUri() + " because no object found to dedupe."); return; } List<String> foundObjects = new ArrayList<String>(); log.debug("Removing duplicates from property: " + getUri()); Iterator<Map<String, String>> dataIterator = data.iterator(); while (dataIterator.hasNext()) { Map<String, String> map = dataIterator.next(); String objectValue = map.get(objectVariableName); // We arbitrarily remove all but the first. Not sure what selection criteria could be brought to bear on this. if (foundObjects.contains(objectValue)) { dataIterator.remove(); } else { foundObjects.add(objectValue); } } } /* Post-processing that must occur after collation, because it does reordering on collated subclass * lists rather than on the entire list. This should ideally be configurable in the config file * like the pre-collation post-processing, but for now due to time constraints it applies to all views. */ protected void postprocessStatementList(List<ObjectPropertyStatementTemplateModel> statements) { moveNullEndDateTimesToTop(statements); } /* SPARQL ORDER BY gives null values the lowest value, so null datetimes occur at the end * of a list in descending sort order. Generally we assume that a null end datetime means the * activity is ongoing in the present, so we want to display those at the top of the list. * Application of this method should be configurable in the config file, but for now due to * time constraints it applies to all views that sort by DESC(?dateTimeEnd), and the variable * name is hard-coded here. (Note, therefore, that using a different variable name * effectively turns off this post-processing.) */ protected void moveNullEndDateTimesToTop(List<ObjectPropertyStatementTemplateModel> statements) { String queryString = getSelectQuery(); Matcher m = ORDER_BY_END_DATE_TIME_PATTERN.matcher(queryString); if ( ! m.find() ) { return; } // Store the statements with null end datetimes in a temporary list, remove them from the original list, // and move them back to the top of the original list. List<ObjectPropertyStatementTemplateModel> tempList = new ArrayList<ObjectPropertyStatementTemplateModel>(); Iterator<ObjectPropertyStatementTemplateModel> iterator = statements.iterator(); while (iterator.hasNext()) { ObjectPropertyStatementTemplateModel stmt = (ObjectPropertyStatementTemplateModel)iterator.next(); String dateTimeEnd = (String) stmt.get(END_DATE_TIME_VARIABLE); if (dateTimeEnd == null) { // If the first statement has a null end datetime, all subsequent statements in the list also do, // so there is nothing to reorder. if (statements.indexOf(stmt) == 0) { break; } tempList.add(stmt); iterator.remove(); } } // Put all the statements with null end datetimes at the top of the list, preserving their original order. statements.addAll(0, tempList); } protected String getObjectKey() { return objectKey; } private class PropertyListConfig { private static final String CONFIG_FILE_PATH = "/config/"; private static final String DEFAULT_CONFIG_FILE_NAME = "listViewConfig-default.xml"; private static final String NODE_NAME_QUERY_CONSTRUCT = "query-construct"; private static final String NODE_NAME_QUERY_SELECT = "query-select"; private static final String NODE_NAME_TEMPLATE = "template"; private static final String NODE_NAME_POSTPROCESSOR = "postprocessor"; private static final String NODE_NAME_COLLATED = "collated"; private static final String NODE_NAME_CRITICAL_DATA_REQUIRED = "critical-data-required"; /* NB The default post-processor is not the same as the post-processor for the default view. The latter * actually defines its own post-processor, whereas the default post-processor is used for custom views * that don't define a post-processor, to ensure that the standard post-processing applies. */ private static final String DEFAULT_POSTPROCESSOR = "edu.cornell.mannlib.vitro.webapp.web.templatemodels.individual.DefaultObjectPropertyDataPostProcessor"; private boolean isDefaultConfig; private Set<String> constructQueries; private String selectQuery; private String templateName; private ObjectPropertyDataPostProcessor postprocessor = null; PropertyListConfig(ObjectProperty op, EditingPolicyHelper policyHelper) throws InvalidConfigurationException { // Get the custom config filename String configFileName = vreq.getWebappDaoFactory().getObjectPropertyDao().getCustomListViewConfigFileName(op); if (configFileName == null) { // no custom config; use default config configFileName = DEFAULT_CONFIG_FILE_NAME; } log.debug("Using list view config file " + configFileName + " for object property " + op.getURI()); String configFilePath = getConfigFilePath(configFileName); try { File config = new File(configFilePath); if ( ! isDefaultConfig(configFileName) && ! config.exists() ) { log.warn("Can't find config file " + configFilePath + " for object property " + op.getURI() + "\n" + ". Using default config file instead."); configFilePath = getConfigFilePath(DEFAULT_CONFIG_FILE_NAME); // Should we test for the existence of the default, and throw an error if it doesn't exist? } setValuesFromConfigFile(configFilePath, op, vreq.getWebappDaoFactory(), policyHelper); } catch (Exception e) { log.error("Error processing config file " + configFilePath + " for object property " + op.getURI(), e); // What should we do here? } if ( ! isDefaultConfig(configFileName) ) { ConfigError configError = checkConfiguration(); if ( configError != null ) { // the configuration contains an error // If this is a collated property, throw an error: this results in creating an // UncollatedPropertyTemplateModel instead. if (ObjectPropertyTemplateModel.this instanceof CollatedObjectPropertyTemplateModel) { throw new InvalidConfigurationException(configError.getMessage()); } // Otherwise, switch to the default config log.warn("Invalid list view config for object property " + op.getURI() + " in " + configFilePath + ":\n" + configError + " Using default config instead."); configFilePath = getConfigFilePath(DEFAULT_CONFIG_FILE_NAME); setValuesFromConfigFile(configFilePath, op, vreq.getWebappDaoFactory(), policyHelper); } } isDefaultConfig = isDefaultConfig(configFileName); } private boolean isDefaultConfig(String configFileName) { return configFileName.equals(DEFAULT_CONFIG_FILE_NAME); } private ConfigError checkConfiguration() { ConfigError error = ObjectPropertyTemplateModel.this.checkQuery(selectQuery); if (error != null) { return error; } if (StringUtils.isBlank(selectQuery)) { return ConfigError.NO_SELECT_QUERY; } if ( StringUtils.isBlank(templateName)) { return ConfigError.NO_TEMPLATE; } Configuration fmConfig = (Configuration) vreq.getAttribute("freemarkerConfig"); TemplateLoader tl = fmConfig.getTemplateLoader(); try { if ( tl.findTemplateSource(templateName) == null ) { return ConfigError.TEMPLATE_NOT_FOUND; } } catch (IOException e) { log.error("Error finding template " + templateName, e); } return null; } private void setValuesFromConfigFile(String configFilePath, ObjectProperty op, WebappDaoFactory wdf, EditingPolicyHelper policyHelper) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db; try { db = dbf.newDocumentBuilder(); Document doc = db.parse(configFilePath); String propertyUri = op.getURI(); // Required values selectQuery = getSelectQuery(doc, propertyUri, policyHelper); templateName = getConfigValue(doc, NODE_NAME_TEMPLATE, propertyUri); // Optional values constructQueries = getConfigValues(doc, NODE_NAME_QUERY_CONSTRUCT, propertyUri); String postprocessorName = getConfigValue(doc, NODE_NAME_POSTPROCESSOR, propertyUri); if (StringUtils.isBlank(postprocessorName)) { log.debug("No postprocessor specified for property " + propertyUri + ". Using default postprocessor."); postprocessorName = DEFAULT_POSTPROCESSOR; } try { getPostProcessor(postprocessorName, wdf); } catch (Exception e) { if (! postprocessorName.equals(DEFAULT_POSTPROCESSOR)) { log.debug("Cannot find postprocessor specified for property " + propertyUri + ". Using default postprocessor."); postprocessorName = DEFAULT_POSTPROCESSOR; getPostProcessor(postprocessorName, wdf); } } } catch (Exception e) { log.error("Error processing config file " + configFilePath, e); } } private String getSelectQuery(Document doc, String propertyUri, EditingPolicyHelper policyHelper) { Node selectQueryNode = doc.getElementsByTagName(NODE_NAME_QUERY_SELECT).item(0); String value = null; if (selectQueryNode != null) { boolean collated = ObjectPropertyTemplateModel.this instanceof CollatedObjectPropertyTemplateModel; /* If not editing the page (policyHelper == null), hide statements with missing linked individual or other * critical information missing (e.g., anchor and url on a link); otherwise, show these statements. * We might want to refine this based on whether the user can edit the statement in question, but that * would require a completely different approach: include the statement in the query results, and then during the * postprocessing phase, check the editing policy, and remove the statement if it's not editable. We would not * preprocess the query, as here. */ boolean criticalDataRequired = policyHelper == null; NodeList children = selectQueryNode.getChildNodes(); int childCount = children.getLength(); value = ""; for (int i = 0; i < childCount; i++) { Node node = children.item(i); if (node.getNodeName().equals(NODE_NAME_COLLATED)) { if (collated) { value += node.getChildNodes().item(0).getNodeValue(); } // else ignore this node } else if (node.getNodeName().equals(NODE_NAME_CRITICAL_DATA_REQUIRED)) { if (criticalDataRequired) { value += node.getChildNodes().item(0).getNodeValue(); } // else ignore this node } else { value += node.getNodeValue(); } } log.debug("Found config parameter " + NODE_NAME_QUERY_SELECT + " for object property " + propertyUri + " with value " + value); } else { log.error("No value found for config parameter " + NODE_NAME_QUERY_SELECT + " for object property " + propertyUri); } return value; } private void getPostProcessor(String name, WebappDaoFactory wdf) throws Exception { Class<?> postprocessorClass = Class.forName(name); Constructor<?> constructor = postprocessorClass.getConstructor(ObjectPropertyTemplateModel.class, WebappDaoFactory.class); postprocessor = (ObjectPropertyDataPostProcessor) constructor.newInstance(ObjectPropertyTemplateModel.this, wdf); } private String getConfigValue(Document doc, String nodeName, String propertyUri) { Node node = doc.getElementsByTagName(nodeName).item(0); String value = null; if (node != null) { value = node.getChildNodes().item(0).getNodeValue(); log.debug("Found config parameter " + nodeName + " for object property " + propertyUri + " with value " + value); } else { log.debug("No value found for config parameter " + nodeName + " for object property " + propertyUri); } return value; } private Set<String> getConfigValues(Document doc, String nodeName, String propertyUri) { Set<String> values = null; NodeList nodes = doc.getElementsByTagName(nodeName); int nodeCount = nodes.getLength(); if (nodeCount > 0) { values = new HashSet<String>(nodeCount); for (int i = 0; i < nodeCount; i++) { Node node = nodes.item(i); String value = node.getChildNodes().item(0).getNodeValue(); values.add(value); log.debug("Found config parameter " + nodeName + " for object property " + propertyUri + " with value " + value); } } else { log.debug("No values found for config parameter " + nodeName + " for object property " + propertyUri); } return values; } private String getConfigFilePath(String filename) { return servletContext.getRealPath(CONFIG_FILE_PATH + filename); } } protected class InvalidConfigurationException extends Exception { private static final long serialVersionUID = 1L; protected InvalidConfigurationException(String s) { super(s); } } /* Access methods for templates */ public String getType() { return TYPE; } public String getTemplate() { return config.templateName; } public abstract boolean isCollatedBySubclass(); @Override public String getAddUrl() { String addUrl = ""; if (addAccess) { if (propertyUri.equals(VitroVocabulary.IND_MAIN_IMAGE)) { return getImageUploadUrl(subjectUri, "add"); } ParamMap params = new ParamMap( "subjectUri", subjectUri, "predicateUri", propertyUri); //Check if special parameters being sent HashMap<String, String> specialParams = UrlBuilder.getSpecialParams(vitroRequest); if(specialParams.size() > 0) { params.putAll(specialParams); } addUrl = UrlBuilder.getUrl(EDIT_PATH, params); } return addUrl; } }
package fr.tvbarthel.apps.cameracolorpicker.activities; import android.animation.Animator; import android.animation.ObjectAnimator; import android.annotation.SuppressLint; import android.graphics.PorterDuff; import android.graphics.Rect; import android.hardware.Camera; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Gravity; import android.view.MenuItem; import android.view.View; import android.view.ViewTreeObserver; import android.widget.FrameLayout; import android.widget.TextView; import fr.tvbarthel.apps.cameracolorpicker.R; import fr.tvbarthel.apps.cameracolorpicker.data.ColorItem; import fr.tvbarthel.apps.cameracolorpicker.data.ColorItems; import fr.tvbarthel.apps.cameracolorpicker.utils.Cameras; import fr.tvbarthel.apps.cameracolorpicker.views.CameraColorPickerPreview; /** * An {@link android.support.v7.app.ActionBarActivity} for picking colors by using the camera of the device. * <p/> * The user aims at a color with the camera of the device, when they click on the preview the color is selected. * An animation notifies the user of the selection. * <p/> * The last selected color can be saved by clicking the save button. * An animation notifies the user of the save. */ public class ColorPickerActivity extends ActionBarActivity implements CameraColorPickerPreview.OnColorSelectedListener, View.OnClickListener { /** * A tag used in the logs. */ protected static final String TAG = ColorPickerActivity.class.getSimpleName(); /** * The name of the property that animates the 'picked color'. * <p/> * Used by {@link fr.tvbarthel.apps.cameracolorpicker.activities.ColorPickerActivity#mPickedColorProgressAnimator}. */ protected static final String PICKED_COLOR_PROGRESS_PROPERTY_NAME = "pickedColorProgress"; /** * The name of the property that animates the 'save completed'. * <p/> * Used by {@link fr.tvbarthel.apps.cameracolorpicker.activities.ColorPickerActivity#mSaveCompletedProgressAnimator}. */ protected static final String SAVE_COMPLETED_PROGRESS_PROPERTY_NAME = "saveCompletedProgress"; /** * A safe way to get an instance of the back {@link android.hardware.Camera}. */ private static Camera getCameraInstance() { Camera c = null; try { c = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK); } catch (Exception e) { Log.e(TAG, e.getMessage()); } return c; } /** * An instance of the {@link android.hardware.Camera} used for displaying the preview. */ protected Camera mCamera; /** * A boolean for knowing the orientation of the activity. */ protected boolean mIsPortrait; /** * A simple {@link android.widget.FrameLayout} that contains the preview. */ protected FrameLayout mPreviewContainer; /** * The {@link fr.tvbarthel.apps.cameracolorpicker.views.CameraColorPickerPreview} used for the preview. */ protected CameraColorPickerPreview mCameraPreview; /** * A reference to the {@link fr.tvbarthel.apps.cameracolorpicker.activities.ColorPickerActivity.CameraAsyncTask} that gets the {@link android.hardware.Camera}. */ protected CameraAsyncTask mCameraAsyncTask; /** * The color selected by the user. * <p/> * The user "selects" a color by pointing a color with the camera. */ protected int mSelectedColor; /** * The last picked color. * <p/> * The user "picks" a color by clicking the preview. */ protected int mLastPickedColor; /** * A simple {@link android.view.View} used for showing the picked color. */ protected View mPickedColorPreview; /** * A simple {@link android.view.View} used for animating the color being picked. */ protected View mPickedColorPreviewAnimated; /** * An {@link android.animation.ObjectAnimator} used for animating the color being picked. */ protected ObjectAnimator mPickedColorProgressAnimator; /** * The delta for the translation on the x-axis of the mPickedColorPreviewAnimated. */ protected float mTranslationDeltaX; /** * The delta for the translation on the y-axis of the mPickedColorPreviewAnimated. */ protected float mTranslationDeltaY; /** * A simple {@link android.widget.TextView} used for showing a human readable representation of the picked color. */ protected TextView mColorPreviewText; /** * A simple {@link android.view.View} used for showing the selected color. */ protected View mPointerRing; /** * An icon representing the "save completed" state. */ protected View mSaveCompletedIcon; /** * The save button. */ protected View mSaveButton; /** * A float representing the progress of the "save completed" state. */ protected float mSaveCompletedProgress; /** * An {@link android.animation.ObjectAnimator} used for animating the "save completed" state. */ protected ObjectAnimator mSaveCompletedProgressAnimator; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_color_picker); initPickedColorProgressAnimator(); initSaveCompletedProgressAnimator(); initViews(); initTranslationDeltas(); } @Override protected void onResume() { super.onResume(); // Setup the camera asynchronously. mCameraAsyncTask = new CameraAsyncTask(); mCameraAsyncTask.execute(); } @Override protected void onPause() { super.onPause(); // Cancel the Camera AsyncTask. mCameraAsyncTask.cancel(true); // Release the camera. if (mCamera != null) { mCamera.stopPreview(); mCamera.setPreviewCallback(null); mCamera.release(); mCamera = null; } // Remove the camera preview if (mCameraPreview != null) { mPreviewContainer.removeView(mCameraPreview); } } @Override public boolean onOptionsItemSelected(MenuItem item) { final int itemId = item.getItemId(); boolean handled; switch (itemId) { case android.R.id.home: finish(); handled = true; break; default: handled = super.onOptionsItemSelected(item); } return handled; } @Override public void onColorSelected(int color) { mSelectedColor = color; mPointerRing.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_ATOP); } @Override public void onClick(View v) { if (v == mCameraPreview) { animatePickedColor(mSelectedColor); } else if (v.getId() == R.id.activity_color_picker_save_button) { ColorItems.saveColorItem(this, new ColorItem(mLastPickedColor)); setSaveCompleted(true); } } /** * Initialize the views used in this activity. * <p/> * Internally find the view by their ids and set the click listeners. */ protected void initViews() { mIsPortrait = getResources().getBoolean(R.bool.is_portrait); mPreviewContainer = (FrameLayout) findViewById(R.id.activity_color_picker_preview_container); mPickedColorPreview = findViewById(R.id.activity_color_picker_color_preview); mPickedColorPreviewAnimated = findViewById(R.id.activity_color_picker_animated_preview); mColorPreviewText = (TextView) findViewById(R.id.activity_color_picker_color_preview_text); mPointerRing = findViewById(R.id.activity_color_picker_pointer_ring); mSaveCompletedIcon = findViewById(R.id.activity_color_picker_save_completed); mSaveButton = findViewById(R.id.activity_color_picker_save_button); mSaveButton.setOnClickListener(this); mLastPickedColor = ColorItems.getLastPickedColor(this); applyPreviewColor(mLastPickedColor); } /** * Initialize the deltas used for the translation of the preview of the picked color. */ @SuppressLint("NewApi") protected void initTranslationDeltas() { ViewTreeObserver vto = mPointerRing.getViewTreeObserver(); if (vto.isAlive()) { vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { ViewTreeObserver vto = mPointerRing.getViewTreeObserver(); if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN) { vto.removeGlobalOnLayoutListener(this); } else { vto.removeOnGlobalLayoutListener(this); } final Rect pointerRingRect = new Rect(); final Rect colorPreviewAnimatedRect = new Rect(); mPointerRing.getGlobalVisibleRect(pointerRingRect); mPickedColorPreviewAnimated.getGlobalVisibleRect(colorPreviewAnimatedRect); mTranslationDeltaX = pointerRingRect.left - colorPreviewAnimatedRect.left; mTranslationDeltaY = pointerRingRect.top - colorPreviewAnimatedRect.top; } }); } } /** * Initialize the animator used for the progress of the picked color. */ protected void initPickedColorProgressAnimator() { mPickedColorProgressAnimator = ObjectAnimator.ofFloat(this, PICKED_COLOR_PROGRESS_PROPERTY_NAME, 1f, 0f); mPickedColorProgressAnimator.setDuration(400); mPickedColorProgressAnimator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { mPickedColorPreviewAnimated.setVisibility(View.VISIBLE); mPickedColorPreviewAnimated.getBackground().setColorFilter(mSelectedColor, PorterDuff.Mode.SRC_ATOP); } @Override public void onAnimationEnd(Animator animation) { ColorItems.saveLastPickedColor(ColorPickerActivity.this, mLastPickedColor); applyPreviewColor(mLastPickedColor); mPickedColorPreviewAnimated.setVisibility(View.INVISIBLE); } @Override public void onAnimationCancel(Animator animation) { mPickedColorPreviewAnimated.setVisibility(View.INVISIBLE); } @Override public void onAnimationRepeat(Animator animation) { } }); } /** * Initialize the animator used for the progress of the "save completed" state. */ protected void initSaveCompletedProgressAnimator() { mSaveCompletedProgressAnimator = ObjectAnimator.ofFloat(this, SAVE_COMPLETED_PROGRESS_PROPERTY_NAME, 1f, 0f); } /** * Apply the preview color. * <p/> * Display the preview color and its human representation. * * @param previewColor the preview color to apply. */ protected void applyPreviewColor(int previewColor) { setSaveCompleted(false); mPickedColorPreview.getBackground().setColorFilter(previewColor, PorterDuff.Mode.SRC_ATOP); mColorPreviewText.setText(ColorItem.makeHexString(previewColor)); } /** * Animate the color being picked. * * @param pickedColor the color being picked. */ protected void animatePickedColor(int pickedColor) { mLastPickedColor = pickedColor; if (mPickedColorProgressAnimator.isRunning()) { mPickedColorProgressAnimator.cancel(); } mPickedColorProgressAnimator.start(); } /** * Set the "save completed" state. * <p/> * True means that the save is completed. The preview color should not be saved again. * * @param isSaveCompleted the "save completed" state. */ protected void setSaveCompleted(boolean isSaveCompleted) { mSaveButton.setEnabled(!isSaveCompleted); mSaveCompletedProgressAnimator.cancel(); mSaveCompletedProgressAnimator.setFloatValues(mSaveCompletedProgress, isSaveCompleted ? 0f : 1f); mSaveCompletedProgressAnimator.start(); } /** * Set the progress of the picked color animation. * <p/> * Used by {@link fr.tvbarthel.apps.cameracolorpicker.activities.ColorPickerActivity#mPickedColorProgressAnimator}. * * @param progress A value in closed range [0,1] representing the progress of the picked color animation. */ protected void setPickedColorProgress(float progress) { final float fastOppositeProgress = (float) Math.pow(1 - progress, 0.3f); final float translationX = (float) (mTranslationDeltaX * Math.pow(progress, 2f)); final float translationY = mTranslationDeltaY * progress; mPickedColorPreviewAnimated.setTranslationX(translationX); mPickedColorPreviewAnimated.setTranslationY(translationY); mPickedColorPreviewAnimated.setScaleX(fastOppositeProgress); mPickedColorPreviewAnimated.setScaleY(fastOppositeProgress); } /** * Set the progress of the animation of the "save completed" state. * <p/> * Used by {@link fr.tvbarthel.apps.cameracolorpicker.activities.ColorPickerActivity#mSaveCompletedProgressAnimator}. * * @param progress A value in closed range [0,1] representing the progress of the animation of the "save completed" state. */ protected void setSaveCompletedProgress(float progress) { mSaveButton.setScaleX(progress); mSaveButton.setRotation(45 * (1 - progress)); mSaveCompletedIcon.setScaleX(1 - progress); mSaveCompletedProgress = progress; } /** * Async task used to configure and start the camera preview. */ private class CameraAsyncTask extends AsyncTask<Void, Void, Camera> { /** * The {@link android.view.ViewGroup.LayoutParams} used for adding the preview to its container. */ protected FrameLayout.LayoutParams mPreviewParams; @Override protected Camera doInBackground(Void... params) { Camera camera = getCameraInstance(); if (camera == null) { ColorPickerActivity.this.finish(); } else { //configure Camera parameters Camera.Parameters cameraParameters = camera.getParameters(); //get optimal camera preview size according to the layout used to display it Camera.Size bestSize = Cameras.getBestPreviewSize( cameraParameters.getSupportedPreviewSizes() , mPreviewContainer.getWidth() , mPreviewContainer.getHeight() , mIsPortrait); //set optimal camera preview cameraParameters.setPreviewSize(bestSize.width, bestSize.height); camera.setParameters(cameraParameters); //set camera orientation to match with current device orientation Cameras.setCameraDisplayOrientation(ColorPickerActivity.this, camera); //get proportional dimension for the layout used to display preview according to the preview size used int[] adaptedDimension = Cameras.getProportionalDimension( bestSize , mPreviewContainer.getWidth() , mPreviewContainer.getHeight() , mIsPortrait); //set up params for the layout used to display the preview mPreviewParams = new FrameLayout.LayoutParams(adaptedDimension[0], adaptedDimension[1]); mPreviewParams.gravity = Gravity.CENTER; } return camera; } @Override protected void onPostExecute(Camera camera) { super.onPostExecute(camera); // Check if the task is cancelled before trying to use the camera. if (!isCancelled()) { mCamera = camera; if (mCamera == null) { ColorPickerActivity.this.finish(); } else { //set up camera preview mCameraPreview = new CameraColorPickerPreview(ColorPickerActivity.this, mCamera); mCameraPreview.setOnColorSelectedListener(ColorPickerActivity.this); mCameraPreview.setOnClickListener(ColorPickerActivity.this); //add camera preview mPreviewContainer.addView(mCameraPreview, 0, mPreviewParams); } } } @Override protected void onCancelled(Camera camera) { super.onCancelled(camera); if (camera != null) { camera.release(); } } } }
package org.eclipse.birt.report.designer.ui.dialogs; import java.math.BigDecimal; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import org.eclipse.birt.core.data.DataTypeUtil; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.core.format.DateFormatter; import org.eclipse.birt.core.format.NumberFormatter; import org.eclipse.birt.core.format.StringFormatter; import org.eclipse.birt.report.designer.data.ui.util.SelectValueFetcher; import org.eclipse.birt.report.designer.internal.ui.dialogs.BaseDialog; import org.eclipse.birt.report.designer.internal.ui.dialogs.ImportValueDialog; import org.eclipse.birt.report.designer.internal.ui.dialogs.SelectionChoiceDialog; import org.eclipse.birt.report.designer.internal.ui.swt.custom.ITableAreaModifier; import org.eclipse.birt.report.designer.internal.ui.swt.custom.TableArea; import org.eclipse.birt.report.designer.internal.ui.util.DataUtil; import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler; import org.eclipse.birt.report.designer.internal.ui.util.IHelpContextIds; import org.eclipse.birt.report.designer.internal.ui.util.UIUtil; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.designer.ui.IReportGraphicConstants; import org.eclipse.birt.report.designer.ui.ReportPlatformUIImages; import org.eclipse.birt.report.designer.ui.actions.NewDataSetAction; import org.eclipse.birt.report.designer.ui.views.attributes.providers.ChoiceSetFactory; import org.eclipse.birt.report.designer.util.DEUtil; import org.eclipse.birt.report.model.api.DataSetHandle; import org.eclipse.birt.report.model.api.PropertyHandle; import org.eclipse.birt.report.model.api.ResultSetColumnHandle; import org.eclipse.birt.report.model.api.ScalarParameterHandle; import org.eclipse.birt.report.model.api.SelectionChoiceHandle; import org.eclipse.birt.report.model.api.StructureFactory; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.birt.report.model.api.elements.ReportDesignConstants; import org.eclipse.birt.report.model.api.elements.structures.SelectionChoice; import org.eclipse.birt.report.model.api.metadata.IChoice; import org.eclipse.birt.report.model.api.metadata.IChoiceSet; import org.eclipse.birt.report.model.api.util.ParameterValidationUtil; import org.eclipse.birt.report.model.api.util.StringUtil; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.ISharedImages; import com.ibm.icu.util.ULocale; /** * The dialog used to create or edit a parameter */ public class ParameterDialog extends BaseDialog { private static final String CHOICE_NO_DEFAULT = Messages.getString( "ParameterDialog.Choice.NoDefault" ); //$NON-NLS-1$ // private static final String CHOICE_NULL_VALUE = Messages.getString( // "ParameterDialog.Choice.NullValue" ); //$NON-NLS-1$ private static final String CHOICE_NONE = Messages.getString( "ParameterDialog.Choice.None" ); //$NON-NLS-1$ private static final String CHOICE_DISPLAY_TEXT = Messages.getString( "ParameterDialog.Choice.DisplayText" ); //$NON-NLS-1$ private static final String CHOICE_VALUE_COLUMN = Messages.getString( "ParameterDialog.Choice.ValueColumn" ); //$NON-NLS-1$ private static final String CHOICE_ASCENDING = Messages.getString( "ParameterDialog.Choice.ASCENDING" ); //$NON-NLS-1$ private static final String CHOICE_DESCENDING = Messages.getString( "ParameterDialog.Choice.DESCENDING" ); //$NON-NLS-1$ private static final String CHOICE_SELECT_VALUE = Messages.getString( "ParameterDialog.Choice.SelectValue" ); //$NON-NLS-1$ // private static final String CHOICE_BLANK_VALUE = Messages.getString( // "ParameterDialog.Choice.BlankValue" ); //$NON-NLS-1$ private static final String GROUP_MORE_OPTION = Messages.getString( "ParameterDialog.Group.MoreOption" ); //$NON-NLS-1$ private static final String LABEL_NAME = Messages.getString( "ParameterDialog.Label.Name" ); //$NON-NLS-1$ // private static final String LABEL_DATETIME_PROMPT = Messages.getString( // "ParameterDialog.Label.DateTImePrompt" ); //$NON-NLS-1$ private static final String LABEL_DATETIME_PROMPT = Messages.getFormattedString( "ParameterDialog.datetime.prompt", new String[]{"yyyy-MM-dd HH:mm:ss.SSS"} ); //$NON-NLS-1$ //$NON-NLS-2$ // private static final String LABEL_DATE_PROMPT = // Messages.getFormattedString( "ParameterDialog.date.prompt", new // String[]{"MM/DD/YYYY"} ); //$NON-NLS-1$ //$NON-NLS-2$ private static final String LABEL_DATE_PROMPT = Messages.getFormattedString( "ParameterDialog.date.prompt", new String[]{"yyyy-MM-dd"} ); //$NON-NLS-1$ //$NON-NLS-2$ // private static final String LABEL_TIME_PROMPT = // Messages.getFormattedString( "ParameterDialog.time.prompt", new // String[]{"hh:mm:ss AM/PM"} ); //$NON-NLS-1$ //$NON-NLS-2$ private static final String LABEL_TIME_PROMPT = Messages.getFormattedString( "ParameterDialog.time.prompt", new String[]{"hh:mm:ss"} ); //$NON-NLS-1$ //$NON-NLS-2$ private static final String LABEL_PROMPT_TEXT = Messages.getString( "ParameterDialog.Label.PromptText" ); //$NON-NLS-1$ private static final String LABEL_PARAM_DATA_TYPE = Messages.getString( "ParameterDialog.Label.DataType" ); //$NON-NLS-1$ private static final String LABEL_DISPALY_TYPE = Messages.getString( "ParameterDialog.Label.DisplayType" ); //$NON-NLS-1$ private static final String LABEL_DEFAULT_VALUE = Messages.getString( "ParameterDialog.Label.DefaultValue" ); //$NON-NLS-1$ private static final String LABEL_HELP_TEXT = Messages.getString( "ParameterDialog.Label.HelpText" ); //$NON-NLS-1$ private static final String LABEL_LIST_OF_VALUE = Messages.getString( "ParameterDialog.Label.ListOfValue" ); //$NON-NLS-1$ private static final String LABEL_SORT_GROUP = Messages.getString( "ParameterDialog.Label.SortGroup" ); //$NON-NLS-1$ private static final String LABEL_VALUES = Messages.getString( "ParameterDialog.Label.Value" ); //$NON-NLS-1$ private static final String LABEL_FORMAT = Messages.getString( "ParameterDialog.Label.Format" ); //$NON-NLS-1$ private static final String LABEL_LIST_LIMIT = Messages.getString( "ParameterDialog.Label.Listlimit" ); //$NON-NLS-1$ private static final String LABEL_NULL = Messages.getString( "ParameterDialog.Label.Null" ); //$NON-NLS-1$ private static final String LABEL_SELECT_DISPLAY_TEXT = Messages.getString( "ParameterDialog.Label.SelectDisplayText" ); //$NON-NLS-1$ private static final String LABEL_SELECT_VALUE_COLUMN = Messages.getString( "ParameterDialog.Label.SelectValueColumn" ); //$NON-NLS-1$ private static final String LABEL_SELECT_DATA_SET = Messages.getString( "ParameterDialog.Label.SelectDataSet" ); //$NON-NLS-1$ private static final String LABEL_PREVIEW = Messages.getString( "ParameterDialog.Label.Preview" ); //$NON-NLS-1$ private static final String LABEL_SORT_KEY = Messages.getString( "ParameterDialog.Label.SortKey" ); //$NON-NLS-1$ private static final String LABEL_SORT_DIRECTION = Messages.getString( "ParameterDialog.Label.SortDirection" ); //$NON-NLS-1$ private static final String CHECKBOX_ISREQUIRED = Messages.getString( "ParameterDialog.CheckBox.IsRequired" ); //$NON-NLS-1$ private static final String CHECKBOX_DO_NOT_ECHO = Messages.getString( "ParameterDialog.CheckBox.DoNotEchoInput" ); //$NON-NLS-1$ private static final String CHECKBOX_HIDDEN = Messages.getString( "ParameterDialog.CheckBox.Hidden" ); //$NON-NLS-1$ private static final String CHECKBOX_DISTINCT = Messages.getString( "ParameterDialog.CheckBox.Distinct" ); //$NON-NLS-1$ private static final String BUTTON_LABEL_CHANGE_FORMAT = Messages.getString( "ParameterDialog.Button.ChangeFormat" ); //$NON-NLS-1$ private static final String BUTTON_LABEL_IMPORT = Messages.getString( "ParameterDialog.Button.ImportValue" ); //$NON-NLS-1$ private static final String BUTTON_LABEL_SET_DEFAULT = Messages.getString( "ParameterDialog.Button.SetDefault" ); //$NON-NLS-1$ private static final String BUTTON_LABEL_REMOVE_DEFAULT = Messages.getString( "ParameterDialog.Button.RemoveDefault" ); //$NON-NLS-1$ private static final String BUTTON_CREATE_DATA_SET = Messages.getString( "ParameterDialog.Button.CreateDataSet" ); //$NON-NLS-1$ private static final String RADIO_DYNAMIC = Messages.getString( "ParameterDialog.Radio.Dynamic" ); //$NON-NLS-1$ private static final String CHECK_ALLOW_MULTI = Messages.getString( "ParameterDialog.Check.AllowMulti" ); //$NON-NLS-1$ private static final String RADIO_STATIC = Messages.getString( "ParameterDialog.Radio.Static" ); //$NON-NLS-1$ private static final String ERROR_TITLE_INVALID_LIST_LIMIT = Messages.getString( "ParameterDialog.ErrorTitle.InvalidListLimit" ); //$NON-NLS-1$ private static final String ERROR_MSG_CANNOT_BE_BLANK = Messages.getString( "ParameterDialog.ErrorMessage.CanootBeBlank" ); //$NON-NLS-1$ private static final String ERROR_MSG_CANNOT_BE_NULL = Messages.getString( "ParameterDialog.ErrorMessage.CanootBeNull" ); //$NON-NLS-1$ private static final String ERROR_MSG_DUPLICATED_VALUE = Messages.getString( "ParameterDialog.ErrorMessage.DuplicatedValue" ); //$NON-NLS-1$ private static final String ERROR_MSG_DUPLICATED_LABEL = Messages.getString( "ParameterDialog.ErrorMessage.DuplicatedLabel" ); //$NON-NLS-1$ private static final String ERROR_MSG_DUPLICATED_LABELKEY = Messages.getString( "ParameterDialog.ErrorMessage.DuplicatedLabelKey" ); //$NON-NLS-1$ private static final String ERROR_MSG_MISMATCH_DATA_TYPE = Messages.getString( "ParameterDialog.ErrorMessage.MismatchDataType" ); //$NON-NLS-1$ private static final String ERROR_MSG_DUPLICATED_NAME = Messages.getString( "ParameterDialog.ErrorMessage.DuplicatedName" ); //$NON-NLS-1$ private static final String ERROR_MSG_NAME_IS_EMPTY = Messages.getString( "ParameterDialog.ErrorMessage.EmptyName" ); //$NON-NLS-1$ private static final String ERROR_MSG_NO_DEFAULT_VALUE = Messages.getString( "ParameterDialog.ErrorMessage.NoDefaultValue" ); //$NON-NLS-1$ private static final String ERROR_MSG_NO_AVAILABLE_COLUMN = Messages.getString( "ParameterDialog.ErrorMessage.NoAvailableColumn" ); //$NON-NLS-1$ private static final String ERROR_MSG_INVALID_LIST_LIMIT = Messages.getString( "ParameterDialog.ErrorMessage.InvalidListLimit" ); //$NON-NLS-1$ private static final String FLAG_DEFAULT = Messages.getString( "ParameterDialog.Flag.Default" ); //$NON-NLS-1$ private static final String COLUMN_VALUE = Messages.getString( "ParameterDialog.Column.Value" ); //$NON-NLS-1$ private static final String COLUMN_DISPLAY_TEXT = Messages.getString( "ParameterDialog.Column.DisplayText" ); //$NON-NLS-1$ private static final String COLUMN_DISPLAY_TEXT_KEY = Messages.getString( "ParameterDialog.Column.DisplayTextKey" ); //$NON-NLS-1$ private static final String COLUMN_IS_DEFAULT = Messages.getString( "ParameterDialog.Column.Default" ); //$NON-NLS-1$ private static final String BOOLEAN_TRUE = Messages.getString( "ParameterDialog.Boolean.True" ); //$NON-NLS-1$ private static final String BOOLEAN_FALSE = Messages.getString( "ParameterDialog.Boolean.False" ); //$NON-NLS-1$ private static final String PARAM_CONTROL_LIST = DesignChoiceConstants.PARAM_CONTROL_LIST_BOX + "/List"; //$NON-NLS-1$ private static final String PARAM_CONTROL_COMBO = DesignChoiceConstants.PARAM_CONTROL_LIST_BOX + "/Combo"; //$NON-NLS-1$ private static final String DISPLAY_NAME_CONTROL_LIST = Messages.getString( "ParameterDialog.DisplayLabel.List" ); //$NON-NLS-1$ private static final String DISPLAY_NAME_CONTROL_COMBO = Messages.getString( "ParameterDialog.DisplayLabel.Combo" ); //$NON-NLS-1$ private static final String NONE_DISPLAY_TEXT = Messages.getString( "ParameterDialog.Label.None" ); //$NON-NLS-1$ private static final Image DEFAULT_ICON = ReportPlatformUIImages.getImage( IReportGraphicConstants.ICON_DEFAULT ); private static final Image ERROR_ICON = ReportPlatformUIImages.getImage( ISharedImages.IMG_OBJS_ERROR_TSK ); private static final String STANDARD_DATE_TIME_PATTERN = "MM/dd/yyyy hh:mm:ss a"; //$NON-NLS-1$ private boolean allowMultiValueVisible = true; private HashMap dirtyProperties = new HashMap( 5 ); private ArrayList choiceList = new ArrayList( ); private static final IChoiceSet DATA_TYPE_CHOICE_SET = DEUtil.getMetaDataDictionary( ) .getElement( ReportDesignConstants.SCALAR_PARAMETER_ELEMENT ) .getProperty( ScalarParameterHandle.DATA_TYPE_PROP ) .getAllowedChoices( ); private static final IChoiceSet CONTROL_TYPE_CHOICE_SET = DEUtil.getMetaDataDictionary( ) .getChoiceSet( DesignChoiceConstants.CHOICE_PARAM_CONTROL ); private ScalarParameterHandle inputParameter; private boolean loading = true; private Text nameEditor, promptTextEditor, helpTextEditor, formatField; // Prompt message line private Label promptMessageLine; // Error message line private CLabel errorMessageLine; // Check boxes private Button isRequired, doNotEcho, isHidden, distinct; // Push buttons private Button importValue, changeDefault, changeFormat, createDataSet; // Radio buttons private Button dynamicRadio, staticRadio; private Button allowMultiChoice; // Combo chooser for static private Combo dataTypeChooser, controlTypeChooser, defaultValueChooser; // Combo chooser for dynamic private Combo dataSetChooser, columnChooser, displayTextChooser, sortKeyChooser, sortDirectionChooser; private Button valueColumnExprButton; // Label private Label previewLabel, sortKeyLabel, sortDirectionLabel; private TableViewer valueTable; private String lastDataType, lastControlType; private String formatCategroy, formatPattern; private String defaultValue; private Composite valueArea, sorttingArea; private List columnList; private IStructuredContentProvider contentProvider = new IStructuredContentProvider( ) { public void dispose( ) { } public void inputChanged( Viewer viewer, Object oldInput, Object newInput ) { } public Object[] getElements( Object inputElement ) { ArrayList list = ( (ArrayList) inputElement ); ArrayList elementsList = (ArrayList) list.clone( ); return elementsList.toArray( ); } }; private ITableLabelProvider labelProvider = new ITableLabelProvider( ) { public Image getColumnImage( Object element, int columnIndex ) { if ( valueTable.getColumnProperties( ).length == 5 && columnIndex == 1 ) { SelectionChoice choice = ( (SelectionChoice) element ); if ( isDefaultChoice( choice ) ) { return DEFAULT_ICON; } } return null; } public String getColumnText( Object element, int columnIndex ) { SelectionChoice choice = ( (SelectionChoice) element ); final int valueIndex = valueTable.getColumnProperties( ).length - 3; String text = null; if ( valueTable.getColumnProperties( ).length == 5 && columnIndex == 1 ) { if ( isDefaultChoice( choice ) ) { text = FLAG_DEFAULT; } } else if ( columnIndex == valueIndex ) { text = choice.getValue( ); } else if ( columnIndex == valueIndex + 1 ) { text = choice.getLabel( ); if ( text == null ) { // text = format( choice.getValue( ) ); text = ""; } } else if ( columnIndex == valueIndex + 2 ) { text = choice.getLabelResourceKey( ); } if ( text == null ) { text = ""; //$NON-NLS-1$ } return text; } public void addListener( ILabelProviderListener listener ) { } public void dispose( ) { } public boolean isLabelProperty( Object element, String property ) { return false; } public void removeListener( ILabelProviderListener listener ) { } }; private final ITableAreaModifier tableAreaModifier = new ITableAreaModifier( ) { public boolean editItem( final Object element ) { final SelectionChoice choice = (SelectionChoice) element; boolean isDefault = isDefaultChoice( choice ); SelectionChoiceDialog dialog = new SelectionChoiceDialog( Messages.getString( "ParameterDialog.SelectionDialog.Edit" ) ); //$NON-NLS-1$ dialog.setInput( choice ); dialog.setValidator( new SelectionChoiceDialog.ISelectionChoiceValidator( ) { public String validate( String displayLableKey, String displayLabel, String value ) { return validateChoice( choice, displayLableKey, displayLabel, value ); } } ); if ( dialog.open( ) == Dialog.OK ) { choice.setValue( convertToStandardFormat( choice.getValue( ) ) ); if ( isDefault ) { changeDefaultValue( choice.getValue( ) ); } return true; } return false; } public boolean newItem( ) { SelectionChoice choice = StructureFactory.createSelectionChoice( ); SelectionChoiceDialog dialog = new SelectionChoiceDialog( Messages.getString( "ParameterDialog.SelectionDialog.New" ) ); //$NON-NLS-1$ dialog.setInput( choice ); dialog.setValidator( new SelectionChoiceDialog.ISelectionChoiceValidator( ) { public String validate( String displayLabelKey, String displayLabel, String value ) { return validateChoice( null, displayLabelKey, displayLabel, value ); } } ); if ( dialog.open( ) == Dialog.OK ) { choice.setValue( convertToStandardFormat( choice.getValue( ) ) ); choiceList.add( choice ); return true; } return false; } public boolean removeItem( Object[] elements ) { for ( int i = 0; i < elements.length; i++ ) { if ( isDefaultChoice( (SelectionChoice) elements[i] ) ) { changeDefaultValue( null ); } choiceList.remove( elements[i] ); } return true; } }; private Text listLimit; /** * Create a new parameter dialog with given title under the active shell * * @param title * the title of the dialog */ public ParameterDialog( String title ) { this( UIUtil.getDefaultShell( ), title ); } /** * Create a new parameter dialog with given title under the specified shell * * @param parentShell * the parent shell of the dialog * @param title * the title of the dialog */ public ParameterDialog( Shell parentShell, String title ) { super( parentShell, title ); } public ParameterDialog( Shell parentShell, String title, boolean allowMultiValueVisible ) { super( parentShell, title ); this.allowMultiValueVisible = allowMultiValueVisible; } protected Control createDialogArea( Composite parent ) { Composite parentComposite = (Composite) super.createDialogArea( parent ); Composite topComposite = new Composite( parentComposite, SWT.NONE ); topComposite.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); topComposite.setLayout( new GridLayout( 2, false ) ); createPropertiesSection( topComposite ); createDisplayOptionsSection( topComposite ); createValuesDefineSection( parentComposite ); UIUtil.bindHelp( parent, IHelpContextIds.PARAMETER_DIALOG_ID ); return parentComposite; } private void createPropertiesSection( Composite composite ) { Composite propertiesSection = new Composite( composite, SWT.NONE ); propertiesSection.setLayout( new GridLayout( ) ); GridData gd = new GridData( ); gd.widthHint = 200; propertiesSection.setLayoutData( gd ); createLabel( propertiesSection, LABEL_NAME ); nameEditor = new Text( propertiesSection, SWT.BORDER ); nameEditor.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); nameEditor.addModifyListener( new ModifyListener( ) { public void modifyText( ModifyEvent e ) { updateMessageLine( ); } } ); createLabel( propertiesSection, LABEL_PROMPT_TEXT ); promptTextEditor = new Text( propertiesSection, SWT.BORDER ); promptTextEditor.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); createLabel( propertiesSection, LABEL_PARAM_DATA_TYPE ); dataTypeChooser = new Combo( propertiesSection, SWT.READ_ONLY | SWT.DROP_DOWN ); dataTypeChooser.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); dataTypeChooser.setItems( ChoiceSetFactory.getDisplayNamefromChoiceSet( DATA_TYPE_CHOICE_SET ) ); dataTypeChooser.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { changeDataType( ); updateCheckBoxArea( ); refreshColumns( false ); } } ); createLabel( propertiesSection, LABEL_DISPALY_TYPE ); controlTypeChooser = new Combo( propertiesSection, SWT.READ_ONLY | SWT.DROP_DOWN ); controlTypeChooser.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); controlTypeChooser.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { changeControlType( ); } } ); } private void createDisplayOptionsSection( Composite composite ) { Group displayOptionSection = new Group( composite, SWT.NONE ); displayOptionSection.setText( GROUP_MORE_OPTION ); displayOptionSection.setLayout( new GridLayout( 2, false ) ); displayOptionSection.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); createLabel( displayOptionSection, LABEL_HELP_TEXT ); helpTextEditor = new Text( displayOptionSection, SWT.BORDER ); helpTextEditor.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); createLabel( displayOptionSection, LABEL_FORMAT ); Composite formatSection = new Composite( displayOptionSection, SWT.NONE ); formatSection.setLayout( UIUtil.createGridLayoutWithoutMargin( 2, false ) ); formatSection.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); formatField = new Text( formatSection, SWT.BORDER | SWT.SINGLE | SWT.READ_ONLY ); formatField.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); changeFormat = new Button( formatSection, SWT.PUSH ); changeFormat.setText( BUTTON_LABEL_CHANGE_FORMAT ); setButtonLayoutData( changeFormat ); changeFormat.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { popupFormatBuilder( true ); } } ); createLabel( displayOptionSection, null ); Group previewArea = new Group( displayOptionSection, SWT.NONE ); previewArea.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); previewArea.setLayout( UIUtil.createGridLayoutWithoutMargin( ) ); previewArea.setText( LABEL_PREVIEW ); previewLabel = new Label( previewArea, SWT.NONE ); previewLabel.setAlignment( SWT.CENTER ); previewLabel.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); // start create list limitation area createLabel( displayOptionSection, LABEL_LIST_LIMIT ); Composite limitArea = new Composite( displayOptionSection, SWT.NULL ); GridLayout layout = new GridLayout( 2, false ); layout.marginWidth = 0; layout.marginHeight = 0; limitArea.setLayout( layout ); GridData data = new GridData( GridData.FILL_HORIZONTAL ); data.verticalSpan = 1; limitArea.setLayoutData( data ); listLimit = new Text( limitArea, SWT.BORDER ); data = new GridData( ); data.widthHint = 80; listLimit.setLayoutData( data ); listLimit.addVerifyListener( new VerifyListener( ) { public void verifyText( VerifyEvent e ) { e.doit = ( "0123456789\0\b\u007f".indexOf( e.character ) != -1 ); //$NON-NLS-1$ } } ); Label values = new Label( limitArea, SWT.NULL ); values.setText( Messages.getString( "ParameterDialog.Label.values" ) ); //$NON-NLS-1$ values.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); // end createLabel( displayOptionSection, null ); // Dummy Composite checkBoxArea = new Composite( displayOptionSection, SWT.NONE ); checkBoxArea.setLayout( UIUtil.createGridLayoutWithoutMargin( 2, false ) ); checkBoxArea.setLayoutData( new GridData( GridData.FILL_BOTH ) ); isRequired = new Button( checkBoxArea, SWT.CHECK ); isRequired.setText( CHECKBOX_ISREQUIRED ); addCheckBoxListener( isRequired, CHECKBOX_ISREQUIRED ); doNotEcho = new Button( checkBoxArea, SWT.CHECK ); doNotEcho.setText( CHECKBOX_DO_NOT_ECHO ); addCheckBoxListener( doNotEcho, CHECKBOX_DO_NOT_ECHO ); isHidden = new Button( checkBoxArea, SWT.CHECK ); isHidden.setText( CHECKBOX_HIDDEN ); addCheckBoxListener( isHidden, CHECKBOX_HIDDEN ); distinct = new Button( checkBoxArea, SWT.CHECK ); distinct.setText( CHECKBOX_DISTINCT ); distinct.setSelection( false ); addCheckBoxListener( distinct, CHECKBOX_DISTINCT ); } private void createValuesDefineSection( Composite composite ) { Group valuesDefineSection = new Group( composite, SWT.NONE ); valuesDefineSection.setText( LABEL_LIST_OF_VALUE ); valuesDefineSection.setLayout( new GridLayout( 2, false ) ); valuesDefineSection.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); Composite choiceArea = new Composite( valuesDefineSection, SWT.NONE ); choiceArea.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); choiceArea.setLayout( UIUtil.createGridLayoutWithoutMargin( 4, true ) ); staticRadio = new Button( choiceArea, SWT.RADIO ); staticRadio.setText( RADIO_STATIC ); GridData gd = new GridData( GridData.HORIZONTAL_ALIGN_BEGINNING ); staticRadio.setLayoutData( gd ); staticRadio.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { switchParamterType( ); } } ); dynamicRadio = new Button( choiceArea, SWT.RADIO ); dynamicRadio.setText( RADIO_DYNAMIC ); dynamicRadio.setLayoutData( gd ); dynamicRadio.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { switchParamterType( ); } } ); Label dummy = new Label( choiceArea, SWT.NONE ); dummy.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); allowMultiChoice = new Button( choiceArea, SWT.CHECK ); allowMultiChoice.setText( CHECK_ALLOW_MULTI ); gd = new GridData( GridData.HORIZONTAL_ALIGN_END ); staticRadio.setLayoutData( gd ); valueArea = new Composite( valuesDefineSection, SWT.NONE ); valueArea.setLayout( UIUtil.createGridLayoutWithoutMargin( 2, false ) ); gd = new GridData( GridData.FILL_BOTH ); gd.heightHint = 300; gd.widthHint = 550; gd.horizontalSpan = 2; valueArea.setLayoutData( gd ); createLabel( valuesDefineSection, null ); errorMessageLine = new CLabel( valuesDefineSection, SWT.NONE ); GridData msgLineGridData = new GridData( GridData.FILL_HORIZONTAL ); msgLineGridData.horizontalSpan = 2; errorMessageLine.setLayoutData( msgLineGridData ); } /** * Set the input of the dialog, which cannot be null * * @param input * the input of the dialog, which cannot be null */ public void setInput( Object input ) { // Assert.isNotNull( input ); inputParameter = (ScalarParameterHandle) input; } protected boolean initDialog( ) { // Assert.isNotNull( inputParameter ); nameEditor.setText( inputParameter.getName( ) ); if ( !StringUtil.isBlank( inputParameter.getPromptText( ) ) ) { promptTextEditor.setText( inputParameter.getPromptText( ) ); } helpTextEditor.setText( UIUtil.convertToGUIString( inputParameter.getHelpText( ) ) ); if ( inputParameter.getValueType( ) .equals( DesignChoiceConstants.PARAM_VALUE_TYPE_STATIC ) ) { staticRadio.setSelection( true ); for ( Iterator iter = inputParameter.getPropertyHandle( ScalarParameterHandle.SELECTION_LIST_PROP ) .iterator( ); iter.hasNext( ); ) { SelectionChoiceHandle choiceHandle = (SelectionChoiceHandle) iter.next( ); choiceList.add( choiceHandle.getStructure( ) ); } } else { dynamicRadio.setSelection( true ); } defaultValue = inputParameter.getDefaultValue( ); if ( PARAM_CONTROL_LIST.endsWith( getSelectedControlType( ) ) && allowMultiValueVisible ) { allowMultiChoice.setVisible( true ); if ( DesignChoiceConstants.SCALAR_PARAM_TYPE_MULTI_VALUE.endsWith( inputParameter.getParamType( ) ) ) { allowMultiChoice.setSelection( true ); } else { allowMultiChoice.setSelection( false ); } } else { allowMultiChoice.setVisible( false ); } // try // if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( // getSelectedDataType( ) ) ) // // not use DataTypeUtil.toString() for datetime here, it has a // // bug loses seconds. // defaultValue = convertToStandardFormat( DataTypeUtil.toDate( // defaultValue ) ); // else if ( DesignChoiceConstants.PARAM_TYPE_DATE.equals( // getSelectedDataType( ) ) ) // defaultValue = DataTypeUtil.toString( DataTypeUtil.toSqlDate( // defaultValue ) ); // else if ( DesignChoiceConstants.PARAM_TYPE_TIME.equals( // getSelectedDataType( ) ) ) // defaultValue = DataTypeUtil.toString( DataTypeUtil.toSqlTime( // defaultValue ) ); // catch ( BirtException e ) // // TODO Auto-generated catch block // ExceptionHandler.handle( e ); // logger.log( Level.SEVERE, e.getMessage( ), e ); if ( inputParameter.getPropertyHandle( ScalarParameterHandle.LIST_LIMIT_PROP ) .isSet( ) ) { listLimit.setText( String.valueOf( inputParameter.getListlimit( ) ) ); } isHidden.setSelection( inputParameter.isHidden( ) ); // allowNull.setSelection( inputParameter.allowNull( ) ); // allowBlank.setSelection( inputParameter.allowBlank( ) ); isRequired.setSelection( inputParameter.isRequired( ) ); doNotEcho.setSelection( inputParameter.isConcealValue( ) ); // needSort.setSelection( !inputParameter.isFixedOrder( ) ); distinct.setSelection( !inputParameter.distinct( ) ); changeDataType( ); dataTypeChooser.setText( DATA_TYPE_CHOICE_SET.findChoice( inputParameter.getDataType( ) ) .getDisplayName( ) ); switchParamterType( ); loading = false; return true; } private void initValueArea( ) { String controlType = getSelectedControlType( ); if ( isStatic( ) ) { if ( DesignChoiceConstants.PARAM_CONTROL_CHECK_BOX.equals( controlType ) ) { if ( isValidValue( defaultValue ) != null ) { defaultValue = null; defaultValueChooser.select( 0 ); } else { if ( defaultValue == null ) { defaultValueChooser.select( defaultValueChooser.indexOf( CHOICE_NO_DEFAULT ) ); } else if ( Boolean.valueOf( defaultValue ).booleanValue( ) ) { defaultValueChooser.select( 1 ); } else { defaultValueChooser.select( 2 ); } } } else if ( DesignChoiceConstants.PARAM_CONTROL_TEXT_BOX.equals( controlType ) ) { if ( getSelectedDataType( ).equals( DesignChoiceConstants.PARAM_TYPE_STRING ) ) { defaultValueChooser.setText( DEUtil.resolveNull( defaultValue ) ); } else if ( defaultValue != null ) { if ( ( defaultValue.equals( Boolean.toString( true ) ) || defaultValue.equals( Boolean.toString( false ) ) ) ) { defaultValue = null; } else { defaultValueChooser.setText( defaultValue ); } } } else if ( PARAM_CONTROL_COMBO.equals( controlType ) || PARAM_CONTROL_LIST.equals( controlType ) ) { initSorttingArea( ); // To fix bug Bugzilla 169927 // Please also refer to Bugzilla 175788 if ( lastControlType != null && lastControlType.equals( DesignChoiceConstants.PARAM_CONTROL_TEXT_BOX ) ) { defaultValue = null; } } refreshValueTable( ); } else { refreshDataSets( ); if ( inputParameter.getDataSetName( ) != null ) { dataSetChooser.setText( inputParameter.getDataSetName( ) ); } refreshColumns( false ); String columnName = getColumnName( inputParameter.getValueExpr( ) ); if ( columnName != null ) { columnChooser.setText( columnName ); } columnName = getColumnName( inputParameter.getLabelExpr( ) ); if ( columnName != null ) { displayTextChooser.setText( columnName ); } if ( getSelectedDataType( ).equals( DesignChoiceConstants.PARAM_TYPE_STRING ) ) { defaultValueChooser.setText( DEUtil.resolveNull( defaultValue ) ); } else if ( defaultValue != null ) { defaultValueChooser.setText( defaultValue ); } initSorttingArea( ); } updateMessageLine( ); } private void initSorttingArea( ) { if ( !inputParameter.isFixedOrder( ) ) { sortKeyLabel.setEnabled( true ); sortKeyChooser.setEnabled( true ); sortDirectionLabel.setEnabled( true ); sortDirectionChooser.setEnabled( true ); distinct.setEnabled( true ); distinct.setSelection( !inputParameter.distinct( ) ); String sortKey = inputParameter.getSortBy( ); if ( sortKey == null || sortKey.equals( DesignChoiceConstants.PARAM_SORT_VALUES_LABEL ) ) { sortKeyChooser.setText( CHOICE_DISPLAY_TEXT ); } else { sortKeyChooser.setText( CHOICE_VALUE_COLUMN ); } String sortDirection = inputParameter.getSortDirection( ); if ( sortDirection == null || sortDirection.equals( DesignChoiceConstants.SORT_DIRECTION_ASC ) ) { sortDirectionChooser.setText( CHOICE_ASCENDING ); } else { sortDirectionChooser.setText( CHOICE_DESCENDING ); } } else { sortKeyLabel.setEnabled( true ); sortKeyChooser.setEnabled( true ); sortDirectionLabel.setEnabled( false ); sortDirectionChooser.setEnabled( false ); distinct.setEnabled( false ); } } private void initFormatField( ) { String type = getSelectedDataType( ); if ( ( DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( lastControlType ) && DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( type ) ) || ( DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( lastControlType ) && DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( type ) ) ) { return; } IChoiceSet choiceSet = getFormatChoiceSet( type ); if ( choiceSet == null ) { formatCategroy = formatPattern = null; } else { if ( !loading || ( ( inputParameter.getCategory( ) == null && inputParameter.getPattern( ) == null ) ) ) { if ( DesignChoiceConstants.PARAM_TYPE_STRING.equals( type ) ) { formatCategroy = choiceSet.findChoice( DesignChoiceConstants.STRING_FORMAT_TYPE_UNFORMATTED ) .getName( ); } else if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( type ) ) { formatCategroy = choiceSet.findChoice( DesignChoiceConstants.DATETIEM_FORMAT_TYPE_UNFORMATTED ) .getName( ); } else if ( DesignChoiceConstants.PARAM_TYPE_DATE.equals( type ) ) { formatCategroy = choiceSet.findChoice( DesignChoiceConstants.DATE_FORMAT_TYPE_UNFORMATTED ) .getName( ); } else if ( DesignChoiceConstants.PARAM_TYPE_TIME.equals( type ) ) { formatCategroy = choiceSet.findChoice( DesignChoiceConstants.DATE_FORMAT_TYPE_UNFORMATTED ) .getName( ); } else if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( type ) || DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( type ) || DesignChoiceConstants.PARAM_TYPE_INTEGER.equals( type ) ) { formatCategroy = choiceSet.findChoice( DesignChoiceConstants.NUMBER_FORMAT_TYPE_UNFORMATTED ) .getName( ); } formatPattern = null; } else { formatCategroy = inputParameter.getCategory( ); if ( formatCategroy == null ) { formatCategroy = DesignChoiceConstants.STRING_FORMAT_TYPE_UNFORMATTED; } formatPattern = inputParameter.getPattern( ); } } updateFormatField( ); } private List getColumnValueList( ) { try { String queryExpr = getExpression( columnChooser.getText( ) ); if ( queryExpr == null || queryExpr.equals( "" ) ) //$NON-NLS-1$ { return Collections.EMPTY_LIST; } ArrayList valueList = new ArrayList( ); valueList.addAll( SelectValueFetcher.getSelectValueList( queryExpr, getDataSetHandle( ) ) ); return valueList; } catch ( Exception e ) { ExceptionHandler.handle( e ); return Collections.EMPTY_LIST; } } private void refreshDataSets( ) { String selectedDataSetName = dataSetChooser.getText( ); String[] oldList = dataSetChooser.getItems( ); List dataSetList = new ArrayList( ); for ( Iterator iterator = inputParameter.getModuleHandle( ) .getVisibleDataSets( ) .iterator( ); iterator.hasNext( ); ) { DataSetHandle DataSetHandle = (DataSetHandle) iterator.next( ); dataSetList.add( DataSetHandle.getQualifiedName( ) ); } if ( inputParameter.getDataSetName( ) != null && !dataSetList.contains( inputParameter.getDataSetName( ) ) ) { dataSetList.add( 0, inputParameter.getDataSetName( ) ); } if ( oldList.length != dataSetList.size( ) ) { dataSetChooser.setItems( (String[]) dataSetList.toArray( new String[]{} ) ); if ( StringUtil.isBlank( selectedDataSetName ) ) { dataSetChooser.select( 0 ); refreshColumns( false ); } else { dataSetChooser.setText( selectedDataSetName ); } } } private DataSetHandle getDataSetHandle( ) { return inputParameter.getModuleHandle( ) .findDataSet( dataSetChooser.getText( ) ); } private void refreshColumns( boolean onlyFilter ) { if ( columnChooser == null ) { return; } if ( !onlyFilter ) { DataSetHandle dataSetHandle = getDataSetHandle( ); try { columnList = DataUtil.getColumnList( dataSetHandle ); } catch ( SemanticException e ) { ExceptionHandler.handle( e ); } displayTextChooser.removeAll( ); displayTextChooser.add( NONE_DISPLAY_TEXT ); for ( Iterator iter = columnList.iterator( ); iter.hasNext( ); ) { displayTextChooser.add( ( (ResultSetColumnHandle) iter.next( ) ).getColumnName( ) ); } displayTextChooser.setText( NONE_DISPLAY_TEXT ); } String originalSelection = columnChooser.getText( ); columnChooser.removeAll( ); for ( Iterator iter = columnList.iterator( ); iter.hasNext( ); ) { ResultSetColumnHandle cachedColumn = (ResultSetColumnHandle) iter.next( ); if ( matchDataType( cachedColumn ) ) { columnChooser.add( cachedColumn.getColumnName( ) ); } } if ( columnChooser.indexOf( originalSelection ) != -1 ) { columnChooser.setText( originalSelection ); } // else if ( columnChooser.getItemCount( ) > 0 ) // columnChooser.select( 0 ); columnChooser.setEnabled( columnChooser.getItemCount( ) > 0 ); valueColumnExprButton.setEnabled( columnChooser.getItemCount( ) > 0 ); updateMessageLine( ); } private boolean matchDataType( ResultSetColumnHandle column ) { String type = getSelectedDataType( ); if ( type.equals( DesignChoiceConstants.PARAM_TYPE_STRING ) || DesignChoiceConstants.COLUMN_DATA_TYPE_ANY.equals( column.getDataType( ) ) ) { return true; } if ( DesignChoiceConstants.COLUMN_DATA_TYPE_DATETIME.equals( column.getDataType( ) ) ) { return type.equals( DesignChoiceConstants.PARAM_TYPE_DATETIME ); } else if ( DesignChoiceConstants.COLUMN_DATA_TYPE_DECIMAL.equals( column.getDataType( ) ) ) { return type.equals( DesignChoiceConstants.PARAM_TYPE_DECIMAL ); } else if ( DesignChoiceConstants.COLUMN_DATA_TYPE_FLOAT.equals( column.getDataType( ) ) ) { return type.equals( DesignChoiceConstants.PARAM_TYPE_FLOAT ); } else if ( DesignChoiceConstants.COLUMN_DATA_TYPE_INTEGER.equals( column.getDataType( ) ) ) { return type.equals( DesignChoiceConstants.PARAM_TYPE_INTEGER ); } else if ( DesignChoiceConstants.COLUMN_DATA_TYPE_DATE.equals( column.getDataType( ) ) ) { return type.equals( DesignChoiceConstants.PARAM_TYPE_DATE ); } else if ( DesignChoiceConstants.COLUMN_DATA_TYPE_TIME.equals( column.getDataType( ) ) ) { return type.equals( DesignChoiceConstants.PARAM_TYPE_TIME ); } else if ( DesignChoiceConstants.COLUMN_DATA_TYPE_BOOLEAN.equals( column.getDataType( ) ) ) { return type.equals( DesignChoiceConstants.COLUMN_DATA_TYPE_BOOLEAN ); } return false; } private String getInputControlType( ) { String type = null; if ( inputParameter.getControlType( ) == null ) { type = DesignChoiceConstants.PARAM_CONTROL_TEXT_BOX; } else if ( DesignChoiceConstants.PARAM_CONTROL_LIST_BOX.equals( inputParameter.getControlType( ) ) ) { if ( inputParameter.isMustMatch( ) ) { // type = PARAM_CONTROL_COMBO; type = PARAM_CONTROL_LIST; } else { // type = PARAM_CONTROL_LIST; type = PARAM_CONTROL_COMBO; } } else { type = inputParameter.getControlType( ); } return type; } private String getSelectedDataType( ) { String type = null; if ( StringUtil.isBlank( dataTypeChooser.getText( ) ) ) { type = inputParameter.getDataType( ); } else { IChoice choice = DATA_TYPE_CHOICE_SET.findChoiceByDisplayName( dataTypeChooser.getText( ) ); type = choice.getName( ); } return type; } /** * Gets the internal name of the control type from the display name */ private String getSelectedControlType( ) { String displayText = controlTypeChooser.getText( ); if ( StringUtil.isBlank( displayText ) ) { return getInputControlType( ); } if ( DISPLAY_NAME_CONTROL_COMBO.equals( displayText ) ) { return PARAM_CONTROL_COMBO; } if ( DISPLAY_NAME_CONTROL_LIST.equals( displayText ) ) { return PARAM_CONTROL_LIST; } return CONTROL_TYPE_CHOICE_SET.findChoiceByDisplayName( displayText ) .getName( ); } private void changeDataType( ) { String type = getSelectedDataType( ); if ( type.equals( lastDataType ) ) { return; } // When data type is changed, validate the default value first. if the // old default value is invalid, // then set the default value to null, else let in remain it unchanged. // -- Begin -- try { validateValue( defaultValue ); } catch ( BirtException e1 ) { defaultValue = null; } // -- End -- if ( buildControlTypeList( type ) ) { changeControlType( ); } initFormatField( ); if ( type.equals( DesignChoiceConstants.PARAM_TYPE_STRING ) ) { clearDefaultValueChooser( isRequired.getSelection( ) ); } else if ( !type.equals( DesignChoiceConstants.PARAM_TYPE_BOOLEAN ) ) { clearDefaultValueText( ); clearDefaultValueChooserSelections( ); } if ( ( isStatic( ) && !distinct.isEnabled( ) ) || ( distinct.isEnabled( ) && !distinct.getSelection( ) ) ) { makeUniqueAndValid( ); refreshValueTable( ); } else { refreshColumns( true ); } lastDataType = type; updateMessageLine( ); } private boolean buildControlTypeList( String type ) { String[] choices; if ( isStatic( ) ) { if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN.equals( type ) ) { choices = new String[3]; } else { choices = new String[4]; } } else { choices = new String[2]; } if ( controlTypeChooser.getItemCount( ) != choices.length ) { String originalSelection = controlTypeChooser.getText( ); if ( isStatic( ) ) { if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN.equals( type ) ) { choices[0] = CONTROL_TYPE_CHOICE_SET.findChoice( DesignChoiceConstants.PARAM_CONTROL_CHECK_BOX ) .getDisplayName( ); choices[1] = DISPLAY_NAME_CONTROL_COMBO; } else { choices[0] = CONTROL_TYPE_CHOICE_SET.findChoice( DesignChoiceConstants.PARAM_CONTROL_TEXT_BOX ) .getDisplayName( ); // choices[1] = DISPLAY_NAME_CONTROL_LIST; choices[1] = DISPLAY_NAME_CONTROL_COMBO; choices[2] = DISPLAY_NAME_CONTROL_LIST; } // choices[choices.length - 2] = DISPLAY_NAME_CONTROL_COMBO; // choices[choices.length - 2] = DISPLAY_NAME_CONTROL_LIST; choices[choices.length - 1] = CONTROL_TYPE_CHOICE_SET.findChoice( DesignChoiceConstants.PARAM_CONTROL_RADIO_BUTTON ) .getDisplayName( ); } else { choices[0] = DISPLAY_NAME_CONTROL_COMBO; choices[1] = DISPLAY_NAME_CONTROL_LIST; } controlTypeChooser.setItems( choices ); if ( originalSelection.length( ) == 0 ) {// initialize controlTypeChooser.setText( getInputControlDisplayName( ) ); } else { int index = controlTypeChooser.indexOf( originalSelection ); if ( index == -1 ) {// The original control type cannot be // supported controlTypeChooser.select( 0 ); return true; } controlTypeChooser.setText( originalSelection ); } } return false; } // false: change anything; true: remove duplicated private boolean makeUniqueAndValid( ) { boolean change = false; try { Set set = new HashSet( ); for ( Iterator iter = choiceList.iterator( ); iter.hasNext( ); ) { SelectionChoice choice = (SelectionChoice) iter.next( ); if ( set.contains( validateValue( choice.getValue( ) ) ) || isValidValue( choice.getValue( ) ) != null ) { iter.remove( ); change = true; } else { set.add( validateValue( choice.getValue( ) ) ); } } } catch ( BirtException e ) { // TODO Auto-generated catch block e.printStackTrace( ); } return change; } private void changeControlType( ) { if ( isStatic( ) ) { String type = getSelectedControlType( ); if ( !type.equals( lastControlType ) ) { if ( DesignChoiceConstants.PARAM_CONTROL_CHECK_BOX.equals( type ) ) { clearArea( valueArea ); switchToCheckBox( ); } else if ( PARAM_CONTROL_COMBO.equals( type ) || PARAM_CONTROL_LIST.equals( type ) || DesignChoiceConstants.PARAM_CONTROL_RADIO_BUTTON.equals( type ) ) { // Radio ,Combo and List has the same UI if ( !PARAM_CONTROL_COMBO.equals( lastControlType ) && !PARAM_CONTROL_LIST.equals( lastControlType ) && !DesignChoiceConstants.PARAM_CONTROL_RADIO_BUTTON.equals( lastControlType ) ) { clearArea( valueArea ); switchToList( ); } } else if ( DesignChoiceConstants.PARAM_CONTROL_TEXT_BOX.equals( type ) ) { clearArea( valueArea ); switchToText( ); } valueArea.layout( ); initValueArea( ); lastControlType = type; } } updateCheckBoxArea( ); updateMessageLine( ); boolean radioEnable = false; if ( PARAM_CONTROL_COMBO.equals( getSelectedControlType( ) ) || PARAM_CONTROL_LIST.equals( getSelectedControlType( ) ) ) { radioEnable = true; } if ( radioEnable != staticRadio.isEnabled( ) ) { staticRadio.setEnabled( radioEnable ); dynamicRadio.setEnabled( radioEnable ); } if ( PARAM_CONTROL_LIST.equals( getSelectedControlType( ) ) && allowMultiValueVisible ) { allowMultiChoice.setVisible( true ); } else { allowMultiChoice.setVisible( false ); } } private void switchParamterType( ) { clearArea( valueArea ); lastControlType = null; if ( isStatic( ) ) { switchToStatic( ); } else { switchToDynamic( ); } buildControlTypeList( getSelectedDataType( ) ); valueArea.layout( ); initValueArea( ); updateCheckBoxArea( ); } private void switchToCheckBox( ) { createLabel( valueArea, LABEL_DEFAULT_VALUE ); defaultValueChooser = new Combo( valueArea, SWT.READ_ONLY | SWT.BORDER ); defaultValueChooser.add( CHOICE_NO_DEFAULT ); defaultValueChooser.add( BOOLEAN_TRUE ); defaultValueChooser.add( BOOLEAN_FALSE ); defaultValueChooser.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); defaultValueChooser.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { switch ( defaultValueChooser.getSelectionIndex( ) ) { case 0 : defaultValue = null; break; case 1 : defaultValue = Boolean.toString( true ); break; case 2 : defaultValue = Boolean.toString( false ); break; } updateMessageLine( ); } } ); } private void switchToList( ) { createLabel( valueArea, LABEL_VALUES ); Composite tableAreaComposite = new Composite( valueArea, SWT.NONE ); tableAreaComposite.setLayout( UIUtil.createGridLayoutWithoutMargin( ) ); tableAreaComposite.setLayoutData( new GridData( GridData.FILL_BOTH ) ); TableArea tableArea = new TableArea( tableAreaComposite, SWT.SINGLE | SWT.FULL_SELECTION | SWT.BORDER, tableAreaModifier ); tableArea.setLayoutData( new GridData( GridData.FILL_BOTH ) ); Table table = tableArea.getTable( ); table.setLinesVisible( true ); table.setHeaderVisible( true ); String[] columns; int[] columnWidth; columns = new String[]{ null, COLUMN_IS_DEFAULT, COLUMN_VALUE, COLUMN_DISPLAY_TEXT, COLUMN_DISPLAY_TEXT_KEY }; columnWidth = new int[]{ 10, 70, 105, 105, 105 }; for ( int i = 0; i < columns.length; i++ ) { TableColumn column = new TableColumn( table, SWT.LEFT ); column.setResizable( columns[i] != null ); if ( columns[i] != null ) { column.setText( columns[i] ); } column.setWidth( columnWidth[i] ); } valueTable = tableArea.getTableViewer( ); valueTable.setColumnProperties( columns ); valueTable.setContentProvider( contentProvider ); valueTable.setLabelProvider( labelProvider ); tableArea.setInput( choiceList ); valueTable.addSelectionChangedListener( new ISelectionChangedListener( ) { public void selectionChanged( SelectionChangedEvent event ) { updateTableButtons( ); } } ); Composite buttonBar = new Composite( tableAreaComposite, SWT.NONE ); buttonBar.setLayout( UIUtil.createGridLayoutWithoutMargin( 4, false ) ); buttonBar.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); importValue = new Button( buttonBar, SWT.PUSH ); importValue.setText( BUTTON_LABEL_IMPORT ); setButtonLayoutData( importValue ); // Disabled when no date set defined importValue.setEnabled( !inputParameter.getModuleHandle( ) .getVisibleDataSets( ) .isEmpty( ) ); importValue.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { boolean defaultValueRemoved = true; String type = getSelectedDataType( ); List choices = new ArrayList( ); Map labelMap = new HashMap( ); for ( Iterator iter = choiceList.iterator( ); iter.hasNext( ); ) { SelectionChoice choice = (SelectionChoice) iter.next( ); choices.add( choice.getValue( ) ); if ( choice.getLabel( ) != null ) { labelMap.put( choice.getValue( ), choice.getLabel( ) ); } } ImportValueDialog dialog = new ImportValueDialog( type, choices ); if ( dialog.open( ) == OK ) { String[] importValues = (String[]) dialog.getResult( ); choiceList.clear( ); for ( int i = 0; i < importValues.length; i++ ) { SelectionChoice choice = StructureFactory.createSelectionChoice( ); choice.setValue( importValues[i] ); if ( labelMap.get( importValues[i] ) != null ) { choice.setLabel( (String) labelMap.get( importValues[i] ) ); } choiceList.add( choice ); if ( defaultValue != null && defaultValue.equals( importValues[i] ) ) { defaultValueRemoved = false; } } refreshValueTable( ); if ( defaultValue != null && defaultValueRemoved ) { changeDefaultValue( null ); } } } } ); changeDefault = new Button( buttonBar, SWT.TOGGLE ); changeDefault.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { SelectionChoice choice = (SelectionChoice) ( (IStructuredSelection) valueTable.getSelection( ) ).getFirstElement( ); if ( isDefaultChoice( choice ) ) { changeDefaultValue( null ); } else { changeDefaultValue( choice.getValue( ) ); } refreshValueTable( ); changeDefault.getParent( ).layout( ); } } ); int width1 = UIUtil.getStringWidth( BUTTON_LABEL_REMOVE_DEFAULT, changeDefault ) + 10; int width2 = UIUtil.getStringWidth( BUTTON_LABEL_SET_DEFAULT, changeDefault ) + 10; int width = width1 >= width2 ? width1 : width2; GridData gd = new GridData( ); gd.widthHint = width; changeDefault.setLayoutData( gd ); createPromptLine( tableAreaComposite ); updateTableButtons( ); createSortingArea( valueArea ); } private void switchToText( ) { createDefaultEditor( ); createLabel( valueArea, null ); createPromptLine( valueArea ); } private void switchToStatic( ) { changeControlType( ); listLimit.setEditable( false ); } private void switchToDynamic( ) { Composite composite = new Composite( valueArea, SWT.NONE ); GridData gd = new GridData( GridData.FILL_HORIZONTAL ); gd.horizontalSpan = 2; composite.setLayoutData( gd ); composite.setLayout( UIUtil.createGridLayoutWithoutMargin( 3, false ) ); createLabel( composite, LABEL_SELECT_DATA_SET ); dataSetChooser = new Combo( composite, SWT.BORDER | SWT.READ_ONLY ); dataSetChooser.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); dataSetChooser.addSelectionListener( new SelectionAdapter( ) { public void widgetDefaultSelected( SelectionEvent e ) { refreshColumns( false ); } public void widgetSelected( SelectionEvent e ) { refreshColumns( false ); } } ); createDataSet = new Button( composite, SWT.PUSH ); createDataSet.setText( BUTTON_CREATE_DATA_SET ); setButtonLayoutData( createDataSet ); createDataSet.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { new NewDataSetAction( ).run( ); refreshDataSets( ); } } ); createLabel( composite, LABEL_SELECT_VALUE_COLUMN ); // columnChooser = new Combo( composite, SWT.BORDER | SWT.READ_ONLY ); columnChooser = new Combo( composite, SWT.BORDER | SWT.DROP_DOWN ); columnChooser.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); columnChooser.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { updateButtons( ); } } ); valueColumnExprButton = new Button( composite, SWT.PUSH ); // valueColumnExprButton.setText( "..." ); //$NON-NLS-1$ UIUtil.setExpressionButtonImage( valueColumnExprButton ); valueColumnExprButton.setToolTipText( Messages.getString( "ParameterDialog.toolTipText.OpenExprButton" ) ); //$NON-NLS-1$ valueColumnExprButton.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent event ) { ExpressionBuilder expressionBuilder = new ExpressionBuilder( getExpression( columnChooser.getText( ) ) ); expressionBuilder.setExpressionProvier( new ParameterExpressionProvider( inputParameter, dataSetChooser.getText( ) ) ); if ( expressionBuilder.open( ) == OK ) { setExpression( columnChooser, expressionBuilder.getResult( ) .trim( ) ); } } } ); // createLabel( composite, null ); createLabel( composite, LABEL_SELECT_DISPLAY_TEXT ); // displayTextChooser = new Combo( composite, SWT.BORDER | SWT.READ_ONLY displayTextChooser = new Combo( composite, SWT.BORDER | SWT.DROP_DOWN ); displayTextChooser.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); Button displayTextExprButton = new Button( composite, SWT.PUSH ); // displayTextExprButton.setText( "..." ); //$NON-NLS-1$ UIUtil.setExpressionButtonImage( displayTextExprButton ); displayTextExprButton.setToolTipText( Messages.getString( "ParameterDialog.toolTipText.OpenExprButton" ) ); //$NON-NLS-1$ displayTextExprButton.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent event ) { ExpressionBuilder expressionBuilder = new ExpressionBuilder( getExpression( displayTextChooser.getText( ) ) ); expressionBuilder.setExpressionProvier( new ParameterExpressionProvider( inputParameter, dataSetChooser.getText( ) ) ); if ( expressionBuilder.open( ) == OK ) { setExpression( displayTextChooser, expressionBuilder.getResult( ).trim( ) ); } } } ); createDefaultEditor( ); createSortingArea( valueArea ); createLabel( valueArea, null ); createPromptLine( valueArea ); listLimit.setEditable( true ); } private void createSortingArea( Composite parent ) { // Sorting conditions here sorttingArea = new Composite( parent, SWT.NONE ); GridData sorttingAreaGridData = new GridData( GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_END ); sorttingAreaGridData.horizontalSpan = 2; sorttingArea.setLayoutData( sorttingAreaGridData ); sorttingArea.setLayout( UIUtil.createGridLayoutWithoutMargin( 1, false ) ); Group sortGroup = new Group( sorttingArea, SWT.NONE ); sortGroup.setText( LABEL_SORT_GROUP ); sortGroup.setLayout( new GridLayout( 2, false ) ); sortGroup.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); Composite sortKeyArea = new Composite( sortGroup, SWT.NONE ); sortKeyArea.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); sortKeyArea.setLayout( new GridLayout( 2, false ) ); // createLabel( sortKeyArea, LABEL_SORT_KEY ); sortKeyLabel = new Label( sortKeyArea, SWT.NONE ); sortKeyLabel.setText( LABEL_SORT_KEY ); sortKeyChooser = new Combo( sortKeyArea, SWT.BORDER | SWT.READ_ONLY ); sortKeyChooser.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); sortKeyChooser.add( CHOICE_NONE ); sortKeyChooser.add( CHOICE_DISPLAY_TEXT ); sortKeyChooser.add( CHOICE_VALUE_COLUMN ); sortKeyChooser.setText( CHOICE_NONE ); sortKeyChooser.addSelectionListener( new SelectionListener( ) { public void widgetDefaultSelected( SelectionEvent e ) { } public void widgetSelected( SelectionEvent e ) { if ( !( (Combo) e.widget ).getText( ).equals( CHOICE_NONE ) ) { sortDirectionLabel.setEnabled( true ); sortDirectionChooser.setEnabled( true ); } else { sortDirectionLabel.setEnabled( false ); sortDirectionChooser.setEnabled( false ); } } } ); Composite sortDirectionArea = new Composite( sortGroup, SWT.NONE ); sortDirectionArea.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); sortDirectionArea.setLayout( new GridLayout( 2, false ) ); // createLabel( sortDirectionArea, LABEL_SORT_DIRECTION ); sortDirectionLabel = new Label( sortDirectionArea, SWT.NONE ); sortDirectionLabel.setText( LABEL_SORT_DIRECTION ); sortDirectionChooser = new Combo( sortDirectionArea, SWT.BORDER | SWT.READ_ONLY ); sortDirectionChooser.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); sortDirectionChooser.add( CHOICE_ASCENDING ); sortDirectionChooser.add( CHOICE_DESCENDING ); sortDirectionChooser.setText( CHOICE_ASCENDING ); } private void clearDefaultValueText( ) { if ( defaultValueChooser == null || defaultValueChooser.isDisposed( ) ) return; String textValue = defaultValueChooser.getText( ); if ( textValue != null && textValue.length( ) == 0 ) { defaultValueChooser.setText( "" ); //$NON-NLS-1$ } } private void clearDefaultValueChooserSelections( ) { if ( defaultValueChooser == null || defaultValueChooser.isDisposed( ) ) return; if ( defaultValueChooser.getItemCount( ) > 1 ) { defaultValueChooser.removeAll( ); } } private void createDefaultEditor( ) { createLabel( valueArea, LABEL_DEFAULT_VALUE ); defaultValueChooser = new Combo( valueArea, SWT.BORDER ); defaultValueChooser.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); if ( !isStatic( ) ) { defaultValueChooser.add( CHOICE_SELECT_VALUE ); } // if ( getSelectedDataType( ).equals( // DesignChoiceConstants.PARAM_TYPE_STRING ) // && !isRequired.getSelection( ) ) // defaultValueChooser.add( CHOICE_NULL_VALUE ); // defaultValueChooser.add( CHOICE_BLANK_VALUE ); defaultValueChooser.addVerifyListener( new VerifyListener( ) { public void verifyText( VerifyEvent e ) { // TODO Auto-generated method stub String selection = e.text; if ( defaultValueChooser.indexOf( selection ) == -1 ) { e.doit = true; return; } if ( selection.equals( CHOICE_SELECT_VALUE ) ) { e.doit = false; } else { e.doit = true; } } } ); defaultValueChooser.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { if ( defaultValueChooser.getSelectionIndex( ) == -1 ) return; String selection = defaultValueChooser.getItem( defaultValueChooser.getSelectionIndex( ) ); if ( selection.equals( CHOICE_SELECT_VALUE ) ) { List columnValueList = getColumnValueList( ); if ( columnValueList.isEmpty( ) ) return; SelectParameterDefaultValueDialog dialog = new SelectParameterDefaultValueDialog( Display.getCurrent( ) .getActiveShell( ), Messages.getString( "SelectParameterDefaultValueDialog.Title" ) ); //$NON-NLS-1$ dialog.setColumnValueList( columnValueList ); int status = dialog.open( ); if ( status == Window.OK ) { String selectedValue = dialog.getSelectedValue( ); if ( selectedValue != null ) defaultValueChooser.setText( selectedValue ); } } else { // if ( selection.equals( CHOICE_NULL_VALUE ) ) // changeDefaultValue( null ); // else if ( selection.equals( CHOICE_BLANK_VALUE ) ) // changeDefaultValue( "" ); //$NON-NLS-1$ if ( isStatic( ) ) { refreshValueTable( ); } } } } ); defaultValueChooser.addModifyListener( new ModifyListener( ) { public void modifyText( ModifyEvent e ) { String value = defaultValueChooser.getText( ); // if ( value.equals( CHOICE_NULL_VALUE ) // || value.equals( CHOICE_BLANK_VALUE ) ) // return; changeDefaultValue( UIUtil.convertToModelString( value, false ) ); if ( isStatic( ) ) { refreshValueTable( ); } } } ); } private void createPromptLine( Composite parent ) { promptMessageLine = new Label( parent, SWT.NONE ); promptMessageLine.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); } private Object validateValue( String value ) throws BirtException { String tempdefaultValue = value; if ( !( ( DesignChoiceConstants.PARAM_TYPE_STRING.endsWith( getSelectedDataType( ) ) ) || ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN.endsWith( getSelectedDataType( ) ) ) ) ) { if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( getSelectedDataType( ) ) ) { tempdefaultValue = convertToStandardFormat( DataTypeUtil.toDate( tempdefaultValue ) ); } else if ( DesignChoiceConstants.PARAM_TYPE_DATE.equals( getSelectedDataType( ) ) ) { tempdefaultValue = convertToStandardFormat( DataTypeUtil.toSqlDate( tempdefaultValue ) ); } else if ( DesignChoiceConstants.PARAM_TYPE_TIME.equals( getSelectedDataType( ) ) ) { tempdefaultValue = convertToStandardFormat( DataTypeUtil.toSqlTime( tempdefaultValue ) ); } return ParameterValidationUtil.validate( getSelectedDataType( ), STANDARD_DATE_TIME_PATTERN, tempdefaultValue, ULocale.getDefault( ) ); } if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN.equals( getSelectedDataType( ) ) ) { if ( tempdefaultValue != null && tempdefaultValue.equals( CHOICE_NO_DEFAULT ) ) { return DataTypeUtil.toBoolean( null ); } return DataTypeUtil.toBoolean( tempdefaultValue ); } else return tempdefaultValue; } protected void okPressed( ) { // Validate the date first -- begin -- bug 164765 try { validateValue( defaultValue ); } catch ( BirtException e1 ) { ExceptionHandler.handle( e1 ); return; } // Validate the date first -- end -- try { // Save the name and display name inputParameter.setName( nameEditor.getText( ) ); inputParameter.setPromptText( UIUtil.convertToModelString( promptTextEditor.getText( ), true ) ); inputParameter.setParamType( DesignChoiceConstants.SCALAR_PARAM_TYPE_SIMPLE ); String newControlType = getSelectedControlType( ); if ( PARAM_CONTROL_COMBO.equals( newControlType ) ) { newControlType = DesignChoiceConstants.PARAM_CONTROL_LIST_BOX; // inputParameter.setMustMatch( true ); inputParameter.setMustMatch( false ); } else if ( PARAM_CONTROL_LIST.equals( newControlType ) ) { newControlType = DesignChoiceConstants.PARAM_CONTROL_LIST_BOX; // inputParameter.setMustMatch( false ); inputParameter.setMustMatch( true ); if ( allowMultiChoice.isVisible( ) && allowMultiChoice.getSelection( ) ) { inputParameter.setParamType( DesignChoiceConstants.SCALAR_PARAM_TYPE_MULTI_VALUE ); } } else { inputParameter.setProperty( ScalarParameterHandle.MUCH_MATCH_PROP, null ); } // Save control type inputParameter.setControlType( newControlType ); // Save default value // if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( // getSelectedDataType( ) ) ) // defaultValue = convertToStandardFormat( DataTypeUtil.toDate( // defaultValue ) ); // else if ( DesignChoiceConstants.PARAM_TYPE_DATE.equals( // getSelectedDataType( ) ) ) // defaultValue = convertToStandardFormat( DataTypeUtil.toSqlDate( // defaultValue ) ); // else if ( DesignChoiceConstants.PARAM_TYPE_TIME.equals( // getSelectedDataType( ) ) ) // defaultValue = convertToStandardFormat( DataTypeUtil.toSqlTime( // defaultValue ) ); inputParameter.setDefaultValue( defaultValue ); // Set data type inputParameter.setDataType( DATA_TYPE_CHOICE_SET.findChoiceByDisplayName( dataTypeChooser.getText( ) ) .getName( ) ); // Clear original choices list PropertyHandle selectionChioceList = inputParameter.getPropertyHandle( ScalarParameterHandle.SELECTION_LIST_PROP ); selectionChioceList.setValue( null ); if ( isStatic( ) ) { // Save static choices list inputParameter.setValueType( DesignChoiceConstants.PARAM_VALUE_TYPE_STATIC ); if ( !DesignChoiceConstants.PARAM_CONTROL_TEXT_BOX.equals( newControlType ) && !DesignChoiceConstants.PARAM_CONTROL_CHECK_BOX.equals( newControlType ) ) { for ( Iterator iter = choiceList.iterator( ); iter.hasNext( ); ) { SelectionChoice choice = (SelectionChoice) iter.next( ); if ( isValidValue( choice.getValue( ) ) == null ) { selectionChioceList.addItem( choice ); } } } inputParameter.setDataSetName( null ); inputParameter.setValueExpr( null ); inputParameter.setLabelExpr( null ); } else { // Save dynamic settings inputParameter.setValueType( DesignChoiceConstants.PARAM_VALUE_TYPE_DYNAMIC ); inputParameter.setDataSetName( dataSetChooser.getText( ) ); inputParameter.setValueExpr( getExpression( columnChooser.getText( ) ) ); if ( displayTextChooser.getText( ).equals( LABEL_NULL ) ) { inputParameter.setLabelExpr( "" ); //$NON-NLS-1$ } else { inputParameter.setLabelExpr( getExpression( displayTextChooser.getText( ) ) ); } } // Save help text inputParameter.setHelpText( UIUtil.convertToModelString( helpTextEditor.getText( ), false ) ); // Save format inputParameter.setCategory( formatCategroy ); inputParameter.setPattern( formatPattern ); if ( isStatic( ) && ( PARAM_CONTROL_COMBO.equals( getSelectedControlType( ) ) || DesignChoiceConstants.PARAM_CONTROL_RADIO_BUTTON.equals( getSelectedControlType( ) ) ) && !containValue( null, defaultValue, COLUMN_VALUE ) ) { defaultValue = null; } // Save options if ( dirtyProperties.containsKey( CHECKBOX_HIDDEN ) ) { inputParameter.setHidden( getProperty( CHECKBOX_HIDDEN ) ); } if ( dirtyProperties.containsKey( CHECKBOX_ISREQUIRED ) ) { inputParameter.setIsRequired( getProperty( CHECKBOX_ISREQUIRED ) ); } if ( doNotEcho.isEnabled( ) ) { if ( dirtyProperties.containsKey( CHECKBOX_DO_NOT_ECHO ) ) { inputParameter.setConcealValue( getProperty( CHECKBOX_DO_NOT_ECHO ) ); } } else { inputParameter.setProperty( ScalarParameterHandle.CONCEAL_VALUE_PROP, null ); } if ( distinct.isEnabled( ) ) { inputParameter.setDistinct( !distinct.getSelection( ) ); } else { inputParameter.setDistinct( true ); } if ( sorttingArea != null && !sorttingArea.isDisposed( ) && sorttingArea.isVisible( ) ) { if ( !sortKeyChooser.getText( ).equals( CHOICE_NONE ) ) { inputParameter.setFixedOrder( false ); if ( sortKeyChooser.getText( ).equals( CHOICE_DISPLAY_TEXT ) ) { inputParameter.setSortBy( DesignChoiceConstants.PARAM_SORT_VALUES_LABEL ); } else if ( sortKeyChooser.getText( ) .equals( CHOICE_VALUE_COLUMN ) ) { inputParameter.setSortBy( DesignChoiceConstants.PARAM_SORT_VALUES_VALUE ); } if ( sortDirectionChooser.getText( ) .equals( CHOICE_ASCENDING ) ) { inputParameter.setSortDirection( DesignChoiceConstants.SORT_DIRECTION_ASC ); } else if ( sortDirectionChooser.getText( ) .equals( CHOICE_DESCENDING ) ) { inputParameter.setSortDirection( DesignChoiceConstants.SORT_DIRECTION_DESC ); } } else { inputParameter.setFixedOrder( true ); inputParameter.setSortBy( null ); inputParameter.setSortDirection( null ); } } else { inputParameter.setProperty( ScalarParameterHandle.FIXED_ORDER_PROP, null ); } // Save limits if ( !isStatic( ) && !StringUtil.isBlank( listLimit.getText( ) ) ) { try { inputParameter.setListlimit( Integer.parseInt( listLimit.getText( ) ) ); } catch ( NumberFormatException ex ) { ExceptionHandler.openErrorMessageBox( ERROR_TITLE_INVALID_LIST_LIMIT, MessageFormat.format( ERROR_MSG_INVALID_LIST_LIMIT, new Object[]{ Integer.toString( Integer.MAX_VALUE ) } ) ); } } else { inputParameter.setProperty( ScalarParameterHandle.LIST_LIMIT_PROP, null ); } } catch ( Exception e ) { ExceptionHandler.handle( e ); return; } setResult( inputParameter ); super.okPressed( ); } private void createLabel( Composite parent, String content ) { Label label = new Label( parent, SWT.NONE ); if ( content != null ) { label.setText( content ); } setLabelLayoutData( label ); } private void setLabelLayoutData( Label label ) { GridData gd = new GridData( ); if ( label.getText( ).equals( LABEL_VALUES ) ) { gd.verticalAlignment = GridData.BEGINNING; } label.setLayoutData( gd ); } private void addCheckBoxListener( final Button checkBox, final String key ) { checkBox.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { checkBoxChange( checkBox, key ); } } ); } /** * @param key * @param checkBox * */ protected void checkBoxChange( Button checkBox, String key ) { dirtyProperties.put( key, new Boolean( checkBox.getSelection( ) ) ); if ( CHECKBOX_ISREQUIRED.equals( key ) || CHECKBOX_DISTINCT.equals( key ) ) { if ( ( isStatic( ) && !distinct.isEnabled( ) ) || ( distinct.isEnabled( ) && !distinct.getSelection( ) ) ) { boolean change = makeUniqueAndValid( ); if ( change ) { refreshValueTable( ); } } if ( getSelectedDataType( ).equals( DesignChoiceConstants.PARAM_TYPE_STRING ) ) { clearDefaultValueChooser( checkBox.getSelection( ) ); } updateMessageLine( ); } } private void clearDefaultValueChooser( boolean isChecked ) { if ( isChecked ) { clearDefaultValueText( ); clearDefaultValueChooserSelections( ); } else { if ( defaultValueChooser == null || defaultValueChooser.isDisposed( ) || defaultValueChooser.getItemCount( ) > 1 ) return; // defaultValueChooser.add( CHOICE_NULL_VALUE ); // defaultValueChooser.add( CHOICE_BLANK_VALUE ); } } private void clearArea( Composite area ) { Control[] children = area.getChildren( ); for ( int i = 0; i < children.length; i++ ) { children[i].dispose( ); } } private void updateTableButtons( ) { boolean isEnable = true; SelectionChoice selectedChoice = null; if ( valueTable.getSelection( ).isEmpty( ) ) { isEnable = false; } else { selectedChoice = (SelectionChoice) ( (IStructuredSelection) valueTable.getSelection( ) ).getFirstElement( ); // if ( selectedChoice == dummyChoice ) // isEnable = false; } boolean isDefault = isEnable && isDefaultChoice( selectedChoice ); if ( isDefault ) { changeDefault.setText( BUTTON_LABEL_REMOVE_DEFAULT ); } else { changeDefault.setText( BUTTON_LABEL_SET_DEFAULT ); } changeDefault.setSelection( isDefault ); changeDefault.setEnabled( isEnable ); } private void updateButtons( ) { boolean canFinish = !StringUtil.isBlank( nameEditor.getText( ) ); if ( canFinish ) { if ( errorMessageLine != null && !errorMessageLine.isDisposed( ) ) { canFinish = ( errorMessageLine.getImage( ) == null ); } if ( columnChooser != null && !isStatic( ) ) { canFinish &= ( getExpression( columnChooser.getText( ) ) != null ); } } getOkButton( ).setEnabled( canFinish ); } private void updateCheckBoxArea( ) { // Do not echo check if ( DesignChoiceConstants.PARAM_CONTROL_TEXT_BOX.equals( getSelectedControlType( ) ) ) { doNotEcho.setEnabled( true ); distinct.setEnabled( false ); } else { doNotEcho.setEnabled( false ); distinct.setEnabled( true ); } } private void updateMessageLine( ) { String errorMessage = validateName( ); if ( errorMessage == null ) { // 1. No available column error if ( !isStatic( ) && columnChooser != null && columnChooser.getItemCount( ) == 0 ) { errorMessage = ERROR_MSG_NO_AVAILABLE_COLUMN; } // 2. No default value error if ( defaultValue == null && ( PARAM_CONTROL_COMBO.equals( getSelectedControlType( ) ) || DesignChoiceConstants.PARAM_CONTROL_RADIO_BUTTON.equals( getSelectedControlType( ) ) ) ) { // if ( isStatic( ) ) // errorMessage = ( !canBeNull( ) || !containValue( null, // null, // COLUMN_VALUE ) ) ? ERROR_MSG_NO_DEFAULT_VALUE // : null; // else // errorMessage = canBeNull( ) ? null // : ERROR_MSG_NO_DEFAULT_VALUE; errorMessage = canBeNull( ) ? null : ERROR_MSG_NO_DEFAULT_VALUE; } } if ( errorMessage != null ) { errorMessageLine.setText( errorMessage ); errorMessageLine.setImage( ERROR_ICON ); } else { errorMessageLine.setText( "" ); //$NON-NLS-1$ errorMessageLine.setImage( null ); } if ( promptMessageLine != null && !promptMessageLine.isDisposed( ) ) { if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( getSelectedDataType( ) ) ) { promptMessageLine.setText( LABEL_DATETIME_PROMPT ); } else if ( DesignChoiceConstants.PARAM_TYPE_DATE.equals( getSelectedDataType( ) ) ) { promptMessageLine.setText( LABEL_DATE_PROMPT ); } else if ( DesignChoiceConstants.PARAM_TYPE_TIME.equals( getSelectedDataType( ) ) ) { promptMessageLine.setText( LABEL_TIME_PROMPT ); } else { promptMessageLine.setText( "" ); //$NON-NLS-1$ } } updateButtons( ); } private String validateName( ) { String name = nameEditor.getText( ).trim( ); if ( name.length( ) == 0 ) { return ERROR_MSG_NAME_IS_EMPTY; } if ( !name.equals( inputParameter.getName( ) ) && inputParameter.getModuleHandle( ).findParameter( name ) != null ) { return ERROR_MSG_DUPLICATED_NAME; } if ( defaultValueChooser != null && ( !defaultValueChooser.isDisposed( ) ) && defaultValueChooser.getText( ).length( ) != 0 ) { try { validateValue( defaultValueChooser.getText( ) ); } catch ( BirtException e ) { return ERROR_MSG_MISMATCH_DATA_TYPE; } } return null; } private void refreshValueTable( ) { if ( valueTable != null && !valueTable.getTable( ).isDisposed( ) ) { valueTable.refresh( ); updateTableButtons( ); } } private boolean getProperty( String key ) { return ( (Boolean) dirtyProperties.get( key ) ).booleanValue( ); } private String format( String string ) { if ( canBeNull( ) && string == null ) { return LABEL_NULL; } if ( StringUtil.isBlank( string ) || formatCategroy == null ) { return string; } try { String pattern = formatPattern; if ( formatPattern == null ) { if ( isCustom( ) ) { return string; } pattern = formatCategroy; } String type = getSelectedDataType( ); if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( type ) ) { string = convertToStandardFormat( DataTypeUtil.toDate( string ) ); } else if ( DesignChoiceConstants.PARAM_TYPE_DATE.equals( type ) ) { string = convertToStandardFormat( DataTypeUtil.toSqlDate( string ) ); } else if ( DesignChoiceConstants.PARAM_TYPE_TIME.equals( type ) ) { string = convertToStandardFormat( DataTypeUtil.toSqlTime( string ) ); } else if ( DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( type ) ) { string = new NumberFormatter( pattern ).format( DataTypeUtil.toDouble( string ) .doubleValue( ) ); } else if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( type ) ) { string = new NumberFormatter( pattern ).format( DataTypeUtil.toBigDecimal( string ) ); } else if ( DesignChoiceConstants.PARAM_TYPE_STRING.equals( type ) ) { string = new StringFormatter( pattern ).format( string ); } } catch ( BirtException e ) { logger.log( Level.SEVERE, e.getMessage( ), e ); } return string; } /** * Check if the specified value is valid * * @param value * the value to check * @return Returns the error message if the input value is invalid,or null * if it is valid */ private String isValidValue( String value ) { if ( canBeNull( ) ) { if ( value == null || value.length( ) == 0 ) { return null; } } else { if ( value == null || value.length( ) == 0 ) { return ERROR_MSG_CANNOT_BE_NULL; } } // bug 153405 // if ( value == null || value.length( ) == 0 ) // return ERROR_MSG_CANNOT_BE_NULL; if ( canBeBlank( ) ) { if ( StringUtil.isBlank( value ) ) { return null; } } else { if ( StringUtil.isBlank( value ) ) { return ERROR_MSG_CANNOT_BE_BLANK; } } try { validateValue( value ); } catch ( BirtException e ) { return ERROR_MSG_MISMATCH_DATA_TYPE; } return null; } private boolean isEqual( String value1, String value2 ) { Object v1 = null; Object v2 = null; try { v1 = validateValue( value1 ); v2 = validateValue( value2 ); } catch ( BirtException e ) { } if ( v1 == null ) { return v2 == null; } if ( v1 instanceof Double && v2 instanceof Double ) { return ( (Double) v1 ).compareTo( (Double) v2 ) == 0; } if ( v1 instanceof BigDecimal && v2 instanceof BigDecimal ) { return ( (BigDecimal) v1 ).compareTo( (BigDecimal) v2 ) == 0; } if ( v1 instanceof Integer && v2 instanceof Integer ) { return ( (Integer) v1 ).compareTo( (Integer) v2 ) == 0; } return v1.equals( v2 ); } private Object getValue( String value ) throws BirtException { if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN.equals( getSelectedDataType( ) ) ) { return DataTypeUtil.toBoolean( value ); } else if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( getSelectedDataType( ) ) ) { return DataTypeUtil.toBigDecimal( value ); } else if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( getSelectedDataType( ) ) ) { return DataTypeUtil.toDate( value ); } else if ( DesignChoiceConstants.PARAM_TYPE_DATE.equals( getSelectedDataType( ) ) ) { return DataTypeUtil.toSqlDate( value ); } else if ( DesignChoiceConstants.PARAM_TYPE_TIME.equals( getSelectedDataType( ) ) ) { return DataTypeUtil.toSqlTime( value ); } else if ( DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( getSelectedDataType( ) ) ) { return DataTypeUtil.toDouble( value ); } else if ( DesignChoiceConstants.PARAM_TYPE_INTEGER.equals( getSelectedDataType( ) ) ) { return DataTypeUtil.toInteger( value ); } return value; } private IChoiceSet getFormatChoiceSet( String type ) { IChoiceSet choiceSet = null; if ( DesignChoiceConstants.PARAM_TYPE_STRING.equals( type ) ) { choiceSet = DEUtil.getMetaDataDictionary( ) .getChoiceSet( DesignChoiceConstants.CHOICE_STRING_FORMAT_TYPE ); } else if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( type ) ) { choiceSet = DEUtil.getMetaDataDictionary( ) .getChoiceSet( DesignChoiceConstants.CHOICE_DATETIME_FORMAT_TYPE ); } else if ( DesignChoiceConstants.PARAM_TYPE_DATE.equals( type ) ) { choiceSet = DEUtil.getMetaDataDictionary( ) .getChoiceSet( DesignChoiceConstants.CHOICE_DATE_FORMAT_TYPE ); } else if ( DesignChoiceConstants.PARAM_TYPE_TIME.equals( type ) ) { choiceSet = DEUtil.getMetaDataDictionary( ) .getChoiceSet( DesignChoiceConstants.CHOICE_TIME_FORMAT_TYPE ); } else if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( type ) || DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( type ) || DesignChoiceConstants.PARAM_TYPE_INTEGER.equals( type ) ) { choiceSet = DEUtil.getMetaDataDictionary( ) .getChoiceSet( DesignChoiceConstants.CHOICE_NUMBER_FORMAT_TYPE ); } return choiceSet; } private void updateFormatField( ) { String displayFormat; String previewString; String type = getSelectedDataType( ); IChoiceSet choiceSet = getFormatChoiceSet( type ); if ( choiceSet == null ) { // Boolean type; displayFormat = DEUtil.getMetaDataDictionary( ) .getChoiceSet( DesignChoiceConstants.CHOICE_STRING_FORMAT_TYPE ) .findChoice( DesignChoiceConstants.STRING_FORMAT_TYPE_UNFORMATTED ) .getDisplayName( ); previewString = "True"; //$NON-NLS-1$ } else { if ( formatCategroy == null ) { return; } displayFormat = choiceSet.findChoice( formatCategroy ) .getDisplayName( ); if ( isCustom( ) ) { displayFormat += ": " + formatPattern; //$NON-NLS-1$ } // if ( defaultValue != null ) // previewString = format( defaultValue ); // else if ( type.equals( DesignChoiceConstants.PARAM_TYPE_DATETIME ) ) { previewString = new DateFormatter( isCustom( ) ? formatPattern : ( formatCategroy.equals( DesignChoiceConstants.DATETIEM_FORMAT_TYPE_UNFORMATTED ) ? DateFormatter.DATETIME_UNFORMATTED : formatCategroy ), ULocale.getDefault( ) ).format( new Date( ) ); } else if ( type.equals( DesignChoiceConstants.PARAM_TYPE_DATE ) ) { previewString = new DateFormatter( isCustom( ) ? formatPattern : ( formatCategroy.equals( DesignChoiceConstants.DATE_FORMAT_TYPE_UNFORMATTED ) ? DateFormatter.DATE_UNFORMATTED : formatCategroy ), ULocale.getDefault( ) ).format( new Date( ) ); } else if ( type.equals( DesignChoiceConstants.PARAM_TYPE_TIME ) ) { previewString = new DateFormatter( isCustom( ) ? formatPattern : ( formatCategroy.equals( "Unformatted" ) ? DateFormatter.TIME_UNFORMATTED //$NON-NLS-1$ : formatCategroy ), ULocale.getDefault( ) ).format( new Date( ) ); } else if ( type.equals( DesignChoiceConstants.PARAM_TYPE_STRING ) ) { previewString = new StringFormatter( isCustom( ) ? formatPattern : formatCategroy, ULocale.getDefault( ) ).format( Messages.getString( "ParameterDialog.Label.Sample" ) ); //$NON-NLS-1$ } else if ( type.equals( DesignChoiceConstants.PARAM_TYPE_INTEGER ) ) { previewString = new NumberFormatter( isCustom( ) ? formatPattern : formatCategroy, ULocale.getDefault( ) ).format( 1234567890 ); } else { previewString = new NumberFormatter( isCustom( ) ? formatPattern : formatCategroy, ULocale.getDefault( ) ).format( 123456789.01234 ); } } formatField.setText( displayFormat ); previewLabel.setText( convertNullString( previewString ) ); changeFormat.setEnabled( choiceSet != null ); } private String convertNullString( String str ) { if ( str == null ) { return "";//$NON-NLS-1$ } return str; } private boolean containValue( SelectionChoice selectedChoice, String newValue, String property ) { for ( Iterator iter = choiceList.iterator( ); iter.hasNext( ); ) { SelectionChoice choice = (SelectionChoice) iter.next( ); if ( choice != selectedChoice ) { String value = null; if ( COLUMN_VALUE.equals( property ) ) { value = choice.getValue( ); if ( isEqual( value, newValue ) ) { return true; } } if ( COLUMN_DISPLAY_TEXT_KEY.equals( property ) ) { value = choice.getLabelResourceKey( ); if ( value == null ) { value = choice.getValue( ); } if ( value == null ) { value = LABEL_NULL; } if ( value.equals( newValue ) ) { return true; } } if ( COLUMN_DISPLAY_TEXT.equals( property ) ) { value = choice.getLabel( ); if ( value == null ) { value = choice.getValue( ); } if ( value == null ) { value = LABEL_NULL; } if ( value.equals( newValue ) ) { return true; } } } } return false; } private void popupFormatBuilder( boolean refresh ) { String dataType = getSelectedDataType( ); int formatType; if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN.equals( dataType ) ) { return; } if ( DesignChoiceConstants.PARAM_TYPE_STRING.equals( dataType ) ) { formatType = FormatBuilder.STRING; } else if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( dataType ) ) { formatType = FormatBuilder.DATETIME; } else if ( DesignChoiceConstants.PARAM_TYPE_DATE.equals( dataType ) ) { formatType = FormatBuilder.DATE; } else if ( DesignChoiceConstants.PARAM_TYPE_TIME.equals( dataType ) ) { formatType = FormatBuilder.TIME; } else { formatType = FormatBuilder.NUMBER; } FormatBuilder formatBuilder = new FormatBuilder( formatType ); formatBuilder.setInputFormat( formatCategroy, formatPattern ); formatBuilder.setPreviewText( defaultValue ); if ( formatBuilder.open( ) == OK ) { formatCategroy = ( (String[]) formatBuilder.getResult( ) )[0]; formatPattern = ( (String[]) formatBuilder.getResult( ) )[1]; updateFormatField( ); if ( refresh ) { refreshValueTable( ); } } } private boolean canBeBlank( ) { boolean canBeBlank = false; // if ( PARAM_CONTROL_LIST.equals( getSelectedControlType( ) ) // || DesignChoiceConstants.PARAM_CONTROL_TEXT_BOX.equals( // getSelectedControlType( ) ) ) { if ( dirtyProperties.containsKey( CHECKBOX_ISREQUIRED ) ) { canBeBlank = !( ( (Boolean) dirtyProperties.get( CHECKBOX_ISREQUIRED ) ).booleanValue( ) ); } else { canBeBlank = !( inputParameter.isRequired( ) ); } } return canBeBlank; } private boolean canBeNull( ) { boolean canBeNull = false; if ( dirtyProperties.containsKey( CHECKBOX_ISREQUIRED ) ) { canBeNull = !( ( (Boolean) dirtyProperties.get( CHECKBOX_ISREQUIRED ) ).booleanValue( ) ); } else { canBeNull = !( inputParameter.isRequired( ) ); } return canBeNull; } private boolean isDefaultChoice( SelectionChoice choice ) { String choiceValue = choice.getValue( ); String defaultValue = convertToStandardFormat( this.defaultValue ); if ( canBeNull( ) && choiceValue == null && defaultValue == null ) { return true; } return choiceValue != null && isEqual( choiceValue, defaultValue ); } private boolean isStatic( ) { return staticRadio.getSelection( ); } private String convertToStandardFormat( String string ) { if ( string != null && DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( getSelectedDataType( ) ) ) { try { string = convertToStandardFormat( DataTypeUtil.toDate( string, ULocale.US ) ); } catch ( BirtException e ) { } } return string; } private String convertToStandardFormat( Date date ) { if ( date == null ) { return null; } return new DateFormatter( STANDARD_DATE_TIME_PATTERN, ULocale.getDefault( ) ).format( date ); } private String getExpression( String columnName ) { if ( columnName.equals( NONE_DISPLAY_TEXT ) ) { return null; } for ( Iterator iter = columnList.iterator( ); iter.hasNext( ); ) { ResultSetColumnHandle cachedColumn = (ResultSetColumnHandle) iter.next( ); if ( cachedColumn.getColumnName( ).equals( columnName ) ) { return DEUtil.getExpression( cachedColumn ); } } // return null; return columnName; } private String getColumnName( String expression ) { for ( Iterator iter = columnList.iterator( ); iter.hasNext( ); ) { ResultSetColumnHandle cachedColumn = (ResultSetColumnHandle) iter.next( ); if ( DEUtil.getExpression( cachedColumn ).equals( expression ) ) { return cachedColumn.getColumnName( ); } } // return null; return expression; } private String getInputControlDisplayName( ) { String type = getInputControlType( ); String displayName = null; if ( CONTROL_TYPE_CHOICE_SET.findChoice( type ) != null ) { displayName = CONTROL_TYPE_CHOICE_SET.findChoice( type ) .getDisplayName( ); } else { if ( PARAM_CONTROL_COMBO.equals( type ) ) { displayName = DISPLAY_NAME_CONTROL_COMBO; } else if ( PARAM_CONTROL_LIST.equals( type ) ) { displayName = DISPLAY_NAME_CONTROL_LIST; } } return displayName; } private String validateChoice( SelectionChoice choice, String displayLabelKey, String displayLabel, String value ) { String errorMessage = isValidValue( value ); if ( errorMessage != null ) { return errorMessage; } String newValue = convertToStandardFormat( value ); if ( distinct.isEnabled( ) && distinct.getSelection( ) ) { if ( containValue( choice, displayLabelKey, COLUMN_DISPLAY_TEXT_KEY ) ) { return ERROR_MSG_DUPLICATED_LABELKEY; } else return null; } if ( containValue( choice, newValue, COLUMN_VALUE ) ) { return ERROR_MSG_DUPLICATED_VALUE; } if ( ( displayLabel == null && containValue( choice, newValue, COLUMN_DISPLAY_TEXT ) ) || ( containValue( choice, displayLabel, COLUMN_DISPLAY_TEXT ) ) ) { return ERROR_MSG_DUPLICATED_LABEL; } if ( containValue( choice, displayLabelKey, COLUMN_DISPLAY_TEXT_KEY ) ) { return ERROR_MSG_DUPLICATED_LABELKEY; } return null; } private void changeDefaultValue( String value ) { defaultValue = value; updateFormatField( ); updateMessageLine( ); } private boolean isCustom( ) { if ( DesignChoiceConstants.STRING_FORMAT_TYPE_CUSTOM.equals( formatCategroy ) || DesignChoiceConstants.NUMBER_FORMAT_TYPE_CUSTOM.equals( formatCategroy ) || DesignChoiceConstants.DATETIEM_FORMAT_TYPE_CUSTOM.equals( formatCategroy ) || DesignChoiceConstants.DATE_FORMAT_TYPE_CUSTOM.equals( formatCategroy ) || DesignChoiceConstants.TIME_FORMAT_TYPE_CUSTOM.equals( formatCategroy ) ) { return true; } return false; } private void setExpression( Combo chooser, String key ) { chooser.deselectAll( ); key = StringUtil.trimString( key ); if ( StringUtil.isBlank( key ) ) { chooser.setText( "" ); //$NON-NLS-1$ return; } for ( int i = 0; i < columnList.size( ); i++ ) { if ( key.equals( DEUtil.getExpression( columnList.get( i ) ) ) ) { chooser.select( i ); return; } } chooser.setText( key ); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.zoneproject.extractor.twitterreader; import java.util.ArrayList; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Desclaux Christophe <christophe@zouig.org> */ public class TwitterApiTest { public TwitterApiTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getSources method, of class TwitterApi. */ @Test public void testGetHashTags() { System.out.println("getHashTags"); String[] expResult = {"#descl","#you","#nice"}; String[] result = TwitterApi.getHashTags("hello #descl how are #you in #nice?"); for(String r: result) { System.out.println(r); } assertArrayEquals(expResult, result); } }
package biz.netcentric.cq.tools.actool.installationhistory; import java.util.LinkedHashSet; import java.util.Set; import java.util.TreeSet; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.ValueFormatException; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.version.VersionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import biz.netcentric.cq.tools.actool.comparators.TimestampPropertyComparator; public class HistoryUtils { private static final String PROPERTY_SLING_RESOURCE_TYPE = "sling:resourceType"; private static final String ACHISTORY_ROOT_NODE = "achistory"; private static final String STATISTICS_ROOT_NODE = "var/statistics"; private static final String PROPERTY_TIMESTAMP = "timestamp"; private static final String PROPERTY_MESSAGES = "messages"; private static final String PROPERTY_EXECUTION_TIME = "executionTime"; private static final String PROPERTY_SUCCESS = "success"; private static final String PROPERTY_INSTALLATION_DATE = "installationDate"; private static final Logger LOG = LoggerFactory.getLogger(HistoryUtils.class); public static Node getAcHistoryRootNode(final Session session) throws RepositoryException{ final Node rootNode = session.getRootNode(); Node statisticsRootNode = safeGetNode(rootNode, STATISTICS_ROOT_NODE, "nt:unstructured"); Node acHistoryRootNode = safeGetNode(statisticsRootNode, ACHISTORY_ROOT_NODE, "sling:OrderedFolder"); return acHistoryRootNode; } public static Node persistHistory(final Session session, AcInstallationHistoryPojo history, final int nrOfHistoriesToSave) throws RepositoryException{ Node acHistoryRootNode = getAcHistoryRootNode(session); Node newHistoryNode = safeGetNode(acHistoryRootNode, "history_" + System.currentTimeMillis(), "nt:unstructured"); String path = newHistoryNode.getPath(); setHistoryNodeProperties(newHistoryNode, history); deleteObsoleteHistoryNodes(acHistoryRootNode, nrOfHistoriesToSave); Node previousHistoryNode = (Node) acHistoryRootNode.getNodes().next(); if(previousHistoryNode != null){ acHistoryRootNode.orderBefore(newHistoryNode.getName(), previousHistoryNode.getName()); } String message = "saved history in node: " + path; history.addMessage(message); LOG.info(message); return newHistoryNode; } private static Node safeGetNode(final Node baseNode, final String name, final String typeToCreate) throws RepositoryException { if (!baseNode.hasNode(name)) { LOG.info("create node: {}", name); return baseNode.addNode(name, typeToCreate); } else { return baseNode.getNode(name); } } private static void setHistoryNodeProperties(final Node historyNode, AcInstallationHistoryPojo history) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException{ historyNode.setProperty(PROPERTY_INSTALLATION_DATE, history.getInstallationDate().toString()); historyNode.setProperty(PROPERTY_SUCCESS, history.isSuccess()); historyNode.setProperty(PROPERTY_EXECUTION_TIME, history.getExecutionTime()); historyNode.setProperty(PROPERTY_MESSAGES, history.getVerboseMessageHistory()); historyNode.setProperty(PROPERTY_TIMESTAMP, history.getInstallationDate().getTime()); historyNode.setProperty(PROPERTY_SLING_RESOURCE_TYPE, "/apps/netcentric/actool/components/historyRenderer"); } private static void deleteObsoleteHistoryNodes(final Node acHistoryRootNode, final int nrOfHistoriesToSave) throws RepositoryException{ NodeIterator childNodeIt = acHistoryRootNode.getNodes(); Set<Node> historyChildNodes = new TreeSet<Node>(new TimestampPropertyComparator()); while(childNodeIt.hasNext()){ historyChildNodes.add(childNodeIt.nextNode()); } int index = 1; for(Node node : historyChildNodes){ if(index > nrOfHistoriesToSave){ LOG.info("delete obsolete history node: ", node.getPath()); node.remove(); } index++; } } public static String[] getInstallationLogs(final Session session) throws RepositoryException{ Node acHistoryRootNode = getAcHistoryRootNode(session); return getAssembledHistoryLinks(acHistoryRootNode); } private static String[] getAssembledHistoryLinks(Node acHistoryRootNode) throws RepositoryException, PathNotFoundException { Set<String> messages = new LinkedHashSet<String>(); int cnt = 1; for (NodeIterator iterator = acHistoryRootNode.getNodes(); iterator.hasNext();) { Node node = (Node) iterator.next(); if(node != null){ String successStatusString = "failed"; if(node.getProperty(PROPERTY_SUCCESS).getBoolean()){ successStatusString = "ok"; } messages.add(cnt + ". " + node.getPath() + " " + "(" + successStatusString + ")" ); } cnt++; } return messages.toArray(new String[messages.size()]); } public static String getLogTxt(final Session session, final String path) { return getLog(session, path, "\n").toString(); } public static String getLogHtml(final Session session, final String path) { return getLog(session, path, "<br />").toString(); } public static String getLog(final Session session, final String path, final String lineFeed) { StringBuilder sb = new StringBuilder(); try { Node acHistoryRootNode = getAcHistoryRootNode(session); Node historyNode = acHistoryRootNode.getNode(path); if(historyNode != null){ sb.append("Installation triggered: " + historyNode.getProperty(PROPERTY_INSTALLATION_DATE).getString()); sb.append(lineFeed + historyNode.getProperty(PROPERTY_MESSAGES).getString().replace("\n", lineFeed)); sb.append(lineFeed + "Execution time: " + historyNode.getProperty(PROPERTY_EXECUTION_TIME).getLong() + " ms"); sb.append(lineFeed + "Success: " + historyNode.getProperty(PROPERTY_SUCCESS).getBoolean()); } } catch (RepositoryException e) { LOG.error("RepositoryException: {}", e); } return sb.toString(); } }
package com.continuuity.internal.app.runtime.distributed; import com.continuuity.app.program.Program; import com.continuuity.app.program.Programs; import com.continuuity.app.queue.QueueReader; import com.continuuity.app.runtime.Arguments; import com.continuuity.app.runtime.ProgramController; import com.continuuity.app.runtime.ProgramOptions; import com.continuuity.app.runtime.ProgramRunner; import com.continuuity.common.conf.CConfiguration; import com.continuuity.common.conf.Constants; import com.continuuity.common.conf.KafkaConstants; import com.continuuity.common.guice.ConfigModule; import com.continuuity.common.guice.IOModule; import com.continuuity.common.guice.LocationRuntimeModule; import com.continuuity.common.metrics.MetricsCollectionService; import com.continuuity.data.runtime.DataFabricModules; import com.continuuity.internal.app.queue.QueueReaderFactory; import com.continuuity.internal.app.queue.SingleQueue2Reader; import com.continuuity.internal.app.runtime.AbstractListener; import com.continuuity.internal.app.runtime.BasicArguments; import com.continuuity.internal.app.runtime.DataFabricFacade; import com.continuuity.internal.app.runtime.DataFabricFacadeFactory; import com.continuuity.internal.app.runtime.SimpleProgramOptions; import com.continuuity.internal.app.runtime.SmartDataFabricFacade; import com.continuuity.internal.kafka.client.ZKKafkaClientService; import com.continuuity.kafka.client.KafkaClientService; import com.continuuity.logging.appender.LogAppenderInitializer; import com.continuuity.logging.guice.LoggingModules; import com.continuuity.metrics.guice.MetricsClientRuntimeModule; import com.continuuity.weave.api.Command; import com.continuuity.weave.api.ServiceAnnouncer; import com.continuuity.weave.api.WeaveContext; import com.continuuity.weave.api.WeaveRunnable; import com.continuuity.weave.api.WeaveRunnableSpecification; import com.continuuity.weave.common.Cancellable; import com.continuuity.weave.common.Services; import com.continuuity.weave.filesystem.LocalLocationFactory; import com.continuuity.weave.filesystem.LocationFactory; import com.continuuity.weave.zookeeper.RetryStrategies; import com.continuuity.weave.zookeeper.ZKClientService; import com.continuuity.weave.zookeeper.ZKClientServices; import com.continuuity.weave.zookeeper.ZKClients; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableMap; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.SettableFuture; import com.google.gson.Gson; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.PrivateModule; import com.google.inject.Scopes; import com.google.inject.assistedinject.FactoryModuleBuilder; import com.google.inject.name.Named; import com.google.inject.name.Names; import com.google.inject.util.Modules; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.apache.hadoop.conf.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.util.Map; import java.util.concurrent.TimeUnit; /** * A {@link WeaveRunnable} for running a program through a {@link ProgramRunner}. * * @param <T> The {@link ProgramRunner} type. */ public abstract class AbstractProgramWeaveRunnable<T extends ProgramRunner> implements WeaveRunnable { private static final Logger LOG = LoggerFactory.getLogger(AbstractProgramWeaveRunnable.class); private String name; private String hConfName; private String cConfName; private Injector injector; private Program program; private ProgramOptions programOpts; private ProgramController controller; private Configuration hConf; private CConfiguration cConf; private ZKClientService zkClientService; private KafkaClientService kafkaClientService; private MetricsCollectionService metricsCollectionService; protected AbstractProgramWeaveRunnable(String name, String hConfName, String cConfName) { this.name = name; this.hConfName = hConfName; this.cConfName = cConfName; } protected abstract Class<T> getProgramClass(); @Override public WeaveRunnableSpecification configure() { return WeaveRunnableSpecification.Builder.with() .setName(name) .withConfigs(ImmutableMap.of( "hConf", hConfName, "cConf", cConfName )) .build(); } @Override public void initialize(WeaveContext context) { name = context.getSpecification().getName(); Map<String, String> configs = context.getSpecification().getConfigs(); LOG.info("Initialize runnable: " + name); try { CommandLine cmdLine = parseArgs(context.getArguments()); // Loads configurations hConf = new Configuration(); hConf.clear(); hConf.addResource(new File(configs.get("hConf")).toURI().toURL()); cConf = CConfiguration.create(); cConf.clear(); cConf.addResource(new File(configs.get("cConf")).toURI().toURL()); zkClientService = ZKClientServices.delegate( ZKClients.reWatchOnExpire( ZKClients.retryOnFailure( ZKClientService.Builder.of(cConf.get(Constants.Zookeeper.QUORUM)) .setSessionTimeout(10000) .build(), RetryStrategies.fixDelay(2, TimeUnit.SECONDS) ) ) ); String kafkaZKNamespace = cConf.get(KafkaConstants.ConfigKeys.ZOOKEEPER_NAMESPACE_CONFIG); kafkaClientService = new ZKKafkaClientService( kafkaZKNamespace == null ? zkClientService : ZKClients.namespace(zkClientService, "/" + kafkaZKNamespace) ); injector = Guice.createInjector(createModule(context, kafkaClientService)); metricsCollectionService = injector.getInstance(MetricsCollectionService.class); // Initialize log appender LogAppenderInitializer logAppenderInitializer = injector.getInstance(LogAppenderInitializer.class); logAppenderInitializer.initialize(); try { program = injector.getInstance(ProgramFactory.class).create(cmdLine.getOptionValue(RunnableOptions.JAR)); } catch (IOException e) { throw Throwables.propagate(e); } Arguments runtimeArguments = new Gson().fromJson(cmdLine.getOptionValue(RunnableOptions.RUNTIME_ARGS), BasicArguments.class); programOpts = new SimpleProgramOptions(name, new BasicArguments(ImmutableMap.of( "instanceId", Integer.toString(context.getInstanceId()), "instances", Integer.toString(context.getInstanceCount()), "runId", context.getApplicationRunId().getId())), runtimeArguments); LOG.info("Runnable initialized: " + name); } catch (Throwable t) { LOG.error(t.getMessage(), t); throw Throwables.propagate(t); } } @Override public void handleCommand(Command command) throws Exception { if (ProgramCommands.SUSPEND.equals(command)) { controller.suspend().get(); return; } if (ProgramCommands.RESUME.equals(command)) { controller.resume().get(); return; } if ("instances".equals(command.getCommand())) { int instances = Integer.parseInt(command.getOptions().get("count")); controller.command("instances", instances).get(); return; } LOG.warn("Ignore unsupported command: " + command); } @Override public void stop() { try { LOG.info("Stopping runnable: " + name); controller.stop().get(); LOG.info("Runnable stopped: " + name); } catch (Exception e) { LOG.error("Fail to stop. {}", e, e); throw Throwables.propagate(e); } finally { LOG.info("Stopping metrics service"); Futures.getUnchecked(Services.chainStop(metricsCollectionService, kafkaClientService, zkClientService)); } } @Override public void run() { LOG.info("Starting metrics service"); Futures.getUnchecked(Services.chainStart(zkClientService, kafkaClientService, metricsCollectionService)); LOG.info("Starting runnable: " + name); controller = injector.getInstance(getProgramClass()).run(program, programOpts); final SettableFuture<ProgramController.State> state = SettableFuture.create(); controller.addListener(new AbstractListener() { @Override public void stopped() { state.set(ProgramController.State.STOPPED); } @Override public void error(Throwable cause) { LOG.error("Program runner error out.", cause); state.set(ProgramController.State.ERROR); } }, MoreExecutors.sameThreadExecutor()); LOG.info("Program runner terminated. State: {}", Futures.getUnchecked(state)); } private CommandLine parseArgs(String[] args) { Options opts = new Options() .addOption(createOption(RunnableOptions.JAR, "Program jar location")) .addOption(createOption(RunnableOptions.RUNTIME_ARGS, "Runtime arguments")); try { return new PosixParser().parse(opts, args); } catch (ParseException e) { throw Throwables.propagate(e); } } private Option createOption(String opt, String desc) { Option option = new Option(opt, true, desc); option.setRequired(true); return option; } // TODO(terence) make this works for different mode private Module createModule(final WeaveContext context, final KafkaClientService kafkaClientService) { return Modules.combine(new ConfigModule(cConf, hConf), new IOModule(), new MetricsClientRuntimeModule(kafkaClientService).getDistributedModules(), new LocationRuntimeModule().getDistributedModules(), new LoggingModules().getDistributedModules(), new DataFabricModules(cConf, hConf).getDistributedModules(), new AbstractModule() { @Override protected void configure() { bind(InetAddress.class).annotatedWith(Names.named(Constants.AppFabric.SERVER_ADDRESS)) .toInstance(context.getHost()); // For program loading install(createProgramFactoryModule()); // For Binding queue reader stuff (for flowlets) install(createFactoryModule(QueueReaderFactory.class, QueueReader.class, SingleQueue2Reader.class)); // For binding DataSet transaction stuff install(createFactoryModule(DataFabricFacadeFactory.class, DataFabricFacade.class, SmartDataFabricFacade.class)); bind(ServiceAnnouncer.class).toInstance(new ServiceAnnouncer() { @Override public Cancellable announce(String serviceName, int port) { return context.announce(serviceName, port); } }); } }); } private <T> Module createFactoryModule(final Class<?> factoryClass, final Class<T> sourceClass, final Class<? extends T> targetClass) { return new FactoryModuleBuilder() .implement(sourceClass, targetClass) .build(factoryClass); } private Module createProgramFactoryModule() { return new PrivateModule() { @Override protected void configure() { bind(LocationFactory.class) .annotatedWith(Names.named("program.location.factory")) .toInstance(new LocalLocationFactory(new File(System.getProperty("user.dir")))); bind(ProgramFactory.class).in(Scopes.SINGLETON); expose(ProgramFactory.class); } }; } /** * A private factory for creating instance of Program. * It's needed so that we can inject different LocationFactory just for loading program. */ private static final class ProgramFactory { private final LocationFactory locationFactory; @Inject ProgramFactory(@Named("program.location.factory") LocationFactory locationFactory) { this.locationFactory = locationFactory; } public Program create(String path) throws IOException { return Programs.create(locationFactory.create(path)); } } }
package org.csstudio.trends.databrowser2.model; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.logging.Level; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.csstudio.apputil.macros.IMacroTableProvider; import org.csstudio.apputil.macros.InfiniteLoopException; import org.csstudio.apputil.macros.MacroUtil; import org.csstudio.apputil.time.RelativeTime; import org.csstudio.apputil.time.StartEndTimeParser; import org.csstudio.apputil.xml.DOMHelper; import org.csstudio.apputil.xml.XMLWriter; import org.csstudio.data.values.ITimestamp; import org.csstudio.data.values.TimestampFactory; import org.csstudio.trends.databrowser2.Activator; import org.csstudio.trends.databrowser2.Messages; import org.csstudio.trends.databrowser2.imports.ImportArchiveReaderFactory; import org.csstudio.trends.databrowser2.preferences.Preferences; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.graphics.RGB; import org.w3c.dom.Document; import org.w3c.dom.Element; /** Data Browser model * <p> * Maintains a list of {@link ModelItem}s * * @author Kay Kasemir * @author Takashi Nakamoto changed the model to accept multiple items with * the same name so that Data Browser can show the * trend of the same PV in different axes or with * different waveform indexes. */ @SuppressWarnings("nls") public class Model { /** File extension for data browser config files. * plugin.xml registers the editor for this file extension */ final public static String FILE_EXTENSION = "plt"; //$NON-NLS-1$ /** Previously used file extension */ final public static String FILE_EXTENSION_OLD = "css-plt"; //$NON-NLS-1$ // XML file tags final public static String TAG_DATABROWSER = "databrowser"; final public static String TAG_SCROLL = "scroll"; final public static String TAG_UPDATE_PERIOD = "update_period"; final public static String TAG_LIVE_SAMPLE_BUFFER_SIZE = "ring_size"; final public static String TAG_PVLIST = "pvlist"; final public static String TAG_PV = "pv"; final public static String TAG_NAME = "name"; final public static String TAG_DISPLAYNAME = "display_name"; final public static String TAG_FORMULA = "formula"; final public static String TAG_AXES = "axes"; final public static String TAG_AXIS = "axis"; final public static String TAG_LINEWIDTH = "linewidth"; final public static String TAG_COLOR = "color"; final public static String TAG_RED = "red"; final public static String TAG_GREEN = "green"; final public static String TAG_BLUE = "blue"; final public static String TAG_TRACE_TYPE = "trace_type"; final public static String TAG_SCAN_PERIOD = "period"; final public static String TAG_INPUT = "input"; final public static String TAG_ARCHIVE = "archive"; final public static String TAG_URL = "url"; final public static String TAG_KEY = "key"; final public static String TAG_START = "start"; final public static String TAG_END = "end"; final public static String TAG_LOG_SCALE = "log_scale"; final public static String TAG_AUTO_SCALE = "autoscale"; final public static String TAG_MAX = "max"; final public static String TAG_MIN = "min"; final public static String TAG_BACKGROUND = "background"; final public static String TAG_ARCHIVE_RESCALE = "archive_rescale"; final public static String TAG_REQUEST = "request"; final public static String TAG_VISIBLE = "visible"; final public static String TAG_ANNOTATIONS = "annotations"; final public static String TAG_ANNOTATION = "annotation"; public static final String TAG_ANNOTATION_CURSOR_LINE_STYLE = "line_style"; public static final String TAG_ANNOTATION_SHOW_NAME = "show_name"; public static final String TAG_ANNOTATION_SHOW_POSITION = "show_position"; public static final String TAG_ANNOTATION_COLOR = "color"; public static final String TAG_ANNOTATION_FONT = "font"; final public static String TAG_TIME = "time"; final public static String TAG_VALUE = "value"; final public static String TAG_WAVEFORM_INDEX = "waveform_index"; /**AJOUT XYGraphMemento * @author L.PHILIPPE GANIL */ final public static String TAG_TITLE = "title"; final public static String TAG_TITLE_TEXT = "text"; final public static String TAG_TITLE_COLOR= "color"; final public static String TAG_TITLE_FONT ="font"; public static final String TAG_FONT = "font"; public static final String TAG_SCALE_FONT = "scale_font"; final public static String TAG_TIME_AXIS = "time_axis"; //GRID LINE public static final String TAG_GRID_LINE = "grid_line"; public static final String TAG_SHOW_GRID_LINE = "show_grid_line"; public static final String TAG_DASH_GRID_LINE = "dash_grid_line"; //FORMAT public static final String TAG_FORMAT = "format"; public static final String TAG_AUTO_FORMAT = "auto_format"; public static final String TAG_TIME_FORMAT = "time_format"; public static final String TAG_FORMAT_PATTERN = "format_pattern"; public static final String TAG_GRAPH_SETTINGS = "graph_settings"; public static final String TAG_SHOW_TITLE = "show_title"; public static final String TAG_SHOW_LEGEND = "show_legend"; public static final String TAG_SHOW_PLOT_AREA_BORDER = "show_plot_area_border"; public static final String TAG_TRANSPARENT = "transparent"; /** Default colors for newly added item, used over when reaching the end. * <p> * Very hard to find a long list of distinct colors. * This list is definitely too short... */ final private static RGB[] default_colors = { new RGB( 21, 21, 196), // blue new RGB(242, 26, 26), // red new RGB( 33, 179, 33), // green new RGB( 0, 0, 0), // black new RGB(128, 0, 255), // violett new RGB(255, 170, 0), // (darkish) yellow new RGB(255, 0, 240), // pink new RGB(243, 132, 132), // peachy new RGB( 0, 255, 11), // neon green new RGB( 0, 214, 255), // neon blue new RGB(114, 40, 3), // brown new RGB(219, 128, 4), // orange }; /** Macros */ private IMacroTableProvider macros = null; /** Listeners to model changes */ final private ArrayList<ModelListener> listeners = new ArrayList<ModelListener>(); /** Axes configurations */ final private ArrayList<AxisConfig> axes = new ArrayList<AxisConfig>(); /** * Time Axes configurations * Ignore MIN-MAX part because the range is set by start & end properties */ private AxisConfig timeAxis; public AxisConfig getTimeAxis() { return timeAxis; } /** All the items in this model */ final private ArrayList<ModelItem> items = new ArrayList<ModelItem>(); /** 'run' flag * @see #start() * @see #stop() */ private boolean is_running = false; /** Period in seconds for scrolling or refreshing */ private double update_period = Preferences.getUpdatePeriod(); /** Timer used to scan PVItems */ final private Timer scanner = new Timer("ScanTimer", true); /** <code>true</code> if scrolling is enabled */ private boolean scroll_enabled = true; /** Time span of data in seconds */ private double time_span = Preferences.getTimeSpan(); /** End time of the data range */ private ITimestamp end_time = TimestampFactory.now(); /** Background color */ private RGB background = new RGB(255, 255, 255); /** Annotations */ private AnnotationInfo[] annotations = new AnnotationInfo[0]; /** How should plot rescale when archived data arrives? */ private ArchiveRescale archive_rescale = Preferences.getArchiveRescale(); /** * Manage XYGraph Configuration Settings * @author L.PHILIPPE GANIL */ private XYGraphSettings graphSettings = new XYGraphSettings(); public XYGraphSettings getGraphSettings() { return graphSettings; } public void setGraphSettings(XYGraphSettings xYGraphMem) { graphSettings = xYGraphMem; //fireXYGraphMemChanged(settings); } public void fireGraphConfigChanged() { for (ModelListener listener : listeners) listener.changedXYGraphConfig(); } /** @param macros Macros to use in this model */ public void setMacros(final IMacroTableProvider macros) { this.macros = macros; } /** Resolve macros * @param text Text that might contain "$(macro)" * @return Text with all macros replaced by their value */ public String resolveMacros(final String text) { if (macros == null) return text; try { return MacroUtil.replaceMacros(text, macros); } catch (InfiniteLoopException ex) { Activator.getLogger().log(Level.WARNING, "Problem in macro {0}: {1}", new Object[] { text, ex.getMessage()}); return "Macro Error"; } } /** @param listener New listener to notify */ public void addListener(final ModelListener listener) { listeners.add(listener); } /** @param listener Listener to remove */ public void removeListener(final ModelListener listener) { listeners.remove(listener); } /** @return Number of axes in model */ public int getAxisCount() { return axes.size(); } /** @param axis_index Index of axis, 0 ... <code>getAxisCount()-1</code> * @return {@link AxisConfig} */ public AxisConfig getAxis(final int axis_index) { return axes.get(axis_index); } /** * Return the AxisConfig with the specifc name or null * @param axis_index Index of axis, 0 ... <code>getAxisCount()-1</code> * @return {@link AxisConfig} */ public AxisConfig getAxis(final String name) { for(AxisConfig axis : axes){ //System.err.println(axis.getName() + " == " + name + "=" + (axis.getName().equals(name))); if(axis.getName().equals(name)) return axis; } return null; } /** Locate index of value axis * @param axis Value axis configuration * @return Index of axis (0, ...) or -1 if not in Model */ public int getAxisIndex(final AxisConfig axis) { return axes.indexOf(axis); } /** @param axis Axis to test * @return First ModelItem that uses the axis, <code>null</code> if * axis is empty */ public ModelItem getFirstItemOnAxis(final AxisConfig axis) { for (ModelItem item : items) if (item.getAxis() == axis) return item; return null; } /** @param axis Axis to test * @return ModelItem linked to this axis count */ public int countActiveItemsOnAxis(final AxisConfig axis) { int count = 0; for (ModelItem item : items) if (item.getAxis() == axis && item.isVisible()) count++; return count; } /** @return First unused axis (no items on axis), * <code>null</code> if none found */ public AxisConfig getEmptyAxis() { for (AxisConfig axis : axes) if (getFirstItemOnAxis(axis) == null) return axis; return null; } /** Add value axis with default settings * @return Newly added axis configuration */ public AxisConfig addAxis(String name) { if (name == null) name = NLS.bind(Messages.Plot_ValueAxisNameFMT, getAxisCount() + 1); final AxisConfig axis = new AxisConfig(name); axis.setColor(getNextItemColor()); addAxis(axis); return axis; } /** @param axis New axis to add */ public void addAxis(final AxisConfig axis) { axes.add(axis); axis.setModel(this); fireAxisChangedEvent(null); } /** Add axis at given index. * Adding at '1' means the new axis will be at index '1', * and what used to be at '1' will be at '2' and so on. * @param index Index where axis will be placed. * @param axis New axis to add */ public void addAxis(final int index, final AxisConfig axis) { axes.add(index, axis); axis.setModel(this); fireAxisChangedEvent(null); } /** @param axis Axis to remove * @throws Error when axis not in model, or axis in use by model item */ public void removeAxis(final AxisConfig axis) { if (! axes.contains(axis)) throw new Error("Unknown AxisConfig"); for (ModelItem item : items) if (item.getAxis() == axis) throw new Error("Cannot removed AxisConfig while in use"); axis.setModel(null); axes.remove(axis); fireAxisChangedEvent(null); } /** @return How should plot rescale after archived data arrived? */ public ArchiveRescale getArchiveRescale() { return archive_rescale; } /** @param archive_rescale How should plot rescale after archived data arrived? */ public void setArchiveRescale(final ArchiveRescale archive_rescale) { if (this.archive_rescale == archive_rescale) return; this.archive_rescale = archive_rescale; for (ModelListener listener : listeners) listener.changedArchiveRescale(); } /** @return {@link ModelItem} count in model */ public int getItemCount() { return items.size(); } /** Get one {@link ModelItem} * @param i 0... getItemCount()-1 * @return {@link ModelItem} */ public ModelItem getItem(final int i) { return items.get(i); } /** Locate item by name. * If different items with the same exist in this model, the first * occurrence will be returned. If no item is found with the given * name, <code>null</code> will be returned. * Now that this model may have different items with the same name, * this method is not recommended to locate an item. This method * just returns an item which just happens to have the given name. * Use {@link #indexOf(ModelItem)} or {@link #getItem(int)} to locate * an item in this model. * @param name * @return ModelItem by that name or <code>null</code> */ public ModelItem getItem(final String name) { for (ModelItem item : items) if (item.getName().equals(name)) return item; return null; } /** Returns the index of the specified item, or -1 if this list does not contain * the item. * @param item * @return ModelItem */ public int indexOf(final ModelItem item) { return items.indexOf(item); } /** Called by items to set their initial color * @return 'Next' suggested item color */ private RGB getNextItemColor() { return default_colors[items.size() % default_colors.length]; } /** Add item to the model. * <p> * If the item has no color, this will define its color based * on the model's next available color. * <p> * If the model is already 'running', the item will be 'start'ed. * * @param item {@link ModelItem} to add * @throws RuntimeException if item is already in model * @throws Exception on error trying to start a PV Item that's added to a * running model */ public void addItem(final ModelItem item) throws Exception { // A new item with the same PV name are allowed to be added in the // model. This way Data Browser can show the trend of the same PV // in different axes or with different waveform indexes. For example, // one may want to show the first element of epics://aaa:bbb in axis 1 // while showing the third element of the same PV in axis 2 to compare // their trends in one chart. // if (getItem(item.getName()) != null) // throw new RuntimeException("Item " + item.getName() + " already in Model"); // But, if exactly the same instance of the given ModelItem already exists in this // model, it will not be added. if (items.indexOf(item) != -1) throw new RuntimeException("Item " + item.getName() + " already in Model"); // Assign default color if (item.getColor() == null) item.setColor(getNextItemColor()); // Force item to be on an axis if (item.getAxis() == null) { if (axes.size() == 0) addAxis(item.getDisplayName()); item.setAxis(axes.get(0)); } // Check item axis if (! axes.contains(item.getAxis())) throw new Exception("Item " + item.getName() + " added with invalid axis " + item.getAxis()); // Add to model items.add(item); item.setModel(this); if (is_running && item instanceof PVItem) ((PVItem)item).start(scanner); // Notify listeners of new item for (ModelListener listener : listeners) listener.itemAdded(item); } /** Remove item from the model. * <p> * If the model and thus item are 'running', * the item will be 'stopped'. * @param item * @throws RuntimeException if item is already in model */ public void removeItem(final ModelItem item) { if (is_running && item instanceof PVItem) { final PVItem pv = (PVItem)item; pv.stop(); // Delete its samples: // For one, so save memory. // Also, in case item is later added back in, its old samples // will have gaps because the item was stopped pv.getSamples().clear(); } if (! items.remove(item)) throw new RuntimeException("Unknown item " + item.getName()); // Detach item from model item.setModel(null); // Notify listeners of removed item for (ModelListener listener : listeners) listener.itemRemoved(item); // Remove axis if unused AxisConfig axis = item.getAxis(); item.setAxis(null); if (countActiveItemsOnAxis(axis) == 0) { removeAxis(axis); fireAxisChangedEvent(null); } } /** @return Period in seconds for scrolling or refreshing */ public double getUpdatePeriod() { return update_period; } /** @param period_secs New update period in seconds */ public void setUpdatePeriod(final double period_secs) { // Don't allow updates faster than 10Hz (0.1 seconds) if (period_secs < 0.1) update_period = 0.1; else update_period = period_secs; // Notify listeners for (ModelListener listener : listeners) listener.changedUpdatePeriod(); } /** The model supports two types of start/end time handling: * <ol> * <li>Scroll mode: While <code>isScrollEnabled=true</code>, * the end time is supposed to be 'now' and the start time is * supposed to be <code>getTimespan()</code> seconds before 'now'. * <li>Fixed start/end time: While <code>isScrollEnabled=false</code>, * the methods <code>getStartTime()</code>, <code>getEndTime</code> * return a fixed start/end time. * </ol> * @return <code>true</code> if scrolling is enabled */ synchronized public boolean isScrollEnabled() { return scroll_enabled; } /** @param scroll_enabled Should scrolling be enabled? */ public void enableScrolling(final boolean scroll_enabled) { synchronized (this) { if (this.scroll_enabled == scroll_enabled) return; this.scroll_enabled = scroll_enabled; } // Notify listeners for (ModelListener listener : listeners) listener.scrollEnabled(scroll_enabled); } /** @return time span of data in seconds * @see #isScrollEnabled() */ synchronized public double getTimespan() { return time_span; } /** @param start_time Start and .. * @param end_time end time of the range to display */ public void setTimerange(final ITimestamp start_time, final ITimestamp end_time) { final double new_span = end_time.toDouble() - start_time.toDouble(); if (new_span > 0) { synchronized (this) { this.end_time = end_time; time_span = new_span; } } // Notify listeners for (ModelListener listener : listeners) listener.changedTimerange(); } /** @param time_span time span of data in seconds * @see #isScrollEnabled() */ public void setTimespan(final double time_span) { if (time_span > 0) { synchronized (this) { this.time_span = time_span; } } // Notify listeners for (ModelListener listener : listeners) listener.changedTimerange(); } /** @return Start time of the data range * @see #isScrollEnabled() */ synchronized public ITimestamp getStartTime() { return TimestampFactory.fromDouble(getEndTime().toDouble() - time_span); } /** @return End time of the data range * @see #isScrollEnabled() */ synchronized public ITimestamp getEndTime() { if (scroll_enabled) end_time = TimestampFactory.now(); return end_time; } /** @return String representation of start time. While scrolling, this is * a relative time, otherwise an absolute date/time. */ synchronized public String getStartSpecification() { if (scroll_enabled) return new RelativeTime(-time_span).toString(); else return getStartTime().toString(); } /** @return String representation of end time. While scrolling, this is * a relative time, otherwise an absolute date/time. */ synchronized public String getEndSpecification() { if (scroll_enabled) return RelativeTime.NOW; else return end_time.toString(); } /** @return Background color */ public RGB getPlotBackground() { return background; } /** @param rgb New background color */ public void setPlotBackground(final RGB rgb) { if (background.equals(rgb)) return; background = rgb; // Notify listeners System.out.println("**** Model.setPlotBackground() ****"); for (ModelListener listener : listeners) listener.changedColors(); } /** @param annotations Annotations to keep in model */ public void setAnnotations(final AnnotationInfo[] annotations) { setAnnotations(annotations, true); } public void setAnnotations(final AnnotationInfo[] annotations, final boolean fireChanged) { this.annotations = annotations; if (fireChanged) fireAnnotationsChanged(); } protected void fireAnnotationsChanged() { for (ModelListener listener : listeners) listener.changedAnnotations(); } /** @return Annotation infos of model */ public AnnotationInfo[] getAnnotations() { return annotations; } /** Start all items: Connect PVs, initiate scanning, ... * @throws Exception on error */ public void start() throws Exception { if (is_running) throw new RuntimeException("Model already started"); for (ModelItem item : items) { if (!(item instanceof PVItem)) continue; final PVItem pv_item = (PVItem) item; pv_item.start(scanner); } is_running = true; } /** Stop all items: Disconnect PVs, ... */ public void stop() { if (!is_running) throw new RuntimeException("Model wasn't started"); is_running = false; for (ModelItem item : items) { if (!(item instanceof PVItem)) continue; final PVItem pv_item = (PVItem) item; pv_item.stop(); ImportArchiveReaderFactory.removeCachedArchives(pv_item.getArchiveDataSources()); } } /** Test if any ModelItems received new samples, * if formulas need to be re-computed, * since the last time this method was called. * @return <code>true</code> if there were new samples */ public boolean updateItemsAndCheckForNewSamples() { boolean anything_new = false; // Update any formulas for (ModelItem item : items) { if (item instanceof FormulaItem && ((FormulaItem)item).reevaluate()) anything_new = true; } // Check and reset PV Items for (ModelItem item : items) { if (item instanceof PVItem && item.getSamples().testAndClearNewSamplesFlag()) anything_new = true; } return anything_new; } /** Notify listeners of changed axis configuration * @param axis Axis that changed */ public void fireAxisChangedEvent(final AxisConfig axis) { for (ModelListener listener : listeners) listener.changedAxis(axis); } /** Notify listeners of changed item visibility * @param item Item that changed */ void fireItemVisibilityChanged(final ModelItem item) { for (ModelListener listener : listeners) listener.changedItemVisibility(item); } /** Notify listeners of changed item configuration * @param item Item that changed */ void fireItemLookChanged(final ModelItem item) { for (ModelListener listener : listeners) listener.changedItemLook(item); } /** Notify listeners of changed item configuration * @param item Item that changed */ void fireItemDataConfigChanged(final PVItem item) { for (ModelListener listener : listeners) listener.changedItemDataConfig(item); } /** Find a formula that uses a model item as an input. * @param item Item that's potentially used in a formula * @return First Formula found that uses this item, or <code>null</code> if none found */ public FormulaItem getFormulaWithInput(final ModelItem item) { // Update any formulas for (ModelItem i : items) { if (! (i instanceof FormulaItem)) continue; final FormulaItem formula = (FormulaItem) i; if (formula.usesInput(item)) return formula; } return null; } /** Write RGB color to XML document * @param writer * @param level Indentation level * @param tag_name * @param color */ static void writeColor(final PrintWriter writer, final int level, final String tag_name, final RGB color) { XMLWriter.start(writer, level, tag_name); writer.println(); XMLWriter.XML(writer, level+1, Model.TAG_RED, color.red); XMLWriter.XML(writer, level+1, Model.TAG_GREEN, color.green); XMLWriter.XML(writer, level+1, Model.TAG_BLUE, color.blue); XMLWriter.end(writer, level, tag_name); writer.println(); } /** Load RGB color from XML document * @param node Parent node of the color * @param color_tag Name of tag that contains the color * @return RGB or <code>null</code> if no color found */ static RGB loadColorFromDocument(final Element node, final String color_tag) { if (node == null) return new RGB(0, 0, 0); final Element color = DOMHelper.findFirstElementNode(node.getFirstChild(), color_tag); if (color == null) return null; final int red = DOMHelper.getSubelementInt(color, Model.TAG_RED, 0); final int green = DOMHelper.getSubelementInt(color, Model.TAG_GREEN, 0); final int blue = DOMHelper.getSubelementInt(color, Model.TAG_BLUE, 0); return new RGB(red, green, blue); } /** Load RGB color from XML document * @param node Parent node of the color * @return RGB or <code>null</code> if no color found */ static RGB loadColorFromDocument(final Element node) { return loadColorFromDocument(node, Model.TAG_COLOR); } /** Write XML formatted Model content. * @param out OutputStream, will be closed when done. */ public void write(final OutputStream out) { final PrintWriter writer = new PrintWriter(out); XMLWriter.header(writer); XMLWriter.start(writer, 0, TAG_DATABROWSER); writer.println(); //L.PHILIPPE //Save config graph settings XYGraphSettingsXMLUtil XYGraphMemXML = new XYGraphSettingsXMLUtil(graphSettings); XYGraphMemXML.write(writer); // Time axis XMLWriter.XML(writer, 1, TAG_SCROLL, isScrollEnabled()); XMLWriter.XML(writer, 1, TAG_UPDATE_PERIOD, getUpdatePeriod()); if (isScrollEnabled()) { XMLWriter.XML(writer, 1, TAG_START, new RelativeTime(-getTimespan())); XMLWriter.XML(writer, 1, TAG_END, RelativeTime.NOW); } else { XMLWriter.XML(writer, 1, TAG_START, getStartTime()); XMLWriter.XML(writer, 1, TAG_END, getEndTime()); } // Time axis config XMLWriter.start(writer, 1, TAG_TIME_AXIS); writer.println(); timeAxis.write(writer); XMLWriter.end(writer, 1, TAG_TIME_AXIS); writer.println(); // Misc. writeColor(writer, 1, TAG_BACKGROUND, background); XMLWriter.XML(writer, 1, TAG_ARCHIVE_RESCALE, archive_rescale.name()); // Value axes XMLWriter.start(writer, 1, TAG_AXES); writer.println(); for (AxisConfig axis : axes) axis.write(writer); XMLWriter.end(writer, 1, TAG_AXES); writer.println(); // Annotations XMLWriter.start(writer, 1, TAG_ANNOTATIONS); writer.println(); for (AnnotationInfo annotation : annotations) annotation.write(writer); XMLWriter.end(writer, 1, TAG_ANNOTATIONS); writer.println(); // PVs (Formulas) XMLWriter.start(writer, 1, TAG_PVLIST); writer.println(); for (ModelItem item : items) item.write(writer); XMLWriter.end(writer, 1, TAG_PVLIST); writer.println(); XMLWriter.end(writer, 0, TAG_DATABROWSER); writer.close(); } public void setTimeAxis(AxisConfig timeAxis) { this.timeAxis = timeAxis; } /** Read XML formatted Model content. * @param stream InputStream, will be closed when done. * @throws Exception on error * @throws RuntimeException if model was already in use */ public void read(final InputStream stream) throws Exception { final DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); final Document doc = docBuilder.parse(stream); loadFromDocument(doc); } /** Load model * @param doc DOM document * @throws Exception on error * @throws RuntimeException if model was already in use */ private void loadFromDocument(final Document doc) throws Exception { if (is_running || items.size() > 0) throw new RuntimeException("Model was already in use"); // Check if it's a <databrowser/>. doc.getDocumentElement().normalize(); final Element root_node = doc.getDocumentElement(); if (!root_node.getNodeName().equals(TAG_DATABROWSER)) throw new Exception("Wrong document type"); synchronized (this) { scroll_enabled = DOMHelper.getSubelementBoolean(root_node, TAG_SCROLL, scroll_enabled); } update_period = DOMHelper.getSubelementDouble(root_node, TAG_UPDATE_PERIOD, update_period); final String start = DOMHelper.getSubelementString(root_node, TAG_START); final String end = DOMHelper.getSubelementString(root_node, TAG_END); if (start.length() > 0 && end.length() > 0) { final StartEndTimeParser times = new StartEndTimeParser(start, end); setTimerange(TimestampFactory.fromCalendar(times.getStart()), TimestampFactory.fromCalendar(times.getEnd())); } RGB color = loadColorFromDocument(root_node, TAG_BACKGROUND); if (color != null) background = color; try { archive_rescale = ArchiveRescale.valueOf( DOMHelper.getSubelementString(root_node, TAG_ARCHIVE_RESCALE)); } catch (Throwable ex) { archive_rescale = ArchiveRescale.STAGGER; } // Load Time Axis final Element timeAxisNode = DOMHelper.findFirstElementNode(root_node.getFirstChild(), TAG_TIME_AXIS); if (timeAxisNode != null) { // Load PV items Element axisNode = DOMHelper.findFirstElementNode(timeAxisNode.getFirstChild(), TAG_AXIS); timeAxis = AxisConfig.fromDocument(axisNode); } // Load value Axes Element list = DOMHelper.findFirstElementNode(root_node.getFirstChild(), TAG_AXES); if (list != null) { // Load PV items Element item = DOMHelper.findFirstElementNode( list.getFirstChild(), TAG_AXIS); while (item != null) { addAxis(AxisConfig.fromDocument(item)); item = DOMHelper.findNextElementNode(item, TAG_AXIS); } } // Load Annotations list = DOMHelper.findFirstElementNode(root_node.getFirstChild(), TAG_ANNOTATIONS); if (list != null) { // Load PV items Element item = DOMHelper.findFirstElementNode( list.getFirstChild(), TAG_ANNOTATION); final List<AnnotationInfo> infos = new ArrayList<AnnotationInfo>(); try { while (item != null) { final AnnotationInfo annotation = AnnotationInfo.fromDocument(item); infos.add(annotation); item = DOMHelper.findNextElementNode(item, TAG_ANNOTATION); } } catch (Throwable ex) { Activator.getLogger().log(Level.INFO, "XML error in Annotation", ex); } // Add to document annotations = infos.toArray(new AnnotationInfo[infos.size()]); } //ADD by Laurent PHILIPPE // Load Title and graph settings try { graphSettings = XYGraphSettingsXMLUtil.fromDocument(root_node.getFirstChild()); } catch (Throwable ex) { Activator.getLogger().log(Level.INFO, "XML error in Title or graph settings", ex); } // Backwards compatibility with previous data browser which // used global buffer size for all PVs final int buffer_size = DOMHelper.getSubelementInt(root_node, Model.TAG_LIVE_SAMPLE_BUFFER_SIZE, -1); // Load PVs/Formulas list = DOMHelper.findFirstElementNode(root_node.getFirstChild(), TAG_PVLIST); if (list != null) { // Load PV items Element item = DOMHelper.findFirstElementNode( list.getFirstChild(), TAG_PV); while (item != null) { final PVItem model_item = PVItem.fromDocument(this, item); if (buffer_size > 0) model_item.setLiveCapacity(buffer_size); // Adding item creates the axis for it if not already there addItem(model_item); // Backwards compatibility with previous data browser which // stored axis configuration with each item: Update axis from that. final AxisConfig axis = model_item.getAxis(); String s = DOMHelper.getSubelementString(item, TAG_AUTO_SCALE); if (s.equalsIgnoreCase("true")) axis.setAutoScale(true); s = DOMHelper.getSubelementString(item, TAG_LOG_SCALE); if (s.equalsIgnoreCase("true")) axis.setLogScale(true); final double min = DOMHelper.getSubelementDouble(item, Model.TAG_MIN, axis.getMin()); final double max = DOMHelper.getSubelementDouble(item, Model.TAG_MAX, axis.getMax()); axis.setRange(min, max); item = DOMHelper.findNextElementNode(item, TAG_PV); } // Load Formulas item = DOMHelper.findFirstElementNode( list.getFirstChild(), TAG_FORMULA); while (item != null) { addItem(FormulaItem.fromDocument(this, item)); item = DOMHelper.findNextElementNode(item, TAG_FORMULA); } } } }
package edu.cmu.sphinx.frontend; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; /** * A BatchFileAudioSource takes a file (called batch file onwards) * that contains a list of audio files, * and converts the audio data in each of the audio files into * AudioFrame(s). One would obtain the AudioFrames using * the <code>read()</code> method. This class uses the StreamAudioSource * class. In fact, it converts each audio file in the batch file into * an InputStream, and sets it to the InputStream of StreamAudioSource. * Its read() method then calls StreamAudioSource.read(). * The only difference is that BatchFileAudiosource * takes a batch file, whereas StreamAudioSource takes an InputStream. * * The format of the batch file would look like: <pre> * /home/user1/data/music.au * /home/user1/data/talking.au * ... * </pre> * * @see StreamAudioSource */ public class BatchFileAudioSource implements DataSource { private BufferedReader reader; private StreamAudioSource streamAudioSource = null; /** * Constructs a BatchFileAudioSource with the given InputStream. * * @param batchFile contains a list of the audio files * * @throws java.io.IOException if error opening the batch file */ public BatchFileAudioSource(String batchFile) throws IOException { reader = new BufferedReader(new FileReader(batchFile)); streamAudioSource = new StreamAudioSource(null); String firstFile = reader.readLine(); if (firstFile != null) { fileSetStream(firstFile); } } /** * Construct an InputStream with the given audio file, and set it as * the InputStream of the streamAudioSource. * * @param audioFile the file containing audio data * * @throws java.io.IOException if error setting the stream */ private void fileSetStream(String audioFile) throws IOException { streamAudioSource.setInputStream (new FileInputStream(audioFile + ".raw")); streamAudioSource.reset(); } /** * Reads and returns the next AudioFrame. * Returns null if all the data in all the files have been read. * * @return the next AudioFrame or <code>null</code> if no more is * available * * @throws java.io.IOException */ public Data read() throws IOException { if (streamAudioSource == null) { return null; } Data frame = streamAudioSource.read(); if (frame != null) { return frame; } // if we reached the end of the current file, go to the next one String nextFile = reader.readLine(); if (nextFile != null) { fileSetStream(nextFile); return streamAudioSource.read(); } else { reader.close(); } return null; } }
package org.cometd.server.ext; import java.util.Map; import org.cometd.bayeux.Channel; import org.cometd.bayeux.server.ServerMessage; import org.cometd.bayeux.server.ServerSession; import org.cometd.bayeux.server.ServerMessage.Mutable; import org.cometd.bayeux.server.ServerSession.Extension; import org.eclipse.jetty.util.ArrayQueue; import org.eclipse.jetty.util.log.Log; /** * Acknowledged Message Client extension. * * Tracks the batch id of messages sent to a client. * */ public class AcknowledgedMessagesClientExtension implements Extension { private final ServerSession _session; private final ArrayQueue<ServerMessage> _queue; private final ArrayIdQueue<ServerMessage> _unackedQueue; private long _lastAck; public AcknowledgedMessagesClientExtension(ServerSession session) { _session=session; _queue=(ArrayQueue<ServerMessage>)session.getQueue(); _unackedQueue=new ArrayIdQueue<ServerMessage>(16,32,session.getQueue()); _unackedQueue.setCurrentId(1); } public boolean rcv(ServerSession from, Mutable message) { return true; } public boolean rcvMeta(ServerSession session, Mutable message) { if (Channel.META_CONNECT.equals(message.getChannel())) { Map<String,Object> ext=message.getExt(false); if (ext != null) { assert session==_session; synchronized(_queue) { Long acked=(Long)ext.get("ack"); if (acked != null) { if (acked.longValue()<=_lastAck) { Log.debug(session+" lost ACK "+acked.longValue()+"<="+_lastAck); for (ServerMessage m:_unackedQueue) m.incRef(); for (ServerMessage m:_queue) m.decRef(); _queue.clear(); _queue.addAll(_unackedQueue); } else { _lastAck=acked.longValue(); // We have received an ack ID, so delete the acked // messages. final int s=_unackedQueue.size(); if (s > 0) { if (_unackedQueue.getAssociatedIdUnsafe(s - 1) <= acked) { // we can just clear the queue for (int i=0; i < s; i++) { final ServerMessage q=_unackedQueue.getUnsafe(i); q.decRef(); } _unackedQueue.clear(); } else { // we need to remove elements until we see unacked for (int i=0; i < s; i++) { final long a=_unackedQueue.getAssociatedIdUnsafe(0); if (a <= acked) { final ServerMessage q=_unackedQueue.remove(); q.decRef(); continue; } break; } } } } } } } } return true; } public ServerMessage send(ServerSession to, ServerMessage message) { synchronized(_queue) { message.incRef(); _unackedQueue.add(message); } return message; } public boolean sendMeta(ServerSession to, Mutable message) { if (message.getChannel().equals(Channel.META_CONNECT)) { synchronized(_queue) { Map<String,Object> ext=message.getExt(true); ext.put("ack",_unackedQueue.getCurrentId()); _unackedQueue.incrementCurrentId(); } } return true; } }
package org.csstudio.platform.utility.jms; import java.util.Hashtable; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSException; import javax.jms.MapMessage; import javax.jms.Message; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.Topic; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; /** * TODO (Markus Moeller) : * * @author Markus Moeller * @version 1.0 * @since 22.07.2011 */ public class JmsSimpleProducer { private Hashtable<String, String> properties; private Context context; private ConnectionFactory factory; private Connection connection; private Session session; private Topic topic; private MessageProducer producer; private String clientId; private String jmsUrl; private String jmsTopic; public JmsSimpleProducer(String id, String url, String f, String t) { clientId = id; jmsUrl = url; jmsTopic = t; properties = new Hashtable<String, String>(); // Set the properties for the context properties.put(Context.INITIAL_CONTEXT_FACTORY, f); properties.put(Context.PROVIDER_URL, jmsUrl); try { // Create a context context = new InitialContext(properties); // Create a connection factory factory = (ConnectionFactory)context.lookup("ConnectionFactory"); // Create a connection connection = factory.createConnection(); // Set client id connection.setClientID(clientId); // Start the connection connection.start(); // Create a session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); topic = session.createTopic(jmsTopic); // Create a message producer producer = session.createProducer(topic); } catch(NamingException ne) { closeAll(); } catch(JMSException jmse) { closeAll(); } } /** * * @return The fresh MapMessage */ public MapMessage createMapMessage() { MapMessage message = null; if(session != null) { try { message = session.createMapMessage(); } catch(JMSException jmse) { // Can be ignored } } return message; } /** * * @param message * @return True if the message has been sent, otherwise false */ public boolean sendMessage(Message message) { boolean success = false; try { // TODO: producer.send(message, DeliveryMode.PERSISTENT, 1, 0); producer.send(message); } catch (JMSException jmse) { // Can be ignored } return success; } public boolean isConnected() { return (connection != null); } public void closeAll() { if(producer!=null){try{producer.close();}catch(Exception e){/*Can be ignored*/}producer=null;} topic = null; if(connection!=null){try{connection.stop();}catch(Exception e){/*Can be ignored*/}} if(session!=null){try{session.close();}catch(Exception e){/*Can be ignored*/}session=null;} if(connection!=null){try{connection.close();}catch(Exception e){/*Can be ignored*/}connection=null;} factory = null; if(context!=null){try{context.close();}catch(Exception e){/*Can be ignored*/}context=null;} if(properties != null) { properties.clear(); properties = null; } } }
package org.mustbe.consulo.csharp.lang.psi.impl.source.resolve.overrideSystem; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.ListIterator; import org.consulo.lombok.annotations.Logger; import org.jetbrains.annotations.NotNull; import org.mustbe.consulo.csharp.lang.psi.CSharpArrayMethodDeclaration; import org.mustbe.consulo.csharp.lang.psi.CSharpElementCompareUtil; import org.mustbe.consulo.csharp.lang.psi.CSharpMethodDeclaration; import org.mustbe.consulo.csharp.lang.psi.CSharpModifier; import org.mustbe.consulo.csharp.lang.psi.impl.msil.CSharpTransform; import org.mustbe.consulo.csharp.lang.psi.impl.resolve.CSharpElementGroupImpl; import org.mustbe.consulo.csharp.lang.psi.impl.resolve.CSharpResolveContextUtil; import org.mustbe.consulo.csharp.lang.psi.impl.source.resolve.AbstractScopeProcessor; import org.mustbe.consulo.csharp.lang.psi.impl.source.resolve.ExecuteTarget; import org.mustbe.consulo.csharp.lang.psi.impl.source.resolve.ExecuteTargetUtil; import org.mustbe.consulo.csharp.lang.psi.impl.source.resolve.MemberResolveScopeProcessor; import org.mustbe.consulo.csharp.lang.psi.impl.source.resolve.util.CSharpResolveUtil; import org.mustbe.consulo.csharp.lang.psi.resolve.CSharpResolveContext; import org.mustbe.consulo.csharp.lang.psi.resolve.CSharpResolveSelector; import org.mustbe.consulo.csharp.lang.psi.resolve.MemberByNameSelector; import org.mustbe.consulo.csharp.lang.psi.resolve.StaticResolveSelectors; import org.mustbe.consulo.dotnet.psi.DotNetLikeMethodDeclaration; import org.mustbe.consulo.dotnet.psi.DotNetModifier; import org.mustbe.consulo.dotnet.psi.DotNetModifierList; import org.mustbe.consulo.dotnet.psi.DotNetModifierListOwner; import org.mustbe.consulo.dotnet.psi.DotNetType; import org.mustbe.consulo.dotnet.psi.DotNetTypeDeclaration; import org.mustbe.consulo.dotnet.psi.DotNetVariable; import org.mustbe.consulo.dotnet.psi.DotNetVirtualImplementOwner; import org.mustbe.consulo.dotnet.psi.search.searches.ClassInheritorsSearch; import org.mustbe.consulo.dotnet.resolve.DotNetGenericExtractor; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiNamedElement; import com.intellij.psi.ResolveState; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.util.CommonProcessors; import com.intellij.util.Processor; import com.intellij.util.Query; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; /** * @author VISTALL * @since 14.12.14 */ @Logger public class OverrideUtil { public static boolean isRequireOverrideModifier(@NotNull DotNetModifierListOwner modifierListOwner) { DotNetModifierList modifierList = modifierListOwner.getModifierList(); if(modifierList == null) { return false; } return modifierList.hasModifierInTree(CSharpModifier.ABSTRACT) || modifierList.hasModifierInTree(CSharpModifier.VIRTUAL) || modifierList .hasModifierInTree(CSharpModifier.OVERRIDE); } @NotNull public static PsiElement[] filterOverrideElements(@NotNull AbstractScopeProcessor processor, @NotNull PsiElement scopeElement, @NotNull PsiElement[] psiElements, @NotNull OverrideProcessor overrideProcessor) { if(psiElements.length == 0) { return psiElements; } if(!ExecuteTargetUtil.canProcess(processor, ExecuteTarget.ELEMENT_GROUP, ExecuteTarget.EVENT, ExecuteTarget.PROPERTY)) { List<PsiElement> elements = CSharpResolveUtil.mergeGroupsToIterable(psiElements); return ContainerUtil.toArray(elements, PsiElement.ARRAY_FACTORY); } List<PsiElement> elements = CSharpResolveUtil.mergeGroupsToIterable(psiElements); return filterOverrideElements(scopeElement, elements, overrideProcessor); } @NotNull @SuppressWarnings("unchecked") public static PsiElement[] filterOverrideElements(@NotNull PsiElement scopeElement, @NotNull Collection<PsiElement> elements, @NotNull OverrideProcessor overrideProcessor) { List<PsiElement> copyElements = new ArrayList<PsiElement>(elements); for(PsiElement element : elements) { if(!copyElements.contains(element)) { continue; } if(element instanceof DotNetVirtualImplementOwner) { if(element instanceof CSharpMethodDeclaration && ((CSharpMethodDeclaration) element).isDelegate()) { continue; } DotNetVirtualImplementOwner virtualImplementOwner = (DotNetVirtualImplementOwner) element; DotNetType typeForImplement = virtualImplementOwner.getTypeForImplement(); for(PsiElement tempIterateElement : elements) { // skip self if(tempIterateElement == element) { continue; } if(CSharpElementCompareUtil.isEqual(tempIterateElement, element, CSharpElementCompareUtil.CHECK_RETURN_TYPE, scopeElement)) { if(!overrideProcessor.elementOverride(virtualImplementOwner, (DotNetVirtualImplementOwner) tempIterateElement)) { return PsiElement.EMPTY_ARRAY; } copyElements.remove(tempIterateElement); } } // if he have hide impl, remove it if(typeForImplement != null) { copyElements.remove(element); } } } List<PsiElement> groupElements = new SmartList<PsiElement>(); List<PsiElement> elseElements = new SmartList<PsiElement>(); for(PsiElement copyElement : copyElements) { if(copyElement instanceof DotNetLikeMethodDeclaration) { groupElements.add(copyElement); } else { elseElements.add(copyElement); } } if(elseElements.isEmpty() && groupElements.isEmpty()) { return PsiElement.EMPTY_ARRAY; } else if(elseElements.isEmpty()) { return new PsiElement[]{new CSharpElementGroupImpl<PsiElement>(scopeElement.getProject(), getNameForGroup(groupElements), groupElements)}; } else if(groupElements.isEmpty()) { return ContainerUtil.toArray(elseElements, PsiElement.ARRAY_FACTORY); } else { elseElements.add(new CSharpElementGroupImpl<PsiElement>(scopeElement.getProject(), getNameForGroup(groupElements), groupElements)); return ContainerUtil.toArray(elseElements, PsiElement.ARRAY_FACTORY); } } @NotNull private static String getNameForGroup(List<PsiElement> elements) { assert !elements.isEmpty(); PsiElement element = elements.get(0); if(element instanceof DotNetVariable) { return ((DotNetVariable) element).getName(); } else if(element instanceof CSharpArrayMethodDeclaration) { return "this[]"; } else if(element instanceof DotNetLikeMethodDeclaration) { return ((DotNetLikeMethodDeclaration) element).getName(); } else { LOGGER.error(element.getClass() + " is not handled"); return "override"; } } public static boolean isAllowForOverride(PsiElement parent) { if(parent instanceof CSharpMethodDeclaration && !((CSharpMethodDeclaration) parent).isDelegate() && !((CSharpMethodDeclaration) parent).hasModifier(DotNetModifier.STATIC)) { return true; } return parent instanceof DotNetVirtualImplementOwner; } @NotNull public static Collection<DotNetVirtualImplementOwner> collectOverridingMembers(final DotNetVirtualImplementOwner target) { PsiElement parent = target.getParent(); if(parent == null) { return Collections.emptyList(); } OverrideProcessor.Collector overrideProcessor = new OverrideProcessor.Collector(); MemberResolveScopeProcessor processor = new MemberResolveScopeProcessor(parent, new ExecuteTarget[]{ ExecuteTarget.MEMBER, ExecuteTarget.ELEMENT_GROUP }, overrideProcessor); ResolveState state = ResolveState.initial(); if(target instanceof CSharpArrayMethodDeclaration) { state = state.put(CSharpResolveUtil.SELECTOR, StaticResolveSelectors.INDEX_METHOD_GROUP); } else { String name = ((PsiNamedElement) target).getName(); if(name == null) { return Collections.emptyList(); } state = state.put(CSharpResolveUtil.SELECTOR, new MemberByNameSelector(name)); } CSharpResolveUtil.walkChildren(processor, parent, false, true, state); List<DotNetVirtualImplementOwner> results = overrideProcessor.getResults(); // need filter result due it ill return all elements with target selector ListIterator<DotNetVirtualImplementOwner> listIterator = results.listIterator(); while(listIterator.hasNext()) { DotNetVirtualImplementOwner next = listIterator.next(); if(!CSharpElementCompareUtil.isEqual(next, target, CSharpElementCompareUtil.CHECK_RETURN_TYPE, target)) { listIterator.remove(); } } return results; } @NotNull public static Collection<DotNetVirtualImplementOwner> collectOverridenMembers(final DotNetVirtualImplementOwner target) { PsiElement parent = target.getParent(); if(!(parent instanceof DotNetTypeDeclaration)) { return Collections.emptyList(); } final CSharpResolveSelector selector; if(target instanceof CSharpArrayMethodDeclaration) { selector = StaticResolveSelectors.INDEX_METHOD_GROUP; } else { String name = ((PsiNamedElement) target).getName(); if(name != null) { selector = new MemberByNameSelector(name); } else { selector = null; } } if(selector == null) { return Collections.emptyList(); } final GlobalSearchScope resolveScope = target.getResolveScope(); final List<DotNetVirtualImplementOwner> list = new ArrayList<DotNetVirtualImplementOwner>(); Query<DotNetTypeDeclaration> search = ClassInheritorsSearch.search((DotNetTypeDeclaration) parent, true, CSharpTransform.INSTANCE); search.forEach(new Processor<DotNetTypeDeclaration>() { @Override public boolean process(DotNetTypeDeclaration typeDeclaration) { CSharpResolveContext context = CSharpResolveContextUtil.createContext(DotNetGenericExtractor.EMPTY, resolveScope, typeDeclaration); PsiElement[] elements = selector.doSelectElement(context, false); for(PsiElement element : CSharpResolveUtil.mergeGroupsToIterable(elements)) { if(CSharpElementCompareUtil.isEqual(element, target, CSharpElementCompareUtil.CHECK_RETURN_TYPE, target)) { list.add((DotNetVirtualImplementOwner) element); } } return true; } }); return list; } @NotNull public static Collection<DotNetModifierListOwner> collectMembersWithModifier(@NotNull PsiElement element, @NotNull DotNetGenericExtractor extractor, @NotNull CSharpModifier modifier) { List<DotNetModifierListOwner> psiElements = new SmartList<DotNetModifierListOwner>(); for(PsiElement psiElement : getAllMembers(element, element.getResolveScope(), extractor)) { if(psiElement instanceof DotNetModifierListOwner && ((DotNetModifierListOwner) psiElement).hasModifier(modifier)) { psiElements.add((DotNetModifierListOwner) psiElement); } } return psiElements; } @NotNull public static Collection<PsiElement> getAllMembers(@NotNull PsiElement element, @NotNull GlobalSearchScope scope, @NotNull DotNetGenericExtractor extractor) { CommonProcessors.CollectProcessor<PsiElement> collectProcessor = new CommonProcessors.CollectProcessor<PsiElement>(); CSharpResolveContextUtil.createContext(extractor, scope, element).processElements(collectProcessor, true); Collection<PsiElement> results = collectProcessor.getResults(); List<PsiElement> mergedElements = CSharpResolveUtil.mergeGroupsToIterable(results); PsiElement[] psiElements = OverrideUtil.filterOverrideElements(element, mergedElements, OverrideProcessor.ALWAYS_TRUE); return CSharpResolveUtil.mergeGroupsToIterable(psiElements); } }
package org.eclipse.birt.data.engine.olap.data.impl.aggregation; import org.eclipse.birt.data.engine.olap.data.impl.dimension.Member; import org.eclipse.birt.data.engine.olap.data.util.IStructure; import org.eclipse.birt.data.engine.olap.data.util.IStructureCreator; import org.eclipse.birt.data.engine.olap.data.util.ObjectArrayUtil; public class Row4Aggregation implements IStructure { private Member[] levelMembers; private Object[] measures; private Object[] parameterValues; /* * (non-Javadoc) * @see org.eclipse.birt.data.olap.data.util.IStructure#getFieldValues() */ public Object[] getFieldValues( ) { Object[][] objectArrays = new Object[getLevelMembers().length+2][]; for ( int i = 0; i < getLevelMembers().length; i++ ) { objectArrays[i] = getLevelMembers()[i].getFieldValues( ); } objectArrays[objectArrays.length-2] = measures; objectArrays[objectArrays.length-1] = parameterValues; return ObjectArrayUtil.convert( objectArrays ); } public static IStructureCreator getCreator() { return new Row4AggregationCreator( ); } void setLevelMembers( Member[] levelMembers ) { this.levelMembers = levelMembers; } Member[] getLevelMembers( ) { return levelMembers; } void setMeasures( Object[] measures ) { this.measures = measures; } Object[] getMeasures( ) { return measures; } Object[] getParameterValues( ) { return parameterValues; } void setParameterValues( Object[] parameterValues ) { this.parameterValues = parameterValues; } } /** * * @author Administrator * */ class Row4AggregationCreator implements IStructureCreator { private static IStructureCreator levelMemberCreator = Member.getCreator( ); /* * (non-Javadoc) * @see org.eclipse.birt.data.olap.data.util.IStructureCreator#createInstance(java.lang.Object[]) */ public IStructure createInstance( Object[] fields ) { Object[][] objectArrays = ObjectArrayUtil.convert( fields ); Row4Aggregation result = new Row4Aggregation( ); result.setLevelMembers( new Member[objectArrays.length - 2] ); for ( int i = 0; i < result.getLevelMembers().length; i++ ) { result.getLevelMembers()[i] = (Member) levelMemberCreator.createInstance( objectArrays[i] ); } result.setMeasures( objectArrays[objectArrays.length-2] ); result.setParameterValues( objectArrays[objectArrays.length-1] ); return result; } }
package io.debezium.connector.oracle.logminer.parser; import java.util.ArrayList; import java.util.Collections; import java.util.List; import io.debezium.DebeziumException; import io.debezium.connector.oracle.logminer.RowMapper; import io.debezium.connector.oracle.logminer.valueholder.LogMinerColumnValue; import io.debezium.connector.oracle.logminer.valueholder.LogMinerColumnValueImpl; import io.debezium.connector.oracle.logminer.valueholder.LogMinerDmlEntry; import io.debezium.connector.oracle.logminer.valueholder.LogMinerDmlEntryImpl; import io.debezium.relational.Column; import io.debezium.relational.Table; /** * A simple DML parser implementation specifically for Oracle LogMiner. * * The syntax of each DML operation is restricted to the format generated by Oracle LogMiner. The * following are examples of each expected syntax: * * <pre> * insert into "schema"."table"("C1","C2") values ('v1','v2'); * update "schema"."table" set "C1" = 'v1a', "C2" = 'v2a' where "C1" = 'v1' and "C2" = 'v2'; * delete from "schema"."table" where "C1" = 'v1' AND "C2" = 'v2'; * </pre> * * Certain data types are not emitted as string literals, such as {@code DATE} and {@code TIMESTAMP}. * For these data types, they're emitted as function calls. The parser can detect this use case and * will emit the values for such columns as the explicit function call. * * Lets take the following {@code UPDATE} statement: * * <pre> * update "schema"."table" * set "C1" = TO_TIMESTAMP('2020-02-02 00:00:00', 'YYYY-MM-DD HH24:MI:SS') * where "C1" = TO_TIMESTAMP('2020-02-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS'); * </pre> * * The new value for {@code C1} would be {@code TO_TIMESTAMP('2020-02-02 00:00:00', 'YYYY-MM-DD HH24:MI:SS')}. * The old value for {@code C1} would be {@code TO_TIMESTAMP('2020-02-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS')}. * * It is important to note that the parser produces a {@link LogMinerDmlEntry} instance that holds * two collections of {@link LogMinerColumnValue}, each representing either the before or after * state from the parsed DML statement. * * Not all DML statements contain all columns and so the collections of {@link LogMinerColumnValue} * will only contain a subset of the table's column values. In addition, the order of the elements * in these collections are based on the order in which the column name/value was parsed in the DML * and is not indicative of the column index order in the relational table. * * As an example, lets take a table with CLOB data type: * * <pre> * create table "schema"."table" ("ID" numeric(9,0), "DATA" clob, "CREATED" date, primary key(id)); * </pre> * * When data is first inserted the rows are materialized in the LogMiner view as follows: * * <pre> * insert into "schema"."table" ("ID","DATA","CREATED") values ('1',EMPTY_CLOB(),TO_DATE(...)); * update "schema"."table" set "DATA"=lob_c WHERE "ID"='1' AND "CREATED"=TO_DATE(...); * </pre> * * The multiple rows are irrelevant, just know that these two DML statements are parsed separately * but will be merged to represent a single logical {@code INSERT} event. * * Taking the same row, a user may then decide to update the same row only modifying the CLOB data, * which would be materialized in the LogMiner view as follows: * * <pre> * update "schema"."table" set "DATA"=lob_c WHERE "ID"='1' AND "CREATED"=TO_DATE('...'); * </pre> * * In the above scenario, the old values will only contain the "ID" and "CREATED" columns in said * order while the new values will contain "DATA", "ID", and "CREATED" in said order. This order * does not reflect the column index order of the table which is "ID", "DATA", and "CREATED". * * The BaseChangeRecordEmitter class is responsible in a later step to reorder the values read * from the {@link LogMinerColumnValue} collections so that the value array is in the correct * column index order of the relational table so that the right values correspond to the correct * fields in the emitted event. * * @author Chris Cranford */ public class LogMinerDmlParser implements DmlParser { private static final String NULL = "NULL"; private static final String INSERT_INTO = "insert into "; private static final String UPDATE = "update "; private static final String DELETE_FROM = "delete from "; private static final String AND = "and "; private static final String OR = "or "; private static final String SET = " set "; private static final String WHERE = " where "; private static final String VALUES = " values "; private static final String IS_NULL = "IS NULL"; // Use by Oracle for specific data types that cannot be represented in SQL private static final String UNSUPPORTED = "Unsupported"; private static final String UNSUPPORTED_TYPE = "Unsupported Type"; private static final int INSERT_INTO_LENGTH = INSERT_INTO.length(); private static final int UPDATE_LENGTH = UPDATE.length(); private static final int DELETE_FROM_LENGTH = DELETE_FROM.length(); private static final int VALUES_LENGTH = VALUES.length(); private static final int SET_LENGTH = SET.length(); private static final int WHERE_LENGTH = WHERE.length(); @Override public LogMinerDmlEntry parse(String sql, Table table, String txId) { if (table == null) { throw new DmlParserException("DML parser requires a non-null table"); } if (sql != null && sql.length() > 0) { switch (sql.charAt(0)) { case 'i': return parseInsert(sql, table); case 'u': return parseUpdate(sql, table); case 'd': return parseDelete(sql, table); } } throw new DmlParserException("Unknown supported SQL '" + sql + "'"); } /** * Parse an {@code INSERT} SQL statement. * * @param sql the sql statement * @param table the table * @return the parsed DML entry record or {@code null} if the SQL was not parsed */ private LogMinerDmlEntry parseInsert(String sql, Table table) { try { // advance beyond "insert into " int index = INSERT_INTO_LENGTH; // parse table index = parseTableName(sql, index); // capture column names List<LogMinerColumnValue> newValues = new ArrayList<>(table.columns().size()); index = parseColumnListClause(sql, index, newValues); // capture values parseColumnValuesClause(sql, index, newValues); return new LogMinerDmlEntryImpl(RowMapper.INSERT, newValues, Collections.emptyList()); } catch (Exception e) { throw new DmlParserException("Failed to parse insert DML: '" + sql + "'", e); } } /** * Parse an {@code UPDATE} SQL statement. * * @param sql the sql statement * @param table the table * @return the parsed DML entry record or {@code null} if the SQL was not parsed */ private LogMinerDmlEntry parseUpdate(String sql, Table table) { try { // advance beyond "update " int index = UPDATE_LENGTH; // parse table index = parseTableName(sql, index); // parse set List<LogMinerColumnValue> newValues = new ArrayList<>(table.columns().size()); index = parseSetClause(sql, index, newValues); // parse where List<LogMinerColumnValue> oldValues = new ArrayList<>(table.columns().size()); parseWhereClause(sql, index, oldValues); // set after if (!newValues.isEmpty()) { for (int i = 0; i < table.columns().size(); ++i) { final Column column = table.columns().get(i); if (getColumnValueByName(newValues, column.name()) == null) { // No new column value with column name, needs to be added with current value if exists LogMinerColumnValue oldValue = getColumnValueByName(oldValues, column.name()); if (oldValue != null) { LogMinerColumnValue newValue = new LogMinerColumnValueImpl(column.name()); newValue.setColumnData(oldValue.getColumnData()); newValues.add(newValue); } } } } return new LogMinerDmlEntryImpl(RowMapper.UPDATE, newValues, oldValues); } catch (Exception e) { throw new DmlParserException("Failed to parse update DML: '" + sql + "'", e); } } /** * Parses a SQL {@code DELETE} statement. * * @param sql the sql statement * @param table the table * @return the parsed DML entry record or {@code null} if the SQL was not parsed */ private LogMinerDmlEntry parseDelete(String sql, Table table) { try { // advance beyond "delete from " int index = DELETE_FROM_LENGTH; // parse table index = parseTableName(sql, index); // parse where List<LogMinerColumnValue> oldValues = new ArrayList<>(table.columns().size()); parseWhereClause(sql, index, oldValues); return new LogMinerDmlEntryImpl(RowMapper.DELETE, Collections.emptyList(), oldValues); } catch (Exception e) { throw new DmlParserException("Failed to parse delete DML: '" + sql + "'", e); } } /** * Parses a table-name in the SQL clause * * @param sql the sql statement * @param index the index into the sql statement to begin parsing * @return the index into the sql string where the table name ended */ private int parseTableName(String sql, int index) { boolean inQuote = false; for (; index < sql.length(); ++index) { char c = sql.charAt(index); if (c == '"') { if (inQuote) { inQuote = false; continue; } inQuote = true; } else if ((c == ' ' || c == '(') && !inQuote) { break; } } return index; } /** * Parse an {@code INSERT} statement's column-list clause. * * @param sql the sql statement * @param start the index into the sql statement to begin parsing * @param columns the list that will be populated with the column names * @return the index into the sql string where the column-list clause ended */ private int parseColumnListClause(String sql, int start, List<LogMinerColumnValue> columns) { int index = start; boolean inQuote = false; for (; index < sql.length(); ++index) { char c = sql.charAt(index); if (c == '(' && !inQuote) { start = index + 1; } else if (c == ')' && !inQuote) { index++; break; } else if (c == '"') { if (inQuote) { inQuote = false; columns.add(new LogMinerColumnValueImpl(sql.substring(start + 1, index))); start = index + 2; continue; } inQuote = true; } } return index; } /** * Parse an {@code INSERT} statement's column-values clause. * * @param sql the sql statement * @param start the index into the sql statement to begin parsing * @param columns the list of that will populated with the column values * @return the index into the sql string where the column-values clause ended */ private int parseColumnValuesClause(String sql, int start, List<LogMinerColumnValue> columns) { int index = start; int nested = 0; boolean inQuote = false; boolean inValues = false; // verify entering values-clause if (sql.indexOf(VALUES, index) != index) { throw new DebeziumException("Failed to parse DML: " + sql); } index += VALUES_LENGTH; int columnIndex = 0; for (; index < sql.length(); ++index) { char c = sql.charAt(index); if (c == '(' && !inQuote && !inValues) { inValues = true; start = index + 1; } else if (c == '(' && !inQuote) { nested++; } else if (c == '\'') { if (inQuote) { inQuote = false; continue; } inQuote = true; } else if (!inQuote && (c == ',' || c == ')')) { if (c == ')' && nested != 0) { nested continue; } if (c == ',' && nested != 0) { continue; } if (sql.charAt(start) == '\'' && sql.charAt(index - 1) == '\'') { // value is single-quoted at the start/end, substring without the quotes. columns.get(columnIndex).setColumnData(sql.substring(start + 1, index - 1)); } else { // use value as-is String s = sql.substring(start, index); if (!s.equals(UNSUPPORTED_TYPE) && !s.equals(NULL)) { columns.get(columnIndex).setColumnData(s); } } columnIndex++; start = index + 1; } } return index; } /** * Parse an {@code UPDATE} statement's {@code SET} clause. * * @param sql the sql statement * @param start the index into the sql statement to begin parsing * @param columns the list of the changed columns that will be populated * @return the index into the sql string where the set-clause ended */ private int parseSetClause(String sql, int start, List<LogMinerColumnValue> columns) { boolean inDoubleQuote = false; boolean inSingleQuote = false; boolean inColumnName = true; boolean inColumnValue = false; boolean inSpecial = false; int nested = 0; // verify entering set-clause if (sql.indexOf(SET, start) != start) { throw new DebeziumException("Failed to parse DML: " + sql); } start += SET_LENGTH; int index = start; int columnIndex = 0; for (; index < sql.length(); ++index) { char c = sql.charAt(index); char lookAhead = (index + 1 < sql.length()) ? sql.charAt(index + 1) : 0; if (c == '"' && inColumnName) { // Set clause column names are double-quoted if (inDoubleQuote) { inDoubleQuote = false; columns.add(new LogMinerColumnValueImpl(sql.substring(start + 1, index))); start = index + 1; inColumnName = false; continue; } inDoubleQuote = true; start = index; } else if (c == '=' && !inColumnName && !inColumnValue) { inColumnValue = true; // Oracle SQL generated is always ' = ', skipping following space index += 1; start = index + 1; } else if (c == '\'' && inColumnValue) { // Skip over double single quote if (inSingleQuote && lookAhead == '\'') { index += 1; continue; } // Set clause single-quoted column value if (inSingleQuote) { inSingleQuote = false; if (nested == 0) { columns.get(columnIndex++).setColumnData(sql.substring(start + 1, index)); start = index + 1; inColumnValue = false; inColumnName = false; } continue; } if (!inSpecial) { start = index; } inSingleQuote = true; } else if (c == ',' && !inColumnValue && !inColumnName) { // Set clause uses ', ' skip following space inColumnName = true; index += 1; start = index; } else if (inColumnValue && !inSingleQuote) { if (!inSpecial) { start = index; inSpecial = true; } // characters as a part of the value if (c == '(') { nested++; } else if (c == ')' && nested > 0) { nested } else if ((c == ',' || c == ' ' || c == ';') && nested == 0) { String value = sql.substring(start, index); if (value.equals(NULL) || value.equals(UNSUPPORTED_TYPE)) { columnIndex++; start = index + 1; inColumnValue = false; inSpecial = false; inColumnName = true; continue; } else if (value.equals(UNSUPPORTED)) { continue; } columns.get(columnIndex++).setColumnData(value); start = index + 1; inColumnValue = false; inSpecial = false; inColumnName = true; } } else if (!inDoubleQuote && !inSingleQuote) { if (c == 'w' && lookAhead == 'h' && sql.indexOf(WHERE, index - 1) == index - 1) { index -= 1; break; } } } return index; } /** * Parses a {@code WHERE} clause populates the provided column names and values arrays. * * @param sql the sql statement * @param start the index into the sql statement to begin parsing * @param columns the columns parsed from the clause * @return the index into the sql string to continue parsing */ private int parseWhereClause(String sql, int start, List<LogMinerColumnValue> columns) { int nested = 0; boolean inColumnName = true; boolean inColumnValue = false; boolean inDoubleQuote = false; boolean inSingleQuote = false; boolean inSpecial = false; // DBZ-3235 // LogMiner can generate SQL without a WHERE condition under some circumstances and if it does // we shouldn't immediately fail DML parsing. if (start >= sql.length()) { return start; } // verify entering where-clause if (sql.indexOf(WHERE, start) != start) { throw new DebeziumException("Failed to parse DML: " + sql); } start += WHERE_LENGTH; int index = start; int columnIndex = 0; for (; index < sql.length(); ++index) { char c = sql.charAt(index); char lookAhead = (index + 1 < sql.length()) ? sql.charAt(index + 1) : 0; if (c == '"' && inColumnName) { // Where clause column names are double-quoted if (inDoubleQuote) { inDoubleQuote = false; columns.add(new LogMinerColumnValueImpl(sql.substring(start + 1, index))); start = index + 1; inColumnName = false; continue; } inDoubleQuote = true; start = index; } else if (c == '=' && !inColumnName && !inColumnValue) { inColumnValue = true; // Oracle SQL generated is always ' = ', skipping following space index += 1; start = index + 1; } else if (c == 'I' && !inColumnName && !inColumnValue) { if (sql.indexOf(IS_NULL, index) == index) { columnIndex++; index += 6; start = index; continue; } } else if (c == '\'' && inColumnValue) { // Skip over double single quote if (inSingleQuote && lookAhead == '\'') { index += 1; continue; } // Where clause single-quoted column value if (inSingleQuote) { inSingleQuote = false; if (nested == 0) { columns.get(columnIndex++).setColumnData(sql.substring(start + 1, index)); start = index + 1; inColumnValue = false; inColumnName = false; } continue; } if (!inSpecial) { start = index; } inSingleQuote = true; } else if (inColumnValue && !inSingleQuote) { if (!inSpecial) { start = index; inSpecial = true; } if (c == '(') { nested++; } else if (c == ')' && nested > 0) { nested } else if ((c == ';' || c == ' ') && nested == 0) { String value = sql.substring(start, index); if (value.equals(NULL) || value.equals(UNSUPPORTED_TYPE)) { columnIndex++; start = index + 1; inColumnValue = false; inSpecial = false; inColumnName = true; continue; } else if (value.equals(UNSUPPORTED)) { continue; } columns.get(columnIndex++).setColumnData(value); start = index + 1; inColumnValue = false; inSpecial = false; inColumnName = true; } } else if (!inColumnValue && !inColumnName) { if (c == 'a' && lookAhead == 'n' && sql.indexOf(AND, index) == index) { index += 3; start = index; inColumnName = true; } else if (c == 'o' && lookAhead == 'r' && sql.indexOf(OR, index) == index) { index += 2; start = index; inColumnName = true; } } } return index; } /** * Search the provided array for a column value with the given name, returning {@code null} if not found. * * @param values column values array, should not be {@code null} * @param columnName column name to find * @return column value instance or {@code null} if not found. */ private LogMinerColumnValue getColumnValueByName(List<LogMinerColumnValue> values, String columnName) { for (LogMinerColumnValue value : values) { if (value.getColumnName().equals(columnName)) { return value; } } return null; } }
package com.xpn.xwiki.it.selenium; import junit.framework.Test; import com.xpn.xwiki.it.selenium.framework.AbstractXWikiTestCase; import com.xpn.xwiki.it.selenium.framework.AlbatrossSkinExecutor; import com.xpn.xwiki.it.selenium.framework.XWikiTestSuite; /** * Verify the Users, Groups and Rights Management features of XWiki. * * @version $Id$ */ public class UsersGroupsRightsManagementTest extends AbstractXWikiTestCase { public static Test suite() { XWikiTestSuite suite = new XWikiTestSuite("Verify the Users, Groups and Rights Management features of XWiki"); suite.addTestSuite(UsersGroupsRightsManagementTest.class, AlbatrossSkinExecutor.class); return suite; } @Override protected void setUp() throws Exception { super.setUp(); loginAsAdmin(); } /** * <ul> * <li>Validate group creation.</li> * <li>Validate groups administration print "0" members for empty group.</li> * <li>Validate group deletion.</li> * <li>Validate rights automatically cleaned from deleted groups.</li> * </ul> */ public void testCreateAndDeleteGroup() { // Make sure there's no XWikiNewGroup before we try to create it deleteGroup("XWikiNewGroup", true); createGroup("XWikiNewGroup"); // Validate XWIKI-1903: Empty group shows 1 member. assertEquals("Group XWikiNewGroup which is empty print more than 0 members", 0, getGroupMembersCount("XWikiNewGroup")); // Give "view" global right to XWikiNewGroup on wiki openGlobalRightsPage(); clickGroupsRadioButton(); clickViewRightsCheckbox("XWikiNewGroup", "allow"); // Give "comment" page right to XWikiNewGroup on Test.TestCreateAndDeleteGroup page createPage("Test", "TestCreateAndDeleteGroup", "whatever"); clickLinkWithText("Page access rights"); clickGroupsRadioButton(); clickCommentRightsCheckbox("XWikiNewGroup", "allow"); // Delete the newly created group and see if rights are cleaned deleteGroup("XWikiNewGroup", false); // Validate XWIKI-2304: When a user or a group is removed it's not removed from rights objects open("XWiki", "XWikiPreferences", "edit", "editor=object"); assertTextNotPresent("XWikiNewGroup"); open("Test", "TestCreateAndDeleteGroup", "edit", "editor=object"); assertTextNotPresent("XWikiNewGroup"); } /** * Validate that administration show error when trying to create an existing group. */ public void testCreateGroupWhenGroupAlreadyExists() { open("XWiki", "testCreateGroupWhenGroupAlreadyExists", "edit", "editor=wiki"); setFieldValue("content", "some content"); clickEditSaveAndView(); openGroupsPage(); clickLinkWithText("Add new group", false); waitForLightbox("Create new group"); setFieldValue("newgroupi", "testCreateGroupWhenGroupAlreadyExists"); getSelenium().click("//input[@value='Create group']"); // We need to wait till the alert appears since when the user clicks on the "Create Group" button there's // an Ajax call made to the server. waitForCondition("try {selenium.getAlert() == 'testCreateGroupWhenGroupAlreadyExists cannot be used for the " + "group name, as another document with this name already exists.'} catch(err) { false;}"); } /** * <ul> * <li>Validate user creation.</li> * <li>Validate user deletion.</li> * <li>Validate groups automatically cleaned from deleted users.</li> * </ul> */ public void testCreateAndDeleteUser() { // Make sure there's no XWikiNewUser user before we try to create it deleteUser("XWikiNewUser", true); createUser("XWikiNewUser", "XWikiNewUser"); // Verify that new users are automatically added to the XWikiAllGroup group. open("XWiki", "XWikiAllGroup"); assertTextPresent("XWiki.XWikiNewUser"); // Delete the newly created user and see if groups are cleaned deleteUser("XWikiNewUser", false); // Verify that when a user is removed he's removed from the groups he belongs to. open("XWiki", "XWikiAllGroup"); assertTextNotPresent("XWiki.XWikiNewUser"); } /** * Test that the Ajax registration tool accepts non-ASCII symbols. */ public void testCreateNonAsciiUser() { // Make sure there's no AccentUser user before we try to create it deleteUser("AccentUser", true); // Use ISO-8859-1 symbols to make sure that the test works both in ISO-8859-1 and UTF8 createUser("AccentUser", "AccentUser", "a\u00e9b", "c\u00e0d"); // Verify that the user is present in the table assertTextPresent("AccentUser"); // Verify that the correct symbols appear assertTextPresent("a\u00e9b"); assertTextPresent("c\u00e0d"); } /** * Validate group rights. Validate XWIKI-2375: Group and user access rights problem with a name which includes space * characters */ public void testGroupRights() { String username = "TestUser"; // Voluntarily put a space in the group name. String groupname = "Test Group"; // Make sure there's no "TestUser" user and no "Test Group" user before we try to create it deleteUser(username, true); deleteGroup(groupname, true); // Create a new user, a new group, make the user part of that group and create a new page createUser(username, username); createGroup(groupname); addUserToGroup(username, groupname); createPage("Test", "TestGroupRights", "Some content"); // Deny view rights to the group on the newly created page open("Test", "TestGroupRights", "edit", "editor=rights"); clickGroupsRadioButton(); // Click a first time to allow view and a second time to deny it. clickViewRightsCheckbox(groupname, "allow"); clickViewRightsCheckbox(groupname, "deny1"); // Make sure that Admins can still view the page open("Test", "TestGroupRights"); assertTextPresent("Some content"); // And ensure that the newly created user cannot view it login(username, username, false); open("Test", "TestGroupRights"); assertTextPresent("not allowed"); // Cleanup loginAsAdmin(); deleteUser(username, false); deleteGroup(groupname, false); } /** * Test adding a group to a group. Specifically, assert that the group is added as a member itself, not adding all * its members one by one. */ public void testAddGroupToGroup() { String group = "GroupWithGroup"; createGroup(group); openGroupsPage(); String xpath = "//tbody/tr[td/a='" + group + "']/td[3]/img[@title='Edit']"; System.out.println("XPATH: " + xpath); waitForCondition("selenium.isElementPresent(\"" + xpath + "\")"); getSelenium().click("//tbody/tr[td/a=\"" + group + "\"]/td[3]/img[@title=\"Edit\"]"); waitForLightbox("Add new user"); setFieldValue("groupSuggest", "XWiki.XWikiAllGroup"); clickLinkWithLocator("addNewGroup", false); String xpathPrefix = "//div[@id='lb-content']/div/table/tbody/tr/td/table/tbody/tr"; String adminGroupXPath = xpathPrefix + "/td[contains(@class, 'member')]/a[@href='/xwiki/bin/view/XWiki/XWikiAllGroup']"; // this xpath expression is fragile, but we have to start as up as the lightbox does, because // the same table with same ids and classes is already displayed in the Preferences page // (that is, the list of existing groups). waitForCondition("selenium.isElementPresent(\"" + adminGroupXPath + "\")"); // Now assert that XWiki.Admin, member of XWikiAdminGroup is not added as a member of our created group assertElementNotPresent(xpathPrefix + "/td[contains(@class, 'member')]/a[@href='/xwiki/bin/view/XWiki/Admin']"); clickLinkWithLocator("lb-close"); // Now same test, but from the group document UI in inline mode clickLinkWithText(group); this.clickLinkWithText("Inline form"); setFieldValue("groupSuggest", "XWiki.XWikiAdminGroup"); clickLinkWithLocator("addNewGroup", false); waitForCondition("selenium.isTextPresent('XWiki.XWikiAdminGroup')"); // cleanup deleteGroup(group, false); } /** * Validate adding a member to a group via the administration. */ public void testAddUserToGroup() { // Make sure there's no XWikiNewUser user before we try to create it deleteUser("XWikiTestUser", true); createUser("XWikiTestUser", "XWikiTestUser"); addUserToGroup("XWikiTestUser", "XWikiAdminGroup"); deleteUser("XWikiTestUser", true); } /** * Validate member filtering on group sheet. */ public void testFilteringOnGroupSheet() { openGroupsPage(); String rowXPath = "//td[contains(@class, 'member')]/a[@href='/xwiki/bin/view/XWiki/Admin']"; this.clickLinkWithText("XWikiAdminGroup"); this.waitForCondition("selenium.isElementPresent(\"" + rowXPath + "\")"); this.getSelenium().typeKeys("member", "Ad"); this.waitForCondition("selenium.isElementPresent(\"" + rowXPath + "\")"); this.getSelenium().typeKeys("member", "zzz"); this.waitForCondition("!selenium.isElementPresent(\"" + rowXPath + "\")"); } // Helper methods private void createGroup(String groupname) { openGroupsPage(); clickLinkWithText("Add new group", false); waitForLightbox("Create new group"); setFieldValue("newgroupi", groupname); clickLinkWithXPath("//input[@value='Create group']", true); waitForCondition("selenium.isTextPresent('" + groupname + "')"); } /** * @param deleteOnlyIfExists if true then only delete the group if it exists */ private void deleteGroup(String groupname, boolean deleteOnlyIfExists) { if (!deleteOnlyIfExists || (deleteOnlyIfExists && isExistingPage("XWiki", groupname))) { openGroupsPage(); getSelenium().chooseOkOnNextConfirmation(); clickLinkWithLocator("//tbody/tr[td/a='" + groupname + "']//img[@title='Delete']", false); waitForCondition("selenium.isConfirmationPresent()"); assertEquals("The group XWiki." + groupname + " will be deleted. Are you sure you want to proceed?", getSelenium().getConfirmation()); // Wait till the group has been deleted. waitForCondition("!selenium.isElementPresent('//tbody/tr[td/a=\"" + groupname + "\"]')"); } } private void createUser(String login, String pwd) { createUser(login, pwd, "New", "User"); } private void createUser(String login, String pwd, String fname, String lname) { openUsersPage(); clickLinkWithText("Add new user", false); waitForLightbox("Registration"); setFieldValue("register_first_name", fname); setFieldValue("register_last_name", lname); setFieldValue("xwikiname", login); setFieldValue("register_password", pwd); setFieldValue("register2_password", pwd); setFieldValue("register_email", "new.user@xwiki.org"); getSelenium().click("//input[@value='Save']"); // Wait till the user is displayed waitPage(); waitForCondition("selenium.isTextPresent('" + login + "')"); } private void deleteUser(String login, boolean deleteOnlyIfExists) { if (!deleteOnlyIfExists || (deleteOnlyIfExists && isExistingPage("XWiki", login))) { openUsersPage(); getSelenium().chooseOkOnNextConfirmation(); clickLinkWithLocator("//tbody/tr[td/a='" + login + "']//img[@title='Delete']", false); waitForCondition("selenium.isConfirmationPresent()"); assertEquals("The user XWiki." + login + " will be deleted and removed from all groups he belongs to. " + "Are you sure you want to proceed?", getSelenium().getConfirmation()); // Wait till the user has been deleted. waitForCondition("!selenium.isElementPresent('//tbody/tr[td/a=\"" + login + "\"]')"); } } private void addUserToGroup(String user, String group) { openGroupsPage(); String xpath = "//tbody/tr[td/a='" + group + "']/td[3]/img[@title='Edit']"; waitForCondition("selenium.isElementPresent(\"" + xpath + "\")"); getSelenium().click(xpath); waitForLightbox("Add user to group"); setFieldValue("userSuggest", "XWiki." + user); clickLinkWithLocator("addNewUser", false); String xpathPrefix = "//div[@id='lb-content']/div/table/tbody/tr/td/table/tbody/tr"; String newGroupMemberXPath = xpathPrefix + "/td[contains(@class, 'member')]/a[@href='/xwiki/bin/view/XWiki/" + user + "']"; // this xpath expression is fragile, but we have to start as up as the lightbox does, because // the same table with same ids and classes is already displayed in the Preferences page // (that is, the list of existing groups). waitForCondition("selenium.isElementPresent(\"" + newGroupMemberXPath + "\")"); // Close the group edit lightbox clickLinkWithLocator("lb-close"); open("XWiki", group); assertTextPresent(user); } private void waitForLightbox(String lightboxName) { waitForCondition("selenium.page().bodyText().indexOf('" + lightboxName + "') != -1;"); } private void clickGroupsRadioButton() { clickLinkWithXPath("//input[@name='uorg' and @value='groups']", false); } private void openGlobalRightsPage() { openAdministrationPage(); clickLinkWithText("Rights"); } private void openGroupsPage() { openAdministrationPage(); clickLinkWithText("Groups"); // Since the Groups page has a table loaded using Ajax calls we need to ensure it's filled before going // further. We do that by verifying that the AdminGroup and the AllGroup are loaded. waitForCondition("selenium.isTextPresent('XWikiAdminGroup')"); waitForCondition("selenium.isTextPresent('XWikiAllGroup')"); } private void openUsersPage() { // Note: We could have used the following command instead: // open("XWiki", "XWikiUsers", "admin", "editor=users") // However we haven't done it since we also want to verify that clicking on the "Users" tab works. openAdministrationPage(); clickLinkWithText("Users"); } /** * @return the number of members in the passed group. Should only be executed when on the Global Rights page. */ private int getGroupMembersCount(String groupname) { return Integer.parseInt(getSelenium().getText("//tbody/tr[td/a=\"" + groupname + "\"]/td[2]")); } /** * @param actionToVerify the action that the click is supposed to have done. Valid values are "allow", "deny1" or * "none". */ private void clickViewRightsCheckbox(String groupOrUserName, String actionToVerify) { clickRightsCheckbox(groupOrUserName, actionToVerify, 2); } /** * @param actionToVerify the action that the click is supposed to have done. Valid values are "allow", "deny1" or * "none". */ private void clickCommentRightsCheckbox(String groupOrUserName, String actionToVerify) { clickRightsCheckbox(groupOrUserName, actionToVerify, 3); } private void clickRightsCheckbox(String groupOrUserName, String actionToVerify, int positionInTd) { String xpath = "//tbody/tr[td/a='" + groupOrUserName + "']/td[" + positionInTd + "]/img"; clickLinkWithXPath(xpath, false); // Wait till it has been clicked since this can take some time. waitForCondition("selenium.isElementPresent(\"" + xpath + "[contains(@src, '" + actionToVerify + ".png')]\")"); } }
package com.xpn.xwiki.it.selenium.framework; import junit.framework.Assert; /** * Implementation of skin-related actions for the Albatross skin. * * @version $Id: $ */ public class AlbatrossSkinExecutor implements SkinExecutor { private static final String WYSIWYG_LOCATOR_FOR_KEY_EVENTS = "mceSpanFonts"; private static final String WIKI_LOCATOR_FOR_KEY_EVENTS = "content"; private AbstractXWikiTestCase test; public AlbatrossSkinExecutor(AbstractXWikiTestCase test) { this.test = test; } private AbstractXWikiTestCase getTest() { return this.test; } public void clickDeletePage() { getTest().clickLinkWithLocator("//a[string() = 'Delete']"); } public void clickEditPreview() { getTest().submit("formactionpreview"); } public void clickEditSaveAndContinue() { getTest().submit("formactionsac"); } public void clickEditCancelEdition() { getTest().submit("formactioncancel"); } public void clickEditSaveAndView() { getTest().submit("formactionsave"); } public boolean isAuthenticated() { return !(getTest().isElementPresent("headerlogin")); } public void logout() { Assert.assertTrue("User wasn't authenticated.", isAuthenticated()); getTest().clickLinkWithLocator("headerlogout"); Assert.assertFalse("The user is still authenticated after a logout.", isAuthenticated()); } public void login(String username, String password, boolean rememberme) { getTest().open("/xwiki/bin/view/Main/"); if (isAuthenticated()) { logout(); } clickLogin(); getTest().setFieldValue("j_username", username); getTest().setFieldValue("j_password", password); if (rememberme) { getTest().checkField("rememberme"); } getTest().submit(); Assert.assertTrue("User has not been authenticated", isAuthenticated()); } public void loginAsAdmin() { login("Admin", "admin", false); } public void clickLogin() { getTest().clickLinkWithLocator("headerlogin"); assertIsLoginPage(); } private void assertIsLoginPage() { getTest().assertElementPresent("loginForm"); getTest().assertElementPresent("j_username"); getTest().assertElementPresent("j_password"); getTest().assertElementPresent("rememberme"); } public void clickRegister() { getTest().clickLinkWithLocator("headerregister"); assertIsRegisterPage(); } private void assertIsRegisterPage() { // tests that the register form exists getTest().assertElementPresent("register"); getTest().assertElementPresent("register_first_name"); getTest().assertElementPresent("register_last_name"); getTest().assertElementPresent("xwikiname"); getTest().assertElementPresent("register_password"); getTest().assertElementPresent("register2_password"); getTest().assertElementPresent("register_email"); } // For WYSIWYG editor public void editInWysiwyg(String space, String page) { getTest().open("/xwiki/bin/edit/" + space + "/" + page + "?editor=wysiwyg"); } public void clearWysiwygContent() { getTest().getSelenium().waitForCondition( "selenium.browserbot.getCurrentWindow().tinyMCE.setContent(\"\"); true", "18000"); } public void typeInWysiwyg(String text) { getTest().getSelenium().typeKeys(WYSIWYG_LOCATOR_FOR_KEY_EVENTS, text); } public void typeInWiki(String text) { getTest().getSelenium().type(WIKI_LOCATOR_FOR_KEY_EVENTS, text); } public void typeEnterInWysiwyg() { getTest().getSelenium().keyPress(WYSIWYG_LOCATOR_FOR_KEY_EVENTS, "\\13"); } public void typeShiftEnterInWysiwyg() { getTest().getSelenium().shiftKeyDown(); getTest().getSelenium().keyPress(WYSIWYG_LOCATOR_FOR_KEY_EVENTS, "\\13"); } public void clickWysiwygUnorderedListButton() { getTest().clickLinkWithLocator("//img[@title='Unordered list']", false); } public void clickWysiwygOrderedListButton() { getTest().clickLinkWithLocator("//img[@title='Ordered list']", false); } public void clickWysiwygIndentButton() { getTest().clickLinkWithLocator("//img[@title='Indent']", false); } public void clickWysiwygOutdentButton() { getTest().clickLinkWithLocator("//img[@title='Outdent']", false); } public void clickWikiBoldButton() { getTest().clickLinkWithXPath("//img[@title='Bold']", false); } public void clickWikiItalicsButton() { getTest().clickLinkWithXPath("//img[@title='Italics']", false); } public void clickWikiUnderlineButton() { getTest().clickLinkWithXPath("//img[@title='Underline']", false); } public void clickWikiLinkButton() { getTest().clickLinkWithXPath("//img[@title='Internal Link']", false); } public void clickWikiHRButton() { getTest().clickLinkWithXPath("//img[@title='Horizontal ruler']", false); } public void clickWikiImageButton() { getTest().clickLinkWithXPath("//img[@title='Attached Image']", false); } public void clickWikiSignatureButton() { getTest().clickLinkWithXPath("//img[@title='sig']", false); } public void assertWikiTextGeneratedByWysiwyg(String text) { getTest().clickLinkWithText("Wiki"); Assert.assertEquals(text, getTest().getSelenium().getValue("content")); } public void assertHTMLGeneratedByWysiwyg(String xpath) throws Exception { getTest().getSelenium().selectFrame("mce_editor_0"); Assert.assertTrue( getTest().getSelenium().isElementPresent("xpath=/html/body/" + xpath)); getTest().getSelenium().selectFrame("relative=top"); } public void assertGeneratedHTML(String xpath) throws Exception { Assert.assertTrue( getTest().getSelenium().isElementPresent("xpath=//div[@id='xwikicontent']/" + xpath)); } }
package org.eclipse.birt.report.engine.api.impl; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.birt.core.archive.IDocArchiveReader; import org.eclipse.birt.core.archive.RAInputStream; import org.eclipse.birt.core.script.ParameterAttribute; import org.eclipse.birt.core.util.IOUtil; import org.eclipse.birt.report.engine.api.EngineException; import org.eclipse.birt.report.engine.api.IBookmarkInfo; import org.eclipse.birt.report.engine.api.IReportDocumentHelper; import org.eclipse.birt.report.engine.api.IReportRunnable; import org.eclipse.birt.report.engine.api.ITOCTree; import org.eclipse.birt.report.engine.api.InstanceID; import org.eclipse.birt.report.engine.api.TOCNode; import org.eclipse.birt.report.engine.api.impl.LinkedObjectManager.LinkedEntry; import org.eclipse.birt.report.engine.content.IContent; import org.eclipse.birt.report.engine.content.impl.BookmarkContent; import org.eclipse.birt.report.engine.content.impl.ReportContent; import org.eclipse.birt.report.engine.executor.ApplicationClassLoader; import org.eclipse.birt.report.engine.extension.engine.IReportDocumentExtension; import org.eclipse.birt.report.engine.extension.engine.IReportEngineExtension; import org.eclipse.birt.report.engine.i18n.MessageConstants; import org.eclipse.birt.report.engine.internal.document.DocumentExtension; import org.eclipse.birt.report.engine.internal.document.IPageHintReader; import org.eclipse.birt.report.engine.internal.document.PageHintReader; import org.eclipse.birt.report.engine.internal.document.v3.ReportContentReaderV3; import org.eclipse.birt.report.engine.internal.document.v4.InstanceIDComparator; import org.eclipse.birt.report.engine.internal.executor.doc.Fragment; import org.eclipse.birt.report.engine.internal.index.DocumentIndexReader; import org.eclipse.birt.report.engine.internal.index.IDocumentIndexReader; import org.eclipse.birt.report.engine.ir.EngineIRReader; import org.eclipse.birt.report.engine.ir.Report; import org.eclipse.birt.report.engine.presentation.IPageHint; import org.eclipse.birt.report.engine.presentation.PageSection; import org.eclipse.birt.report.engine.toc.ITOCReader; import org.eclipse.birt.report.engine.toc.ITreeNode; import org.eclipse.birt.report.engine.toc.TOCReader; import org.eclipse.birt.report.engine.toc.TOCView; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.ModuleOption; import org.eclipse.birt.report.model.api.ModuleUtil; import org.eclipse.birt.report.model.api.ReportDesignHandle; import org.eclipse.birt.report.model.api.ReportElementHandle; import org.eclipse.birt.report.model.api.ReportItemHandle; import com.ibm.icu.util.TimeZone; import com.ibm.icu.util.ULocale; /** * core stream format TAG DOCUMENT VERSION * * TAG CORE_VERSION_0 DOCUMENT_VERSION TAG * * CORE_VERSION_1 DOCUMENT_VERSION MAP */ public class ReportDocumentReader implements IReportletDocument, ReportDocumentConstants, IReportDocumentHelper { static private Logger logger = Logger.getLogger( ReportDocumentReader.class .getName( ) ); private ReportEngine engine; private IDocArchiveReader archive; private Map moduleOptions; /* * version, parameters, globalVariables are loaded from core stream. */ private String coreVersion; private Map properties = new HashMap( ); private HashMap parameters; private HashMap globalVariables; /** * used to load the page hints */ private IPageHintReader pageHintReader; private ITOCReader tocReader; private IDocumentIndexReader indexReader; /** Design name */ private String systemId; private int checkpoint = CHECKPOINT_INIT; private long pageCount; private boolean sharedArchive; private ApplicationClassLoader applicationClassLoader; private ReportRunnable preparedRunnable = null; private ReportRunnable reportRunnable = null; private boolean coreStreamLoaded = false; private LinkedEntry<ReportDocumentReader> engineCacheEntry; public ReportDocumentReader( ReportEngine engine, IDocArchiveReader archive, boolean sharedArchive ) throws EngineException { this( null, engine, archive, sharedArchive ); } public ReportDocumentReader( ReportEngine engine, IDocArchiveReader archive ) throws EngineException { this( null, engine, archive, false ); } public ReportDocumentReader( String systemId, ReportEngine engine, IDocArchiveReader archive, Map options ) throws EngineException { this( systemId, engine, archive, false, options ); } public ReportDocumentReader( String systemId, ReportEngine engine, IDocArchiveReader archive, boolean sharedArchive ) throws EngineException { this( systemId, engine, archive, sharedArchive, null ); } public ReportDocumentReader( String systemId, ReportEngine engine, IDocArchiveReader archive, boolean sharedArchive, Map options ) throws EngineException { this.engine = engine; this.archive = archive; this.systemId = systemId; this.sharedArchive = sharedArchive; this.moduleOptions = new HashMap( ); this.moduleOptions.put( ModuleOption.PARSER_SEMANTIC_CHECK_KEY, Boolean.FALSE ); if ( options != null ) { this.moduleOptions.putAll( options ); } loadCoreStreamHeader( ); } public IDocArchiveReader getArchive( ) { return this.archive; } public String getVersion( ) { return (String) properties.get( BIRT_ENGINE_VERSION_KEY ); } public String getProperty( String key ) { return (String) properties.get( key ); } protected class ReportDocumentCoreInfo { int checkpoint; long pageCount; String systemId; HashMap globalVariables; HashMap parameters; ITOCReader tocReader; IDocumentIndexReader indexReader; } private void loadCoreStreamHeader( ) throws EngineException { try { Object lock = archive.lock( CORE_STREAM ); try { synchronized ( lock ) { RAInputStream in = archive.getStream( CORE_STREAM ); try { DataInputStream di = new DataInputStream( in ); // check the document version and core stream version checkVersion( di ); // load the stream header, check point, system id and // page count loadCoreStreamHeader( di ); } finally { in.close( ); } } } finally { archive.unlock( lock ); } } catch ( IOException ee ) { close( ); throw new EngineException( MessageConstants.REPORT_DOCUMENT_OPEN_ERROR, ee ); } } private void loadCoreStreamHeader( DataInputStream di ) throws IOException { // load info into a document info object ReportDocumentCoreInfo documentInfo = new ReportDocumentCoreInfo( ); loadCoreStreamHeader( di, documentInfo ); if ( checkpoint != documentInfo.checkpoint ) { checkpoint = documentInfo.checkpoint; pageCount = documentInfo.pageCount; if ( systemId == null ) { systemId = documentInfo.systemId; } } } private void loadCoreStreamHeader( DataInputStream di, ReportDocumentCoreInfo documentInfo ) throws IOException { if ( CORE_VERSION_UNKNOWN.equals( coreVersion ) ) { loadCoreStreamHeaderUnknown( di, documentInfo ); } else if ( CORE_VERSION_0.equals( coreVersion ) || CORE_VERSION_1.equals( coreVersion ) || CORE_VERSION_2.equals( coreVersion ) ) { loadCoreStreamHeaderV0( di, documentInfo ); } else { throw new IOException( "unsupported core stream version: " + coreVersion ); } } /** * read the core stream header which has version UNKNOWN and V0. * * The core stream header contains 3 field: <li>check point</li> <li>page * count</li> <li>system id</li> * * @param coreStream * the core stream. The version has been loaded from the stream. * @param documentInfo * the loaded information is saved into this object. * @throws IOException */ private void loadCoreStreamHeaderUnknown( DataInputStream coreStream, ReportDocumentCoreInfo documentInfo ) throws IOException { documentInfo.checkpoint = CHECKPOINT_INIT; documentInfo.pageCount = PAGECOUNT_INIT; if ( !archive.exists( CHECKPOINT_STREAM ) ) { // no check point stream, old version, return -1 documentInfo.checkpoint = CHECKPOINT_END; initializePageHintReader( ); if ( pageHintReader != null ) { documentInfo.pageCount = pageHintReader.getTotalPage( ); } } else { RAInputStream in = archive.getStream( CHECKPOINT_STREAM ); try { DataInputStream di = new DataInputStream( in ); documentInfo.checkpoint = IOUtil.readInt( di ); documentInfo.pageCount = IOUtil.readLong( di ); } finally { if ( in != null ) { in.close( ); } } } // load the report design name documentInfo.systemId = IOUtil.readString( coreStream ); } /** * load the core stream header for stream with version V1 and V2 * * the core stream header contains 3 field: * * <li>check point</li> <li>page count</li> <li>system id</li> * * @param di * core stream, the version has been loaded from this stream. * @param documentInfo * the header is saved into this object. * @throws IOException */ private void loadCoreStreamHeaderV0( DataInputStream di, ReportDocumentCoreInfo documentInfo ) throws IOException { documentInfo.checkpoint = CHECKPOINT_INIT; documentInfo.pageCount = PAGECOUNT_INIT; documentInfo.checkpoint = IOUtil.readInt( di ); documentInfo.pageCount = IOUtil.readLong( di ); // load the report design name documentInfo.systemId = IOUtil.readString( di ); } private void loadCoreStreamLazily( ) { if ( !coreStreamLoaded ) { synchronized ( this ) { if ( !coreStreamLoaded ) { try { loadCoreStream( ); } catch ( IOException ee ) { logger.log( Level.SEVERE, "Failed to load core stream", ee ); //$NON-NLS-1$ } } } } } synchronized public void refresh( ) { try { loadCoreStream( ); } catch ( IOException ee ) { logger.log( Level.SEVERE, "Failed to refresh", ee ); //$NON-NLS-1$ } } protected void loadCoreStream( ) throws IOException { Object lock = archive.lock( CORE_STREAM ); try { synchronized ( lock ) { RAInputStream in = archive.getStream( CORE_STREAM ); try { DataInputStream di = new DataInputStream( in ); // check the document version and core stream version checkVersion( di ); loadCoreStream( di ); coreStreamLoaded = true; } finally { in.close( ); } } } finally { archive.unlock( lock ); } } private void loadCoreStream( DataInputStream di ) throws IOException { // load info into a document info object ReportDocumentCoreInfo documentInfo = new ReportDocumentCoreInfo( ); loadCoreStreamHeader( di, documentInfo ); loadCoreStreamBody( di, documentInfo ); // save the document info into the object. checkpoint = documentInfo.checkpoint; pageCount = documentInfo.pageCount; globalVariables = documentInfo.globalVariables; parameters = documentInfo.parameters; if ( checkpoint == CHECKPOINT_END ) { if ( indexReader == null ) { indexReader = documentInfo.indexReader; } else { if ( documentInfo.indexReader != null ) { documentInfo.indexReader.close( ); } } if ( tocReader == null ) { tocReader = documentInfo.tocReader; } else { if ( documentInfo.tocReader != null ) { documentInfo.tocReader.close( ); } } } } private void loadCoreStreamBody( DataInputStream di, ReportDocumentCoreInfo documentInfo ) throws IOException { if ( CORE_VERSION_UNKNOWN.equals( coreVersion ) ) { loadCoreStreamBodyUnknown( di, documentInfo ); } else if ( CORE_VERSION_0.equals( coreVersion ) || CORE_VERSION_1.equals( coreVersion ) ) { loadCoreStreamBodyV0( di, documentInfo ); } else if ( CORE_VERSION_2.equals( coreVersion ) ) { loadCoreStreamBodyV2( di, documentInfo ); } else { throw new IOException( "unsupported core stream version: " + coreVersion ); } } protected void loadCoreStreamBodyUnknown( DataInputStream coreStream, ReportDocumentCoreInfo documentInfo ) throws IOException { // load the report parameters ClassLoader loader = getClassLoader( ); Map originalParameters = IOUtil.readMap( coreStream, loader ); documentInfo.parameters = convertToCompatibleParameter( originalParameters ); // load the persistence object documentInfo.globalVariables = (HashMap) IOUtil.readMap( coreStream, loader ); if ( documentInfo.checkpoint == CHECKPOINT_END ) { documentInfo.indexReader = new DocumentIndexReader( IDocumentIndexReader.VERSION_0, archive ); } } protected void loadCoreStreamBodyV0( DataInputStream coreStream, ReportDocumentCoreInfo documentInfo ) throws IOException { ClassLoader loader = getClassLoader( ); Map originalParameters = IOUtil.readMap( coreStream, loader ); documentInfo.parameters = convertToCompatibleParameter( originalParameters ); // load the persistence object documentInfo.globalVariables = (HashMap) IOUtil.readMap( coreStream, loader ); if ( documentInfo.checkpoint == CHECKPOINT_END ) { HashMap<String, Long> bookmarks = readMap( coreStream ); documentInfo.tocReader = new TOCReader( coreStream, getClassLoader( ) ); HashMap<String, Long> reportletsIndexById = readMap( coreStream ); HashMap<String, Long> reportletsIndexByBookmark = readMap( coreStream ); documentInfo.indexReader = new DocumentIndexReader( IDocumentIndexReader.VERSION_1, reportletsIndexByBookmark, reportletsIndexById, bookmarks ); } } protected void loadCoreStreamBodyV2( DataInputStream coreStream, ReportDocumentCoreInfo documentInfo ) throws IOException { ClassLoader loader = getClassLoader( ); Map originalParameters = IOUtil.readMap( coreStream, loader ); documentInfo.parameters = convertToCompatibleParameter( originalParameters ); // load the persistence object documentInfo.globalVariables = (HashMap) IOUtil.readMap( coreStream, loader ); if ( documentInfo.checkpoint == CHECKPOINT_END ) { documentInfo.indexReader = new DocumentIndexReader( IDocumentIndexReader.VERSION_2, archive ); } } private HashMap<String, Long> readMap( DataInputStream di ) throws IOException { HashMap<String, Long> map = new HashMap<String, Long>( ); long count = IOUtil.readLong( di ); for ( long i = 0; i < count; i++ ) { String bookmark = IOUtil.readString( di ); long pageNumber = IOUtil.readLong( di ); map.put( bookmark, new Long( pageNumber ) ); } return map; } private HashMap convertToCompatibleParameter( Map parameters ) { if ( parameters == null ) { return null; } HashMap result = new HashMap( ); Iterator iterator = parameters.entrySet( ).iterator( ); while ( iterator.hasNext( ) ) { Map.Entry entry = (Map.Entry) iterator.next( ); Object key = entry.getKey( ); Object valueObj = entry.getValue( ); ParameterAttribute paramAttr = null; if ( valueObj instanceof ParameterAttribute ) { paramAttr = (ParameterAttribute) valueObj; } else if ( valueObj instanceof Object[] ) { Object[] values = (Object[]) valueObj; if ( values.length == 2 ) { Object value = values[0]; String displayText = (String) values[1]; paramAttr = new ParameterAttribute( value, displayText ); } } if ( paramAttr == null ) { paramAttr = new ParameterAttribute( valueObj, null ); } result.put( key, paramAttr ); } return result; } /** * <pre> * TAG CORE_V DOC_V ENG_V HIGHLIGHT VERSION * 2.0.0 x NULL 1.0.0 NULL FALSE 2.0.0 * 2.0.1 x NULL 1.0.0 NULL FALSE 2.0.0 * 2.0.2 x NULL 1.0.0 NULL FALSE 2.0.0 * 2.1.0 x NULL 2.1.0 NULL TRUE 2.1.0 * 2.1.1 x NULL 2.1.0 NULL TRUE 2.1.0 * 2.1.2 x NULL 2.1.0 NULL TRUE 2.1.0 * 2.1.3 x v0 2.1.3 NULL TRUE 2.1.3 * 2.2.0 x v0 2.1.3 NULL TRUE 2.1.3 * 2.2.1 x v1 2.1.3 2.2.1 FALSE 2.2.1 * 2.2.2 x v1 2.1.3 2.2.1 FALSE 2.2.1 * 2.3.0 x v1 2.1.3 2.2.1 FALSE 2.2.1 * 2.3.1 x v1 2.1.3 2.2.1 FALSE 2.2.1 * 2.3.2 x v1 2.1.3 2.3.2 FALSE 2.3.2 * 2.5.0 x v1 2.1.3 2.5.0 FALSE 2.5.0 * </pre> */ protected void checkVersion( DataInputStream di ) throws IOException { String tag = IOUtil.readString( di ); if ( !REPORT_DOCUMENT_TAG.equals( tag ) ) { throw new IOException( "unknown report document tag" + tag );//$NON-NLS-1$ } String docVersion = IOUtil.readString( di ); if ( docVersion == null ) { throw new IOException( "invalid core stream format" );//$NON-NLS-1$ } if ( !docVersion.startsWith( CORE_VERSION_PREFIX ) ) { // there is no core version, so set the core version to unknown. coreVersion = CORE_VERSION_UNKNOWN; } else if ( CORE_VERSION_0.equals( docVersion ) || CORE_VERSION_1.equals( docVersion ) || CORE_VERSION_2.equals( docVersion ) ) { coreVersion = docVersion; docVersion = IOUtil.readString( di ); if ( CORE_VERSION_1.equals( coreVersion ) || CORE_VERSION_2.equals( coreVersion ) ) { properties = IOUtil.readMap( di ); } } else { throw new IOException( "unknown core stream version" + tag );//$NON-NLS-1$ } String[] supportedVersions = new String[]{ REPORT_DOCUMENT_VERSION_1_0_0, REPORT_DOCUMENT_VERSION_2_1_0, REPORT_DOCUMENT_VERSION_2_1_3}; boolean supportedVersion = false; for ( int i = 0; i < supportedVersions.length; i++ ) { if ( supportedVersions[i].equals( docVersion ) ) { supportedVersion = true; break; } } if ( supportedVersion == false ) { throw new IOException( "unsupport report document version " + docVersion ); //$NON-NLS-1$ } // test if request extension are present String extensions = (String) properties.get( BIRT_ENGINE_EXTENSIONS ); if ( extensions != null && extensions.length( ) > 0 ) { String[] extIds = extensions.split( "," ); for ( String extId : extIds ) { IReportEngineExtension ext = engine.getEngineExtension( extId ); if ( ext == null ) { throw new IOException( "unsupported report extension:" + extId ); } } } if ( properties.get( BIRT_ENGINE_VERSION_KEY ) == null ) { if ( REPORT_DOCUMENT_VERSION_1_0_0.equals( docVersion ) ) { properties.put( BIRT_ENGINE_VERSION_KEY, BIRT_ENGINE_VERSION_2_0_0 ); } else if ( REPORT_DOCUMENT_VERSION_2_1_0.equals( docVersion ) ) { properties.put( BIRT_ENGINE_VERSION_KEY, BIRT_ENGINE_VERSION_2_1_0 ); } else if ( REPORT_DOCUMENT_VERSION_2_1_3.equals( docVersion ) ) { properties.put( BIRT_ENGINE_VERSION_KEY, BIRT_ENGINE_VERSION_2_1_3 ); } } String version = getVersion( ); // FIXME: test if the version is later than BIRT_ENGINE_VERSION if ( properties.get( DATA_EXTRACTION_TASK_VERSION_KEY ) == null ) { // check the data extraction task version if ( BIRT_ENGINE_VERSION_2_0_0.equals( docVersion ) || BIRT_ENGINE_VERSION_2_1_0.equals( version ) ) { properties.put( DATA_EXTRACTION_TASK_VERSION_KEY, DATA_EXTRACTION_TASK_VERSION_0 ); } else { properties.put( DATA_EXTRACTION_TASK_VERSION_KEY, DATA_EXTRACTION_TASK_VERSION_1 ); } } // assign the page-hint version if ( properties.get( PAGE_HINT_VERSION_KEY ) == null ) { properties.put( PAGE_HINT_VERSION_KEY, PAGE_HINT_VERSION_2 ); } } public void close( ) { if ( tocReader != null ) { try { tocReader.close( ); } catch ( IOException ex ) { logger.log( Level.SEVERE, "Failed to close the tocReader", ex ); //$NON-NLS-1$ } tocReader = null; } if ( indexReader != null ) { try { indexReader.close( ); } catch ( IOException ex ) { logger.log( Level.WARNING, "failed to close the index reader", ex ); } indexReader = null; } if ( pageHintReader != null ) { pageHintReader.close( ); pageHintReader = null; } if ( archive != null ) { if ( !sharedArchive ) { try { archive.close( ); } catch ( IOException ex ) { logger .log( Level.SEVERE, "Failed to close the archive", ex ); //$NON-NLS-1$ } } archive = null; } if ( extensions != null ) { for ( Map.Entry<String, IReportDocumentExtension> entry : extensions .entrySet( ) ) { String name = entry.getKey( ); IReportDocumentExtension extension = entry.getValue( ); if ( extension != null ) { try { extension.close( ); } catch ( EngineException ex ) { logger.log( Level.SEVERE, "Failed to close the extension " + name, ex ); } } } extensions.clear( ); extensions = null; } if ( applicationClassLoader != null ) { applicationClassLoader.close( ); } if ( engineCacheEntry != null ) { LinkedObjectManager<ReportDocumentReader> manager = engineCacheEntry .getManager( ); synchronized(manager) { manager.remove( engineCacheEntry ); } } } public InputStream getOriginalDesignStream( ) { try { return archive.getStream( ORIGINAL_DESIGN_STREAM ); } catch ( Exception ex ) { logger.log( Level.SEVERE, "Failed to open the design!", ex ); //$NON-NLS-1$ return null; } } public InputStream getDesignStream( boolean isOriginal ) { try { if ( isOriginal && archive.exists( ORIGINAL_DESIGN_STREAM ) ) { return archive.getStream( ORIGINAL_DESIGN_STREAM ); } return archive.getStream( DESIGN_STREAM ); } catch ( Exception ex ) { logger.log( Level.SEVERE, "Failed to open the design!", ex ); //$NON-NLS-1$ return null; } } private ReportRunnable getReportRunnable( boolean isOriginal, String systemId ) { if ( !isOriginal && preparedRunnable != null ) { return preparedRunnable; } ReportRunnable reportRunnable = null; String name = null; if ( systemId == null ) { name = archive.getName( ); } else { name = systemId; } InputStream stream = getDesignStream( isOriginal ); if ( stream != null ) { try { reportRunnable = (ReportRunnable) engine.openReportDesign( name, stream, moduleOptions ); reportRunnable.setPrepared( !isOriginal ); stream.close( ); } catch ( Exception ex ) { logger.log( Level.SEVERE, "Failed to get the report runnable", //$NON-NLS-1$ ex ); } finally { try { if ( stream != null ) { stream.close( ); } } catch ( IOException ex ) { } } } if ( !isOriginal && preparedRunnable == null ) { preparedRunnable = reportRunnable; } return reportRunnable; } public synchronized IReportRunnable getReportRunnable( ) { if ( reportRunnable == null ) { reportRunnable = getReportRunnable( true, systemId ); } return reportRunnable.cloneRunnable( ); } public synchronized IReportRunnable getPreparedRunnable( ) { if ( preparedRunnable == null ) { preparedRunnable = getReportRunnable( false, systemId ); } return preparedRunnable.cloneRunnable( ); } public Map getParameterValues( ) { loadCoreStreamLazily( ); Map result = new HashMap( ); if ( parameters != null ) { Iterator iterator = parameters.entrySet( ).iterator( ); while ( iterator.hasNext( ) ) { Map.Entry entry = (Map.Entry) iterator.next( ); String name = (String) entry.getKey( ); ParameterAttribute value = (ParameterAttribute) entry .getValue( ); result.put( name, value.getValue( ) ); } } return result; } public Map getParameterDisplayTexts( ) { loadCoreStreamLazily( ); Map result = new HashMap( ); if ( parameters != null ) { Iterator iterator = parameters.entrySet( ).iterator( ); while ( iterator.hasNext( ) ) { Map.Entry entry = (Map.Entry) iterator.next( ); String name = (String) entry.getKey( ); ParameterAttribute value = (ParameterAttribute) entry .getValue( ); result.put( name, value.getDisplayText( ) ); } } return result; } public long getPageCount( ) { return pageCount; } public IPageHint getPageHint( long pageNumber ) { initializePageHintReader( ); if ( pageHintReader != null ) { try { return pageHintReader.getPageHint( pageNumber ); } catch ( IOException ex ) { logger.log( Level.WARNING, "Failed to load page hint " + pageNumber, ex ); } } return null; } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.engine.api.IReportDocument#getPageNumber(java * .lang.String) */ public long getPageNumber( String bookmark ) { if ( !isComplete( ) ) { return -1; } loadCoreStreamLazily( ); if ( indexReader != null ) { try { return indexReader.getPageOfBookmark( bookmark ); } catch ( IOException ex ) { logger.log( Level.WARNING, "failed to load the page number of bookmark:" + bookmark, ex ); } } return -1; } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.api.IReportDocument#getBookmarks() */ public List<String> getBookmarks( ) { if ( !isComplete( ) ) { return null; } loadCoreStreamLazily( ); if ( indexReader != null ) { try { return indexReader.getBookmarks( ); } catch ( IOException ex ) { logger.log( Level.WARNING, "failed to load the bookmark list", ex ); } } return null; } public List<BookmarkContent> getBookmarkContents( ) { if ( !isComplete( ) ) { return null; } loadCoreStreamLazily( ); if ( indexReader != null ) { try { return indexReader.getBookmarkContents( ); } catch ( IOException ex ) { logger.log( Level.WARNING, "failed to load the bookmark info list", ex ); } } return null; } public List<IBookmarkInfo> getBookmarkInfos( Locale locale ) throws EngineException { ArrayList<IBookmarkInfo> results = new ArrayList<IBookmarkInfo>( ); loadCoreStreamLazily( ); if ( indexReader != null ) { try { List<BookmarkContent> bookmarks = indexReader .getBookmarkContents( ); if ( bookmarks == null ) { return null; } ReportDesignHandle report = this.getReportDesign( ); for ( BookmarkContent bookmark : bookmarks ) { long designId = bookmark.getElementId( ); DesignElementHandle handle = report .getElementByID( designId ); if ( handle == null ) continue; String elementType = handle.getName( ); String displayName = null; if ( handle instanceof ReportItemHandle ) { displayName = ( (ReportItemHandle) handle ) .getBookmarkDisplayName( ); } if ( locale != null ) { if ( handle instanceof ReportElementHandle ) { ReportElementHandle elementHandle = (ReportElementHandle) handle; displayName = ModuleUtil.getExternalizedValue( elementHandle, bookmark.getBookmark( ), displayName, ULocale.forLocale( locale ) ); } } results.add( new BookmarkInfo( bookmark.getBookmark( ), displayName, elementType ) ); } } catch ( IOException ex ) { throw new EngineException( "exception when fetching bookmarks", ex ); } } return results; } /** * @param bookmark * the bookmark that a page number is to be retrieved upon * @return the page number that the bookmark appears */ public long getBookmark( String bookmark ) { if ( !isComplete( ) ) { return -1; } loadCoreStreamLazily( ); if ( indexReader != null ) { try { return indexReader.getOffsetOfBookmark( bookmark ); } catch ( IOException ex ) { logger .log( Level.WARNING, "failed to load the offset of bookmark:" + bookmark, ex ); } } return -1; } public ITOCTree getTOCTree( String format, ULocale locale ) { return getTOCTree( format, locale, TimeZone.getDefault( ) ); } public ITOCTree getTOCTree( String format, ULocale locale, TimeZone timeZone ) { try { ITreeNode root = getTOCTree( ); if ( root != null ) { ReportDesignHandle report = ( (ReportRunnable) getOnPreparedRunnable( ) ) .getReport( ); return new TOCView( root, report, locale, timeZone, format ); } } catch ( EngineException ex ) { logger.log( Level.WARNING, ex.getMessage( ), ex ); } return null; } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.engine.api.IReportDocument#findTOC(java.lang. * String) */ public TOCNode findTOC( String tocNodeId ) { ITOCTree tree = getTOCTree( "viewer", ULocale.getDefault( ) ); if ( tree != null ) { return tree.findTOC( tocNodeId ); } return null; } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.engine.api.IReportDocument#findTOCByName(java * .lang.String) */ public List findTOCByName( String tocName ) { ITOCTree tree = getTOCTree( "viewer", ULocale.getDefault( ) ); if ( tree != null ) { return tree.findTOCByValue( tocName ); } return null; } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.engine.api.IReportDocument#getChildren(java.lang * .String) */ public List getChildren( String tocNodeId ) { TOCNode node = findTOC( tocNodeId ); if ( node != null ) { return node.getChildren( ); } return null; } private void initializePageHintReader( ) { if ( pageHintReader != null ) { return; } synchronized ( this ) { if ( pageHintReader != null ) { return; } try { pageHintReader = new PageHintReader( this ); } catch ( IOException ex ) { logger .log( Level.SEVERE, "can't open the page hint stream", ex ); } } } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.api.IReportDocument#getName() */ public String getName( ) { return archive.getName( ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.engine.api.IReportDocument#getGlobalVariables() */ public Map getGlobalVariables( String option ) { loadCoreStreamLazily( ); return globalVariables; } public long getPageNumber( InstanceID iid ) { if ( !isComplete( ) ) { return -1; } initializePageHintReader( ); if ( pageHintReader == null ) { return -1; } int version = pageHintReader.getVersion( ); try { if ( version == IPageHintReader.VERSION_0 ) { long offset = getInstanceOffset( iid ); if ( offset == -1 ) { return -1; } long totalPage = pageHintReader.getTotalPage( ); for ( long pageNumber = 1; pageNumber <= totalPage; pageNumber++ ) { IPageHint hint = pageHintReader.getPageHint( pageNumber ); PageSection section = hint.getSection( 0 ); if ( offset >= section.startOffset ) { return pageNumber; } } } else if ( version == IPageHintReader.VERSION_1 ) { long offset = getInstanceOffset( iid ); if ( offset == -1 ) { return -1; } long totalPage = pageHintReader.getTotalPage( ); for ( long pageNumber = 1; pageNumber <= totalPage; pageNumber++ ) { IPageHint hint = pageHintReader.getPageHint( pageNumber ); int sectionCount = hint.getSectionCount( ); for ( int i = 0; i < sectionCount; i++ ) { PageSection section = hint.getSection( i ); if ( section.startOffset <= offset && offset <= section.endOffset ) { return pageNumber; } } } } else if ( version == IPageHintReader.VERSION_2 || version == IPageHintReader.VERSION_3 || version == IPageHintReader.VERSION_4 || version == IPageHintReader.VERSION_5 || version == IPageHintReader.VERSION_6) { long totalPage = pageHintReader.getTotalPage( ); for ( long pageNumber = 1; pageNumber <= totalPage; pageNumber++ ) { IPageHint hint = pageHintReader.getPageHint( pageNumber ); int sectionCount = hint.getSectionCount( ); Fragment fragment = new Fragment( new InstanceIDComparator( ) ); for ( int i = 0; i < sectionCount; i++ ) { PageSection section = hint.getSection( i ); fragment.addSection( section.starts, section.ends ); } fragment.build( ); if ( fragment.inFragment( iid ) ) { return pageNumber; } } } } catch ( IOException ex ) { } return -1; } public long getInstanceOffset( InstanceID iid ) { if ( !isComplete( ) ) { return -1l; } if ( iid == null ) { return -1l; } loadCoreStreamLazily( ); if ( indexReader != null ) { try { long offset = indexReader.getOffsetOfInstance( iid .toUniqueString( ) ); if ( offset == -1 ) { offset = indexReader.getOffsetOfInstance( iid.toString( ) ); } return offset; } catch ( IOException ex ) { logger.log( Level.WARNING, "failed to get the offset of instance:" + iid.toUniqueString( ), ex ); } } return -1L; } public long getBookmarkOffset( String bookmark ) { if ( !isComplete( ) ) { return -1; } if ( bookmark == null ) { return -1l; } loadCoreStreamLazily( ); if ( indexReader != null ) { try { return indexReader.getOffsetOfBookmark( bookmark ); } catch ( IOException ex ) { logger.log( Level.WARNING, "failed to get the offset of bookmark:" + bookmark, ex ); } } return -1L; } public ClassLoader getClassLoader( ) { if ( applicationClassLoader != null ) { return applicationClassLoader; } synchronized ( this ) { if ( applicationClassLoader == null ) { applicationClassLoader = AccessController .doPrivileged( new PrivilegedAction<ApplicationClassLoader>( ) { public ApplicationClassLoader run( ) { return new ApplicationClassLoader( engine, getOnPreparedRunnable( ), engine .getConfig( ).getAppContext( ) ); } } ); } } return applicationClassLoader; } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.api.IReportDocument#isComplete() */ public boolean isComplete( ) { return checkpoint == CHECKPOINT_END; } public ReportDesignHandle getReportDesign( ) { IReportRunnable reportRunnable = getReportRunnable( ); if ( reportRunnable != null ) { return (ReportDesignHandle) reportRunnable.getDesignHandle( ); } return null; } public Report getReportIR( ReportDesignHandle designHandle ) { try { InputStream stream = archive.getStream( DESIGN_IR_STREAM ); EngineIRReader reader = new EngineIRReader( ); Report reportIR = reader.read( stream ); reportIR.setVersion( getVersion( ) ); reader.link( reportIR, designHandle ); return reportIR; } catch ( IOException ioex ) { // an error occurs in reading the engine ir logger.log( Level.FINE, "Failed to load the engine IR", ioex ); } return null; } public IReportRunnable getOnPreparedRunnable( ) { return getReportRunnable( false, systemId ); } public InputStream getDesignStream( ) { return getDesignStream( true ); } private InstanceID loadInstanceID( ReportContentReaderV3 reader, long offset ) throws IOException { IContent content = reader.readContent( offset ); if ( content != null ) { InstanceID iid = content.getInstanceID( ); DocumentExtension ext = (DocumentExtension) content .getExtension( IContent.DOCUMENT_EXTENSION ); long parentOffset = ext.getParent( ); if ( parentOffset != -1 ) { InstanceID pid = loadInstanceID( reader, parentOffset ); if ( pid != null ) { return new InstanceID( pid, iid ); } } return iid; } return null; } public InstanceID getBookmarkInstance( String bookmark ) { if ( bookmark == null || bookmark.length( ) == 0 ) { return null; } long offset = getBookmarkOffset( bookmark ); if ( offset < 0 ) return null; try { RAInputStream is = archive.getStream( CONTENT_STREAM ); try { ReportContentReaderV3 reader = new ReportContentReaderV3( new ReportContent( ), is, applicationClassLoader ); try { return loadInstanceID( reader, offset ); } finally { reader.close( ); } } finally { is.close( ); } } catch ( IOException ioe ) { logger.log( Level.FINE, "Failed to get the instance ID of the bookmark: " + bookmark, ioe ); } return null; } private Boolean isReportlet; private String reportletBookmark; private String reportletInstanceID; public boolean isReporltetDocument( ) throws IOException { return loadReportletStream( ); } public String getReportletBookmark( ) throws IOException { if ( loadReportletStream( ) ) { return reportletBookmark; } return null; } public InstanceID getReportletInstanceID( ) throws IOException { if ( loadReportletStream( ) ) { return InstanceID.parse( reportletInstanceID ); } return null; } private boolean loadReportletStream( ) throws IOException { if ( isReportlet == null ) { if ( archive.exists( REPORTLET_DOCUMENT_STREAM ) ) { RAInputStream in = archive .getInputStream( REPORTLET_DOCUMENT_STREAM ); try { int version = in.readInt( ); if ( version != REPORTLET_DOCUMENT_VERSION_0 ) { throw new IOException( "unsupported reportlet document " + version ); } int size = in.readInt( ); byte[] bytes = new byte[size]; in.readFully( bytes, 0, size ); DataInputStream s = new DataInputStream( new ByteArrayInputStream( bytes ) ); reportletBookmark = IOUtil.readString( s ); reportletInstanceID = IOUtil.readString( s ); isReportlet = Boolean.TRUE; } finally { in.close( ); } } else { isReportlet = Boolean.FALSE; } } return isReportlet.booleanValue( ); } HashMap<String, IReportDocumentExtension> extensions = new HashMap<String, IReportDocumentExtension>( ); synchronized public IReportDocumentExtension getDocumentExtension( String name ) throws EngineException { IReportDocumentExtension extension = extensions.get( name ); if ( extension == null ) { IReportEngineExtension engineExtension = this.engine .getEngineExtension( name ); if ( engineExtension != null ) { extension = engineExtension.createDocumentExtension( this ); extensions.put( name, extension ); } } return extension; } synchronized public ITreeNode getTOCTree( ) throws EngineException { if ( !isComplete( ) ) { return null; } loadCoreStreamLazily( ); try { if ( tocReader == null ) { tocReader = new TOCReader( archive, getClassLoader( ) ); } return tocReader.readTree( ); } catch ( IOException ex ) { throw new EngineException( "failed to load toc tree", ex ); } } public void setEngineCacheEntry( LinkedEntry<ReportDocumentReader> entry ) { this.engineCacheEntry = entry; } public String getSystemId( ) { return systemId; } }
package org.innovateuk.ifs.finance.domain; import org.innovateuk.ifs.application.domain.Application; import org.innovateuk.ifs.organisation.domain.Organisation; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class ApplicationFinanceTest { private ApplicationFinance applicationFinance; private Organisation organisation; private Application application; @Before public void setUp() { organisation = new Organisation("Worth Internet Systems"); application = new Application(); applicationFinance = new ApplicationFinance(application, organisation); } @Test public void constructorsShouldCreateInstancesOnValidInput() { new ApplicationFinance(); new ApplicationFinance(application, organisation); } @Test public void applicationFinanceShouldReturnCorrectAttributeValues() { assertEquals(applicationFinance.getOrganisation(), organisation); assertEquals(applicationFinance.getApplication(), application); } @Test public void applicationFinanceShouldReturnCorrectAttributeValuesAfterSetId() { Long newId = 2L; applicationFinance.setId(newId); assertEquals(applicationFinance.getId(), newId); } }
package com.worth.ifs.application.security; import com.worth.ifs.BaseUnitTestMocksTest; import com.worth.ifs.application.builder.ApplicationStatusBuilder; import com.worth.ifs.application.constant.ApplicationStatusConstants; import com.worth.ifs.application.domain.Application; import com.worth.ifs.application.domain.ApplicationStatus; import com.worth.ifs.application.resource.FormInputResponseFileEntryResource; import com.worth.ifs.file.resource.FileEntryResource; import com.worth.ifs.user.domain.ProcessRole; import com.worth.ifs.user.domain.Role; import com.worth.ifs.user.domain.User; import org.junit.Test; import org.mockito.InjectMocks; import java.util.Arrays; import java.util.Collections; import java.util.List; import static com.worth.ifs.application.builder.ApplicationBuilder.newApplication; import static com.worth.ifs.file.resource.builders.FileEntryResourceBuilder.newFileEntryResource; import static com.worth.ifs.user.builder.ProcessRoleBuilder.newProcessRole; import static com.worth.ifs.user.builder.RoleBuilder.newRole; import static com.worth.ifs.user.builder.UserBuilder.newUser; import static com.worth.ifs.user.domain.UserRoleType.*; import static java.util.Collections.emptyList; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Tests around the security rules defining who can upload files to a response to a Question in the Application Form */ public class FormInputResponseFileUploadRulesTest extends BaseUnitTestMocksTest { @InjectMocks private FormInputResponseFileUploadRules fileUploadRules; private long formInputId = 123L; private long applicationId = 456L; private long processRoleId = 789L; private Role applicantRole = newRole().withType(APPLICANT).build(); //TODO: Implement tests for lead applicant and collaborator type users as well and not just applicant. @Test public void testApplicantCanUploadFilesInResponsesForOwnApplication() { Application application = newApplication().build(); ApplicationStatus applicationStatusOpen = ApplicationStatusBuilder.newApplicationStatus().withName(ApplicationStatusConstants.OPEN).build(); application.setApplicationStatus(applicationStatusOpen); User user = newUser().build(); ProcessRole applicantProcessRole = newProcessRole().withUser(user).withRole(applicantRole).withApplication(application).build(); FileEntryResource fileEntry = newFileEntryResource().build(); FormInputResponseFileEntryResource file = new FormInputResponseFileEntryResource(fileEntry, formInputId, applicationId, processRoleId); List<Role> roles = Collections.singletonList(applicantRole); when(applicationRepositoryMock.findOne(applicationId)).thenReturn(application); when(roleRepositoryMock.findByNameIn(Arrays.asList(APPLICANT.getName(), LEADAPPLICANT.getName(), COLLABORATOR.getName()))).thenReturn(Collections.singletonList(applicantRole)); when(processRoleRepositoryMock.findByUserIdAndRoleInAndApplicationId(user.getId(), roles, applicationId)).thenReturn(Collections.singletonList(applicantProcessRole)); assertTrue(fileUploadRules.applicantCanUploadFilesInResponsesForOwnApplication(file, user)); verify(roleRepositoryMock).findByNameIn(Arrays.asList(APPLICANT.getName(), LEADAPPLICANT.getName(), COLLABORATOR.getName())); verify(processRoleRepositoryMock).findByUserIdAndRoleInAndApplicationId(user.getId(), roles, applicationId); } @Test public void testApplicantCanUploadFilesInResponsesForOwnApplicationButNotAMemberOfApplication() { User user = newUser().build(); FileEntryResource fileEntry = newFileEntryResource().build(); FormInputResponseFileEntryResource file = new FormInputResponseFileEntryResource(fileEntry, formInputId, applicationId, processRoleId); List<Role> roles = Collections.singletonList(applicantRole); when(roleRepositoryMock.findByNameIn(Arrays.asList(APPLICANT.getName(), LEADAPPLICANT.getName(), COLLABORATOR.getName()))).thenReturn(Collections.singletonList(applicantRole)); when(processRoleRepositoryMock.findByUserIdAndRoleInAndApplicationId(user.getId(), roles, applicationId)).thenReturn(emptyList()); assertFalse(fileUploadRules.applicantCanUploadFilesInResponsesForOwnApplication(file, user)); verify(roleRepositoryMock).findByNameIn(Arrays.asList(APPLICANT.getName(), LEADAPPLICANT.getName(), COLLABORATOR.getName())); verify(processRoleRepositoryMock).findByUserIdAndRoleInAndApplicationId(user.getId(), roles, applicationId); } @Test public void testApplicantCanUploadFilesInResponsesForOwnApplicationButLeadApplicantRoleNotFound() { User user = newUser().build(); FileEntryResource fileEntry = newFileEntryResource().build(); FormInputResponseFileEntryResource file = new FormInputResponseFileEntryResource(fileEntry, formInputId, applicationId, processRoleId); when(roleRepositoryMock.findByNameIn(Arrays.asList(APPLICANT.getName(), LEADAPPLICANT.getName(), COLLABORATOR.getName()))).thenReturn(emptyList()); assertFalse(fileUploadRules.applicantCanUploadFilesInResponsesForOwnApplication(file, user)); verify(roleRepositoryMock).findByNameIn(Arrays.asList(APPLICANT.getName(), LEADAPPLICANT.getName(), COLLABORATOR.getName())); } }
package com.marcelorcorrea.imagedownloader.core.imp; import com.google.common.collect.Iterables; import com.google.common.io.Files; import com.google.common.util.concurrent.*; import com.marcelorcorrea.imagedownloader.core.ImageDownloader; import com.marcelorcorrea.imagedownloader.core.exception.ImageDownloaderException; import com.marcelorcorrea.imagedownloader.core.exception.UnknownContentTypeException; import com.marcelorcorrea.imagedownloader.core.fetcher.ImageFetcher; import com.marcelorcorrea.imagedownloader.core.http.DownloadManager; import com.marcelorcorrea.imagedownloader.core.listener.ImageDownloaderListener; import com.marcelorcorrea.imagedownloader.core.listener.LogImageDownloaderListener; import com.marcelorcorrea.imagedownloader.core.model.ContentType; import com.marcelorcorrea.imagedownloader.core.model.DownloadedImage; import com.marcelorcorrea.imagedownloader.core.parser.HTMLParser; import com.marcelorcorrea.imagedownloader.core.parser.ParserFactory; import com.marcelorcorrea.imagedownloader.core.util.Util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.Executors; /** * @author Marcelo Correa */ public class GenericImageDownloader implements ImageDownloader, ImageFetcher.ImageFetcherCallback { private static final Logger logger = LoggerFactory.getLogger(GenericImageDownloader.class); private static final String CONTENT_TYPE_ERROR_MESSAGE = "Could not retrieve content type of %s"; private final ListeningExecutorService pool; private HTMLParser mParser; private ImageDownloaderListener mListener; private ImageFetcher mImageFetcher; public GenericImageDownloader() { pool = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10)); } private void initialize(String url) { if (mListener == null) { mListener = new LogImageDownloaderListener(); } if (mImageFetcher == null) { mImageFetcher = new DownloadManager(); mImageFetcher.setListener(this); } if (mParser == null) { //Look for best mParser (currently there are two parsers) mParser = ParserFactory.getParser(url); logger.info("Using " + mParser.getClass().getSimpleName()); } } @Override public void download(String url, ContentType selectedContentType, int width, int height) throws ImageDownloaderException, UnknownContentTypeException { try { if (url == null || url.isEmpty()) { logger.error("URL is a required field."); return; } String scheme = new URI(url).getScheme(); if (scheme == null) { url = "http://" + url; } else if (!scheme.equals("http") && !scheme.equals("https")) { logger.error("Only protocols HTTP and HTTPS are supported."); return; } //if everything looks okay, then we can initialize or verify parsers and listeners initialize(url); logger.info("Connecting to: " + url); ContentType urlContentType = mImageFetcher.getContentType(url); if (urlContentType == null) { logger.error(String.format(CONTENT_TYPE_ERROR_MESSAGE, url)); throw new UnknownContentTypeException(String.format(CONTENT_TYPE_ERROR_MESSAGE, url)); } boolean isContentTypeHTML = urlContentType.isHTML(); logger.info("URL Content Type: " + urlContentType + " (" + urlContentType.getValue() + ")"); logger.info("Selected Extension: " + selectedContentType + " (" + selectedContentType.getValue() + ")"); logger.info("URL Content Type is a HTML Content Type? " + isContentTypeHTML); if (isContentTypeHTML) { downloadImagesFromURL(url, selectedContentType, width, height); } else { downloadSingleImageFromURL(url, selectedContentType, width, height); } } catch (UnknownContentTypeException e) { throw e; } catch (IOException | URISyntaxException e) { logger.error(e.getMessage()); throw new ImageDownloaderException(e); } } private void downloadImagesFromURL(String url, ContentType selectedContentType, int width, int height) { try { // Get image sources using mParser Set<String> imgSources = mParser.parse(url, selectedContentType); // Fire OnTaskStart Callback with the number of links to download. mListener.onTaskStart(imgSources.size()); List<ListenableFuture<DownloadedImage>> listenableFutures = new ArrayList<>(); for (String source : imgSources) { ListenableFuture<DownloadedImage> listenableFuture = createAndSubmitWork(source, selectedContentType, width, height); listenableFutures.add(listenableFuture); } ListenableFuture<List<DownloadedImage>> listListenableFuture = Futures.successfulAsList(listenableFutures); Futures.addCallback(listListenableFuture, new FutureCallback<List<DownloadedImage>>() { @Override public void onSuccess(List<DownloadedImage> result) { logger.info("Finished processing {} elements", Iterables.size(result)); mListener.onTaskFinished(); } @Override public void onFailure(Throwable t) { logger.info("Failed because of :: {}", t); } }); } catch (Exception ex) { logger.error("Error while downloading image: " + ex.getClass()); } } private void downloadSingleImageFromURL(String imgSource, ContentType selectedContentType, int width, int height) throws IOException { mListener.onTaskStart(1); ListenableFuture<DownloadedImage> listenableFuture = createAndSubmitWork(imgSource, selectedContentType, width, height); Futures.addCallback(listenableFuture, new FutureCallback<DownloadedImage>() { @Override public void onSuccess(DownloadedImage result) { logger.info("Finished processing single image {}", result); mListener.onTaskFinished(); } @Override public void onFailure(Throwable t) { logger.info("Failed because of :: {}", t); } }); } private ListenableFuture<DownloadedImage> createAndSubmitWork(final String imgSource, ContentType selectedContentType, int width, int height) { Callable<DownloadedImage> callable = createDownloadedImageCallable(imgSource, selectedContentType, width, height); ListenableFuture<DownloadedImage> future = pool.submit(callable); Futures.addCallback(future, new FutureCallback<DownloadedImage>() { @Override public void onSuccess(DownloadedImage downloadedImage) { if (downloadedImage != null) { mListener.onDownloadComplete(imgSource, downloadedImage); } else { logger.error("Error while downloading image: {}", imgSource); mListener.onDownloadFail(imgSource); } } @Override public void onFailure(Throwable throwable) { mListener.onDownloadFail(imgSource); logger.error(throwable.toString()); } }); return future; } private Callable<DownloadedImage> createDownloadedImageCallable(final String imgSource, final ContentType selectedContentType, final int width, final int height) { return new Callable<DownloadedImage>() { @Override public DownloadedImage call() throws Exception { byte[] imageInBytes = mImageFetcher.downloadImage(imgSource, selectedContentType, width, height); if (imageInBytes != null) { String name = Util.getFilename(imgSource, selectedContentType.getRawValue()); return new DownloadedImage(imageInBytes, name); } return null; } }; } @Override public boolean writeToDisk(List<DownloadedImage> images, File directory) { logger.debug("Downloaded Images size: " + images.size()); for (DownloadedImage downloadedImage : images) { writeToDisk(downloadedImage, directory); } return true; } @Override public boolean writeToDisk(DownloadedImage image, File directory) { try { File file = new File(directory, image.getName()); Files.write(image.getBytes(), file); image.setFile(file); } catch (IOException ex) { logger.error("Exception: " + ex + " -- message: " + ex.getMessage()); return false; } logger.debug("File saved successfully!"); return true; } @Override public void setHTMLParser(HTMLParser parser) { this.mParser = parser; } @Override public void setImageFetcher(ImageFetcher imageFetcher) { this.mImageFetcher = imageFetcher; } @Override public void setOnDownloadListener(ImageDownloaderListener imageDownloaderListener) { this.mListener = imageDownloaderListener; } @Override public void notifyDownloadStart(String link, int contentLength) { mListener.onDownloadStart(link, contentLength); } @Override public void notifyDownloadProgress(String link, int total) { mListener.onDownloadInProgress(link, total); } }
package io.quarkus.bootstrap.classloading; import java.io.ByteArrayInputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URL; import java.security.ProtectionDomain; import java.sql.Driver; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.jboss.logging.Logger; /** * The ClassLoader used for non production Quarkus applications (i.e. dev and test mode). */ public class QuarkusClassLoader extends ClassLoader implements Closeable { private static final Logger log = Logger.getLogger(QuarkusClassLoader.class); protected static final String META_INF_SERVICES = "META-INF/services/"; protected static final String JAVA = "java."; static { registerAsParallelCapable(); } public static List<ClassPathElement> getElements(String resourceName, boolean localOnly) { final ClassLoader ccl = Thread.currentThread().getContextClassLoader(); if (!(ccl instanceof QuarkusClassLoader)) { throw new IllegalStateException("The current classloader is not an instance of " + QuarkusClassLoader.class.getName() + " but " + ccl.getClass().getName()); } return ((QuarkusClassLoader) ccl).getElementsWithResource(resourceName, localOnly); } /** * Indicates if a given class is present at runtime. * * @param className the name of the class. */ public static boolean isClassPresentAtRuntime(String className) { return isResourcePresentAtRuntime(className.replace('.', '/') + ".class"); } /** * Indicates if a given resource is present at runtime. * Can also be used to check if a class is present as a class is just a regular resource. * * @param resourceName the path of the resource, for instance {@code path/to/my-resources.properties} for a properties file * or {@code my/package/MyClass.class} for a class. */ public static boolean isResourcePresentAtRuntime(String resourcePath) { for (ClassPathElement cpe : QuarkusClassLoader.getElements(resourcePath, false)) { if (cpe.isRuntime()) { return true; } } return false; } private final String name; private final List<ClassPathElement> elements; private final ConcurrentMap<ClassPathElement, ProtectionDomain> protectionDomains = new ConcurrentHashMap<>(); private final ConcurrentMap<String, Package> definedPackages = new ConcurrentHashMap<>(); private final ClassLoader parent; /** * If this is true it will attempt to load from the parent first */ private final boolean parentFirst; private final boolean aggregateParentResources; private final List<ClassPathElement> bannedElements; private final List<ClassPathElement> parentFirstElements; private final List<ClassPathElement> lesserPriorityElements; private final List<ClassLoaderEventListener> classLoaderEventListeners; /** * The element that holds resettable in-memory classses. * <p> * A reset occurs when new transformers and in-memory classes are added to a ClassLoader. It happens after each * start in dev mode, however in general the reset resources will be the same. There are some cases where this is * not the case though: * <p> * - Dev mode failed start will not end up with transformers or generated classes being registered. The reset * in this case will add them. * - Platform CDI beans that are considered to be removed and have the removed status changed will result in * additional classes being added to the class loader. */ private volatile MemoryClassPathElement resettableElement; private volatile MemoryClassPathElement transformedClasses; private volatile ClassLoaderState state; private final List<Runnable> closeTasks = new ArrayList<>(); static final ClassLoader PLATFORM_CLASS_LOADER; static { ClassLoader cl = null; try { cl = (ClassLoader) ClassLoader.class.getDeclaredMethod("getPlatformClassLoader").invoke(null); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { } PLATFORM_CLASS_LOADER = cl; } private boolean closed; private volatile boolean driverLoaded; private QuarkusClassLoader(Builder builder) { super(builder.parent); this.name = builder.name; this.elements = builder.elements; this.bannedElements = builder.bannedElements; this.parentFirstElements = builder.parentFirstElements; this.lesserPriorityElements = builder.lesserPriorityElements; this.parent = builder.parent; this.parentFirst = builder.parentFirst; this.resettableElement = builder.resettableElement; this.transformedClasses = new MemoryClassPathElement(builder.transformedClasses, true); this.aggregateParentResources = builder.aggregateParentResources; this.classLoaderEventListeners = builder.classLoaderEventListeners.isEmpty() ? Collections.emptyList() : builder.classLoaderEventListeners; setDefaultAssertionStatus(builder.assertionsEnabled); } public static Builder builder(String name, ClassLoader parent, boolean parentFirst) { return new Builder(name, parent, parentFirst); } private String sanitizeName(String name) { if (name.startsWith("/")) { name = name.substring(1); } if (name.endsWith("/")) { name = name.substring(0, name.length() - 1); } return name; } /** * Returns true if the supplied class is a class that would be loaded parent-first */ public boolean isParentFirst(String name) { if (name.startsWith(JAVA)) { return true; } //even if the thread is interrupted we still want to be able to load classes //if the interrupt bit is set then we clear it and restore it at the end boolean interrupted = Thread.interrupted(); try { ClassLoaderState state = getState(); synchronized (getClassLoadingLock(name)) { String resourceName = sanitizeName(name).replace('.', '/') + ".class"; return parentFirst(resourceName, state); } } finally { if (interrupted) { //restore interrupt state Thread.currentThread().interrupt(); } } } private boolean parentFirst(String name, ClassLoaderState state) { return parentFirst || state.parentFirstResources.contains(name); } public void reset(Map<String, byte[]> generatedResources, Map<String, byte[]> transformedClasses) { if (resettableElement == null) { throw new IllegalStateException("Classloader is not resettable"); } synchronized (this) { this.transformedClasses = new MemoryClassPathElement(transformedClasses, true); resettableElement.reset(generatedResources); state = null; } } @Override public Enumeration<URL> getResources(String unsanitisedName) throws IOException { return getResources(unsanitisedName, false); } public Enumeration<URL> getResources(String unsanitisedName, boolean parentAlreadyFoundResources) throws IOException { for (ClassLoaderEventListener l : classLoaderEventListeners) { l.enumeratingResourceURLs(unsanitisedName, this.name); } boolean endsWithTrailingSlash = unsanitisedName.endsWith("/"); ClassLoaderState state = getState(); String name = sanitizeName(unsanitisedName); //for resources banned means that we don't delegate to the parent, as there can be multiple resources //for single resources we still respect this boolean banned = state.bannedResources.contains(name); Set<URL> resources = new LinkedHashSet<>(); //this is a big of a hack, but is necessary to prevent service leakage //in some situations (looking at you gradle) the parent can contain the same //classes as the application. The parent aggregation stops this being a problem //in most cases, however if there are no actual implementations of the service //in the application then this can still cause problems //this approach makes sure that we don't load services that would result //in a ServiceConfigurationError if (name.startsWith(META_INF_SERVICES)) { try { Class<?> c = loadClass(name.substring(META_INF_SERVICES.length())); if (c.getClassLoader() == this) { //if the service class is defined by this class loader then any resources that could be loaded //by the parent would have a different copy of the service class banned = true; } } catch (ClassNotFoundException ignored) { //ignore } } //TODO: in theory resources could have been added in dev mode //but I don't thing this really matters for this code path ClassPathElement[] providers = state.loadableResources.get(name); if (providers != null) { for (ClassPathElement element : providers) { ClassPathResource res = element.getResource(name); //if the requested name ends with a trailing / we make sure //that the resource is a directory, and return a URL that ends with a / //this matches the behaviour of URLClassLoader if (endsWithTrailingSlash) { if (res.isDirectory()) { try { resources.add(new URL(res.getUrl().toString() + "/")); } catch (MalformedURLException e) { throw new RuntimeException(e); } } } else { resources.add(res.getUrl()); } } } else if (name.isEmpty()) { for (ClassPathElement i : elements) { ClassPathResource res = i.getResource(""); if (res != null) { resources.add(res.getUrl()); } } } if (!banned) { if ((resources.isEmpty() && !parentAlreadyFoundResources) || aggregateParentResources) { Enumeration<URL> res; if (parent instanceof QuarkusClassLoader) { res = ((QuarkusClassLoader) parent).getResources(unsanitisedName, !resources.isEmpty()); } else { res = parent.getResources(unsanitisedName); } while (res.hasMoreElements()) { resources.add(res.nextElement()); } } } return Collections.enumeration(resources); } private ClassLoaderState getState() { ClassLoaderState state = this.state; if (state == null) { synchronized (this) { state = this.state; if (state == null) { Map<String, List<ClassPathElement>> elementMap = new HashMap<>(); for (ClassPathElement element : elements) { for (String i : element.getProvidedResources()) { if (i.startsWith("/")) { throw new RuntimeException( "Resources cannot start with /, " + i + " is incorrect provided by " + element); } if (transformedClasses.getResource(i) != null) { elementMap.put(i, Collections.singletonList(transformedClasses)); } else { List<ClassPathElement> list = elementMap.get(i); if (list == null) { elementMap.put(i, list = new ArrayList<>(2)); //default initial capacity of 10 is way too large } list.add(element); } } } Map<String, ClassPathElement[]> finalElements = new HashMap<>(); for (Map.Entry<String, List<ClassPathElement>> i : elementMap.entrySet()) { List<ClassPathElement> entryClassPathElements = i.getValue(); if (!lesserPriorityElements.isEmpty() && (entryClassPathElements.size() > 1)) { List<ClassPathElement> entryNormalPriorityElements = new ArrayList<>(entryClassPathElements.size()); List<ClassPathElement> entryLesserPriorityElements = new ArrayList<>(entryClassPathElements.size()); for (ClassPathElement classPathElement : entryClassPathElements) { if (lesserPriorityElements.contains(classPathElement)) { entryLesserPriorityElements.add(classPathElement); } else { entryNormalPriorityElements.add(classPathElement); } } // ensure the lesser priority elements are added later entryClassPathElements = new ArrayList<>(entryClassPathElements.size()); entryClassPathElements.addAll(entryNormalPriorityElements); entryClassPathElements.addAll(entryLesserPriorityElements); } finalElements.put(i.getKey(), entryClassPathElements.toArray(new ClassPathElement[entryClassPathElements.size()])); } Set<String> banned = new HashSet<>(); for (ClassPathElement i : bannedElements) { banned.addAll(i.getProvidedResources()); } Set<String> parentFirstResources = new HashSet<>(); for (ClassPathElement i : parentFirstElements) { parentFirstResources.addAll(i.getProvidedResources()); } return this.state = new ClassLoaderState(finalElements, banned, parentFirstResources); } } } return state; } @Override public URL getResource(String unsanitisedName) { for (ClassLoaderEventListener l : classLoaderEventListeners) { l.gettingURLFromResource(unsanitisedName, this.name); } boolean endsWithTrailingSlash = unsanitisedName.endsWith("/"); String name = sanitizeName(unsanitisedName); ClassLoaderState state = getState(); if (state.bannedResources.contains(name)) { return null; } //TODO: because of dev mode we iterate, to see if any resources were added //not for .class files though, adding them causes a restart //this is very important for bytebuddy performance if (name.endsWith(".class") && !endsWithTrailingSlash) { ClassPathElement[] providers = state.loadableResources.get(name); if (providers != null) { return providers[0].getResource(name).getUrl(); } } else { for (ClassPathElement i : elements) { ClassPathResource res = i.getResource(name); if (res != null) { //if the requested name ends with a trailing / we make sure //that the resource is a directory, and return a URL that ends with a / //this matches the behaviour of URLClassLoader if (endsWithTrailingSlash) { if (res.isDirectory()) { try { return new URL(res.getUrl().toString() + "/"); } catch (MalformedURLException e) { throw new RuntimeException(e); } } } else { return res.getUrl(); } } } } return parent.getResource(unsanitisedName); } @Override public InputStream getResourceAsStream(String unsanitisedName) { for (ClassLoaderEventListener l : classLoaderEventListeners) { l.openResourceStream(unsanitisedName, this.name); } String name = sanitizeName(unsanitisedName); ClassLoaderState state = getState(); if (state.bannedResources.contains(name)) { return null; } //dev mode may have added some files, so we iterate to check, but not for classes if (name.endsWith(".class")) { ClassPathElement[] providers = state.loadableResources.get(name); if (providers != null) { return new ByteArrayInputStream(providers[0].getResource(name).getData()); } } else { for (ClassPathElement i : elements) { ClassPathResource res = i.getResource(name); if (res != null) { if (res.isDirectory()) { try { return res.getUrl().openStream(); } catch (IOException e) { log.debug("Ignoring exception that occurred while opening a stream for resource " + unsanitisedName, e); // behave like how java.lang.ClassLoader#getResourceAsStream() behaves // and don't propagate the exception continue; } } return new ByteArrayInputStream(res.getData()); } } } return parent.getResourceAsStream(unsanitisedName); } /** * This method is needed to make packages work correctly on JDK9+, as it will be called * to load the package-info class. * * @param moduleName * @param name * @return */ @Override protected Class<?> findClass(String moduleName, String name) { try { return loadClass(name, false); } catch (ClassNotFoundException e) { return null; } } @Override public Class<?> loadClass(String name) throws ClassNotFoundException { for (ClassLoaderEventListener l : classLoaderEventListeners) { l.loadClass(name, this.name); } return loadClass(name, false); } @Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { for (ClassLoaderEventListener l : classLoaderEventListeners) { l.loadClass(name, this.name); } if (name.startsWith(JAVA)) { return parent.loadClass(name); } //even if the thread is interrupted we still want to be able to load classes //if the interrupt bit is set then we clear it and restore it at the end boolean interrupted = Thread.interrupted(); try { ClassLoaderState state = getState(); synchronized (getClassLoadingLock(name)) { Class<?> c = findLoadedClass(name); if (c != null) { return c; } String resourceName = sanitizeName(name).replace('.', '/') + ".class"; boolean parentFirst = parentFirst(resourceName, state); if (state.bannedResources.contains(resourceName)) { throw new ClassNotFoundException(name); } if (parentFirst) { try { return parent.loadClass(name); } catch (ClassNotFoundException ignore) { log.tracef("Class %s not found in parent first load from %s", name, parent); } } ClassPathElement[] resource = state.loadableResources.get(resourceName); if (resource != null) { ClassPathElement classPathElement = resource[0]; ClassPathResource classPathElementResource = classPathElement.getResource(resourceName); if (classPathElementResource != null) { //can happen if the class loader was closed byte[] data = classPathElementResource.getData(); definePackage(name, classPathElement); Class<?> cl = defineClass(name, data, 0, data.length, protectionDomains.computeIfAbsent(classPathElement, (ce) -> ce.getProtectionDomain(this))); if (Driver.class.isAssignableFrom(cl)) { driverLoaded = true; } return cl; } } if (!parentFirst) { return parent.loadClass(name); } throw new ClassNotFoundException(name); } } finally { if (interrupted) { //restore interrupt state Thread.currentThread().interrupt(); } } } private void definePackage(String name, ClassPathElement classPathElement) { final String pkgName = getPackageNameFromClassName(name); //we can't use getPackage here //if can return a package from the parent if ((pkgName != null) && definedPackages.get(pkgName) == null) { synchronized (getClassLoadingLock(pkgName)) { if (definedPackages.get(pkgName) == null) { Manifest mf = classPathElement.getManifest(); if (mf != null) { Attributes ma = mf.getMainAttributes(); definedPackages.put(pkgName, definePackage(pkgName, ma.getValue(Attributes.Name.SPECIFICATION_TITLE), ma.getValue(Attributes.Name.SPECIFICATION_VERSION), ma.getValue(Attributes.Name.SPECIFICATION_VENDOR), ma.getValue(Attributes.Name.IMPLEMENTATION_TITLE), ma.getValue(Attributes.Name.IMPLEMENTATION_VERSION), ma.getValue(Attributes.Name.IMPLEMENTATION_VENDOR), null)); return; } // this could certainly be improved to use the actual manifest definedPackages.put(pkgName, definePackage(pkgName, null, null, null, null, null, null, null)); } } } } private String getPackageNameFromClassName(String className) { final int index = className.lastIndexOf('.'); if (index == -1) { // we return null here since in this case no package is defined // this is same behavior as Package.getPackage(clazz) exhibits // when the class is in the default package return null; } return className.substring(0, index); } public List<ClassPathElement> getElementsWithResource(String name) { return getElementsWithResource(name, false); } public List<ClassPathElement> getElementsWithResource(String name, boolean localOnly) { List<ClassPathElement> ret = new ArrayList<>(); if (parent instanceof QuarkusClassLoader && !localOnly) { ret.addAll(((QuarkusClassLoader) parent).getElementsWithResource(name)); } ClassPathElement[] classPathElements = getState().loadableResources.get(name); if (classPathElements == null) { return ret; } ret.addAll(Arrays.asList(classPathElements)); return ret; } public List<String> getLocalClassNames() { List<String> ret = new ArrayList<>(); for (String name : getState().loadableResources.keySet()) { if (name.endsWith(".class")) { ret.add(name.substring(0, name.length() - 6).replace('/', '.')); } } return ret; } public Class<?> visibleDefineClass(String name, byte[] b, int off, int len) throws ClassFormatError { return super.defineClass(name, b, off, len); } public void addCloseTask(Runnable task) { synchronized (closeTasks) { closeTasks.add(task); } } @Override public void close() { synchronized (this) { if (closed) { return; } closed = true; } List<Runnable> tasks; synchronized (closeTasks) { tasks = new ArrayList<>(closeTasks); } for (Runnable i : tasks) { try { i.run(); } catch (Throwable t) { log.error("Failed to run close task", t); } } if (driverLoaded) { //DriverManager only lets you remove drivers with the same CL as the caller //so we need do define the cleaner in this class loader try (InputStream is = getClass().getResourceAsStream("DriverRemover.class")) { byte[] data = JarClassPathElement.readStreamContents(is); Runnable r = (Runnable) defineClass(DriverRemover.class.getName(), data, 0, data.length) .getConstructor(ClassLoader.class).newInstance(this); r.run(); } catch (Exception e) { log.debug("Failed to clean up DB drivers"); } } for (ClassPathElement element : elements) { //note that this is a 'soft' close //all resources are closed, however the CL can still be used //but after close no resources will be held past the scope of an operation try (ClassPathElement ignored = element) { //the close() operation is implied by the try-with syntax } catch (Exception e) { log.error("Failed to close " + element, e); } } for (ClassPathElement element : bannedElements) { //note that this is a 'soft' close //all resources are closed, however the CL can still be used //but after close no resources will be held past the scope of an operation try (ClassPathElement ignored = element) { //the close() operation is implied by the try-with syntax } catch (Exception e) { log.error("Failed to close " + element, e); } } ResourceBundle.clearCache(this); } public boolean isClosed() { return closed; } @Override public String toString() { return "QuarkusClassLoader:" + name + "@" + Integer.toHexString(hashCode()); } public static class Builder { final String name; final ClassLoader parent; final List<ClassPathElement> elements = new ArrayList<>(); final List<ClassPathElement> bannedElements = new ArrayList<>(); final List<ClassPathElement> parentFirstElements = new ArrayList<>(); final List<ClassPathElement> lesserPriorityElements = new ArrayList<>(); final boolean parentFirst; MemoryClassPathElement resettableElement; private Map<String, byte[]> transformedClasses = Collections.emptyMap(); boolean aggregateParentResources; boolean assertionsEnabled; private final ArrayList<ClassLoaderEventListener> classLoaderEventListeners = new ArrayList<>(5); public Builder(String name, ClassLoader parent, boolean parentFirst) { this.name = name; this.parent = parent; this.parentFirst = parentFirst; } /** * Adds an element that can be used to load classes. * <p> * Order is important, if there are multiple elements that provide the same * class then the first one passed to this method will be used. * <p> * The provided element will be closed when the ClassLoader is closed. * * @param element The element to add * @return This builder */ public Builder addElement(ClassPathElement element) { log.debugf("Adding elements %s to QuarkusClassLoader %s", element, name); elements.add(element); return this; } /** * Adds a resettable MemoryClassPathElement to the class loader. * <p> * This element is mutable, and its contents will be modified if the class loader * is reset. * <p> * If this is not explicitly added to the elements list then it will be automatically * added as the highest priority element. * * @param resettableElement The element * @return This builder */ public Builder setResettableElement(MemoryClassPathElement resettableElement) { this.resettableElement = resettableElement; return this; } /** * Adds an element that contains classes that will always be loaded in a parent first manner. * <p> * Note that this does not mean that the parent will always have this class, it is possible that * in some cases the class will end up being loaded by this loader, however an attempt will always * be made to load these from the parent CL first * <p> * Note that elements passed to this method will not be automatically closed, as * references to this element are not retained after the class loader has been built. * * @param element The element to add * @return This builder */ public Builder addParentFirstElement(ClassPathElement element) { log.debugf("Adding parent first element %s to QuarkusClassLoader %s", element, name); parentFirstElements.add(element); return this; } /** * Adds an element that contains classes that should never be loaded by this loader. * <p> * Note that elements passed to this method will not be automatically closed, as * references to this element are not retained after the class loader has been built. * <p> * This is because banned elements are generally expected to be loaded by another ClassLoader, * so this prevents the need to create multiple ClassPathElements for the same resource. * <p> * Banned elements have the highest priority, a banned element will never be loaded, * and resources will never appear to be present. * * @param element The element to add * @return This builder */ public Builder addBannedElement(ClassPathElement element) { bannedElements.add(element); return this; } /** * Adds an element which will only be used to load a class or resource if no normal * element containing that class or resource exists. * This is used in order control the order of elements when multiple contain the same classes * * @param element The element to add * @return This builder */ public Builder addLesserPriorityElement(ClassPathElement element) { lesserPriorityElements.add(element); return this; } /** * If this is true then a getResources call will always include the parent resources. * <p> * If this is false then getResources will not return parent resources if local resources were found. * <p> * This only takes effect if parentFirst is false. */ public Builder setAggregateParentResources(boolean aggregateParentResources) { this.aggregateParentResources = aggregateParentResources; return this; } public Builder setAssertionsEnabled(boolean assertionsEnabled) { this.assertionsEnabled = assertionsEnabled; return this; } public Builder setTransformedClasses(Map<String, byte[]> transformedClasses) { this.transformedClasses = transformedClasses; return this; } public Builder addClassLoaderEventListeners(List<ClassLoaderEventListener> classLoadListeners) { this.classLoaderEventListeners.addAll(classLoadListeners); return this; } /** * Builds the class loader * * @return The class loader */ public QuarkusClassLoader build() { if (resettableElement != null) { if (!elements.contains(resettableElement)) { elements.add(0, resettableElement); } } this.classLoaderEventListeners.trimToSize(); return new QuarkusClassLoader(this); } } public ClassLoader parent() { return parent; } static final class ClassLoaderState { final Map<String, ClassPathElement[]> loadableResources; final Set<String> bannedResources; final Set<String> parentFirstResources; ClassLoaderState(Map<String, ClassPathElement[]> loadableResources, Set<String> bannedResources, Set<String> parentFirstResources) { this.loadableResources = loadableResources; this.bannedResources = bannedResources; this.parentFirstResources = parentFirstResources; } } @Override public String getName() { return name; } }
package org.intermine.webservice.server.template.result; import junit.framework.TestCase; import org.apache.log4j.Logger; import org.intermine.TestUtil; import org.intermine.api.template.TemplateQuery; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.pathquery.PathConstraint; import org.intermine.pathquery.PathConstraintAttribute; import org.intermine.pathquery.PathConstraintLookup; import org.intermine.pathquery.PathQuery; import org.intermine.webservice.server.WebServiceConstants; /** * @author Jakub Kulaviak, dbutano **/ public class TemplateResultLinkGeneratorTest extends TestCase { private String prefix = "http://localhost:8080/query/" + WebServiceConstants.MODULE_NAME; private static final Logger LOG = Logger.getLogger(TemplateResultLinkGeneratorTest.class); public void testExtraValueLink() { PathQuery ret = new PathQuery(TestUtil.getModel()); PathConstraint c1 = new PathConstraintLookup("Gene.name", "zen", "Drosophila_melanogaster"); TemplateQuery tmpl = new TemplateQuery("template1", "title", "comments", ret); tmpl.addConstraint(c1); tmpl.setEditable(c1, true); String link = new TemplateResultLinkGenerator().getHtmlLink("http://localhost:8080/query", tmpl); String expected = prefix + "/template/results?name=template1&constraint1=Gene.name&op1=LOOKUP&value1=zen&" + "extra1=Drosophila_melanogaster&format=tab&size=" + TemplateResultLinkGenerator.DEFAULT_RESULT_SIZE + "&layout=minelink|paging"; assertEquals(expected, link); } public void testMultipleConstraintsLink() { PathQuery ret = new PathQuery(TestUtil.getModel()); PathConstraint c1 = new PathConstraintAttribute("Gene.name", ConstraintOp.MATCHES, "zen"); PathConstraint c2 = new PathConstraintAttribute("Gene.length", ConstraintOp.LESS_THAN, "100"); TemplateQuery tmpl = new TemplateQuery("template1", "title", "comments", ret); tmpl.addConstraint(c1); tmpl.setEditable(c1, true); tmpl.addConstraint(c2); tmpl.setEditable(c2, true); String link = new TemplateResultLinkGenerator() .getHtmlLink("http://localhost:8080/query", tmpl); String expected = prefix + "/template/results?name=template1" + "&constraint1=Gene.name&op1=LIKE&value1=zen" + "&constraint2=Gene.length&op2=lt&value2=100" + "&format=tab&size=" + TemplateResultLinkGenerator.DEFAULT_RESULT_SIZE + "&layout=minelink|paging"; assertEquals(expected, link); } }
package de.lmu.ifi.dbs.database; import de.lmu.ifi.dbs.data.FeatureVector; import de.lmu.ifi.dbs.data.MetricalObject; import de.lmu.ifi.dbs.utilities.UnableToComplyException; import de.lmu.ifi.dbs.utilities.Util; import de.lmu.ifi.dbs.utilities.optionhandling.AttributeSettings; import java.util.ArrayList; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; /** * Provides a mapping for associations based on a Hashtable and functions to get * the next usable ID for insertion, making IDs reusable after deletion of the * entry. Make sure to delete any associations when deleting an entry (e.g. by * calling {@link #deleteAssociations(Integer) deleteAssociations(id)}). * * @author Arthur Zimek (<a * href="mailto:zimek@dbs.ifi.lmu.de">zimek@dbs.ifi.lmu.de</a>) */ public abstract class AbstractDatabase<T extends MetricalObject> implements Database<T> { /** * Map to hold association maps. */ private final Map<AssociationID, Map<Integer, Object>> associations; /** * Counter to provide a new Integer id. */ private int counter; /** * Provides a list of reusable ids. */ private List<Integer> reusableIDs; /** * Whether the limit is reached. */ private boolean reachedLimit; /** * Holds the parameter settings. */ private String[] parameters; /** * Provides an abstract database including a mapping for associations based * on a Hashtable and functions to get the next usable ID for insertion, * making IDs reusable after deletion of the entry. Make sure to delete any * associations when deleting an entry (e.g. by calling * {@link #deleteAssociations(Integer) deleteAssociations(id)}). */ protected AbstractDatabase() { associations = new Hashtable<AssociationID, Map<Integer, Object>>(); counter = 1; reachedLimit = false; reusableIDs = new ArrayList<Integer>(); } /** * @see de.lmu.ifi.dbs.database.Database#associate(AssociationID, Integer, Object) */ public void associate(final AssociationID associationID, final Integer objectID, final Object association) { if(!associations.containsKey(associationID)) { associations.put(associationID, new Hashtable<Integer, Object>()); } associations.get(associationID).put(objectID, association); } /** * @see de.lmu.ifi.dbs.database.Database#getAssociation(AssociationID, Integer) */ public Object getAssociation(final AssociationID associationID, final Integer objectID) { if(associations.containsKey(associationID)) { return associations.get(associationID).get(objectID); } else { return null; } } /** * Provides a new id for the specified metrical object suitable as key for a * new insertion and sets this id in the specified metrical object. * * @return a new id suitable as key for a new insertion * @throws UnableToComplyException * if the database has reached the limit and, therefore, new * insertions are not possible */ protected Integer setNewID(T object) throws UnableToComplyException { if(reachedLimit && reusableIDs.size() == 0) { throw new UnableToComplyException("Database reached limit of storage."); } else { Integer id = counter; if(counter < Integer.MAX_VALUE && !reachedLimit) { counter++; } else { if(reusableIDs.size() > 0) { counter = reusableIDs.remove(0); } else { reachedLimit = true; } } object.setID(id); return id; } } /** * Makes the given id reusable for new insertion operations. * * @param id * the id to become reusable */ protected void restoreID(final Integer id) { { reusableIDs.add(id); } } /** * Deletes associations for the given id if there are any. * * @param id * id of which all associations are to be deleted */ protected void deleteAssociations(final Integer id) { for(AssociationID a : associations.keySet()) { associations.get(a).remove(id); } } /** * Returns all associations for a given ID. * * @param id * the id for which the associations are to be returned * @return all associations for a given ID */ protected Map<AssociationID, Object> getAssociations(final Integer id) { Map<AssociationID, Object> idAssociations = new Hashtable<AssociationID, Object>(); for(AssociationID associationID : associations.keySet()) { if(associations.get(associationID).containsKey(id)) { idAssociations.put(associationID, associations.get(associationID).get(id)); } } return idAssociations; } /** * Sets the specified association to the specified id. * * @param id * the id which is to associate with specified associations * @param idAssociations * the associations to be associated with the specified id */ protected void setAssociations(final Integer id, final Map<AssociationID, Object> idAssociations) { for(AssociationID associationID : idAssociations.keySet()) { associate(associationID, id, idAssociations.get(associationID)); } } /** * @see Database#partition(Map) */ @SuppressWarnings("unchecked") public Map<Integer, Database<T>> partition(Map<Integer, List<Integer>> partitions) throws UnableToComplyException { Map<Integer, Database<T>> databases = new Hashtable<Integer, Database<T>>(); for(Integer partitionID : partitions.keySet()) { List<Map<AssociationID, Object>> associations = new ArrayList<Map<AssociationID, Object>>(); List<T> objects = new ArrayList<T>(); List<Integer> ids = partitions.get(partitionID); for(Integer id : ids) { objects.add((T) get(id).copy()); associations.add(getAssociations(id)); } Database<T> database; try { database = (Database<T>) getClass().newInstance(); database.setParameters(getParameters()); database.insert(objects, associations); databases.put(partitionID, database); } catch(InstantiationException e) { throw new UnableToComplyException(e.getMessage()); } catch(IllegalAccessException e) { throw new UnableToComplyException(e.getMessage()); } } return databases; } /** * SequentialDatabase does not require any parameters. Thus, this method * returns the given parameters unchanged. * * @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#setParameters(String[]) */ public String[] setParameters(String[] args) { this.parameters = Util.copy(args); return args; } /** * Returns the parameter setting of the attributes. * * @return the parameter setting of the attributes */ public List<AttributeSettings> getParameterSettings() { return new ArrayList<AttributeSettings>(); } /** * Returns a copy of the parameter array as it has been given in the * setParameters method. * * @return a copy of the parameter array as it has been given in the * setParameters method */ public String[] getParameters() { return Util.copy(this.parameters); } /** * Checks whether an association is set for every id in the database. * * @param associationID * an association id to be checked * @return true, if the association is set for every id in the database, * false otherwise */ public boolean isSet(AssociationID associationID) { boolean isSet = true; for(Iterator<Integer> dbIter = this.iterator(); dbIter.hasNext() && isSet;) { Integer id = dbIter.next(); isSet = isSet && this.getAssociation(associationID, id) != null; } return isSet; } /** * @see de.lmu.ifi.dbs.database.Database#randomSample(int, long) */ public List<Integer> randomSample(int k, long seed) { if(k < 0) { throw new IllegalArgumentException("Illegal value for size of random sample: " + k); } List<Integer> sample = new ArrayList<Integer>(k); Integer[] ids = new Integer[this.size()]; // get all ids { int i = 0; for(Iterator<Integer> dbIter = this.iterator(); dbIter.hasNext(); i++) { ids[i] = dbIter.next(); } } Random random = new Random(seed); for(int i = 0; i < k; i++) { sample.add(ids[random.nextInt(ids.length)]); } return sample; } /** * @see de.lmu.ifi.dbs.database.Database#kNNQuery(java.lang.Integer, int, * de.lmu.ifi.dbs.distance.DistanceFunction) */ // public <D extends Distance> List<QueryResult<D>> kNNQuery(Integer id, int k, DistanceFunction<T, D> distanceFunction) // T queryObject = this.get(id); // return kNNQuery(queryObject, k, distanceFunction); /** * @see Database#dimensionality() */ public int dimensionality() throws UnsupportedOperationException { Iterator<Integer> iter = this.iterator(); if(iter.hasNext()) { T entry = this.get(iter.next()); if(entry instanceof FeatureVector) { // noinspection unchecked return ((FeatureVector) entry).getDimensionality(); } else { throw new UnsupportedOperationException("Database entries are not implementing interface " + FeatureVector.class.getName() + "."); } } else { throw new UnsupportedOperationException("Database is empty."); } } }
package org.codehaus.xfire; import java.io.InputStream; import java.io.OutputStream; import javax.xml.stream.XMLStreamReader; import org.codehaus.xfire.service.ServiceRegistry; import org.codehaus.xfire.transport.TransportManager; /** * <p>Central processing point for XFire. This can be instantiated * programmatically by using one of the implementations (such as * <code>DefaultXFire</code> or can be managed by a container like * Pico or Plexus. * </p> * <p> * Central, however, does not mean that there can be only one. * Implementations can be very lightweight, creating fast generic * SOAP processors. * </p> * @author <a href="mailto:dan@envoisolutions.com">Dan Diephouse</a> * @since Feb 18, 2004 */ public interface XFire { final public static String ROLE = XFire.class.getName(); /** * Processes a new SOAP Message request. Faults are handled * according to the message contract of the particular service. * A <code>XFireRuntimeException</code>s may still be thrown if * something fatal goes wrong in the pipeline. * * @param in An InputStream to the SOAP document. * @param context The MessageContext. */ void invoke(InputStream in, MessageContext context) throws XFireRuntimeException; /** * Processes a new SOAP Message request. Faults are handled * according to the message contract of the particular service. * A <code>XFireRuntimeException</code>s may still be thrown if * something fatal goes wrong in the pipeline. * * @param in An InputStream to the SOAP document. * @param context The MessageContext. */ void invoke(XMLStreamReader reader, MessageContext context) throws XFireRuntimeException; /** * Generate WSDL for a service. * * @param service * The name of the service. * @param out * The OutputStream to write the WSDL to. */ void generateWSDL(String service, OutputStream out); /** * Get the <code>ServiceRegistry</code>. */ ServiceRegistry getServiceRegistry(); /** * Get the <code>TransportManager</code>. */ TransportManager getTransportManager(); }
package de.shandschuh.slightbackup.parser; import org.xml.sax.helpers.DefaultHandler; import android.content.Context; import de.shandschuh.slightbackup.R; import de.shandschuh.slightbackup.Strings; public abstract class Parser extends DefaultHandler { protected static final String COUNT = "count"; protected Context context; protected ImportTask importTask; protected boolean canceled; private StringBuilder hintStringBuilder; public Parser(Context context, ImportTask importTask) { this.context = context; this.importTask = importTask; } public final void cancel() { canceled = true; } public boolean isCanceled() { return canceled; } public static Parser createParserByFilename(String filename, Context context, ImportTask importTask) { filename = filename.substring(filename.lastIndexOf('/')+1); if (filename.startsWith(Strings.CALLLOGS)) { return new CallLogParser(context, importTask); } else if (filename.startsWith(Strings.MESSAGES)) { return new MessageParser(context, importTask); } else if (filename.startsWith(Strings.BOOKMARKS)) { return new BookmarkParser(context, importTask); } else if (filename.startsWith(Strings.USERDICTIONARY)) { return new UserDictionaryParser(context, importTask); } else if (filename.startsWith(Strings.PLAYLISTS)) { return new PlaylistParser(context, importTask); } else if (filename.startsWith(Strings.SETTINGS)) { return new SettingsParser(context, importTask); } return null; } public static int getTranslatedParserName(String filename) { filename = filename.substring(filename.lastIndexOf('/')+1); if (filename.startsWith(Strings.CALLLOGS)) { return R.string.calllogs; } else if (filename.startsWith(Strings.MESSAGES)) { return R.string.messages; } else if (filename.startsWith(Strings.BOOKMARKS)) { return R.string.bookmarks; } else if (filename.startsWith(Strings.USERDICTIONARY)) { return R.string.userdictionary; } else if (filename.startsWith(Strings.PLAYLISTS)) { return R.string.playlists; } else if (filename.startsWith(Strings.SETTINGS)) { return R.string.settings; } return android.R.string.unknownName; } public void addHint(CharSequence charSequence) { if (hintStringBuilder == null) { hintStringBuilder = new StringBuilder(charSequence); } else { hintStringBuilder.append('\n'); hintStringBuilder.append(charSequence); } } public StringBuilder getHints() { return hintStringBuilder; } public boolean hasHints() { return hintStringBuilder != null && hintStringBuilder.length() > 0; } }
package de.ust.skill.common.jvm.streams; import java.nio.ByteBuffer; /** * Implementations of this class are used to turn a byte stream into a stream of integers and floats. * * @author Timm Felden */ public abstract class InStream { protected final ByteBuffer input; protected InStream(ByteBuffer input) { this.input = input; } /** * @return take an f64 from the stream */ final public double f64() { return input.getDouble(); } /** * @return take an f32 from the stream */ public final float f32() { return input.getFloat(); } /** * @return take an v64 from the stream */ public final long v64() { long rval; return (0 != ((rval = i8()) & 0x80)) ? multiByteV64(rval) : rval; } /** * multi byte v64 values are treated in a different function to enable inlining of more common single byte v64 * values */ @SuppressWarnings("all") private long multiByteV64(long rval) { long r; rval = (rval & 0x7f) | (((r = i8()) & 0x7f) << 7); if (0 != (r & 0x80)) { rval |= ((r = i8()) & 0x7f) << 14; if (0 != (r & 0x80)) { rval |= ((r = i8()) & 0x7f) << 21; if (0 != (r & 0x80)) { rval |= ((r = i8()) & 0x7f) << 28; if (0 != (r & 0x80)) { rval |= ((r = i8()) & 0x7f) << 35; if (0 != (r & 0x80)) { rval |= ((r = i8()) & 0x7f) << 42; if (0 != (r & 0x80)) { rval |= ((r = i8()) & 0x7f) << 49; if (0 != (r & 0x80)) { rval |= (((long) i8()) << 56); } } } } } } } return rval; } /** * @return take an i64 from the stream */ public final long i64() { return input.getLong(); } /** * @return take an i32 from the stream * @throws UnexpectedEOF * if there is no i32 in the stream */ public final int i32() { return input.getInt(); } /** * @return take an i16 from the stream */ public final short i16() { return input.getShort(); } /** * @return take an i8 from the stream */ public final byte i8() { return input.get(); } /** * @return take a bool from the stream */ public final boolean bool() { return input.get() != 0; } /** * @return raw byte array taken from the stream */ public final byte[] bytes(long length) { final byte[] rval = new byte[(int) length]; input.get(rval); return rval; } /** * @return true iff there are at least n bytes left in the stream */ public final boolean has(int n) { return input.limit() >= n + input.position(); } /** * @return true iff at the end of file (or stream) */ public final boolean eof() { return input.limit() == input.position(); } /** * use with care! * * @param position * jump to target position, without the ability to restore the old position */ public abstract void jump(long position); final public long position() { return input.position(); } }
package org.eclipse.birt.report.model.api.util; import java.math.BigDecimal; import java.text.ParseException; import java.util.Date; import java.util.Locale; import org.eclipse.birt.core.data.DataTypeUtil; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.core.format.DateFormatter; import org.eclipse.birt.core.format.NumberFormatter; import org.eclipse.birt.core.format.StringFormatter; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.birt.report.model.api.metadata.PropertyValueException; import org.eclipse.birt.report.model.api.metadata.ValidationValueException; import org.eclipse.birt.report.model.i18n.ModelMessages; import org.eclipse.birt.report.model.metadata.BooleanPropertyType; import com.ibm.icu.text.DateFormat; import com.ibm.icu.text.NumberFormat; import com.ibm.icu.util.ULocale; import com.ibm.icu.util.UResourceBundle; /** * Validates the parameter value with the given data type and format pattern * string. This util class can validate the parameter of the following types: * * <ul> * <li><code>PARAM_TYPE_DATETIME</code></li> * <li><code>PARAM_TYPE_FLOAT</code></li> * <li><code>PARAM_TYPE_DECIMAL</code></li> * <li><code>PARAM_TYPE_BOOLEAN</code></li> * <li><code>PARAM_TYPE_STRING</code></li> * <li><code>PARAM_TYPE_INTEGER</code></li> * </ul> * * @see org.eclipse.birt.report.model.api.elements.DesignChoiceConstants */ public class ParameterValidationUtil { /** * Default locale of the validation issues. If the caller does not provide * the locale information, we will use it. */ private static final ULocale DEFAULT_LOCALE = ULocale.US; /** * Default date-time format string. */ public static final String DEFAULT_DATETIME_FORMAT = "MM/dd/yyyy hh:mm:ss a"; //$NON-NLS-1$ /** * Validates a input parameter value with the given data type. The returned * value is locale and format independent. The data type can be one of the * following: * * <ul> * <li><code>PARAM_TYPE_DATETIME</code></li> * <li><code>PARAM_TYPE_FLOAT</code></li> * <li><code>PARAM_TYPE_DECIMAL</code></li> * <li><code>PARAM_TYPE_BOOLEAN</code></li> * <li><code>PARAM_TYPE_STRING</code></li> * </ul> * * @param dataType * the data type of the value * @param value * the input value to validate * @param locale * the locale information * @return the validated value if the input value is valid for the given * data type * @throws ValidationValueException * if the input value is not valid with the given data type */ static private Object validate( String dataType, String value, ULocale locale ) throws ValidationValueException { if ( value == null ) return null; if ( DesignChoiceConstants.PARAM_TYPE_DATETIME .equalsIgnoreCase( dataType ) ) return doVidateDateTime( value, locale ); else if ( DesignChoiceConstants.PARAM_TYPE_FLOAT .equalsIgnoreCase( dataType ) ) { Number number = doValidateNumber( dataType, value, locale ); if ( number == null ) return null; return new Double( number.doubleValue( ) ); } else if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL .equalsIgnoreCase( dataType ) ) { Number number = doValidateNumber( dataType, value, locale ); if ( number == null ) return null; return new BigDecimal( number.toString( ) ); } else if ( DesignChoiceConstants.PARAM_TYPE_INTEGER .equalsIgnoreCase( dataType ) ) { Number number = doValidateNumber( dataType, value, locale ); if ( number == null ) return null; return new Integer( number.intValue( ) ); } else if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN .equalsIgnoreCase( dataType ) ) { return doValidateBoolean( value, locale ); } else if ( DesignChoiceConstants.PARAM_TYPE_STRING .equalsIgnoreCase( dataType ) ) { return value; } else { assert false; return null; } } /** * Validates the input value at the given locale. The format is: short date * and medium time. * * @param value * the value to validate * @param locale * the locale information * @return the date value if validation is successful * @throws ValidationValueException * if the value is invalid */ static final Date doVidateDateTime( String value, ULocale locale ) throws ValidationValueException { try { return DataTypeUtil.toDate( value, locale ); } catch ( BirtException e ) { throw new ValidationValueException( value, PropertyValueException.DESIGN_EXCEPTION_INVALID_VALUE, DesignChoiceConstants.PARAM_TYPE_DATETIME ); } } /** * Validates the input value at the given locale. The format is: general * number. * * @param dataType * the data type * @param value * the value to validate * @param locale * the locale information * @return the double value if validation is successful * @throws ValidationValueException * if the value is invalid */ static final Number doValidateNumber( String dataType, String value, ULocale locale ) throws ValidationValueException { assert DesignChoiceConstants.PARAM_TYPE_FLOAT .equalsIgnoreCase( dataType ) || DesignChoiceConstants.PARAM_TYPE_DECIMAL .equalsIgnoreCase( dataType ) || DesignChoiceConstants.PARAM_TYPE_INTEGER .equalsIgnoreCase( dataType ); value = StringUtil.trimString( value ); if ( value == null ) return null; NumberFormat localeFormatter = DesignChoiceConstants.PARAM_TYPE_INTEGER .equalsIgnoreCase( dataType ) ? NumberFormat .getIntegerInstance( locale ) : NumberFormat .getNumberInstance( locale ); try { // Parse in locale-dependent way. // Use the decimal separator from the locale. return localeFormatter.parse( value ); } catch ( ParseException e ) { throw new ValidationValueException( value, PropertyValueException.DESIGN_EXCEPTION_INVALID_VALUE, dataType ); } } static public Object validate( String dataType, String format, String value, Locale locale ) throws ValidationValueException { return validate( dataType, format, value, ULocale.forLocale( locale ) ); } static public Object validate( String dataType, String format, String value, ULocale locale ) throws ValidationValueException { if ( value == null ) return null; if ( StringUtil.isBlank( format ) ) return validate( dataType, value, locale ); try { if ( DesignChoiceConstants.PARAM_TYPE_DATETIME .equalsIgnoreCase( dataType ) ) return doValidateDateTimeByPattern( format, value, locale ); else if ( DesignChoiceConstants.PARAM_TYPE_FLOAT .equalsIgnoreCase( dataType ) ) { Number number = doValidateNumberByPattern( dataType, format, value, locale ); if ( number == null ) return null; return new Double( number.doubleValue( ) ); } else if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL .equalsIgnoreCase( dataType ) ) { Number number = doValidateNumberByPattern( dataType, format, value, locale ); if ( number == null ) return null; return new BigDecimal( number.toString( ) ); } else if ( DesignChoiceConstants.PARAM_TYPE_INTEGER .equalsIgnoreCase( dataType ) ) { Number number = doValidateNumberByPattern( dataType, format, value, locale ); if ( number == null ) return null; return new Integer( number.intValue( ) ); } else if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN .equalsIgnoreCase( dataType ) ) { return doValidateBoolean( value, locale ); } else if ( DesignChoiceConstants.PARAM_TYPE_STRING .equalsIgnoreCase( dataType ) ) { if ( StringUtil.isBlank( value ) ) return value; else if ( DesignChoiceConstants.STRING_FORMAT_TYPE_UNFORMATTED .equalsIgnoreCase( format ) ) return value; else { StringFormatter formatter = new StringFormatter( locale ); formatter.applyPattern( format ); try { return formatter.parser( value ); } catch ( ParseException e ) { throw new ValidationValueException( value, PropertyValueException.DESIGN_EXCEPTION_INVALID_VALUE, DesignChoiceConstants.PARAM_TYPE_STRING ); } } } else { assert false; return null; } } catch ( ValidationValueException e ) { return validate( dataType, value, locale ); } } static public Object validate( String dataType, String format, String value ) throws ValidationValueException { return validate( dataType, format, value, DEFAULT_LOCALE ); } /** * Validates the input boolean value with the given locale. * * @param value * the input value to validate * @param locale * the locale information * @return the <code>Boolean</code> object if the input is valid, * otherwise <code>null</code> * @throws ValidationValueException */ static private Boolean doValidateBoolean( String value, ULocale locale ) throws ValidationValueException { if ( StringUtil.isBlank( value ) ) return null; // 1. Internal boolean name. if ( value.equalsIgnoreCase( BooleanPropertyType.TRUE ) ) return Boolean.TRUE; else if ( value.equalsIgnoreCase( BooleanPropertyType.FALSE ) ) return Boolean.FALSE; // 2. A localized Boolean name. Convert the localized // Boolean name into Boolean instance. if ( value.equalsIgnoreCase( getMessage( locale, BooleanPropertyType.BOOLEAN_TRUE_RESOURCE_KEY ) ) ) { return Boolean.TRUE; } else if ( value.equalsIgnoreCase( getMessage( locale, BooleanPropertyType.BOOLEAN_FALSE_RESOURCE_KEY ) ) ) { return Boolean.FALSE; } throw new ValidationValueException( value, PropertyValueException.DESIGN_EXCEPTION_INVALID_VALUE, DesignChoiceConstants.PARAM_TYPE_BOOLEAN ); } /** * Gets the message with the given locale and key. * * @param locale * the locale information * @param key * the message key * @return the message if found, otherwise the message key */ static private String getMessage( ULocale locale, String key ) { // works around bug in some J2EE server; see Bugzilla #126073 String packageName = ModelMessages.class.getName( ).substring( 0, ModelMessages.class.getName( ).lastIndexOf( "." ) ); //$NON-NLS-1$ String localeName = locale == null ? null : locale.toString( ); UResourceBundle resourceBundle = UResourceBundle.getBundleInstance( packageName + ".Messages", //$NON-NLS-1$ localeName, ModelMessages.class.getClassLoader( ) ); if ( resourceBundle != null ) return resourceBundle.getString( key ); return key; } /** * Validates the input date time string with the given format. The format * can be pre-defined choices or the pattern string. * * @param format * the format to validate * @param value * the value to validate * @param locale * the locale information * @return the date value if validation is successful * @throws ValidationValueException * if the value to validate is invalid */ static private Date doValidateDateTimeByPattern( String format, String value, ULocale locale ) throws ValidationValueException { assert !StringUtil.isBlank( format ); if ( DesignChoiceConstants.DATETIEM_FORMAT_TYPE_UNFORMATTED .equalsIgnoreCase( format ) ) return doVidateDateTime( value, locale ); if ( StringUtil.isBlank( value ) ) return null; try { DateFormatter formatter = new DateFormatter( locale ); formatter.applyPattern( format ); return formatter.parse( value ); } catch ( ParseException e ) { throw new ValidationValueException( value, PropertyValueException.DESIGN_EXCEPTION_INVALID_VALUE, DesignChoiceConstants.PARAM_TYPE_DATETIME ); } } /** * Validates the input date time string with the given format. * * @param dataType * the data type of the value * @param format * the format pattern * @param value * the value to validate * @param locale * the locale information * @return the double value if the validation is successful * @throws ValidationValueException * if the value to validate is invalid */ static private Number doValidateNumberByPattern( String dataType, String format, String value, ULocale locale ) throws ValidationValueException { assert DesignChoiceConstants.PARAM_TYPE_FLOAT .equalsIgnoreCase( dataType ) || DesignChoiceConstants.PARAM_TYPE_DECIMAL .equalsIgnoreCase( dataType ) || DesignChoiceConstants.PARAM_TYPE_INTEGER .equalsIgnoreCase( dataType ); if ( DesignChoiceConstants.NUMBER_FORMAT_TYPE_UNFORMATTED .equalsIgnoreCase( format ) ) return doValidateNumber( dataType, value, locale ); assert !StringUtil.isBlank( format ); if ( StringUtil.isBlank( value ) ) return null; NumberFormatter formatter = new NumberFormatter( locale ); formatter.applyPattern( format ); try { return formatter.parse( value ); } catch ( ParseException e ) { throw new ValidationValueException( value, PropertyValueException.DESIGN_EXCEPTION_INVALID_VALUE, dataType ); } } /** * Gets the display string for the value with the given data type, format, * locale. The value must be the valid data type. That is: * * <ul> * <li>if data type is <code>PARAM_TYPE_DATETIME</code>, then the value * must be <code>java.util.Date<code>.</li> * <li>if the data type is <code>PARAM_TYPE_FLOAT</code>, then the value must * be <code>java.lang.Double</code>.</li> * <li>if the data type is <code>PARAM_TYPE_DECIMAL</code>, then the value must * be <code>java.math.BigDecimal</code>.</li> * <li>if the data type is <code>PARAM_TYPE_BOOLEAN</code>, then the value must * be <code>java.lang.Boolean</code>.</li> * <li>if the data type is <code>PARAM_TYPE_STRING</code>, then the value must * be <code>java.lang.String</code>.</li> * </ul> * * @param dataType * the data type of the input value * @param format * the format pattern to validate * @param value * the input value to validate * @param locale * the locale information * @return the formatted string */ static public String getDisplayValue( String dataType, String format, Object value, Locale locale ) { return getDisplayValue( dataType, format, value, ULocale .forLocale( locale ) ); } /** * Gets the display string for the value with default locale and default * format, The value must be the valid data type. That is: * * <ul> * <li>if data type is <code>PARAM_TYPE_DATETIME</code>, then the value * must be <code>java.util.Date<code>.</li> * <li>if the data type is <code>PARAM_TYPE_FLOAT</code>, then the value must * be <code>java.lang.Double</code>.</li> * <li>if the data type is <code>PARAM_TYPE_DECIMAL</code>, then the value must * be <code>java.math.BigDecimal</code>.</li> * <li>if the data type is <code>PARAM_TYPE_BOOLEAN</code>, then the value must * be <code>java.lang.Boolean</code>.</li> * <li>if the data type is <code>PARAM_TYPE_STRING</code>, then the value must * be <code>java.lang.String</code>.</li> * </ul> * * @param value * the input value to validate * @return the formatted string */ static public String getDisplayValue( Object value ) { if ( value == null ) return null; if ( value instanceof Date ) { DateFormatter formatter = new DateFormatter( DEFAULT_LOCALE ); formatter.applyPattern( DEFAULT_DATETIME_FORMAT ); return formatter.format( (Date) value ); } else if ( value instanceof Float ) { NumberFormatter formatter = new NumberFormatter( DEFAULT_LOCALE ); return formatter.format( ( (Number) value ).floatValue( ) ); } else if ( value instanceof Double ) { NumberFormatter formatter = new NumberFormatter( DEFAULT_LOCALE ); return formatter.format( ( (Number) value ).doubleValue( ) ); } else if ( value instanceof BigDecimal ) { NumberFormatter formatter = new NumberFormatter( DEFAULT_LOCALE ); return formatter.format( ( (BigDecimal) value ) ); } else if ( value instanceof Integer || value instanceof Long ) { NumberFormatter formatter = new NumberFormatter( DEFAULT_LOCALE ); return formatter.format( ( (Number) value ).longValue( ) ); } else if ( value instanceof Boolean ) { if ( ( (Boolean) value ).booleanValue( ) ) { return getMessage( DEFAULT_LOCALE, BooleanPropertyType.BOOLEAN_TRUE_RESOURCE_KEY ); } return getMessage( DEFAULT_LOCALE, BooleanPropertyType.BOOLEAN_FALSE_RESOURCE_KEY ); } else if ( value instanceof String ) { StringFormatter formatter = new StringFormatter( DEFAULT_LOCALE ); return formatter.format( (String) value ); } else { StringFormatter formatter = new StringFormatter( DEFAULT_LOCALE ); return formatter.format( value.toString( ) ); } } /** * Gets the display string for the value with the given data type, format, * locale. The value must be the valid data type. That is: * * <ul> * <li>if data type is <code>PARAM_TYPE_DATETIME</code>, then the value * must be <code>java.util.Date<code>.</li> * <li>if the data type is <code>PARAM_TYPE_FLOAT</code>, then the value must * be <code>java.lang.Double</code>.</li> * <li>if the data type is <code>PARAM_TYPE_DECIMAL</code>, then the value must * be <code>java.math.BigDecimal</code>.</li> * <li>if the data type is <code>PARAM_TYPE_BOOLEAN</code>, then the value must * be <code>java.lang.Boolean</code>.</li> * <li>if the data type is <code>PARAM_TYPE_STRING</code>, then the value must * be <code>java.lang.String</code>.</li> * </ul> * * @param dataType * the data type of the input value * @param format * the format pattern to validate * @param value * the input value to validate * @param locale * the locale information * @return the formatted string */ static public String getDisplayValue( String dataType, String format, Object value, ULocale locale ) { if ( value == null ) return null; if ( StringUtil.isBlank( format ) ) { return getDisplayValue( dataType, value, locale ); } if ( DesignChoiceConstants.PARAM_TYPE_DATETIME .equalsIgnoreCase( dataType ) || value instanceof Date ) { DateFormatter formatter = new DateFormatter( locale ); formatter.applyPattern( format ); return formatter.format( (Date) value ); } else if ( DesignChoiceConstants.PARAM_TYPE_FLOAT .equalsIgnoreCase( dataType ) || value instanceof Float || value instanceof Double ) { if ( value instanceof Float ) { NumberFormatter formatter = new NumberFormatter( locale ); formatter.applyPattern( format ); return formatter.format( ( (Number) value ).floatValue( ) ); } else { NumberFormatter formatter = new NumberFormatter( locale ); formatter.applyPattern( format ); return formatter.format( ( (Number) value ).doubleValue( ) ); } } else if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL .equalsIgnoreCase( dataType ) || value instanceof BigDecimal ) { NumberFormatter formatter = new NumberFormatter( locale ); formatter.applyPattern( format ); return formatter.format( ( (BigDecimal) value ) ); } else if ( DesignChoiceConstants.PARAM_TYPE_INTEGER .equalsIgnoreCase( dataType ) || value instanceof Integer || value instanceof Long ) { NumberFormatter formatter = new NumberFormatter( locale ); formatter.applyPattern( format ); return formatter.format( ( (Number) value ).longValue( ) ); } else if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN .equalsIgnoreCase( dataType ) || value instanceof Boolean ) { if ( ( (Boolean) value ).booleanValue( ) ) { return getMessage( locale, BooleanPropertyType.BOOLEAN_TRUE_RESOURCE_KEY ); } return getMessage( locale, BooleanPropertyType.BOOLEAN_FALSE_RESOURCE_KEY ); } else if ( DesignChoiceConstants.PARAM_TYPE_STRING .equalsIgnoreCase( dataType ) || value instanceof String ) { StringFormatter formatter = new StringFormatter( locale ); formatter.applyPattern( format ); return formatter.format( (String) value ); } else { StringFormatter formatter = new StringFormatter( locale ); formatter.applyPattern( format ); return formatter.format( value.toString( ) ); } } /** * Gets the display string for the value with the given data type, format * and the default locale defined by the class(Locale.US). The value must be * the valid data type. That is: * * <ul> * <li>if data type is <code>PARAM_TYPE_DATETIME</code>, then the value * must be <code>java.util.Date<code>.</li> * <li>if the data type is <code>PARAM_TYPE_FLOAT</code>, then the value must * be <code>java.lang.Double</code>.</li> * <li>if the data type is <code>PARAM_TYPE_DECIMAL</code>, then the value must * be <code>java.math.BigDecimal</code>.</li> * <li>if the data type is <code>PARAM_TYPE_BOOLEAN</code>, then the value must * be <code>java.lang.Boolean</code>.</li> * <li>if the data type is <code>PARAM_TYPE_STRING</code>, then the value must * be <code>java.lang.String</code>.</li> * </ul> * * @param dataType * the data type of the input value * @param format * the format pattern to validate * @param value * the input value to validate * @return the formatted string */ static public String getDisplayValue( String dataType, String format, Object value ) { return getDisplayValue( dataType, format, value, DEFAULT_LOCALE ); } /** * Gets the display string for the value with the given data type and the * locale. The value must be the valid data type. * * @param dataType * the data type of the input value * @param value * the input value to validate * @param locale * the locale information * @return the formatted string * */ static private String getDisplayValue( String dataType, Object value, ULocale locale ) { if ( DesignChoiceConstants.PARAM_TYPE_DATETIME .equalsIgnoreCase( dataType ) || value instanceof Date ) { DateFormat formatter = DateFormat.getDateTimeInstance( DateFormat.MEDIUM, DateFormat.MEDIUM, locale ); return formatter.format( (Date) value ); } else if ( DesignChoiceConstants.PARAM_TYPE_FLOAT .equalsIgnoreCase( dataType ) || value instanceof Float || value instanceof Double ) { if ( value instanceof Float ) { NumberFormat formatter = NumberFormat .getNumberInstance( locale ); return formatter.format( ( (Number) value ).floatValue( ) ); } else { NumberFormat formatter = NumberFormat .getNumberInstance( locale ); return formatter.format( ( (Number) value ).doubleValue( ) ); } } else if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL .equalsIgnoreCase( dataType ) || value instanceof BigDecimal ) { NumberFormat formatter = NumberFormat.getNumberInstance( locale ); return formatter.format( ( (BigDecimal) value ) ); } else if ( DesignChoiceConstants.PARAM_TYPE_INTEGER .equalsIgnoreCase( dataType ) || value instanceof Integer || value instanceof Long ) { NumberFormat formatter = NumberFormat.getNumberInstance( locale ); return formatter.format( ( (Number) value ).longValue( ) ); } else if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN .equalsIgnoreCase( dataType ) || value instanceof Boolean ) { if ( ( (Boolean) value ).booleanValue( ) ) { return getMessage( locale, BooleanPropertyType.BOOLEAN_TRUE_RESOURCE_KEY ); } return getMessage( locale, BooleanPropertyType.BOOLEAN_FALSE_RESOURCE_KEY ); } else if ( DesignChoiceConstants.PARAM_TYPE_STRING .equalsIgnoreCase( dataType ) || value instanceof String ) { return (String) value; } else { return value.toString( ); } } }
package dk.itu.jglyph.features; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import dk.itu.jglyph.Edge; import dk.itu.jglyph.JGlyph; import dk.itu.jglyph.Node; public class FeatureExtractors { private static FeatureExtractors instance = null; private List<IFeatureExtractor> extractors; private List<String> descriptions; private FeatureExtractors() { extractors = new ArrayList<>(); descriptions = new ArrayList<>(); addExtractor((JGlyph g) -> minAngle(g), "Minimum angle."); addExtractor((JGlyph g) -> avgAngle(g), "Average angle."); addExtractor((JGlyph g) -> maxAngle(g), "Maximum angle."); addExtractor((JGlyph g) -> minDistanceToCenter(g), "Minimum distance to center."); addExtractor((JGlyph g) -> avgDistanceToCenter(g), "Average distance to center"); addExtractor((JGlyph g) -> maxDistanceToCenter(g), "Maximum distance to center."); addExtractor((JGlyph g) -> minEdgeLength(g), "Minimum edge length."); addExtractor((JGlyph g) -> avgEdgeLength(g), "Average edge length."); addExtractor((JGlyph g) -> maxEdgeLength(g), "Maximum edge length."); addExtractor((JGlyph g) -> avgStrokeEndsX(g), "Average stroke ends X."); addExtractor((JGlyph g) -> avgStrokeEndsY(g), "Average stroke ends Y."); addExtractor((JGlyph g) -> unitCount(g), "Unit count."); addExtractor((JGlyph g) -> edgeCount(g), "Edge count."); addExtractor((JGlyph g) -> strokeEstimate(g), "Stroke count estimate."); } private void addExtractor(IFeatureExtractor extractor, String description) { extractors.add(extractor); descriptions.add(description); } public IFeatureExtractor getExtractor(int index) { return extractors.get(index); } public double[] extractFeatures(JGlyph glyph) { int length = extractors.size(); double[] features = new double[length]; for(int i = 0; i < length; ++i) { IFeatureExtractor extractor = extractors.get(i); features[i] = extractor.extract(glyph); } return(features); } public String getDescription(int index) { return descriptions.get(index); } public int count() { return extractors.size(); } public static FeatureExtractors getInstance() { if(instance == null) { instance = new FeatureExtractors(); } return(instance); } public static double minAngle(JGlyph glyph) { List<Double> angles = getAngles(glyph); if (angles.size() == 0) return Math.PI; double min = Double.MAX_VALUE; for (Double d : angles) { if (d < min && d != 0) min = d; // TODO do we need to use epsilon for the last comparison? } return min; } public static double avgAngle(JGlyph glyph) { List<Double> angles = getAngles(glyph); if (angles.size() == 0) return Math.PI; double sum = 0; // System.out.println(angles); for (Double d : angles) { sum += d; } return sum / angles.size(); } public static double maxAngle(JGlyph glyph) { List<Double> angles = getAngles(glyph); if (angles.size() == 0) return Math.PI; double max = Double.MIN_VALUE; for (Double d : angles) { if (d > max) max = d; } return max; } private static List<Double> getAngles(JGlyph g) { List<Double> result = new ArrayList<Double>(); for (Node node : g.getNodes()) { // TODO x/y cannot be double with our current creation scheme int id = g.getNodeId((int)node.x, (int)node.y); List<Edge> edges = g.getEdges(id); for (int i = 0; i < edges.size(); i++) { for (int j = i+1; j < edges.size(); j++) { Edge e1 = edges.get(i); Edge e2 = edges.get(j); Node n1 = node.equals(e1.from) ? e1.to : e1.from; Node n2 = node.equals(e2.from) ? e2.to : e2.from; //Skip dots if (node.equals(n1) || node.equals(n2)) continue; // TODO 0/180 could be sorted our here but we might need that for other metrics result.add(getAngle(node, n1, n2)); } } } return result; } private static Double getAngle(Node center, Node n1, Node n2) { double x1 = n1.x - center.x; double x2 = n2.x - center.x; double y1 = n1.y - center.y; double y2 = n2.y - center.y; double dot = x1*x2 + y1*y2; double l1 = Math.sqrt(x1*x1 + y1*y1); double l2 = Math.sqrt(x2*x2 + y2*y2); return Math.acos(dot/(l1*l2)); } /** Minimum distance from center for stroke start/end */ public static double minDistanceToCenter(JGlyph glyph) { List<Node> ends = glyph.getEndsOfStrokes(); if(ends.isEmpty()) { return(0); } Node centroid = glyph.getCentroid(); double minSq = Double.MAX_VALUE; for(Node end : glyph.getEndsOfStrokes()) { double distSq = end.distanceSq(centroid); if(distSq < minSq) { minSq = distSq; } } double min = Math.sqrt(minSq); return(min); } /** Average distance from center for stroke start/end */ public static double avgDistanceToCenter(JGlyph glyph) { List<Node> ends = glyph.getEndsOfStrokes(); int count = ends.size(); if(count == 0) { return(0); } Node centroid = glyph.getCentroid(); double sum = 0; for(Node end : ends) { sum += end.distance(centroid); } double average = sum / count; return(average); } /** Maximum distance from center for stroke start/end */ public static double maxDistanceToCenter(JGlyph glyph) { List<Node> ends = glyph.getEndsOfStrokes(); if(ends.isEmpty()) { return(0); } Node centroid = glyph.getCentroid(); double maxSq = Double.MIN_VALUE; for(Node end : glyph.getEndsOfStrokes()) { double distSq = end.distanceSq(centroid); if(distSq > maxSq) { maxSq = distSq; } } double max = Math.sqrt(maxSq); return(max); } /** Number of edges */ public static double edgeCount(JGlyph glyph) { int count = glyph.getEdges().size(); return(count); } /** Number of connected units */ public static double unitCount(JGlyph glyph) { Iterable<Edge> edges = glyph.getEdges(); // List of sets found List<List<Node>> sets = new ArrayList<List<Node>>(); for (Edge edge : edges) { // Set of nodes that are connected to this edge List<Node> currentSet = new ArrayList<Node>(); currentSet.add(edge.from); currentSet.add(edge.to); if (sets.size() > 0) { for (Iterator<List<Node>> iterator = sets.iterator(); iterator.hasNext();) { List<Node> set = iterator.next(); if (set.contains(edge.from) || set.contains(edge.to)) { currentSet.addAll(set); iterator.remove(); } // TODO test if the edge crosses the set } } sets.add(currentSet); } return sets.size(); } /** An estimate for how many strokes would be needed to draw this */ public static double strokeEstimate(JGlyph glyph) { List<Node> ends = glyph.getEndsOfStrokes(); int count = ends.size(); int estimate = count / 2; return(estimate); } /** Average X for all edges */ public static double avgX(JGlyph glyph) { double sum = 0; int count = 0; for (Edge edge : glyph.getEdges()) { sum += edge.from.x + edge.to.x; count++; } return sum/(count*2); } /** Average Y for all edges */ public static double avgY(JGlyph glyph) { double sum = 0; int count = 0; for (Edge edge : glyph.getEdges()) { sum += edge.from.y + edge.to.y; count++; } return sum/(count*2); } /** Average X for stroke ends */ public static double avgStrokeEndsX(JGlyph glyph) { List<Node> ends = glyph.getEndsOfStrokes(); int count = ends.size(); Node centroid = glyph.getCentroid(); if(count == 0) { return(centroid.x); } double sum = 0; for(Node end : ends) { sum += end.x; } double average = sum / count; return(average); } /** Average Y for stroke ends */ public static double avgStrokeEndsY(JGlyph glyph) { List<Node> ends = glyph.getEndsOfStrokes(); int count = ends.size(); Node centroid = glyph.getCentroid(); if(count == 0) { return(centroid.y); } double sum = 0; for(Node end : ends) { sum += end.y; } double average = sum / count; return(average); } /** Minimum edge length */ public static double minEdgeLength(JGlyph glyph) { double minLength = Double.MAX_VALUE; for (Edge edge : glyph.getEdges()) { double length = length(edge); if (length < minLength) minLength = length; } return minLength; } /** Maximum edge length */ public static double maxEdgeLength(JGlyph glyph) { double maxLength = Double.MIN_VALUE; for (Edge edge : glyph.getEdges()) { double length = length(edge); if (length > maxLength) maxLength = length; } return maxLength; } /** Average edge length */ public static double avgEdgeLength(JGlyph glyph) { double sum = 0; int count = 0; for (Edge edge : glyph.getEdges()) { sum += length(edge); count++; } return sum/count; } private static double length(Edge edge) { double dx = edge.from.x-edge.to.x; double dy = edge.from.y-edge.to.y; return Math.sqrt(dx*dx+dy*dy); } }
package com.booking.replication.applier.hbase.schema; import com.booking.replication.applier.hbase.HBaseApplier; import com.booking.replication.applier.hbase.StorageConfig; import com.booking.replication.augmenter.model.schema.SchemaAtPositionCache; import com.booking.replication.augmenter.model.schema.SchemaSnapshot; import com.booking.replication.augmenter.model.schema.SchemaTransitionSequence; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.TableExistsException; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Admin; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.io.compress.Compression; import org.apache.hadoop.hbase.util.Bytes; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.IOException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class HBaseSchemaManager { private static final Logger LOG = LogManager.getLogger(HBaseSchemaManager.class); private final Configuration hbaseConfig; private final StorageConfig storageConfig; private Connection connection; private final Map<String, Integer> seenHBaseTables = new ConcurrentHashMap<>(); private final Map<String, Object> configuration; // Mirrored tables private static final int MIRRORED_TABLE_DEFAULT_REGIONS = 16; private static final int MIRRORED_TABLE_NUMBER_OF_VERSIONS = 1000; // schema history table private static final int SCHEMA_HISTORY_TABLE_NR_VERSIONS = 1; private final boolean DRY_RUN; private static boolean USE_SNAPPY; private static final byte[] CF = Bytes.toBytes("d"); private static final ObjectMapper MAPPER = new ObjectMapper(); public HBaseSchemaManager(Map<String, Object> configuration) { DRY_RUN = (boolean) configuration.get(HBaseApplier.Configuration.DRYRUN); USE_SNAPPY = (boolean) configuration.get(HBaseApplier.Configuration.HBASE_USE_SNAPPY); this.configuration = configuration; this.storageConfig = StorageConfig.build(configuration); this.hbaseConfig = storageConfig.getConfig(); if (!DRY_RUN) { try { connection = ConnectionFactory.createConnection(storageConfig.getConfig()); LOG.info("HBaseSchemaManager successfully established connection to HBase."); } catch (IOException e) { LOG.error("HBaseSchemaManager could not connect to HBase", e); } } } public synchronized void createHBaseTableIfNotExists(String hbaseTableName) throws IOException { if (!DRY_RUN) { hbaseTableName = hbaseTableName.toLowerCase(); try ( Admin admin = connection.getAdmin()) { if (seenHBaseTables.containsKey(hbaseTableName)) { return; } if (connection == null) { connection = ConnectionFactory.createConnection(storageConfig.getConfig()); } TableName tableName; String namespace = (String) configuration.get(HBaseApplier.Configuration.TARGET_NAMESPACE); if (namespace.isEmpty()) { tableName = TableName.valueOf(hbaseTableName); } else { tableName = TableName.valueOf(namespace, hbaseTableName); } if (admin.tableExists(tableName)) { LOG.warn("Table " + tableName + " exists in HBase, but not in schema cache. Probably a case of a table that was dropped and than created again"); seenHBaseTables.put(hbaseTableName, 1); } else { HTableDescriptor tableDescriptor = new HTableDescriptor(tableName); HColumnDescriptor cd = new HColumnDescriptor("d"); if (USE_SNAPPY) { cd.setCompressionType(Compression.Algorithm.SNAPPY); } cd.setMaxVersions(MIRRORED_TABLE_NUMBER_OF_VERSIONS); tableDescriptor.addFamily(cd); tableDescriptor.setCompactionEnabled(true); admin.createTable(tableDescriptor); seenHBaseTables.put(hbaseTableName, 1); LOG.warn("Created hbase table " + hbaseTableName); } } catch (IOException e) { throw new IOException("Failed to create table in HBase", e); } } } public void writeSchemaSnapshot(SchemaSnapshot schemaSnapshot, Map<String, Object> configuration) throws IOException, SchemaTransitionException { // get sql_statement String ddl = schemaSnapshot.getSchemaTransitionSequence().getDdl(); if (ddl == null) { throw new SchemaTransitionException("DDL can not be null"); } // get pre/post schemas SchemaAtPositionCache schemaSnapshotBefore = schemaSnapshot.getSchemaBefore(); SchemaAtPositionCache schemaSnapshotAfter = schemaSnapshot.getSchemaAfter(); Map<String, String> createStatementsBefore = schemaSnapshot.getSchemaBefore().getCreateTableStatements(); Map<String, String> createStatementsAfter = schemaSnapshot.getSchemaAfter().getCreateTableStatements(); SchemaTransitionSequence schemaTransitionSequence = schemaSnapshot.getSchemaTransitionSequence(); // json-ify // TODO: add unit test that makes sure that snapshot format is compatible with HBaseSnapshotter String jsonSchemaSnapshotBefore = MAPPER.writeValueAsString(schemaSnapshotBefore); String jsonSchemaSnapshotAfter = MAPPER.writeValueAsString(schemaSnapshotAfter); String jsonSchemaTransitionSequence = MAPPER.writeValueAsString(schemaTransitionSequence); String jsonCreateStatementsBefore = MAPPER.writeValueAsString(createStatementsBefore); String jsonCreateStatementsAfter = MAPPER.writeValueAsString(createStatementsAfter); // get event timestamp Long eventTimestamp = schemaSnapshot.getSchemaTransitionSequence().getSchemaTransitionTimestamp(); String hbaseTableName = HBaseTableNameMapper.getSchemaSnapshotHistoryHBaseTableName(configuration); String hbaseRowKey = eventTimestamp.toString(); if ((boolean)configuration.get(HBaseApplier.Configuration.INITIAL_SNAPSHOT_MODE)) { // in initial-snapshot mode timestamp is overridden by 0 so all create statements // fall under the same timestamp. This is ok since there should be only one schema // snapshot for the initial-snapshot. However, having key=0 is not good, so replace // it with: hbaseRowKey = "initial-snapshot"; } try ( Admin admin = connection.getAdmin() ) { if (connection == null) { connection = ConnectionFactory.createConnection(storageConfig.getConfig()); } TableName tableName = TableName.valueOf(hbaseTableName); if (!admin.tableExists(tableName)) { synchronized (HBaseSchemaManager.class) { if (!admin.tableExists(tableName)) { LOG.info("table " + hbaseTableName + " does not exist in HBase. Creating..."); HTableDescriptor tableDescriptor = new HTableDescriptor(tableName); HColumnDescriptor cd = new HColumnDescriptor("d"); cd.setMaxVersions(SCHEMA_HISTORY_TABLE_NR_VERSIONS); tableDescriptor.addFamily(cd); tableDescriptor.setCompactionEnabled(true); admin.createTable(tableDescriptor); } else { LOG.info("Table " + hbaseTableName + " already exists in HBase. Probably a case of other thread created it."); } } } else { LOG.info("Table " + hbaseTableName + " already exists in HBase. Probably a case of replaying the binlog."); } Put put = new Put(Bytes.toBytes(hbaseRowKey)); String ddlColumnName = "ddl"; put.addColumn( CF, Bytes.toBytes(ddlColumnName), eventTimestamp, Bytes.toBytes(ddl) ); String schemaTransitionSequenceColumnName = "schemaTransitionSequence"; put.addColumn( CF, Bytes.toBytes(schemaTransitionSequenceColumnName), eventTimestamp, Bytes.toBytes(jsonSchemaTransitionSequence) ); String schemaSnapshotPreColumnName = "schemaPreChange"; put.addColumn( CF, Bytes.toBytes(schemaSnapshotPreColumnName), eventTimestamp, Bytes.toBytes(jsonSchemaSnapshotBefore) ); String schemaSnapshotPostColumnName = "schemaPostChange"; put.addColumn( CF, Bytes.toBytes(schemaSnapshotPostColumnName), eventTimestamp, Bytes.toBytes(jsonSchemaSnapshotAfter) ); String preChangeCreateStatementsColumn = "createsPreChange"; put.addColumn( CF, Bytes.toBytes(preChangeCreateStatementsColumn), eventTimestamp, Bytes.toBytes(jsonCreateStatementsBefore) ); String postChangeCreateStatementsColumn = "createsPostChange"; put.addColumn( CF, Bytes.toBytes(postChangeCreateStatementsColumn), eventTimestamp, Bytes.toBytes(jsonCreateStatementsAfter) ); Table hbaseTable = connection.getTable(tableName); hbaseTable.put(put); hbaseTable.close(); } catch (TableExistsException tee) { LOG.warn("trying to create hbase table that already exists", tee); } catch (IOException ioe) { throw new SchemaTransitionException("Failed to store schemaChangePointSnapshot in HBase.", ioe); } } }
package dr.app.tracer.analysis; import dr.inference.trace.MarginalLikelihoodAnalysis; import jam.framework.AuxilaryFrame; import jam.framework.DocumentFrame; import javax.swing.*; import javax.swing.plaf.BorderUIResource; import javax.swing.table.AbstractTableModel; import java.awt.*; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; public class BayesFactorsFrame extends AuxilaryFrame { private List<MarginalLikelihoodAnalysis> marginalLikelihoods = new ArrayList<MarginalLikelihoodAnalysis>(); private JPanel contentPanel; private JComboBox transformCombo; private BayesFactorsModel bayesFactorsModel; private JTable bayesFactorsTable; enum Transform { LN_BF("ln ratios"), LOG10_BF("log10 ratios"), BF("ratios"); Transform(String name) { this.name = name; } public String toString() { return name; } private String name; } public BayesFactorsFrame(DocumentFrame frame, String title, String info, boolean hasErrors, boolean isAICM) { super(frame); setTitle(title); bayesFactorsModel = new BayesFactorsModel(hasErrors, isAICM); bayesFactorsTable = new JTable(bayesFactorsModel); JScrollPane scrollPane1 = new JScrollPane(bayesFactorsTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); contentPanel = new JPanel(new BorderLayout(0, 0)); contentPanel.setOpaque(false); contentPanel.setBorder(new BorderUIResource.EmptyBorderUIResource( new java.awt.Insets(0, 0, 6, 0))); JToolBar toolBar = new JToolBar(); toolBar.setLayout(new FlowLayout(FlowLayout.LEFT)); toolBar.setFloatable(false); transformCombo = new JComboBox(Transform.values()); transformCombo.setFont(UIManager.getFont("SmallSystemFont")); JLabel label = new JLabel("Show:"); label.setFont(UIManager.getFont("SmallSystemFont")); label.setLabelFor(transformCombo); toolBar.add(label); toolBar.add(transformCombo); toolBar.add(new JToolBar.Separator(new Dimension(8, 8))); contentPanel.add(toolBar, BorderLayout.NORTH); transformCombo.addItemListener( new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent ev) { bayesFactorsModel.fireTableDataChanged(); } } ); JPanel panel1 = new JPanel(new BorderLayout(0, 0)); panel1.setOpaque(false); label = new JLabel(info); label.setFont(UIManager.getFont("SmallSystemFont")); panel1.add(label, BorderLayout.NORTH); panel1.add(scrollPane1, BorderLayout.CENTER); contentPanel.add(panel1, BorderLayout.CENTER); label = new JLabel("<html>Marginal likelihood estimated using the method Newton & Raftery <br>" + "(Newton M, Raftery A: Approximate Bayesian inference with the weighted likelihood bootstrap.<br>" + "Journal of the Royal Statistical Society, Series B 1994, 56:3-48)<br>" + "with the modifications proprosed by Suchard et al (2001, <i>MBE</i> <b>18</b>: 1001-1013)</html>"); label.setFont(UIManager.getFont("SmallSystemFont")); if (isAICM) { label = new JLabel("<html>Model comparison through AICM, lower values indicate better model fit. <br> " + "Please cite: Baele, Lemey, Bedford, Rambaut, Suchard and Alekseyenko. Improving the accuracy of demographic" + " and molecular clock model comparison while accommodating phylogenetic uncertainty. In prep.</html>"); label.setFont(UIManager.getFont("SmallSystemFont")); } contentPanel.add(label, BorderLayout.SOUTH); setContentsPanel(contentPanel); getSaveAction().setEnabled(false); getSaveAsAction().setEnabled(false); getCutAction().setEnabled(false); getCopyAction().setEnabled(true); getPasteAction().setEnabled(false); getDeleteAction().setEnabled(false); getSelectAllAction().setEnabled(false); getFindAction().setEnabled(false); getZoomWindowAction().setEnabled(false); } public void addMarginalLikelihood(MarginalLikelihoodAnalysis marginalLikelihood) { this.marginalLikelihoods.add(marginalLikelihood); bayesFactorsModel.fireTableStructureChanged(); bayesFactorsTable.repaint(); } public void initializeComponents() { setSize(new Dimension(640, 480)); } public boolean useExportAction() { return true; } public JComponent getExportableComponent() { return contentPanel; } public void doCopy() { java.awt.datatransfer.Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); java.awt.datatransfer.StringSelection selection = new java.awt.datatransfer.StringSelection(bayesFactorsModel.toString()); clipboard.setContents(selection, selection); } class BayesFactorsModel extends AbstractTableModel { String[] columnNames = {"Trace", "ln P(data | model)", "S.E."}; boolean isAICM = false; private DecimalFormat formatter2 = new DecimalFormat(" private int columnCount; public BayesFactorsModel(boolean hasErrors, boolean isAICM) { this.columnCount = (hasErrors ? 3 : 2); this.isAICM = isAICM; if (isAICM) { columnNames[1] = "AICM"; } } public int getColumnCount() { return columnCount + marginalLikelihoods.size(); } public int getRowCount() { return marginalLikelihoods.size(); } public Object getValueAt(int row, int col) { if (col == 0) { return marginalLikelihoods.get(row).getTraceName(); } if (col == 1) { return formatter2.format(marginalLikelihoods.get(row).getLogMarginalLikelihood()); } else if (columnCount > 2 && col == 2) { return " +/- " + formatter2.format(marginalLikelihoods.get(row).getBootstrappedSE()); } else { if (col - columnCount != row) { double lnML1 = marginalLikelihoods.get(row).getLogMarginalLikelihood(); double lnML2 = marginalLikelihoods.get(col - columnCount).getLogMarginalLikelihood(); double lnRatio = lnML1 - lnML2; if (isAICM) { lnRatio = lnML2 - lnML1; } double value; switch ((Transform) transformCombo.getSelectedItem()) { case BF: value = Math.exp(lnRatio); break; case LN_BF: value = lnRatio; break; case LOG10_BF: value = lnRatio / Math.log(10.0); break; default: throw new IllegalArgumentException("Unknown transform type"); } return formatter2.format(value); } else { return "-"; } } } public String getColumnName(int column) { if (column < columnCount) { return columnNames[column]; } return marginalLikelihoods.get(column - columnCount).getTraceName(); } public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(getColumnName(0)); for (int j = 1; j < getColumnCount(); j++) { buffer.append("\t"); buffer.append(getColumnName(j)); } buffer.append("\n"); for (int i = 0; i < getRowCount(); i++) { buffer.append(getValueAt(i, 0)); for (int j = 1; j < getColumnCount(); j++) { buffer.append("\t"); buffer.append(getValueAt(i, j)); } buffer.append("\n"); } return buffer.toString(); } } }
package dr.evomodel.operators; import dr.evolution.tree.NodeRef; import dr.evolution.util.Taxon; import dr.evomodel.continuous.AbstractMultivariateTraitLikelihood; import dr.evomodel.continuous.SampledMultivariateTraitLikelihood; import dr.evomodel.tree.TreeModel; import dr.geo.GeoSpatialDistribution; import dr.geo.GeoSpatialCollectionModel; import dr.inference.distribution.MultivariateDistributionLikelihood; import dr.inference.model.MatrixParameter; import dr.inference.operators.GibbsOperator; import dr.inference.operators.MCMCOperator; import dr.inference.operators.OperatorFailedException; import dr.inference.operators.SimpleMCMCOperator; import dr.math.MathUtils; import dr.math.matrixAlgebra.SymmetricMatrix; import dr.math.distributions.MultivariateDistribution; import dr.math.distributions.MultivariateNormalDistribution; import dr.xml.*; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; /** * @author Marc Suchard */ public class TraitGibbsOperator extends SimpleMCMCOperator implements GibbsOperator { public static final String GIBBS_OPERATOR = "traitGibbsOperator"; public static final String INTERNAL_ONLY = "onlyInternalNodes"; public static final String TIP_WITH_PRIORS_ONLY = "onlyTipsWithPriors"; public static final String NODE_PRIOR = "nodePrior"; public static final String NODE_LABEL = "taxon"; public static final String ROOT_PRIOR = "rootPrior"; private final TreeModel treeModel; private final MatrixParameter precisionMatrixParameter; private final SampledMultivariateTraitLikelihood traitModel; private final int dim; private final String traitName; private Map<Taxon, GeoSpatialDistribution> nodePrior; private GeoSpatialCollectionModel parameterPrior = null; private boolean onlyInternalNodes = true; private boolean onlyTipsWithPriors = true; private boolean sampleRoot = false; private double[] rootPriorMean; private double[][] rootPriorPrecision; private final int maxTries = 10000; public TraitGibbsOperator(SampledMultivariateTraitLikelihood traitModel, boolean onlyInternalNodes, boolean onlyTipsWithPriors) { super(); this.traitModel = traitModel; this.treeModel = traitModel.getTreeModel(); this.precisionMatrixParameter = (MatrixParameter) traitModel.getDiffusionModel().getPrecisionParameter(); this.traitName = traitModel.getTraitName(); this.onlyInternalNodes = onlyInternalNodes; this.onlyTipsWithPriors = onlyTipsWithPriors; this.dim = treeModel.getMultivariateNodeTrait(treeModel.getRoot(), traitName).length; Logger.getLogger("dr.evomodel").info("Using *NEW* trait Gibbs operator"); } public void setRootPrior(MultivariateNormalDistribution rootPrior) { rootPriorMean = rootPrior.getMean(); rootPriorPrecision = rootPrior.getScaleMatrix(); sampleRoot = true; } public void setTaxonPrior(Taxon taxon, GeoSpatialDistribution distribution) { if (nodePrior == null) nodePrior = new HashMap<Taxon, GeoSpatialDistribution>(); nodePrior.put(taxon, distribution); } public void setParameterPrior(GeoSpatialCollectionModel distribution) { parameterPrior = distribution; } public int getStepCount() { return 1; } private boolean nodePriorExists(NodeRef node) { return nodePrior != null && nodePrior.containsKey(treeModel.getNodeTaxon(node)); } public double doOperation() throws OperatorFailedException { NodeRef node = null; final NodeRef root = treeModel.getRoot(); while (node == null) { if (onlyInternalNodes) node = treeModel.getInternalNode(MathUtils.nextInt( treeModel.getInternalNodeCount())); else { node = treeModel.getNode(MathUtils.nextInt( treeModel.getNodeCount())); if (onlyTipsWithPriors && (treeModel.getChildCount(node) == 0) && // Is a tip !nodePriorExists(node)) { // Does not have a prior node = null; } } if (!sampleRoot && node == root) node = null; } // select any internal (or internal/external) node final double[] initialValue = treeModel.getMultivariateNodeTrait(node,traitName); MeanPrecision mp; if (node != root) mp = operateNotRoot(node); else mp = operateRoot(node); final Taxon taxon = treeModel.getNodeTaxon(node); final boolean nodePriorExists = nodePrior != null && nodePrior.containsKey(taxon); // if (!onlyInternalNodes) { // final boolean isTip = (treeModel.getChildCount(node) == 0); // if (!nodePriorExists && isTip) // System.err.println("Warning: sampling taxon '"+treeModel.getNodeTaxon(node).getId() // +"' tip trait without a prior!!!"); int count = 0; final boolean parameterPriorExists = parameterPrior != null; double[] draw; do { do { if (count > maxTries) { treeModel.setMultivariateTrait(node,traitName,initialValue); throw new OperatorFailedException("Truncated Gibbs is stuck!"); } draw = MultivariateNormalDistribution.nextMultivariateNormalPrecision( mp.mean, mp.precision); count++; } while (nodePriorExists && // There is a prior for this node (nodePrior.get(taxon)).logPdf(draw) == Double.NEGATIVE_INFINITY); // And draw is invalid under prior // TODO Currently only works for flat/truncated priors, make work for MVN treeModel.setMultivariateTrait(node, traitName, draw); } while (parameterPriorExists && (parameterPrior.getLogLikelihood() == Double.NEGATIVE_INFINITY)); return 0; //To change body of implemented methods use File | Settings | File Templates. } private MeanPrecision operateNotRoot(NodeRef node) { double[][] precision = precisionMatrixParameter.getParameterAsMatrix(); NodeRef parent = treeModel.getParent(node); double[] mean = new double[dim]; double weight = 1.0 / traitModel.getRescaledBranchLength(node); double[] trait = treeModel.getMultivariateNodeTrait(parent, traitName); for (int i = 0; i < dim; i++) mean[i] = trait[i] * weight; double weightTotal = weight; for (int j = 0; j < treeModel.getChildCount(node); j++) { NodeRef child = treeModel.getChild(node, j); trait = treeModel.getMultivariateNodeTrait(child, traitName); weight = 1.0 / traitModel.getRescaledBranchLength(child); for (int i = 0; i < dim; i++) mean[i] += trait[i] * weight; weightTotal += weight; } for (int i = 0; i < dim; i++) { mean[i] /= weightTotal; for (int j = i; j < dim; j++) precision[j][i] = precision[i][j] *= weightTotal; } return new MeanPrecision(mean,precision); } class MeanPrecision { final double[] mean; final double[][] precision; MeanPrecision(double[] mean, double[][] precision) { this.mean = mean; this.precision = precision; } } private MeanPrecision operateRoot(NodeRef node) { double[] trait; double weightTotal = 0.0; double[] weightedAverage = new double[dim]; double[][] precision = precisionMatrixParameter.getParameterAsMatrix(); for (int k = 0; k < treeModel.getChildCount(node); k++) { NodeRef child = treeModel.getChild(node, k); trait = treeModel.getMultivariateNodeTrait(child, traitName); final double weight = 1.0 / traitModel.getRescaledBranchLength(child); for (int i = 0; i < dim; i++) { for (int j=0; j<dim; j++) weightedAverage[i] += precision[i][j] * weight * trait[j]; } weightTotal += weight; } for (int i=0; i<dim; i++) { for (int j=0; j<dim; j++) { weightedAverage[i] += rootPriorPrecision[i][j] * rootPriorMean[j]; precision[i][j] = precision[i][j] * weightTotal + rootPriorPrecision[i][j]; } } double[][] variance = new SymmetricMatrix(precision).inverse().toComponents(); trait = new double[dim]; for (int i=0; i<dim; i++) { for (int j=0; j<dim; j++) trait[i] += variance[i][j] * weightedAverage[j]; } return new MeanPrecision(trait,precision); } public String getPerformanceSuggestion() { return null; } public String getOperatorName() { return GIBBS_OPERATOR; } public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return GIBBS_OPERATOR; } private final String[] names = { GIBBS_OPERATOR, "internalTraitGibbsOperator" }; public String[] getParserNames() { return names; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { double weight = xo.getDoubleAttribute(WEIGHT); boolean onlyInternalNodes = xo.getAttribute(INTERNAL_ONLY, true); boolean onlyTipsWithPriors = xo.getAttribute(TIP_WITH_PRIORS_ONLY, true); SampledMultivariateTraitLikelihood traitModel = (SampledMultivariateTraitLikelihood) xo.getChild(AbstractMultivariateTraitLikelihood.class); TraitGibbsOperator operator = new TraitGibbsOperator(traitModel, onlyInternalNodes, onlyTipsWithPriors); operator.setWeight(weight); // Get root prior XMLObject cxo = xo.getChild(ROOT_PRIOR); if (cxo != null) { MultivariateDistributionLikelihood rootPrior = (MultivariateDistributionLikelihood) cxo.getChild(MultivariateDistributionLikelihood.class); if( !(rootPrior.getDistribution() instanceof MultivariateDistribution)) throw new XMLParseException("Only multivariate normal priors allowed for Gibbs sampling the root trait"); operator.setRootPrior((MultivariateNormalDistribution)rootPrior.getDistribution()); } // Get node priors for (int i = 0; i < xo.getChildCount(); i++) { if (xo.getChild(i) instanceof MultivariateDistributionLikelihood) { MultivariateDistribution dist = ((MultivariateDistributionLikelihood) xo.getChild(i)).getDistribution(); if (dist instanceof GeoSpatialDistribution) { GeoSpatialDistribution prior = (GeoSpatialDistribution) dist; String nodeLabel = prior.getLabel(); TreeModel treeModel = traitModel.getTreeModel(); // Get taxon node from tree int index = treeModel.getTaxonIndex(nodeLabel); if (index == -1) { throw new XMLParseException("Taxon '" + nodeLabel + "' not found for geoSpatialDistribution element in traitGibbsOperator element"); } operator.setTaxonPrior(treeModel.getTaxon(index),prior); System.err.println("Adding truncated prior for taxon '"+treeModel.getTaxon(index)+"'"); } } } GeoSpatialCollectionModel collectionModel = (GeoSpatialCollectionModel) xo.getChild(GeoSpatialCollectionModel.class); if (collectionModel != null) { operator.setParameterPrior(collectionModel); System.err.println("Adding truncated prior '"+collectionModel.getId()+ "' for parameter '"+collectionModel.getParameter().getId()+"'"); } return operator; }
package org.eclipse.emf.emfstore.client.model.filetransfer; import java.io.File; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.emf.emfstore.client.model.WorkspaceManager; import org.eclipse.emf.emfstore.client.model.connectionmanager.ConnectionManager; import org.eclipse.emf.emfstore.client.model.impl.ProjectSpaceBase; import org.eclipse.emf.emfstore.client.model.util.EMFStoreCommand; import org.eclipse.emf.emfstore.server.exceptions.FileTransferException; import org.eclipse.emf.emfstore.server.filetransfer.FilePartitionerUtil; import org.eclipse.emf.emfstore.server.filetransfer.FileTransferInformation; import org.eclipse.emf.emfstore.server.model.FileIdentifier; import org.eclipse.emf.emfstore.server.model.ProjectId; import org.eclipse.emf.emfstore.server.model.SessionId; /** * Abstract class for the file transfer job encapsulating methods used for downloads and uploads. * * @author pfeifferc, jfinis */ public abstract class FileTransferJob extends Job { private ConnectionManager connectionManager; private Exception exception; private File file; private ProjectId projectId; private SessionId sessionId; private boolean canceled; private final ProjectSpaceBase projectSpace; private final FileTransferManager transferManager; private final FileTransferCacheManager cache; private final FileTransferInformation fileInformation; private final FileIdentifier fileId; /** * Constructor to be called by subclasses. * * @param transferManager the transfer manager handling the transfer job * @param fileInfo the transfer information of the job * @param name of the transfer job */ protected FileTransferJob(FileTransferManager transferManager, FileTransferInformation fileInfo, String name) { super(name); this.fileInformation = fileInfo; this.fileId = fileInfo.getFileIdentifier(); this.projectSpace = transferManager.getProjectSpace(); this.transferManager = transferManager; this.cache = transferManager.getCache(); } /** * Gets the attributes required for the file transfer. * * @throws FileTransferException if there are any null values in the attributes */ protected void getConnectionAttributes() throws FileTransferException { connectionManager = WorkspaceManager.getInstance().getConnectionManager(); projectId = projectSpace.getProjectId(); if (projectSpace.getUsersession() == null) { throw new FileTransferException("Session ID is unknown. Please login first!"); } else { new EMFStoreCommand() { @Override protected void doRun() { sessionId = projectSpace.getUsersession().getSessionId(); } }.run(false); } } /** * @param monitor monitor */ protected void setTotalWork(IProgressMonitor monitor) { monitor.beginTask("Transfering ", (fileInformation.getFileSize() / FilePartitionerUtil.getChunkSize())); } /** * @see org.eclipse.core.runtime.jobs.Job#canceling() */ @Override protected void canceling() { canceled = true; super.canceling(); } /** * Increments the chunk number by 1. */ protected void incrementChunkNumber() { fileInformation.setChunkNumber(fileInformation.getChunkNumber() + 1); } /** * @param monitor progress monitor */ protected void initializeMonitor(IProgressMonitor monitor) { // set monitor total work based on file size previously retrieved setTotalWork(monitor); // set progress based on how many file chunks that have already been sent monitor.worked(fileInformation.getChunkNumber()); } /** * @return the exception, if there has been any. Null otherwise. */ public Exception getException() { return exception; } /** * Returns the connection manager, handling the connection to the emf store. * * @return the connection manager */ protected ConnectionManager getConnectionManager() { return connectionManager; } /** * Returns the transferred file. * * @return the file where the file transfer is stored */ protected File getFile() { return file; } /** * Sets the transferred file. * * @param file the file to store the transfer in */ protected void setFile(File file) { this.file = file; } /** * Returns the project id of the project to which the file transfer belongs. * * @return project id */ protected ProjectId getProjectId() { return projectId; } /** * Returns the session id for the connection with the emf store. * * @return session id */ protected SessionId getSessionId() { return sessionId; } /** * Whether the user canceled the transfer. * * @return true iff canceled */ protected boolean isCanceled() { return canceled; } /** * Returns the project space which is associated with the file transfer. * * @return the associated project space */ protected ProjectSpaceBase getProjectSpace() { return projectSpace; } /** * Returns the file transfer manager administering the file transfer. * * @return the file transfer manager */ protected FileTransferManager getTransferManager() { return transferManager; } /** * Returns the cache manager associated with the project space of this file transfer. * * @return the cache manager */ protected FileTransferCacheManager getCache() { return cache; } /** * Returns the file transfer information of this transfer. * * @return transfer information */ protected FileTransferInformation getFileInformation() { return fileInformation; } /** * Returns the file identifier of this file transfer. * * @return the file identifier */ protected FileIdentifier getFileId() { return fileId; } /** * Sets the exception for this transfer. Do this in case an exception occurs. This exception can later be retrieved * by get exception. * * @param exception the exception that occurred */ protected void setException(Exception exception) { this.exception = exception; } }
package org.lamport.tla.toolbox.jcloud; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.jclouds.compute.domain.TemplateBuilder; public class PacketNetCloudTLCInstanceParameters extends CloudTLCInstanceParameters { public PacketNetCloudTLCInstanceParameters(final String tlcParams, int numberOfWorkers) { super(tlcParams.trim(), numberOfWorkers); } /* (non-Javadoc) * @see org.lamport.tla.toolbox.jcloud.CloudTLCInstanceParameters#getJavaVMArgs() */ @Override public String getJavaVMArgs() { return System.getProperty("packetnet.vmargs", super.getJavaVMArgs("-Xmx6G -Xms6G")); } /* (non-Javadoc) * @see org.lamport.tla.toolbox.jcloud.CloudTLCInstanceParameters#getJavaWorkerVMArgs() */ @Override public String getJavaWorkerVMArgs() { return System.getProperty("packetnet.vmworkerargs", super.getJavaWorkerVMArgs("-Xmx4G -Xms4G -XX:MaxDirectMemorySize=2g")); } /* (non-Javadoc) * @see org.lamport.tla.toolbox.jcloud.CloudTLCInstanceParameters#getTLCParameters() */ @Override public String getTLCParameters() { return System.getProperty("packetnet.tlcparams", super.getTLCParameters(16)); } /* (non-Javadoc) * @see org.lamport.tla.toolbox.jcloud.CloudTLCInstanceParameters#getCloudProvier() */ @Override public String getCloudProvider() { return "packet"; // as defined by jclouds. } /* (non-Javadoc) * @see org.lamport.tla.toolbox.jcloud.CloudTLCInstanceParameters#getRegion() */ @Override public String getRegion() { return System.getProperty("packetnet.region", "sjc1"); } /* (non-Javadoc) * @see org.lamport.tla.toolbox.jcloud.CloudTLCInstanceParameters#getImageId() */ @Override public String getImageId() { return System.getProperty("packetnet.image", "ubuntu_18_04"); } /* (non-Javadoc) * @see org.lamport.tla.toolbox.jcloud.CloudTLCInstanceParameters#getHardwareId() */ @Override public String getHardwareId() { return System.getProperty("packetnet.instanceType", "baremetal_0"); // t1.small.x86 whose "slug" is baremetal_0. } /* (non-Javadoc) * @see org.lamport.tla.toolbox.jcloud.CloudTLCInstanceParameters#getIdentity() */ @Override public String getIdentity() { final String identity = System.getenv("PACKET_NET_PROJECT_ID"); Assert.isNotNull(identity); return identity; } /* (non-Javadoc) * @see org.lamport.tla.toolbox.jcloud.CloudTLCInstanceParameters#getCredentials() */ @Override public String getCredentials() { final String credential = System.getenv("PACKET_NET_APIKEY"); Assert.isNotNull(credential); return credential; } /* (non-Javadoc) * @see org.lamport.tla.toolbox.jcloud.CloudTLCInstanceParameters#validateCredentials() */ @Override public IStatus validateCredentials() { final String credential = System.getenv("PACKET_NET_PROJECT_ID"); final String identity = System.getenv("PACKET_NET_APIKEY"); if (credential == null || identity == null) { return new Status(Status.ERROR, "org.lamport.tla.toolbox.jcloud", "Invalid credentials, please check the environment variables " + "(PACKET_NET_PROJECT_ID " + "and PACKET_NET_APIKEY) are correctly " + "set up and picked up by the Toolbox." + "\n\nPlease visit the Toolbox help and read section 4 " + "of \"Cloud based distributed TLC\" on how to setup authentication."); } return Status.OK_STATUS; } /* (non-Javadoc) * @see org.lamport.tla.toolbox.jcloud.CloudTLCInstanceParameters#mungeTemplateBuilder(org.jclouds.compute.domain.TemplateBuilder) */ @Override public void mungeTemplateBuilder(TemplateBuilder templateBuilder) { templateBuilder.locationId(getRegion()); } @Override public String getCloudAPIShutdown(final String credentials) { // One might think we could simply invoke curl and terminate the instance right // away. That doesn't work because we want the instance to idle until the // scheduled shutdown call executes in case the Toolbox reuses the instance to // run another model. return String.format( "printf \"#!/bin/bash\\n" + "if /usr/bin/curl https://metadata.packet.net/metadata 2>/dev/null | jq -e -r '.tags | index(\\\"power_off\\\")' > /dev/null; then\\n" + " /usr/bin/curl -X POST -H X-Auth-Token:%s https: + "else\\n" + " /usr/bin/curl -X DELETE -H X-Auth-Token:%s https: + "fi\\n\" | sudo tee /usr/local/bin/packetnet.sh" + " && sudo chmod +x /usr/local/bin/packetnet.sh" + " && " + "printf \"[Unit]\\nDescription=Delete instance via packetnet api on shutdown\\n" + "Requires=network.target\\n" + "DefaultDependencies=no\\n" + "Before=shutdown.target\\n" + "[Service]\\n" + "Type=oneshot\\n" + "RemainAfterExit=true\\n" + "ExecStart=/bin/true\\n" + "ExecStop=/usr/local/bin/packetnet.sh\\n" + "[Install]\\n" + "WantedBy=multi-user.target\\n\" | sudo tee /lib/systemd/system/delete-on-shutdown.service" + " && systemctl enable delete-on-shutdown" // restart delete-on-shutdown service after a reboot. + " && service delete-on-shutdown start", credentials, credentials); } }
package org.jnosql.diana.orientdb.document; import org.jnosql.diana.api.TypeReference; import org.jnosql.diana.api.document.Document; import org.jnosql.diana.api.document.DocumentDeleteQuery; import org.jnosql.diana.api.document.DocumentEntity; import org.jnosql.diana.api.document.DocumentQuery; import org.jnosql.diana.api.document.Documents; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Random; import java.util.function.Consumer; import java.util.logging.Logger; import static java.util.Arrays.asList; import static java.util.Collections.singletonMap; import static java.util.logging.Level.FINEST; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.jnosql.diana.api.document.query.DocumentQueryBuilder.delete; import static org.jnosql.diana.api.document.query.DocumentQueryBuilder.select; import static org.jnosql.diana.orientdb.document.DocumentConfigurationUtils.get; import static org.jnosql.diana.orientdb.document.OrientDBConverter.RID_FIELD; import static org.junit.jupiter.api.Assertions.*; public class OrientDBDocumentCollectionManagerTest { public static final String COLLECTION_NAME = "person"; private static final Logger LOGGER = Logger.getLogger(OrientDBDocumentCollectionManagerTest.class.getName()); private OrientDBDocumentCollectionManager entityManager; @BeforeEach public void setUp() { entityManager = get().get("database"); DocumentEntity documentEntity = getEntity(); Document id = documentEntity.find("name").get(); DocumentQuery query = select().from(COLLECTION_NAME).where(id.getName()).eq(id.get()).build(); DocumentDeleteQuery deleteQuery = delete().from(COLLECTION_NAME).where(id.getName()).eq(id.get()).build(); try { entityManager.delete(deleteQuery); } catch (Exception e) { LOGGER.log(FINEST, "error on OrientDB setup", e); } } @Test public void shouldSave() { DocumentEntity entity = getEntity(); DocumentEntity documentEntity = entityManager.insert(entity); assertNotNull(documentEntity); Optional<Document> document = documentEntity.find(RID_FIELD); assertTrue(document.isPresent()); } @Test public void shouldUpdateSave() { DocumentEntity entity = entityManager.insert(getEntity()); Document newField = Documents.of("newField", "10"); entity.add(newField); entityManager.update(entity); Document id = entity.find(OrientDBConverter.RID_FIELD).get(); DocumentQuery query = select().from(entity.getName()) .where(id.getName()).eq(id.get()) .build(); Optional<DocumentEntity> updated = entityManager.singleResult(query); assertTrue(updated.isPresent()); assertEquals(newField, updated.get().find("newField").get()); } @Test public void shouldRemoveEntity() { DocumentEntity documentEntity = entityManager.insert(getEntity()); Document id = documentEntity.find("name").get(); DocumentQuery query = select().from(COLLECTION_NAME).where(id.getName()).eq(id.get()).build(); DocumentDeleteQuery deleteQuery = delete().from(COLLECTION_NAME).where(id.getName()).eq(id.get()).build(); entityManager.delete(deleteQuery); assertTrue(entityManager.select(query).isEmpty()); } @Test public void shouldFindDocument() { DocumentEntity entity = entityManager.insert(getEntity()); Document id = entity.find("name").get(); DocumentQuery query = select().from(COLLECTION_NAME).where(id.getName()).eq(id.get()).build(); List<DocumentEntity> entities = entityManager.select(query); assertFalse(entities.isEmpty()); assertThat(entities, contains(entity)); } @Test public void shouldSQL() { DocumentEntity entity = entityManager.insert(getEntity()); Optional<Document> id = entity.find("name"); List<DocumentEntity> entities = entityManager.sql("select * from person where name = ?", id.get().get()); assertFalse(entities.isEmpty()); assertThat(entities, contains(entity)); } @Test public void shouldSQL2() { DocumentEntity entity = entityManager.insert(getEntity()); Optional<Document> id = entity.find("name"); List<DocumentEntity> entities = entityManager.sql("select * from person where name = :name", singletonMap("name", id.get().get())); assertFalse(entities.isEmpty()); assertThat(entities, contains(entity)); } @Test public void shouldSaveSubDocument() { DocumentEntity entity = getEntity(); entity.add(Document.of("phones", Document.of("mobile", "1231231"))); DocumentEntity entitySaved = entityManager.insert(entity); Document id = entitySaved.find("name").get(); DocumentQuery query = select().from(COLLECTION_NAME).where(id.getName()).eq(id.get()).build(); DocumentEntity entityFound = entityManager.select(query).get(0); Document subDocument = entityFound.find("phones").get(); List<Document> documents = subDocument.get(new TypeReference<List<Document>>() { }); assertThat(documents, contains(Document.of("mobile", "1231231"))); } @Test public void shouldSaveSubDocument2() { DocumentEntity entity = getEntity(); entity.add(Document.of("phones", Arrays.asList(Document.of("mobile", "1231231"), Document.of("mobile2", "1231231")))); DocumentEntity entitySaved = entityManager.insert(entity); Document id = entitySaved.find("name").get(); DocumentQuery query = select().from(COLLECTION_NAME).where(id.getName()).eq(id.get()).build(); DocumentEntity entityFound = entityManager.select(query).get(0); Document subDocument = entityFound.find("phones").get(); List<Document> documents = subDocument.get(new TypeReference<List<Document>>() { }); assertThat(documents, containsInAnyOrder(Document.of("mobile", "1231231"), Document.of("mobile2", "1231231"))); } @Test public void shouldQueryAnd() { DocumentEntity entity = getEntity(); entity.add(Document.of("age", 24)); entityManager.insert(entity); DocumentQuery query = select().from(COLLECTION_NAME).where("name").eq("Poliana") .and("age").gte( 10).build(); DocumentDeleteQuery deleteQuery = delete().from(COLLECTION_NAME).where("name").eq("Poliana") .and("age").gte( 10).build(); assertFalse(entityManager.select(query).isEmpty()); entityManager.delete(deleteQuery); assertTrue(entityManager.select(query).isEmpty()); } @Test public void shouldQueryOr() { DocumentEntity entity = getEntity(); entity.add(Document.of("age", 24)); entityManager.insert(entity); DocumentQuery query = select().from(COLLECTION_NAME).where("name").eq("Poliana") .or("age").gte(10).build(); DocumentDeleteQuery deleteQuery = delete().from(COLLECTION_NAME).where("name").eq("Poliana") .or("age").gte(10).build(); assertFalse(entityManager.select(query).isEmpty()); entityManager.delete(deleteQuery); assertTrue(entityManager.select(query).isEmpty()); } @Test public void shouldLive() throws InterruptedException { List<DocumentEntity> entities = new ArrayList<>(); Consumer<DocumentEntity> callback = entities::add; DocumentEntity entity = entityManager.insert(getEntity()); Document id = entity.find("name").get(); DocumentQuery query = select().from(COLLECTION_NAME).where(id.getName()).eq(id.get()).build(); entityManager.live(query, callback); entityManager.insert(getEntity()); Thread.sleep(3_000L); assertFalse(entities.isEmpty()); } @Test public void shouldConvertFromListSubdocumentList() { DocumentEntity entity = createSubdocumentList(); entityManager.insert(entity); } @Test public void shouldRetrieveListSubdocumentList() { DocumentEntity entity = entityManager.insert(createSubdocumentList()); Document key = entity.find("_id").get(); DocumentQuery query = select().from("AppointmentBook").where(key.getName()).eq(key.get()).build(); DocumentEntity documentEntity = entityManager.singleResult(query).get(); assertNotNull(documentEntity); List<List<Document>> contacts = (List<List<Document>>) documentEntity.find("contacts").get().get(); assertEquals(3, contacts.size()); assertTrue(contacts.stream().allMatch(d -> d.size() == 3)); } private DocumentEntity createSubdocumentList() { DocumentEntity entity = DocumentEntity.of("AppointmentBook"); entity.add(Document.of("_id", new Random().nextInt())); List<List<Document>> documents = new ArrayList<>(); documents.add(asList(Document.of("name", "Ada"), Document.of("type", ContactType.EMAIL), Document.of("information", "ada@lovelace.com"))); documents.add(asList(Document.of("name", "Ada"), Document.of("type", ContactType.MOBILE), Document.of("information", "11 1231231 123"))); documents.add(asList(Document.of("name", "Ada"), Document.of("type", ContactType.PHONE), Document.of("information", "phone"))); entity.add(Document.of("contacts", documents)); return entity; } private DocumentEntity getEntity() { DocumentEntity entity = DocumentEntity.of(COLLECTION_NAME); Map<String, Object> map = new HashMap<>(); map.put("name", "Poliana"); map.put("city", "Salvador"); List<Document> documents = Documents.of(map); documents.forEach(entity::add); return entity; } }
package org.pocketcampus.plugin.freeroom.server; import static org.pocketcampus.platform.launcher.server.PCServerConfig.PC_SRV_CONFIG; import java.net.HttpURLConnection; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Set; import org.apache.thrift.TException; import org.pocketcampus.platform.sdk.server.database.ConnectionManager; import org.pocketcampus.platform.sdk.server.database.handlers.exceptions.ServerException; import org.pocketcampus.plugin.freeroom.server.exchange.ExchangeServiceImpl; import org.pocketcampus.plugin.freeroom.server.utils.FetchRoomsDetails; import org.pocketcampus.plugin.freeroom.server.utils.OccupancySorted; import org.pocketcampus.plugin.freeroom.server.utils.Utils; import org.pocketcampus.plugin.freeroom.shared.ActualOccupation; import org.pocketcampus.plugin.freeroom.shared.AutoCompleteReply; import org.pocketcampus.plugin.freeroom.shared.AutoCompleteRequest; import org.pocketcampus.plugin.freeroom.shared.FRPeriod; import org.pocketcampus.plugin.freeroom.shared.FRReply; import org.pocketcampus.plugin.freeroom.shared.FRRequest; import org.pocketcampus.plugin.freeroom.shared.FRRoom; import org.pocketcampus.plugin.freeroom.shared.FreeRoomReply; import org.pocketcampus.plugin.freeroom.shared.FreeRoomRequest; import org.pocketcampus.plugin.freeroom.shared.FreeRoomService; import org.pocketcampus.plugin.freeroom.shared.ImWorkingReply; import org.pocketcampus.plugin.freeroom.shared.ImWorkingRequest; import org.pocketcampus.plugin.freeroom.shared.Occupancy; import org.pocketcampus.plugin.freeroom.shared.OccupancyReply; import org.pocketcampus.plugin.freeroom.shared.OccupancyRequest; import org.pocketcampus.plugin.freeroom.shared.WhoIsWorkingReply; import org.pocketcampus.plugin.freeroom.shared.WhoIsWorkingRequest; import org.pocketcampus.plugin.freeroom.shared.WorkingOccupancy; import org.pocketcampus.plugin.freeroom.shared.utils.FRTimes; import android.util.Log; /** * The actual implementation of the server side of the FreeRoom Plugin. * * It responds to different types of request from the clients. * * @author FreeRoom Project Team - Julien WEBER <julien.weber@epfl.ch> and * Valentin MINDER <valentin.minder@epfl.ch> * */ public class FreeRoomServiceImpl implements FreeRoomService.Iface { private final int LIMIT_AUTOCOMPLETE = 50; private ConnectionManager connMgr; private ExchangeServiceImpl mExchangeService; // be careful when changing this, it might lead to invalid data already // stored ! // this is what is used to differentiate a room from a student occupation in // the DB. public enum OCCUPANCY_TYPE { ROOM, USER; }; // margin for error is 15 minute private final long MARGIN_ERROR_TIMESTAMP = 60 * 1000 * 15; private final long ONE_HOUR_MS = 3600 * 1000; public FreeRoomServiceImpl() { System.out.println("Starting FreeRoom plugin server ... V2"); try { connMgr = new ConnectionManager(PC_SRV_CONFIG.getString("DB_URL") + "?allowMultiQueries=true", PC_SRV_CONFIG.getString("DB_USERNAME"), PC_SRV_CONFIG.getString("DB_PASSWORD")); } catch (ServerException e) { e.printStackTrace(); } mExchangeService = new ExchangeServiceImpl( PC_SRV_CONFIG.getString("DB_URL") + "?allowMultiQueries=true", PC_SRV_CONFIG.getString("DB_USERNAME"), PC_SRV_CONFIG.getString("DB_PASSWORD"), this); // update ewa : should be done periodically... boolean updateEWA = false; if (updateEWA) { if (mExchangeService.updateEWAOccupancy()) { System.out.println("EWA data succesfully updated!"); } else { System.err.println("EWA data couldn't be completely loaded!"); } } boolean updateRoomsDetails = false; if (updateRoomsDetails) { FetchRoomsDetails details = new FetchRoomsDetails( PC_SRV_CONFIG.getString("DB_URL") + "?allowMultiQueries=true", PC_SRV_CONFIG.getString("DB_USERNAME"), PC_SRV_CONFIG.getString("DB_PASSWORD")); System.out.println(details.fetchRoomsIntoDB() + " rooms inserted/updated"); } } /** * This method's job is to ensure the data are stored in a proper way. * Whenever you need to insert an occupancy you should call this one. The * start of a user occupancy should be a full hour (e.g 10h00). * * @param period * The period of the occupancy * @param type * Type of the occupancy (for instance user or room occupancy) * @param room * The room, the object has to contains the UID * @return true if the occupancy has been well inserted, false otherwise. */ public boolean insertOccupancy(FRPeriod period, OCCUPANCY_TYPE type, FRRoom room) { System.out.println("Inserting occupancy " + type.toString() + " for room " + room.getDoorCode()); return insertAndCheckOccupancyRoom(period, room, type); } private boolean insertAndCheckOccupancyRoom(FRPeriod period, FRRoom room, OCCUPANCY_TYPE typeToInsert) { long tsStart = period.getTimeStampStart(); long tsEnd = period.getTimeStampEnd(); boolean userOccupation = (typeToInsert == OCCUPANCY_TYPE.USER) ? true : false; // first check if you can fully insert it (no other overlapping // occupancy of rooms) String checkRequest = "SELECT * FROM `fr-occupancy` oc " + "WHERE ((oc.timestampStart < ? AND oc.timestampStart > ?) " + "OR (oc.timestampEnd > ? AND oc.timestampEnd < ?) " + "OR (oc.timestampStart > ? AND oc.timestampEnd < ?)) AND oc.uid = ?"; Connection connectBDD; try { connectBDD = connMgr.getConnection(); PreparedStatement checkQuery = connectBDD .prepareStatement(checkRequest); checkQuery.setLong(1, tsEnd); checkQuery.setLong(2, tsStart); checkQuery.setLong(3, tsStart); checkQuery.setLong(4, tsEnd); checkQuery.setLong(5, tsStart); checkQuery.setLong(6, tsEnd); checkQuery.setString(7, room.getUid()); ResultSet checkResult = checkQuery.executeQuery(); while (checkResult.next()) { OCCUPANCY_TYPE type = OCCUPANCY_TYPE.valueOf(checkResult .getString("type")); String uid = checkResult.getString("uid"); long start = checkResult.getLong("timestampStart"); long end = checkResult.getLong("timestampEnd"); // if we have a match and this is a room occupancy, we cannot go // further there is an overlap if (typeToInsert == OCCUPANCY_TYPE.ROOM && type == OCCUPANCY_TYPE.ROOM) { System.err .println("Error during insertion of occupancy, overlapping of two rooms occupancy. : "); System.err.println("Want to insert : " + room.getUid() + " have conflict with " + uid); return false; // } else if (typeToInsert == OCCUPANCY_TYPE.ROOM) { // // else, we need to adapt the boundaries of the // overlapping // // entries, rooms occupancy has the priority over user // // occupancy // if (start > tsStart && start < tsEnd) { // adaptTimeStampOccupancy(uid, start, tsEnd, end, // OCCUPANCY_TYPE.USER); // } else if (end < tsEnd && end > start) { // adaptTimeStampOccupancy(uid, start, start, tsStart, // OCCUPANCY_TYPE.USER); // } else { // // simply delete it if it is entirely in the period // deleteOccupancy(uid, start); // } else if (typeToInsert == OCCUPANCY_TYPE.USER // && type == OCCUPANCY_TYPE.ROOM) { // // simply adapt our boundaries // userOccupation = true; // if (start > tsStart && start < tsEnd) { // tsEnd = start; // maxEnd = start; // } else if (end < tsEnd && end > tsStart) { // tsStart = end; // minStart = end; // } else { // // there is a course, no possiblity to insert a user // // occupancy here // return false; // } else if (typeToInsert == OCCUPANCY_TYPE.USER){ // // TODO check how user occupancies is updated to see if // // is worth keeping this branchment // if (start > tsStart && start < tsEnd) { // // shouldn't happen // System.out // .println("Error while inserting, trying to insert user occupancy that PARTIALLY overlap another useroccupancy"); // return false; // } else if (end < tsEnd && end > start) { // // shouldn't happen // System.out // .println("Error while inserting, trying to insert user occupancy that PARTIALLY overlap another useroccupancy"); // return false; // // otherwise no problem, insertion is step by step } } // and now insert it ! if (!userOccupation) { return insertOccupancyInDB(room.getUid(), tsStart, tsEnd, OCCUPANCY_TYPE.ROOM, 0); } else { if (tsEnd - tsStart < ONE_HOUR_MS) { System.out.println("occupancy less than a hour"); // return false; } boolean overallInsertion = true; long hourSharpBefore = Utils.roundHourBefore(tsStart); long numberHours = Utils.determineNumberHour(tsStart, tsEnd); for (int i = 0; i < numberHours; ++i) { overallInsertion = overallInsertion && insertOccupancyInDB(room.getUid(), hourSharpBefore + i * ONE_HOUR_MS, hourSharpBefore + (i + 1) * ONE_HOUR_MS, OCCUPANCY_TYPE.USER, 1); } return overallInsertion; } } catch (SQLException e) { e.printStackTrace(); return false; } } private boolean insertOccupancyInDB(String uid, long tsStart, long tsEnd, OCCUPANCY_TYPE type, int count) { String insertRequest = "INSERT INTO `fr-occupancy` (uid, timestampStart, timestampEnd, type, count) " + "VALUES (?, ?, ?, ?, ?) " + "ON DUPLICATE KEY UPDATE count = count + 1"; Connection connectBDD; try { connectBDD = connMgr.getConnection(); PreparedStatement insertQuery = connectBDD .prepareStatement(insertRequest); insertQuery.setString(1, uid); insertQuery.setLong(2, tsStart); insertQuery.setLong(3, tsEnd); insertQuery.setString(4, type.toString()); insertQuery.setInt(5, count); insertQuery.execute(); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } // for test purposes ONLY public FreeRoomServiceImpl(ConnectionManager conn) { System.out.println("Starting TEST FreeRoom plugin server ..."); connMgr = conn; } // TODO TO BE DELETED @Override public FreeRoomReply getFreeRoomFromTime(FreeRoomRequest request) throws TException { return null; } // TODO TO BE DELETED @Override public OccupancyReply checkTheOccupancy(OccupancyRequest request) throws TException { return null; } @Override public FRReply getOccupancy(FRRequest request) throws TException { FRReply reply = new FRReply(HttpURLConnection.HTTP_OK, HttpURLConnection.HTTP_OK + ""); // round the given period to half hours to have a nice display on UI. FRPeriod period = request.getPeriod(); long tsStart = Utils.roundToNearestHalfHourBefore(period .getTimeStampStart()); long tsEnd = Utils .roundToNearestHalfHourAfter(period.getTimeStampEnd()); if (!FRTimes.validCalendars(period)) { // if something is wrong in the request return new FRReply(HttpURLConnection.HTTP_BAD_REQUEST, "Bad timestamps! Your client sent a bad request, sorry"); } boolean onlyFreeRoom = request.isOnlyFreeRooms(); List<String> uidList = request.getUidList(); HashMap<String, List<Occupancy>> occupancies = null; if (uidList == null) { // we want to look into all the rooms occupancies = getOccupancyOfAnyFreeRoom(onlyFreeRoom, tsStart, tsEnd); } else { // or the user specified a specific list of rooms he wants to check occupancies = getOccupancyOfSpecificRoom(uidList, onlyFreeRoom, tsStart, tsEnd); } reply.setOccupancyOfRooms(occupancies); return reply; } private HashMap<String, List<Occupancy>> getOccupancyOfAnyFreeRoom( boolean onlyFreeRooms, long tsStart, long tsEnd) { System.out.println("Requesting any free rooms " + onlyFreeRooms); HashMap<String, List<Occupancy>> result = new HashMap<String, List<Occupancy>>(); if (onlyFreeRooms) { Connection connectBDD; try { connectBDD = connMgr.getConnection(); // first select rooms totally free String request = "SELECT rl.uid, rl.doorCode, rl.capacity " + "FROM `fr-roomslist` rl " + "WHERE rl.uid NOT IN(" + "SELECT ro.uid FROM `fr-occupancy` ro " + "WHERE ((ro.timestampEnd <= ? AND ro.timestampEnd >= ?) " + "OR (ro.timestampStart <= ? AND ro.timestampStart >= ?)" + "OR (ro.timestampStart <= ? AND ro.timestampEnd >= ?)) " + "AND ro.type LIKE ?)"; PreparedStatement query = connectBDD.prepareStatement(request); query.setLong(1, tsEnd); query.setLong(2, tsStart); query.setLong(3, tsEnd); query.setLong(4, tsStart); query.setLong(5, tsStart); query.setLong(6, tsEnd); query.setString(7, OCCUPANCY_TYPE.ROOM.toString()); ResultSet resultQuery = query.executeQuery(); HashMap<String, FRRoom> rooms = new HashMap<String, FRRoom>(); String roomsFreeSQL = ""; while (resultQuery.next()) { if (!rooms.isEmpty()) { roomsFreeSQL += ","; } String uid = resultQuery.getString("uid"); String doorCode = resultQuery.getString("doorCode"); int capacity = resultQuery.getInt("capacity"); FRRoom mRoom = new FRRoom(doorCode, uid); mRoom.setCapacity(capacity); rooms.put(uid, mRoom); roomsFreeSQL += uid; } // TODO call anyspecific list of room with the given list ? be // careful to rooms that has no occupancy won't appear in this // list ! // and also select user occupancy of these rooms String userOccupancyRequest = "SELECT " + "uo.uid, uo.count, uo.timestampStart, uo.timestampEnd " + "FROM `fr-occupancy` uo " + "WHERE uo.uid IN(" + roomsFreeSQL + ") " + "AND uo.type LIKE ? " + "AND ((uo.timestampEnd <= ? AND uo.timestampEnd >= ? ) " + "OR (uo.timestampStart <= ? AND uo.timestampStart >= ?)" + "OR (uo.timestampStart <= ? AND uo.timestampEnd >= ?)) " + "ORDER BY uo.uid ASC, uo.timestampStart ASC"; PreparedStatement queryUser = connectBDD .prepareStatement(userOccupancyRequest); queryUser.setString(1, OCCUPANCY_TYPE.USER.toString()); queryUser.setLong(2, tsEnd); queryUser.setLong(3, tsStart); queryUser.setLong(4, tsEnd); queryUser.setLong(5, tsStart); queryUser.setLong(6, tsStart); queryUser.setLong(7, tsEnd); ResultSet occupancyResult = queryUser.executeQuery(); String currentUID = null; String currentDoorCode = null; OccupancySorted currentOccupancy = null; // and now extract and create occupancies for each rooms // query beeing sorted by UID and then by timestampStart, we // don't need to access at each iteration the room stored in // rooms // hashmap, only when there is a change. And also we can add the // actualoccupation as they come, (sorted by timestamp) while (occupancyResult.next()) { // extract attributes of record long start = occupancyResult.getLong("timestampStart"); long end = occupancyResult.getLong("timestampEnd"); String uid = occupancyResult.getString("uid"); int count = occupancyResult.getInt("count"); FRPeriod period = new FRPeriod(start, end, false); // if this is the first iteration if (currentUID == null) { System.out.println("first iteration"); FRRoom mRoom = rooms.get(uid); currentUID = uid; currentDoorCode = mRoom.getDoorCode(); currentOccupancy = new OccupancySorted(mRoom, tsStart, tsEnd, true); } // we move on to the next room thus re-initialize attributes // for the loop, as well as storing the previous room in the // result hashmap if (!uid.equals(currentUID)) { Occupancy mOccupancy = currentOccupancy.getOccupancy(); addToHashMapOccupancy(currentDoorCode, mOccupancy, result); // remove the room from the list rooms.remove(currentUID); // re-initialize the value, and continue the process for // other rooms FRRoom mRoom = rooms.get(uid); currentDoorCode = mRoom.getDoorCode(); currentOccupancy = new OccupancySorted(mRoom, tsStart, tsEnd, true); currentUID = uid; } ActualOccupation accOcc = new ActualOccupation(period, true); accOcc.setProbableOccupation(count); currentOccupancy.addActualOccupation(accOcc); } // the last room has not been added yet if (currentOccupancy != null && currentOccupancy.size() != 0) { Occupancy mOccupancy = currentOccupancy.getOccupancy(); addToHashMapOccupancy(currentDoorCode, mOccupancy, result); // remove the room from the list rooms.remove(currentUID); } // and finally, check if there is some free rooms left that have // no user occupancy and need manual action (i.e set ratio to 0 // and has to be added in the result hashmap) for (FRRoom mRoom : rooms.values()) { currentOccupancy = new OccupancySorted(mRoom, tsStart, tsEnd, true); FRPeriod period = new FRPeriod(tsStart, tsEnd, false); ActualOccupation accOcc = new ActualOccupation(period, true); accOcc.setProbableOccupation(0); currentOccupancy.addActualOccupation(accOcc); Occupancy mOccupancy = currentOccupancy.getOccupancy(); addToHashMapOccupancy(mRoom.getDoorCode(), mOccupancy, result); } } catch (SQLException e) { e.printStackTrace(); } } return result; } private HashMap<String, List<Occupancy>> getOccupancyOfSpecificRoom( List<String> uidList, boolean onlyFreeRooms, long tsStart, long tsEnd) { if (uidList.isEmpty()) { return getOccupancyOfAnyFreeRoom(onlyFreeRooms, tsStart, tsEnd); } System.out.println("Requesting specific list of rooms " + uidList); HashMap<String, List<Occupancy>> result = new HashMap<String, List<Occupancy>>(); int numberOfRooms = uidList.size(); // formatting for the query String roomsListQueryFormat = ""; for (int i = 0; i < numberOfRooms - 1; ++i) { roomsListQueryFormat += "?,"; } roomsListQueryFormat += "?"; Connection connectBDD; try { connectBDD = connMgr.getConnection(); String request = "SELECT rl.uid, rl.doorCode, rl.capacity, " + "uo.count, uo.timestampStart, uo.timestampEnd, uo.type " + "FROM `fr-roomslist` rl, `fr-occupancy` uo " + "WHERE rl.uid = uo.uid AND rl.uid IN(" + roomsListQueryFormat + ") " + "AND ((uo.timestampEnd <= ? AND uo.timestampEnd >= ? ) " + "OR (uo.timestampStart <= ? AND uo.timestampStart >= ?)" + "OR (uo.timestampStart <= ? AND uo.timestampEnd >= ?)) " + "ORDER BY rl.uid ASC, uo.timestampStart ASC"; PreparedStatement query = connectBDD.prepareStatement(request); int i = 1; for (; i <= numberOfRooms; ++i) { query.setString(i, uidList.get(i - 1)); } query.setLong(i, tsEnd); query.setLong(i + 1, tsStart); query.setLong(i + 2, tsEnd); query.setLong(i + 3, tsStart); query.setLong(i + 4, tsStart); query.setLong(i + 5, tsEnd); ResultSet resultQuery = query.executeQuery(); String currentUID = null; String currentDoorCode = null; OccupancySorted currentOccupancy = null; // and now extract and create occupancies for each rooms // query beeing sorted by UID and then by timestampStart, we // don't need to access at each iteration the room stored in // rooms // hashmap, only when there is a change. And also we can add the // actualoccupation as they come, (sorted by timestamp) while (resultQuery.next()) { // extract attributes of record long start = resultQuery.getLong("timestampStart"); long end = resultQuery.getLong("timestampEnd"); String uid = resultQuery.getString("uid"); int count = resultQuery.getInt("count"); String doorCode = resultQuery.getString("doorCode"); OCCUPANCY_TYPE type = OCCUPANCY_TYPE.valueOf(resultQuery .getString("type")); boolean available = (type == OCCUPANCY_TYPE.USER) ? true : false; int capacity = resultQuery.getInt("capacity"); double ratio = capacity > 0 ? (double) count / capacity : 0.0; FRPeriod period = new FRPeriod(start, end, false); FRRoom mRoom = new FRRoom(doorCode, uid); mRoom.setCapacity(capacity); // if this is the first iteration if (currentUID == null) { currentUID = uid; currentDoorCode = mRoom.getDoorCode(); currentOccupancy = new OccupancySorted(mRoom, tsStart, tsEnd, onlyFreeRooms); } // we move on to the next room thus re-initialize attributes // for the loop, as well as storing the previous room in the // result hashmap if (!uid.equals(currentUID)) { Occupancy mOccupancy = currentOccupancy.getOccupancy(); addToHashMapOccupancy(currentDoorCode, mOccupancy, result); // remove the room from the list uidList.remove(currentUID); // re-initialize the value, and continue the process for // other rooms currentDoorCode = mRoom.getDoorCode(); currentOccupancy = new OccupancySorted(mRoom, tsStart, tsEnd, onlyFreeRooms); currentUID = uid; } ActualOccupation accOcc = new ActualOccupation(period, available); accOcc.setProbableOccupation(count); accOcc.setRatioOccupation(ratio); currentOccupancy.addActualOccupation(accOcc); } // the last room has not been added yet if (currentOccupancy != null && currentOccupancy.size() != 0) { Occupancy mOccupancy = currentOccupancy.getOccupancy(); addToHashMapOccupancy(currentDoorCode, mOccupancy, result); // remove the room from the list uidList.remove(currentUID); } // for all the others rooms that hasn't been matched in the query, // we need to add them too if (!uidList.isEmpty()) { roomsListQueryFormat = ""; for (i = 0; i < uidList.size() - 1; ++i) { roomsListQueryFormat += "?,"; } roomsListQueryFormat += "?"; String infoRequest = "SELECT rl.uid, rl.doorCode, rl.capacity " + "FROM `fr-roomslist` rl " + "WHERE rl.uid IN(" + roomsListQueryFormat + ")"; PreparedStatement infoQuery = connectBDD .prepareStatement(infoRequest); for (i = 1; i <= uidList.size(); ++i) { infoQuery.setString(i, uidList.get(i - 1)); } ResultSet infoRoom = infoQuery.executeQuery(); while (infoRoom.next()) { String uid = infoRoom.getString("uid"); String doorCode = infoRoom.getString("doorCode"); int capacity = infoRoom.getInt("capacity"); FRRoom mRoom = new FRRoom(doorCode, uid); mRoom.setCapacity(capacity); currentOccupancy = new OccupancySorted(mRoom, tsStart, tsEnd, onlyFreeRooms); FRPeriod period = new FRPeriod(tsStart, tsEnd, false); ActualOccupation accOcc = new ActualOccupation(period, true); accOcc.setProbableOccupation(0); currentOccupancy.addActualOccupation(accOcc); Occupancy mOccupancy = currentOccupancy.getOccupancy(); addToHashMapOccupancy(mRoom.getDoorCode(), mOccupancy, result); } } } catch (SQLException e) { e.printStackTrace(); } return result; } /** * Add to a given hashmap the given occupancy by extracting the building * from the doorCode. The hashmap maps a building to a list of Occupancy for * room in this building. **/ private void addToHashMapOccupancy(String doorCode, Occupancy mOcc, HashMap<String, List<Occupancy>> result) { if (mOcc == null) { return; } String building = Utils.extractBuilding(doorCode); System.out.println("adding room " + mOcc.getRoom().getDoorCode()); List<Occupancy> occ = result.get(building); if (occ == null) { occ = new ArrayList<Occupancy>(); result.put(building, occ); } occ.add(mOcc); } /** * Returns all the rooms that satisfies the hint given in the request. * * The hint may be the start of the door code or the uid. * * TODO: verifies that it works with PH D2 398, PHD2 398, PH D2398 and * PHD2398 * */ @Override public AutoCompleteReply autoCompleteRoom(AutoCompleteRequest request) throws TException { System.out.println("Requesting autocomplete of " + request.getConstraint()); AutoCompleteReply reply = new AutoCompleteReply( HttpURLConnection.HTTP_CREATED, "" + HttpURLConnection.HTTP_CREATED); String constraint = request.getConstraint(); // TODO to decomment (testing purpose) if (constraint.length() < 2) { // return new AutoCompleteReply(HttpURLConnection.HTTP_BAD_REQUEST, // "Constraints should be at least 2 characters long."); } List<FRRoom> rooms = new ArrayList<FRRoom>(); Set<String> forbiddenRooms = request.getForbiddenRoomsUID(); String forbidRoomsSQL = ""; if (forbiddenRooms != null) { for (int i = forbiddenRooms.size(); i > 0; --i) { if (i <= 1) { forbidRoomsSQL += "?"; } else { forbidRoomsSQL += "?,"; } } } // avoid all whitespaces for requests constraint = constraint.trim(); constraint = constraint.replaceAll("\\s+", ""); try { Connection connectBDD = connMgr.getConnection(); String requestSQL = ""; if (forbiddenRooms == null) { requestSQL = "SELECT * " + "FROM `fr-roomslist` rl " + "WHERE (rl.uid LIKE (?) OR rl.doorCodeWithoutSpace LIKE (?)) " + "ORDER BY rl.doorCode ASC LIMIT " + LIMIT_AUTOCOMPLETE; } else { requestSQL = "SELECT * " + "FROM `fr-roomslist` rl " + "WHERE (rl.uid LIKE (?) OR rl.doorCodeWithoutSpace LIKE (?)) " + "AND rl.uid NOT IN (" + forbidRoomsSQL + ") " + "ORDER BY rl.doorCode ASC LIMIT " + LIMIT_AUTOCOMPLETE; } PreparedStatement query = connectBDD.prepareStatement(requestSQL); query.setString(1, constraint + "%"); query.setString(2, constraint + "%"); if (forbiddenRooms != null) { int i = 2; for (String roomUID : forbiddenRooms) { query.setString(i, roomUID); ++i; } } // filling the query with values ResultSet resultQuery = query.executeQuery(); while (resultQuery.next()) { FRRoom frRoom = new FRRoom(resultQuery.getString("doorCode"), resultQuery.getString("uid")); // String type = resultQuery.getString("type"); // if (type != null) { // try { // FRRoomType t = FRRoomType.valueOf(type); // frRoom.setType(t); // System.err.println("Type not known " + type); // e.printStackTrace(); int cap = resultQuery.getInt("capacity"); if (cap > 0) { frRoom.setCapacity(cap); } rooms.add(frRoom); } reply = new AutoCompleteReply(HttpURLConnection.HTTP_OK, "" + HttpURLConnection.HTTP_OK); reply.setListRoom(Utils.sortRoomsByBuilding(rooms)); // TODO TO DELETE reply.setListFRRoom(rooms); } catch (SQLException e) { reply = new AutoCompleteReply( HttpURLConnection.HTTP_INTERNAL_ERROR, "" + HttpURLConnection.HTTP_INTERNAL_ERROR); e.printStackTrace(); } return reply; } @Override public ImWorkingReply indicateImWorking(ImWorkingRequest request) throws TException { System.out.println("ImWorkingThere request for room " + request.getWork().getRoom().getDoorCode()); WorkingOccupancy work = request.getWork(); FRPeriod period = work.getPeriod(); FRRoom room = work.getRoom(); boolean success = insertOccupancy(period, OCCUPANCY_TYPE.USER, room); if (success) { return new ImWorkingReply(HttpURLConnection.HTTP_OK, ""); } else { return new ImWorkingReply(HttpURLConnection.HTTP_INTERNAL_ERROR, "Cannot insert user occupancy"); } } @Override public WhoIsWorkingReply whoIsWorking(WhoIsWorkingRequest request) throws TException { // TODO Auto-generated method stub return null; } }
package com.redhat.ceylon.eclipse.code.refactor; import org.eclipse.ltk.ui.refactoring.UserInputWizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import com.redhat.ceylon.eclipse.util.Escaping; import com.redhat.ceylon.ide.common.refactoring.ExtractValueRefactoring; public class ExtractValueInputPage extends UserInputWizardPage { public ExtractValueInputPage(String name) { super(name); } public void createControl(Composite parent) { Composite result = new Composite(parent, SWT.NONE); setControl(result); GridLayout layout = new GridLayout(); layout.numColumns = 2; result.setLayout(layout); Label label = new Label(result, SWT.RIGHT); label.setText("Value name: "); final Text text = new Text(result, SWT.SINGLE|SWT.BORDER); text.setText(getExtractValueRefactoring().getNewName()); text.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false)); text.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent event) { String name = text.getText(); validateIdentifier(name); getExtractValueRefactoring().setNewName(name); } }); final Button et = new Button(result, SWT.CHECK); et.setText("Use explicit type declaration"); et.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent event) { getExtractValueRefactoring().setExplicitType(!getExtractValueRefactoring().getExplicitType()); } @Override public void widgetDefaultSelected(SelectionEvent event) {} }); final Button gs = new Button(result, SWT.CHECK); gs.setText("Create a getter"); gs.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent event) { getExtractValueRefactoring().setGetter(!getExtractValueRefactoring().getGetter()); } @Override public void widgetDefaultSelected(SelectionEvent event) {} }); text.addKeyListener(new SubwordIterator(text)); text.selectAll(); text.setFocus(); } private ExtractValueRefactoring getExtractValueRefactoring() { return (ExtractValueRefactoring) getRefactoring(); } void validateIdentifier(String name) { if (!name.matches("^[a-z_]\\w*$")) { setErrorMessage("Not a legal Ceylon identifier"); setPageComplete(false); } else if (Escaping.KEYWORDS.contains(name)) { setErrorMessage("'" + name + "' is a Ceylon keyword"); setPageComplete(false); } else { setErrorMessage(null); setPageComplete(true); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edacc.properties; import edacc.model.ComputationMethodDAO; import edacc.model.ComputationMethodDoesNotExistException; import edacc.model.DatabaseConnector; import edacc.model.ExperimentResultDAO; import edacc.model.ExperimentResultHasProperty; import edacc.model.ExperimentResultHasPropertyDAO; import edacc.model.InstanceDAO; import edacc.model.InstanceHasProperty; import edacc.model.InstanceHasPropertyDAO; import edacc.model.InstanceHasPropertyNotInDBException; import edacc.model.InstanceNotInDBException; import edacc.model.NoConnectionToDBException; import edacc.model.Property; import edacc.model.PropertyDAO; import edacc.model.PropertyNotInDBException; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.sql.Blob; import java.sql.SQLException; import java.util.StringTokenizer; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author rretz */ public class PropertyComputationUnit implements Runnable { ExperimentResultHasProperty erhp; InstanceHasProperty ihp; PropertyComputationController callback; Property property; PropertyComputationUnit(ExperimentResultHasProperty erhp, PropertyComputationController callback) { this.erhp = erhp; this.callback = callback; this.property = erhp.getProperty(); } PropertyComputationUnit(InstanceHasProperty ihp, PropertyComputationController callback) { this.ihp = ihp; this.callback = callback; this.property = ihp.getProperty(); } @Override public void run() { if(erhp != null){ try { Property property = erhp.getProperty(); switch (property.getPropertySource()) { case LauncherOutput: compute(ExperimentResultDAO.getLauncherOutputFile(erhp.getExpResult())); break; case SolverOutput: compute(ExperimentResultDAO.getSolverOutputFile(erhp.getExpResult())); break; case VerifierOutput: compute(ExperimentResultDAO.getVerifierOutputFile(erhp.getExpResult())); break; case WatcherOutput: compute(ExperimentResultDAO.getWatcherOutputFile(erhp.getExpResult())); break; } } catch (NoConnectionToDBException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception e) { e.printStackTrace(); } }else if(ihp != null){ try { switch (property.getPropertySource()) { case Instance: try { compute(InstanceDAO.getBinaryFileOfInstance(ihp.getInstance())); } catch (InstanceNotInDBException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } break; case InstanceName: parseInstanceName(); break; } } catch (NoConnectionToDBException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception e) { e.printStackTrace(); } } callback.callback(); } private void compute(File f) throws FileNotFoundException, IOException, SQLException, NoConnectionToDBException, InstanceNotInDBException, ComputationMethodDoesNotExistException { if(property.getComputationMethod() != null){ // parse instance file (external program call) if (ihp != null) { File bin = ComputationMethodDAO.getBinaryOfComputationMethod(property.getComputationMethod()); bin.setExecutable(true); Process p = Runtime.getRuntime().exec(bin.getAbsolutePath()); Blob instance = InstanceDAO.getBinary(ihp.getInstance().getId()); BufferedReader instanceReader = new BufferedReader(new InputStreamReader(instance.getBinaryStream())); // The std input stream of the external program. We pipe the content of the instance file into that stream BufferedWriter out = new BufferedWriter(new OutputStreamWriter(p.getOutputStream())); // The std output stream of the external program (-> output of the program). We read the calculated value from this stream. BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); // pipe the content of the instance file to the input of the external program try { int i; while ((i = instanceReader.read()) != -1) out.write(i); } catch (IOException e) { if (!e.getMessage().contains("Broken pipe")) { throw e; } } // Read first line of program output String value = in.readLine(); ihp.setValue(value); System.out.println(value); } }else if(!property.getRegularExpression().equals("") || property.getRegularExpression() != null){ Vector<String> res = new Vector<String>(); BufferedReader buf = new BufferedReader(new FileReader(f)); String tmp; while((tmp = buf.readLine()) != null){ if((tmp = parse(tmp)) != null){ res.add(tmp); if(!property.isMultiple() || ihp != null) break; } } if(ihp != null){ ihp.setValue(res.firstElement()); InstanceHasPropertyDAO.save(ihp); } else if(erhp != null){ erhp.setValue(res); ExperimentResultHasPropertyDAO.save(erhp); } } } private String parse(String toParse) { return null; } private void parseInstanceName() { throw new UnsupportedOperationException("Not yet implemented"); } public static void main(String[] args) { try { DatabaseConnector.getInstance().connect("edacc.informatik.uni-ulm.de", 3306, "edacc", "EDACC2", "edaccteam"); PropertyComputationUnit unit = new PropertyComputationUnit(InstanceHasPropertyDAO.createInstanceHasInstanceProperty(InstanceDAO.getById(1), PropertyDAO.getById(1)), null); unit.compute(null); } catch (NoConnectionToDBException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (PropertyNotInDBException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (PropertyTypeNotExistException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (ComputationMethodDoesNotExistException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception e) { e.printStackTrace(); } } }
package eu.cloudscaleproject.env.extractor.util; import java.lang.reflect.Field; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.gmf.runtime.diagram.core.services.ViewService; import org.eclipse.gmf.runtime.notation.Diagram; import org.eclipse.modisco.infra.discovery.core.AbstractModelDiscoverer; import org.eclipse.modisco.infra.discovery.core.IDiscoveryManager; import org.eclipse.modisco.infra.discovery.core.exception.DiscoveryException; import org.eclipse.modisco.infra.discovery.launch.LaunchConfiguration; import org.eclipse.modisco.infra.discovery.launch.ParameterValue; import org.eclipse.modisco.infra.discovery.ui.Activator; import org.somox.analyzer.simplemodelanalyzer.jobs.SaveSoMoXModelsJob; import org.somox.analyzer.simplemodelanalyzer.jobs.SimpleModelAnalyzerJob; import org.somox.analyzer.simplemodelanalyzer.jobs.SoMoXBlackboard; import org.somox.configuration.SoMoXConfiguration; import org.somox.gast2seff.jobs.GAST2SEFFJob; import org.somox.metrics.IMetric; import org.somox.metrics.naming.NameResemblance; import org.somox.metrics.registry.MetricsRegistry; import org.somox.ui.runconfig.ModelAnalyzerConfiguration; import de.uka.ipd.sdq.pcm.gmf.composite.edit.parts.ComposedProvidingRequiringEntityEditPart; import de.uka.ipd.sdq.pcm.gmf.composite.part.PalladioComponentModelComposedStructureDiagramEditorPlugin; import de.uka.ipd.sdq.pcm.gmf.repository.edit.parts.RepositoryEditPart; import de.uka.ipd.sdq.pcm.gmf.repository.part.PalladioComponentModelRepositoryDiagramEditorPlugin; import eu.cloudscaleproject.env.extractor.alternatives.ConfingAlternative; import eu.cloudscaleproject.env.extractor.alternatives.ResultAlternative; import eu.cloudscaleproject.env.toolchain.ToolchainUtils; import eu.cloudscaleproject.env.toolchain.resources.ResourceProvider; import eu.cloudscaleproject.env.toolchain.resources.ResourceRegistry; public class ExtractorRunJob { public static final String SOMOX_BASE_NAME = "internal_architecture_model"; private IProject project; private ConfingAlternative configFolder; private IProject projectToExtract; private ResultAlternative resultAlternative; public ExtractorRunJob(ConfingAlternative configInputFolder) { this.configFolder = configInputFolder; this.project = configInputFolder.getProject(); this.projectToExtract = configInputFolder.getExtractedProject(); } public IStatus run(IProgressMonitor monitor) throws CoreException { try { this.resultAlternative = createResultPersistenceFolder(); runModisco(monitor); runSomox(monitor); initializeDiagrams(); resultAlternative.save(); resultAlternative.load(); } catch (CoreException e) { throw e; } catch (Exception e) { Status s = new Status(Status.ERROR, Activator.PLUGIN_ID, "Message : "+e.getMessage()); throw new CoreException(s); } return Status.OK_STATUS; } private SimpleDateFormat sdf_name = new SimpleDateFormat("hh:mm:ss"); private ResultAlternative createResultPersistenceFolder() throws CoreException { ResourceProvider resourceProvider = ResourceRegistry.getInstance().getResourceProvider(this.configFolder.getProject(), ToolchainUtils.EXTRACTOR_RES_ID); String name = configFolder.getName() + " [" + sdf_name.format(new Date()) + "]"; return (ResultAlternative) resourceProvider.createNewResource(name, null); } private void runModisco(IProgressMonitor monitor) throws CoreException { LaunchConfiguration modiscoConfiguration = configFolder.getModiscoConfiguration(); AbstractModelDiscoverer<?> discoverer = (AbstractModelDiscoverer<?>) IDiscoveryManager.INSTANCE.createDiscovererImpl(modiscoConfiguration.getDiscoverer().getId()); IFolder modiscoFolder = (IFolder) resultAlternative.getSubResource(ResultAlternative.KEY_FOLDER_MODISCO); IFile java2kdmFile = modiscoFolder.getFile(projectToExtract.getName()+"_java2kdm.xmi"); IFile javaFile = modiscoFolder.getFile(projectToExtract.getName()+"_java.xmi"); IFile kdmFile = modiscoFolder.getFile(projectToExtract.getName()+"_kdm.xmi"); final URI resourceURI = URI.createPlatformResourceURI(java2kdmFile.getFullPath().toString(), true); discoverer.setTargetURI(resourceURI); Map<String, Object> parameters = new HashMap<String, Object>(); EList<ParameterValue> parameterValues = modiscoConfiguration.getParameterValues(); for (ParameterValue parameterValue : parameterValues) { if (parameterValue.getValue() != null) { parameters.put(parameterValue.getParameter().getId(), parameterValue.getValue()); } } try { IDiscoveryManager.INSTANCE.discoverElement(discoverer, projectToExtract, parameters, monitor); resultAlternative.setSubResource(ResultAlternative.KEY_FILE_MODISCO_JAVA2KDM, java2kdmFile); resultAlternative.setSubResource(ResultAlternative.KEY_FILE_MODISCO_JAVA, javaFile); resultAlternative.setSubResource(ResultAlternative.KEY_FILE_MODISCO_KDM, kdmFile); } catch (DiscoveryException e) { IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Please, check your discoverer configuration.", e); //$NON-NLS-1$ throw new CoreException(status); } } private void runSomox(IProgressMonitor monitor) throws CoreException { SoMoXConfiguration somoxConfiguration = configFolder.getSomoxConfiguration(); IFile file = (IFile)resultAlternative.getSubResource(ResultAlternative.KEY_FILE_MODISCO_JAVA2KDM); somoxConfiguration.getFileLocations().setAnalyserInputFile(file.getFullPath().toString()); somoxConfiguration.getFileLocations().setProjectName(this.project.getName()); IFolder res = (IFolder) resultAlternative.getSubResource(ResultAlternative.KEY_FOLDER_SOMOX); somoxConfiguration.getFileLocations().setOutputFolder("/"+res.getProjectRelativePath().toString()); _somoxNameResemblanceBugWorkaround(); try { ModelAnalyzerConfiguration conf = new ModelAnalyzerConfiguration(); conf.setSomoxConfiguration(somoxConfiguration); SoMoXBlackboard blackboard = new SoMoXBlackboard(); SimpleModelAnalyzerJob job = new SimpleModelAnalyzerJob(conf); job.setBlackboard(blackboard); job.execute(monitor); GAST2SEFFJob gast2SeffJob = new GAST2SEFFJob(somoxConfiguration); gast2SeffJob.setBlackboard(blackboard); gast2SeffJob.execute(monitor); SaveSoMoXModelsJob saveJob = new SaveSoMoXModelsJob(somoxConfiguration); saveJob.setBlackboard(blackboard); saveJob.execute(monitor); IFolder somoxFolder = (IFolder) resultAlternative.getSubResource(ResultAlternative.KEY_FOLDER_SOMOX); IFile repositoryModelFile = somoxFolder.getFile(SOMOX_BASE_NAME+".repository"); IFile systemModelFile = somoxFolder.getFile(SOMOX_BASE_NAME+".system"); IFile sourceDecoratorFile = somoxFolder.getFile(SOMOX_BASE_NAME+".sourcecodedecorator"); resultAlternative.setSubResource(ToolchainUtils.KEY_FILE_REPOSITORY, repositoryModelFile); resultAlternative.setSubResource(ToolchainUtils.KEY_FILE_SYSTEM, systemModelFile); resultAlternative.setSubResource(ToolchainUtils.KEY_FILE_SOURCEDECORATOR, sourceDecoratorFile); } catch (Exception e) { IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Please, check your discoverer and SoMoX configuration.", e); //$NON-NLS-1$ throw new CoreException(status); } } private void initializeDiagrams() { IFile repositoryFile = (IFile)resultAlternative.getSubResource(ToolchainUtils.KEY_FILE_REPOSITORY); IFile systemFile = (IFile)resultAlternative.getSubResource(ToolchainUtils.KEY_FILE_SYSTEM); IFolder container = (IFolder)repositoryFile.getParent(); final URI resourceURI = URI.createPlatformResourceURI(repositoryFile.getFullPath().toString(), true); final URI systemURI = URI.createPlatformResourceURI(systemFile.getFullPath().toString(), true); ResourceSet resSet = new ResourceSetImpl(); final Resource systemRes = resSet.createResource(systemURI); final Resource repositoryRes = resSet.createResource(resourceURI); IFile repositoryDiagramFile = container.getFile(SOMOX_BASE_NAME+".repository_diagram"); IFile systemDiagramFile = container.getFile(SOMOX_BASE_NAME+".system_diagram"); final URI resourceDiagramURI = URI.createPlatformResourceURI(repositoryDiagramFile.getFullPath().toString(), true); final URI systemDiagramURI = URI.createPlatformResourceURI(systemDiagramFile.getFullPath().toString(), true); Resource repositoryDiagramResource = resSet.createResource(resourceDiagramURI); Resource systemDiagramResource = resSet.createResource(systemDiagramURI); try { systemRes.load(null); repositoryRes.load(null); Diagram repositoryDiagram = ViewService.createDiagram(repositoryRes.getContents().get(0), RepositoryEditPart.MODEL_ID, PalladioComponentModelRepositoryDiagramEditorPlugin.DIAGRAM_PREFERENCES_HINT); repositoryDiagramResource.getContents().add(repositoryDiagram); repositoryDiagramResource.save(null); Diagram systemDiagram = ViewService.createDiagram(systemRes.getContents().get(0), ComposedProvidingRequiringEntityEditPart.MODEL_ID, PalladioComponentModelComposedStructureDiagramEditorPlugin.DIAGRAM_PREFERENCES_HINT); systemDiagramResource.getContents().add(systemDiagram); systemDiagramResource.save(null); resultAlternative.setSubResource(ResultAlternative.KEY_FILE_REPOSITORY_DIAGRAM, repositoryDiagramFile); resultAlternative.setSubResource(ResultAlternative.KEY_FILE_SYSTEM_DIAGRAM, systemDiagramFile); } catch (Exception e) { e.printStackTrace(); } repositoryRes.unload(); repositoryDiagramResource.unload(); systemRes.unload(); systemDiagramResource.unload(); } private void _somoxNameResemblanceBugWorkaround() { // Clear Unmodifiable Map in NameResemblance metric for (IMetric metric : MetricsRegistry.getRegisteredMetrics().values()) { if (metric instanceof NameResemblance) { NameResemblance nr = ((NameResemblance)metric); try { Field field = NameResemblance.class.getDeclaredField("nameResemblanceMap"); field.setAccessible(true); field.set(nr, new HashMap<>()); } catch (Exception e) { e.printStackTrace(); } } } } }
package edu.mit.streamjit.impl.compiler; import edu.mit.streamjit.impl.compiler.types.RegularType; /** * An Argument represents an argument to a Method. * @author Jeffrey Bosboom <jeffreybosboom@gmail.com> * @since 3/6/2013 */ public class Argument extends Value implements Parented<Method> { private final Method parent; public Argument(Method parent, RegularType type) { super(type); this.parent = parent; } public Argument(Method parent, RegularType type, String name) { super(type, name); this.parent = parent; } @Override public Method getParent() { return parent; } @Override public RegularType getType() { return (RegularType)super.getType(); } @Override public String toString() { if (getName() != null) return getName(); return getClass().getSimpleName()+"@"+hashCode(); } }
package edu.mit.streamjit.impl.compiler; import static com.google.common.base.Preconditions.*; import com.google.common.collect.HashBasedTable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; import com.google.common.collect.Table; import com.google.common.math.IntMath; import edu.mit.streamjit.api.Filter; import edu.mit.streamjit.api.Identity; import edu.mit.streamjit.api.Joiner; import edu.mit.streamjit.api.OneToOneElement; import edu.mit.streamjit.api.Rate; import edu.mit.streamjit.api.RoundrobinJoiner; import edu.mit.streamjit.api.RoundrobinSplitter; import edu.mit.streamjit.api.Splitjoin; import edu.mit.streamjit.api.Splitter; import edu.mit.streamjit.api.StatefulFilter; import edu.mit.streamjit.api.StreamCompilationFailedException; import edu.mit.streamjit.api.Worker; import edu.mit.streamjit.impl.blob.Blob; import edu.mit.streamjit.impl.blob.Blob.Token; import edu.mit.streamjit.impl.blob.Buffer; import edu.mit.streamjit.impl.blob.Buffers; import edu.mit.streamjit.impl.blob.DrainData; import edu.mit.streamjit.impl.common.Configuration; import edu.mit.streamjit.impl.common.ConnectWorkersVisitor; import edu.mit.streamjit.impl.common.IOInfo; import edu.mit.streamjit.impl.common.MessageConstraint; import edu.mit.streamjit.impl.common.Workers; import edu.mit.streamjit.impl.compiler.insts.ArrayLoadInst; import edu.mit.streamjit.impl.compiler.insts.ArrayStoreInst; import edu.mit.streamjit.impl.compiler.insts.BinaryInst; import edu.mit.streamjit.impl.compiler.insts.BranchInst; import edu.mit.streamjit.impl.compiler.insts.CallInst; import edu.mit.streamjit.impl.compiler.insts.CastInst; import edu.mit.streamjit.impl.compiler.insts.Instruction; import edu.mit.streamjit.impl.compiler.insts.JumpInst; import edu.mit.streamjit.impl.compiler.insts.LoadInst; import edu.mit.streamjit.impl.compiler.insts.NewArrayInst; import edu.mit.streamjit.impl.compiler.insts.PhiInst; import edu.mit.streamjit.impl.compiler.insts.ReturnInst; import edu.mit.streamjit.impl.compiler.insts.StoreInst; import edu.mit.streamjit.impl.compiler.types.ArrayType; import edu.mit.streamjit.impl.compiler.types.FieldType; import edu.mit.streamjit.impl.compiler.types.MethodType; import edu.mit.streamjit.impl.compiler.types.RegularType; import edu.mit.streamjit.impl.interp.ArrayChannel; import edu.mit.streamjit.impl.interp.Channel; import edu.mit.streamjit.impl.interp.ChannelFactory; import edu.mit.streamjit.impl.interp.Interpreter; import edu.mit.streamjit.util.Pair; import java.io.PrintWriter; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandleProxies; import java.lang.invoke.MethodHandles; import java.lang.invoke.SwitchPoint; import java.math.RoundingMode; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /** * * @author Jeffrey Bosboom <jeffreybosboom@gmail.com> * @since 4/24/2013 */ public final class Compiler { /** * A counter used to generate package names unique to a given machine. */ private static final AtomicInteger PACKAGE_NUMBER = new AtomicInteger(); private final Set<Worker<?, ?>> workers; private final Configuration config; private final int maxNumCores; private final ImmutableSet<IOInfo> ioinfo; private final Worker<?, ?> firstWorker, lastWorker; /** * Maps a worker to the StreamNode that contains it. Updated by * StreamNode's constructors. (It would be static in * StreamNode if statics of inner classes were supported and worked as * though there was one instance per parent instance.) */ private final Map<Worker<?, ?>, StreamNode> streamNodes = new IdentityHashMap<>(); private final Map<Worker<?, ?>, Method> workerWorkMethods = new IdentityHashMap<>(); private Schedule<StreamNode> schedule; private Schedule<Worker<?, ?>> initSchedule; private final String packagePrefix; private final Module module = new Module(); private final Klass blobKlass; /** * The steady-state execution multiplier (the number of executions to run * per synchronization). */ private final int multiplier; /** * The work method type, which is void(Object[][], int[], int[], Object[][], * int[], int[]). (There is no receiver argument.) */ private final MethodType workMethodType; private ImmutableMap<Token, BufferData> buffers; /** * Contains static fields so that final static fields in blobKlass can load * from them in the blobKlass static initializer. */ private final Klass fieldHelperKlass; public Compiler(Set<Worker<?, ?>> workers, Configuration config, int maxNumCores) { this.workers = workers; this.config = config; this.maxNumCores = maxNumCores; this.ioinfo = IOInfo.externalEdges(workers); //We can only have one first and last worker, though they can have //multiple inputs/outputs. Worker<?, ?> firstWorker = null, lastWorker = null; for (IOInfo io : ioinfo) if (io.isInput()) if (firstWorker == null) firstWorker = io.downstream(); else checkArgument(firstWorker == io.downstream(), "two input workers"); else if (lastWorker == null) lastWorker = io.upstream(); else checkArgument(lastWorker == io.upstream(), "two output workers"); assert firstWorker != null : "Can't happen! No first worker?"; assert lastWorker != null : "Can't happen! No last worker?"; this.firstWorker = firstWorker; this.lastWorker = lastWorker; //We require that all rates of workers in our set are fixed, except for //the output rates of the last worker. for (Worker<?, ?> w : workers) { for (Rate r : w.getPopRates()) checkArgument(r.isFixed()); if (w != lastWorker) for (Rate r : w.getPushRates()) checkArgument(r.isFixed()); } //We don't support messaging. List<MessageConstraint> constraints = MessageConstraint.findConstraints(firstWorker); for (MessageConstraint c : constraints) { checkArgument(!workers.contains(c.getSender())); checkArgument(!workers.contains(c.getRecipient())); } this.packagePrefix = "compiler"+PACKAGE_NUMBER.getAndIncrement()+"."; this.blobKlass = new Klass(packagePrefix + "Blob", module.getKlass(Object.class), Collections.<Klass>emptyList(), module); blobKlass.modifiers().addAll(EnumSet.of(Modifier.PUBLIC, Modifier.FINAL)); this.fieldHelperKlass = new Klass(packagePrefix + "FieldHelper", module.getKlass(Object.class), Collections.<Klass>emptyList(), module); fieldHelperKlass.modifiers().addAll(EnumSet.of(Modifier.PUBLIC, Modifier.FINAL)); this.multiplier = config.getParameter("multiplier", Configuration.IntParameter.class).getValue(); this.workMethodType = module.types().getMethodType(void.class, Object[][].class, int[].class, int[].class, Object[][].class, int[].class, int[].class); } public Blob compile() { for (Worker<?, ?> w : workers) new StreamNode(w); //adds itself to streamNodes map fuse(); //Compute per-node steady state execution counts. for (StreamNode n : ImmutableSet.copyOf(streamNodes.values())) n.internalSchedule(); externalSchedule(); computeInitSchedule(); allocateCores(); declareBuffers(); //We generate a work method for each worker (which may result in //duplicates, but is required in general to handle worker fields), then //generate core code that stitches them together and does any //required data movement. for (Worker<?, ?> w : streamNodes.keySet()) makeWorkMethod(w); for (StreamNode n : ImmutableSet.copyOf(streamNodes.values())) n.makeWorkMethod(); generateCoreCode(); generateStaticInit(); addBlobPlumbing(); //blobKlass.dump(new PrintWriter(System.out, true)); return instantiateBlob(); } /** * Fuses StreamNodes as directed by the configuration. */ private void fuse() { //TODO: some kind of worklist algorithm that fuses until no more fusion //possible, to handle state, peeking, or attempts to fuse with more than //one predecessor. } /** * Allocates StreamNodes to cores as directed by the configuration, possibly * fissing them (if assigning one node to multiple cores). * TODO: do we want to permit unequal fiss allocations (e.g., 6 SSEs here, * 3 SSEs there)? */ private void allocateCores() { //TODO //Note that any node containing a splitter or joiner can only go on one //core (as it has to synchronize for its inputs and outputs). //For now, just put everything on core 0. for (StreamNode n : ImmutableSet.copyOf(streamNodes.values())) n.cores.add(0); } /** * Computes buffer capacity and initial sizes, declaring (but not * arranging for initialization of) the blob class fields pointing to the * buffers. */ private void declareBuffers() { ImmutableMap.Builder<Token, BufferData> builder = ImmutableMap.<Token, BufferData>builder(); for (IOInfo info : IOInfo.internalEdges(workers)) //Only declare buffers for worker pairs not in the same node. If //a node needs internal buffering, it handles that itself. (This //implies that peeking filters cannot be fused upwards, but that's //a bad idea anyway.) if (!streamNodes.get(info.upstream()).equals(streamNodes.get(info.downstream()))) builder.put(info.token(), makeBuffers(info)); //Make buffers for the inputs and outputs of this blob (which may or //may not be overall inputs of the stream graph). for (IOInfo info : ioinfo) if (firstWorker.equals(info.downstream()) || lastWorker.equals(info.upstream())) builder.put(info.token(), makeBuffers(info)); buffers = builder.build(); } /** * Creates buffers in the blobKlass for the given workers, returning a * BufferData describing the buffers created. * * One of upstream xor downstream may be null for the overall input and * output. */ private BufferData makeBuffers(IOInfo info) { Worker<?, ?> upstream = info.upstream(), downstream = info.downstream(); Token token = info.token(); assert upstream != null || downstream != null; final String upstreamId = upstream != null ? Integer.toString(token.getUpstreamIdentifier()) : "input"; final String downstreamId = downstream != null ? Integer.toString(token.getDownstreamIdentifier()) : "output"; final StreamNode upstreamNode = streamNodes.get(upstream); final StreamNode downstreamNode = streamNodes.get(downstream); RegularType objArrayTy = module.types().getRegularType(Object[].class); String fieldName = "buf_"+upstreamId+"_"+downstreamId; assert downstreamNode != upstreamNode; String readerBufferFieldName = token.isOverallOutput() ? null : fieldName + "r"; String writerBufferFieldName = token.isOverallInput() ? null : fieldName + "w"; for (String field : new String[]{readerBufferFieldName, writerBufferFieldName}) if (field != null) new Field(objArrayTy, field, EnumSet.of(Modifier.PUBLIC, Modifier.STATIC), blobKlass); int capacity, initialSize, unconsumedItems; if (info.isInternal()) { assert upstreamNode != null && downstreamNode != null; assert !upstreamNode.equals(downstreamNode) : "shouldn't be buffering on intra-node edge"; capacity = initialSize = initSchedule.getBufferDelta(upstream, downstream); unconsumedItems = capacity - schedule.getThroughput(upstreamNode, downstreamNode); assert unconsumedItems >= 0; } else if (info.isInput()) { assert downstream != null; int chanIdx = info.getDownstreamChannelIndex(); int pop = downstream.getPopRates().get(chanIdx).max(), peek = downstream.getPeekRates().get(chanIdx).max(); unconsumedItems = Math.max(peek - pop, 0); capacity = initialSize = downstreamNode.internalSchedule.getExecutions(downstream) * schedule.getExecutions(downstreamNode) * pop + unconsumedItems; } else if (info.isOutput()) { int push = upstream.getPushRates().get(info.getUpstreamChannelIndex()).max(); capacity = upstreamNode.internalSchedule.getExecutions(upstream) * schedule.getExecutions(upstreamNode) * push; initialSize = 0; unconsumedItems = 0; } else throw new AssertionError(info); return new BufferData(token, readerBufferFieldName, writerBufferFieldName, capacity, initialSize, unconsumedItems); } /** * Computes the initialization schedule using the scheduler. */ private void computeInitSchedule() { Schedule.Builder<Worker<?, ?>> builder = Schedule.builder(); builder.addAll(workers); for (IOInfo info : IOInfo.internalEdges(workers)) { Schedule.Builder<Worker<?, ?>>.ConstraintBuilder constraint = builder.connect(info.upstream(), info.downstream()) .push(info.upstream().getPushRates().get(info.getUpstreamChannelIndex()).max()) .pop(info.downstream().getPopRates().get(info.getDownstreamChannelIndex()).max()) .peek(info.downstream().getPeekRates().get(info.getDownstreamChannelIndex()).max()); //Inter-node edges require at least a steady-state's worth of //buffering (to avoid synchronization); intra-node edges cannot have //any buffering at all. StreamNode upstreamNode = streamNodes.get(info.upstream()); StreamNode downstreamNode = streamNodes.get(info.downstream()); if (!upstreamNode.equals(downstreamNode)) constraint.bufferAtLeast(schedule.getSteadyStateBufferSize(upstreamNode, downstreamNode)); else constraint.bufferExactly(0); } try { initSchedule = builder.build(); } catch (Schedule.ScheduleException ex) { throw new StreamCompilationFailedException("couldn't find initialization schedule", ex); } } /** * Make the work method for the given worker. We actually make two methods * here: first we make a copy with a dummy receiver argument, just to have a * copy to work with. After remapping every use of that receiver (remapping * field accesses to the worker's static fields, remapping JIT-hooks to * their implementations, and remapping utility methods in the worker class * recursively), we then externalEdges the actual work method without the receiver * argument. * @param worker */ private void makeWorkMethod(Worker<?, ?> worker) { StreamNode node = streamNodes.get(worker); int id = Workers.getIdentifier(worker); int numInputs = getNumInputs(worker); int numOutputs = getNumOutputs(worker); Klass workerKlass = module.getKlass(worker.getClass()); Method oldWork = workerKlass.getMethodByVirtual("work", module.types().getMethodType(void.class, worker.getClass())); oldWork.resolve(); //Add a dummy receiver argument so we can clone the user's work method. MethodType rworkMethodType = workMethodType.prependArgument(module.types().getRegularType(workerKlass)); Method newWork = new Method("rwork"+id, rworkMethodType, EnumSet.of(Modifier.PRIVATE, Modifier.STATIC), blobKlass); newWork.arguments().get(0).setName("dummyReceiver"); newWork.arguments().get(1).setName("ichannels"); newWork.arguments().get(2).setName("ioffsets"); newWork.arguments().get(3).setName("iincrements"); newWork.arguments().get(4).setName("ochannels"); newWork.arguments().get(5).setName("ooffsets"); newWork.arguments().get(6).setName("oincrements"); Map<Value, Value> vmap = new IdentityHashMap<>(); vmap.put(oldWork.arguments().get(0), newWork.arguments().get(0)); Cloning.cloneMethod(oldWork, newWork, vmap); BasicBlock entryBlock = new BasicBlock(module, "entry"); newWork.basicBlocks().add(0, entryBlock); //We make copies of the offset arrays. (int[].clone() returns Object, //so we have to cast.) Method clone = Iterables.getOnlyElement(module.getKlass(Object.class).getMethods("clone")); CallInst ioffsetCloneCall = new CallInst(clone, newWork.arguments().get(2)); entryBlock.instructions().add(ioffsetCloneCall); CastInst ioffsetCast = new CastInst(module.types().getArrayType(int[].class), ioffsetCloneCall); entryBlock.instructions().add(ioffsetCast); LocalVariable ioffsetCopy = new LocalVariable((RegularType)ioffsetCast.getType(), "ioffsetCopy", newWork); StoreInst popCountInit = new StoreInst(ioffsetCopy, ioffsetCast); popCountInit.setName("ioffsetInit"); entryBlock.instructions().add(popCountInit); CallInst ooffsetCloneCall = new CallInst(clone, newWork.arguments().get(5)); entryBlock.instructions().add(ooffsetCloneCall); CastInst ooffsetCast = new CastInst(module.types().getArrayType(int[].class), ooffsetCloneCall); entryBlock.instructions().add(ooffsetCast); LocalVariable ooffsetCopy = new LocalVariable((RegularType)ooffsetCast.getType(), "ooffsetCopy", newWork); StoreInst pushCountInit = new StoreInst(ooffsetCopy, ooffsetCast); pushCountInit.setName("ooffsetInit"); entryBlock.instructions().add(pushCountInit); entryBlock.instructions().add(new JumpInst(newWork.basicBlocks().get(1))); //Remap stuff in rwork. for (BasicBlock b : newWork.basicBlocks()) for (Instruction i : ImmutableList.copyOf(b.instructions())) if (Iterables.contains(i.operands(), newWork.arguments().get(0))) remapEliminiatingReceiver(i, worker); //At this point, we've replaced all uses of the dummy receiver argument. assert newWork.arguments().get(0).uses().isEmpty(); Method trueWork = new Method("work"+id, workMethodType, EnumSet.of(Modifier.PRIVATE, Modifier.STATIC), blobKlass); vmap.clear(); vmap.put(newWork.arguments().get(0), null); for (int i = 1; i < newWork.arguments().size(); ++i) vmap.put(newWork.arguments().get(i), trueWork.arguments().get(i-1)); Cloning.cloneMethod(newWork, trueWork, vmap); workerWorkMethods.put(worker, trueWork); newWork.eraseFromParent(); } private void remapEliminiatingReceiver(Instruction inst, Worker<?, ?> worker) { BasicBlock block = inst.getParent(); Method rwork = inst.getParent().getParent(); if (inst instanceof CallInst) { CallInst ci = (CallInst)inst; Method method = ci.getMethod(); Klass filterKlass = module.getKlass(Filter.class); Klass splitterKlass = module.getKlass(Splitter.class); Klass joinerKlass = module.getKlass(Joiner.class); Method peek1Filter = filterKlass.getMethod("peek", module.types().getMethodType(Object.class, Filter.class, int.class)); assert peek1Filter != null; Method peek1Splitter = splitterKlass.getMethod("peek", module.types().getMethodType(Object.class, Splitter.class, int.class)); assert peek1Splitter != null; Method pop1Filter = filterKlass.getMethod("pop", module.types().getMethodType(Object.class, Filter.class)); assert pop1Filter != null; Method pop1Splitter = splitterKlass.getMethod("pop", module.types().getMethodType(Object.class, Splitter.class)); assert pop1Splitter != null; Method push1Filter = filterKlass.getMethod("push", module.types().getMethodType(void.class, Filter.class, Object.class)); assert push1Filter != null; Method push1Joiner = joinerKlass.getMethod("push", module.types().getMethodType(void.class, Joiner.class, Object.class)); assert push1Joiner != null; Method peek2 = joinerKlass.getMethod("peek", module.types().getMethodType(Object.class, Joiner.class, int.class, int.class)); assert peek2 != null; Method pop2 = joinerKlass.getMethod("pop", module.types().getMethodType(Object.class, Joiner.class, int.class)); assert pop2 != null; Method push2 = splitterKlass.getMethod("push", module.types().getMethodType(void.class, Splitter.class, int.class, Object.class)); assert push2 != null; Method inputs = joinerKlass.getMethod("inputs", module.types().getMethodType(int.class, Joiner.class)); assert inputs != null; Method outputs = splitterKlass.getMethod("outputs", module.types().getMethodType(int.class, Splitter.class)); assert outputs != null; Method channelPush = module.getKlass(Channel.class).getMethod("push", module.types().getMethodType(void.class, Channel.class, Object.class)); assert channelPush != null; if (method.equals(peek1Filter) || method.equals(peek1Splitter) || method.equals(peek2)) { Value channelNumber = method.equals(peek2) ? ci.getArgument(1) : module.constants().getSmallestIntConstant(0); Argument ichannels = rwork.getArgument("ichannels"); ArrayLoadInst channel = new ArrayLoadInst(ichannels, channelNumber); LoadInst ioffsets = new LoadInst(rwork.getLocalVariable("ioffsetCopy")); ArrayLoadInst offsetBase = new ArrayLoadInst(ioffsets, channelNumber); Value peekIndex = method.equals(peek2) ? ci.getArgument(2) : ci.getArgument(1); BinaryInst offset = new BinaryInst(offsetBase, BinaryInst.Operation.ADD, peekIndex); ArrayLoadInst item = new ArrayLoadInst(channel, offset); item.setName("peekedItem"); inst.replaceInstWithInsts(item, channel, ioffsets, offsetBase, offset, item); } else if (method.equals(pop1Filter) || method.equals(pop1Splitter) || method.equals(pop2)) { Value channelNumber = method.equals(pop2) ? ci.getArgument(1) : module.constants().getSmallestIntConstant(0); Argument ichannels = rwork.getArgument("ichannels"); ArrayLoadInst channel = new ArrayLoadInst(ichannels, channelNumber); LoadInst ioffsets = new LoadInst(rwork.getLocalVariable("ioffsetCopy")); ArrayLoadInst offset = new ArrayLoadInst(ioffsets, channelNumber); ArrayLoadInst item = new ArrayLoadInst(channel, offset); item.setName("poppedItem"); Argument iincrements = rwork.getArgument("iincrements"); ArrayLoadInst increment = new ArrayLoadInst(iincrements, channelNumber); BinaryInst newOffset = new BinaryInst(offset, BinaryInst.Operation.ADD, increment); ArrayStoreInst storeNewOffset = new ArrayStoreInst(ioffsets, channelNumber, newOffset); inst.replaceInstWithInsts(item, channel, ioffsets, offset, item, increment, newOffset, storeNewOffset); } else if ((method.equals(push1Filter) || method.equals(push1Joiner)) || method.equals(push2)) { Value channelNumber = method.equals(push2) ? ci.getArgument(1) : module.constants().getSmallestIntConstant(0); Value item = method.equals(push2) ? ci.getArgument(2) : ci.getArgument(1); Argument ochannels = rwork.getArgument("ochannels"); ArrayLoadInst channel = new ArrayLoadInst(ochannels, channelNumber); LoadInst ooffsets = new LoadInst(rwork.getLocalVariable("ooffsetCopy")); ArrayLoadInst offset = new ArrayLoadInst(ooffsets, channelNumber); ArrayStoreInst store = new ArrayStoreInst(channel, offset, item); Argument oincrements = rwork.getArgument("oincrements"); ArrayLoadInst increment = new ArrayLoadInst(oincrements, channelNumber); BinaryInst newOffset = new BinaryInst(offset, BinaryInst.Operation.ADD, increment); ArrayStoreInst storeNewOffset = new ArrayStoreInst(ooffsets, channelNumber, newOffset); inst.replaceInstWithInsts(store, channel, ooffsets, offset, store, increment, newOffset, storeNewOffset); } else if (method.equals(outputs)) { inst.replaceInstWithValue(module.constants().getSmallestIntConstant(getNumOutputs(worker))); } else if (method.equals(inputs)) { inst.replaceInstWithValue(module.constants().getSmallestIntConstant(getNumInputs(worker))); } else throw new AssertionError(inst); } else if (inst instanceof LoadInst) { LoadInst li = (LoadInst)inst; assert li.getLocation() instanceof Field; LoadInst replacement = new LoadInst(streamNodes.get(worker).fields.get(worker, (Field)li.getLocation())); li.replaceInstWithInst(replacement); } else throw new AssertionError("Couldn't eliminate reciever: "+inst); } private int getNumInputs(Worker<?, ?> w) { return Workers.getInputChannels(w).size(); } private int getNumOutputs(Worker<?, ?> w) { return Workers.getOutputChannels(w).size(); } /** * Generates the corework* methods, which contain the steady-state code for * each core. (The buffers are assumed to be already prepared.) */ private void generateCoreCode() { Map<Integer, Method> coreCodeMethods = new HashMap<>(); List<StreamNode> nodes = new ArrayList<>(ImmutableSet.copyOf(streamNodes.values())); Collections.sort(nodes, new Comparator<StreamNode>() { @Override public int compare(StreamNode o1, StreamNode o2) { return Integer.compare(o1.id, o2.id); } }); for (StreamNode sn : nodes) for (int core : sn.cores) if (!coreCodeMethods.containsKey(core)) { Method m = new Method("corework"+core, module.types().getMethodType(void.class), EnumSet.of(Modifier.PUBLIC, Modifier.STATIC), blobKlass); coreCodeMethods.put(core, m); m.basicBlocks().add(new BasicBlock(module, "entry")); } for (StreamNode sn : nodes) { Integer iterations = schedule.getExecutions(sn); //TODO: at some point, this division should be config-controlled, so //we can balance well in the presence of stateful (unparallelizable) //filters. For now just divide evenly. //Assign full iterations to all cores, then distribute the remainder //evenly. int full = IntMath.divide(iterations, sn.cores.size(), RoundingMode.DOWN); int remainder = iterations - full*sn.cores.size(); assert remainder >= 0 && remainder < sn.cores.size() : String.format("divided %d / %d into %d with rem %d", iterations, sn.cores.size(), full, remainder); int multiple = 0; for (int i = 0; i < sn.cores.size(); ++i) { Method coreCode = coreCodeMethods.get(sn.cores.get(i)); int howMany = full + (i < remainder ? 1 : 0); if (howMany > 0) { BasicBlock previousBlock = coreCode.basicBlocks().get(coreCode.basicBlocks().size()-1); BasicBlock loop = makeCallLoop(sn.workMethod, multiple, multiple + howMany, previousBlock, "node"+sn.id); coreCode.basicBlocks().add(loop); if (previousBlock.getTerminator() == null) previousBlock.instructions().add(new JumpInst(loop)); else ((BranchInst)previousBlock.getTerminator()).setOperand(3, loop); multiple += howMany; } } assert multiple == iterations : "Didn't assign all iterations to cores"; } for (Method m : coreCodeMethods.values()) { BasicBlock exitBlock = new BasicBlock(module, "exit"); exitBlock.instructions().add(new ReturnInst(module.types().getVoidType())); BasicBlock previousBlock = m.basicBlocks().get(m.basicBlocks().size()-1); m.basicBlocks().add(exitBlock); if (previousBlock.getTerminator() == null) previousBlock.instructions().add(new JumpInst(exitBlock)); else ((BranchInst)previousBlock.getTerminator()).setOperand(3, exitBlock); } } /** * Creates a block that calls the given method with arguments from begin to * end. Block ends in a BranchInst with its false branch not set (to be set * to the next block by the caller). */ private BasicBlock makeCallLoop(Method method, int begin, int end, BasicBlock previousBlock, String loopName) { int tripcount = end-begin; assert tripcount > 0 : String.format("0 tripcount in makeCallLoop: %s, %d, %d, %s, %s", method, begin, end, previousBlock, loopName); BasicBlock body = new BasicBlock(module, loopName+"_loop"); PhiInst count = new PhiInst(module.types().getRegularType(int.class)); count.put(previousBlock, module.constants().getConstant(begin)); body.instructions().add(count); CallInst call = new CallInst(method, count); body.instructions().add(call); BinaryInst increment = new BinaryInst(count, BinaryInst.Operation.ADD, module.constants().getConstant(1)); body.instructions().add(increment); count.put(body, increment); BranchInst branch = new BranchInst(increment, BranchInst.Sense.LT, module.constants().getConstant(end), body, null); body.instructions().add(branch); return body; } private void generateStaticInit() { Method clinit = new Method("<clinit>", module.types().getMethodType(void.class), EnumSet.of(Modifier.STATIC), blobKlass); //Generate fields in field helper, then copy them over in clinit. BasicBlock fieldBlock = new BasicBlock(module, "copyFieldsFromHelper"); clinit.basicBlocks().add(fieldBlock); for (StreamNode node : ImmutableSet.copyOf(streamNodes.values())) for (Field cell : node.fields.values()) { Field helper = new Field(cell.getType().getFieldType(), cell.getName(), EnumSet.of(Modifier.PUBLIC, Modifier.STATIC), fieldHelperKlass); LoadInst li = new LoadInst(helper); StoreInst si = new StoreInst(cell, li); fieldBlock.instructions().add(li); fieldBlock.instructions().add(si); } BasicBlock bufferBlock = new BasicBlock(module, "newBuffers"); clinit.basicBlocks().add(bufferBlock); for (BufferData data : ImmutableSortedSet.copyOf(buffers.values())) for (String fieldName : new String[]{data.readerBufferFieldName, data.writerBufferFieldName}) if (fieldName != null) { Field field = blobKlass.getField(fieldName); NewArrayInst nai = new NewArrayInst((ArrayType)field.getType().getFieldType(), module.constants().getConstant(data.capacity)); StoreInst si = new StoreInst(field, nai); bufferBlock.instructions().add(nai); bufferBlock.instructions().add(si); } BasicBlock exitBlock = new BasicBlock(module, "exit"); clinit.basicBlocks().add(exitBlock); exitBlock.instructions().add(new ReturnInst(module.types().getVoidType())); for (int i = 0; i < clinit.basicBlocks().size()-1; ++i) clinit.basicBlocks().get(i).instructions().add(new JumpInst(clinit.basicBlocks().get(i+1))); } /** * Adds required plumbing code to the blob class, such as the ctor and the * implementations of the Blob methods. */ private void addBlobPlumbing() { //ctor Method init = new Method("<init>", module.types().getMethodType(module.types().getType(blobKlass)), EnumSet.noneOf(Modifier.class), blobKlass); BasicBlock b = new BasicBlock(module); init.basicBlocks().add(b); Method objCtor = module.getKlass(Object.class).getMethods("<init>").iterator().next(); b.instructions().add(new CallInst(objCtor)); b.instructions().add(new ReturnInst(module.types().getVoidType())); //TODO: other Blob interface methods } private Blob instantiateBlob() { ModuleClassLoader mcl = new ModuleClassLoader(module); try { initFieldHelper(mcl.loadClass(fieldHelperKlass.getName())); Class<?> blobClass = mcl.loadClass(blobKlass.getName()); return new CompilerBlobHost(workers, config, blobClass, ImmutableList.copyOf(buffers.values()), initSchedule.getSchedule()); } catch (ClassNotFoundException ex) { throw new AssertionError(ex); } } private void initFieldHelper(Class<?> fieldHelperClass) { for (StreamNode node : ImmutableSet.copyOf(streamNodes.values())) for (Table.Cell<Worker<?, ?>, Field, Object> cell : node.fieldValues.cellSet()) try { fieldHelperClass.getField(node.fields.get(cell.getRowKey(), cell.getColumnKey()).getName()).set(null, cell.getValue()); } catch (NoSuchFieldException | IllegalAccessException ex) { throw new AssertionError(ex); } } private void externalSchedule() { ImmutableSet<StreamNode> nodes = ImmutableSet.copyOf(streamNodes.values()); Schedule.Builder<StreamNode> scheduleBuilder = Schedule.builder(); scheduleBuilder.addAll(nodes); for (StreamNode n : nodes) n.constrainExternalSchedule(scheduleBuilder); scheduleBuilder.multiply(multiplier); try { schedule = scheduleBuilder.build(); } catch (Schedule.ScheduleException ex) { throw new StreamCompilationFailedException("couldn't find external schedule", ex); } } private final class StreamNode { private final int id; private final ImmutableSet<Worker<?, ?>> workers; private final ImmutableSortedSet<IOInfo> ioinfo; private ImmutableMap<Worker<?, ?>, ImmutableSortedSet<IOInfo>> inputIOs, outputIOs; /** * The number of individual worker executions per steady-state execution * of the StreamNode. */ private Schedule<Worker<?, ?>> internalSchedule; /** * This node's work method. May be null if the method hasn't been * created yet. TODO: if we put multiplicities inside work methods, * we'll need one per core. Alternately we could put them outside and * inline/specialize as a postprocessing step. */ private Method workMethod; /** * Maps each worker's fields to the corresponding fields in the blob * class. */ private final Table<Worker<?, ?>, Field, Field> fields = HashBasedTable.create(); /** * Maps each worker's fields to the actual values of those fields. */ private final Table<Worker<?, ?>, Field, Object> fieldValues = HashBasedTable.create(); private final List<Integer> cores = new ArrayList<>(); private StreamNode(Worker<?, ?> worker) { this.id = Workers.getIdentifier(worker); this.workers = (ImmutableSet<Worker<?, ?>>)ImmutableSet.of(worker); this.ioinfo = ImmutableSortedSet.copyOf(IOInfo.TOKEN_SORT, IOInfo.externalEdges(workers)); buildWorkerData(worker); assert !streamNodes.containsKey(worker); streamNodes.put(worker, this); } /** * Fuses two StreamNodes. They should not yet have been scheduled or * had work functions constructed. */ private StreamNode(StreamNode a, StreamNode b) { this.id = Math.min(a.id, b.id); this.workers = ImmutableSet.<Worker<?, ?>>builder().addAll(a.workers).addAll(b.workers).build(); this.ioinfo = ImmutableSortedSet.copyOf(IOInfo.TOKEN_SORT, IOInfo.externalEdges(workers)); this.fields.putAll(a.fields); this.fields.putAll(b.fields); this.fieldValues.putAll(a.fieldValues); this.fieldValues.putAll(b.fieldValues); for (Worker<?, ?> w : a.workers) streamNodes.put(w, this); for (Worker<?, ?> w : b.workers) streamNodes.put(w, this); } /** * Compute the steady-state multiplicities of each worker in this node * for each execution of the node. */ public void internalSchedule() { Schedule.Builder<Worker<?, ?>> scheduleBuilder = Schedule.builder(); scheduleBuilder.addAll(workers); for (IOInfo info : IOInfo.internalEdges(workers)) scheduleBuilder.connect(info.upstream(), info.downstream()) .push(info.upstream().getPushRates().get(info.getUpstreamChannelIndex()).max()) .pop(info.downstream().getPopRates().get(info.getDownstreamChannelIndex()).max()) .peek(info.downstream().getPeekRates().get(info.getDownstreamChannelIndex()).max()) .bufferExactly(0); try { this.internalSchedule = scheduleBuilder.build(); } catch (Schedule.ScheduleException ex) { throw new StreamCompilationFailedException("couldn't find internal schedule for node "+id, ex); } } /** * Adds constraints for each output edge of this StreamNode, with rates * corrected for the internal schedule for both nodes. (Only output * edges so that we don't get duplicate constraints.) */ public void constrainExternalSchedule(Schedule.Builder<StreamNode> scheduleBuilder) { for (IOInfo info : ioinfo) { if (!info.isOutput() || info.token().isOverallOutput()) continue; StreamNode other = streamNodes.get(info.downstream()); int upstreamAdjust = internalSchedule.getExecutions(info.upstream()); int downstreamAdjust = other.internalSchedule.getExecutions(info.downstream()); scheduleBuilder.connect(this, other) .push(info.upstream().getPushRates().get(info.getUpstreamChannelIndex()).max() * upstreamAdjust) .pop(info.downstream().getPopRates().get(info.getDownstreamChannelIndex()).max() * downstreamAdjust) .peek(info.downstream().getPeekRates().get(info.getDownstreamChannelIndex()).max() * downstreamAdjust) .bufferExactly(0); } } private void buildWorkerData(Worker<?, ?> worker) { Klass workerKlass = module.getKlass(worker.getClass()); //Build the new fields. Klass splitter = module.getKlass(Splitter.class), joiner = module.getKlass(Joiner.class), filter = module.getKlass(Filter.class); for (Klass k = workerKlass; !k.equals(filter) && !k.equals(splitter) && !k.equals(joiner); k = k.getSuperclass()) { for (Field f : k.fields()) { java.lang.reflect.Field rf = f.getBackingField(); Set<Modifier> modifiers = EnumSet.of(Modifier.PRIVATE, Modifier.STATIC); //We can make the new field final if the original field is final or //if the worker isn't stateful. if (f.modifiers().contains(Modifier.FINAL) || !(worker instanceof StatefulFilter)) modifiers.add(Modifier.FINAL); Field nf = new Field(f.getType().getFieldType(), "w" + id + "$" + f.getName(), modifiers, blobKlass); fields.put(worker, f, nf); try { rf.setAccessible(true); Object value = rf.get(worker); fieldValues.put(worker, f, value); } catch (IllegalAccessException ex) { //Either setAccessible will succeed or we'll throw a //SecurityException, so we'll never get here. throw new AssertionError("Can't happen!", ex); } } } } private void makeWorkMethod() { assert workMethod == null : "remaking node work method"; mapIOInfo(); MethodType nodeWorkMethodType = module.types().getMethodType(module.types().getVoidType(), module.types().getRegularType(int.class)); workMethod = new Method("nodework"+this.id, nodeWorkMethodType, EnumSet.of(Modifier.PRIVATE, Modifier.STATIC), blobKlass); Argument multiple = Iterables.getOnlyElement(workMethod.arguments()); multiple.setName("multiple"); BasicBlock entryBlock = new BasicBlock(module, "entry"); workMethod.basicBlocks().add(entryBlock); Map<Token, Value> localBuffers = new HashMap<>(); ImmutableList<Worker<?, ?>> orderedWorkers = Workers.topologicalSort(workers); for (Worker<?, ?> w : orderedWorkers) { int wid = Workers.getIdentifier(w); //Input buffers List<Worker<?, ?>> preds = (List<Worker<?, ?>>)Workers.getPredecessors(w); List<Value> ichannels; List<Value> ioffsets = new ArrayList<>(); if (preds.isEmpty()) { ichannels = ImmutableList.<Value>of(getReaderBuffer(Token.createOverallInputToken(w))); int r = w.getPopRates().get(0).max() * internalSchedule.getExecutions(w); BinaryInst offset = new BinaryInst(multiple, BinaryInst.Operation.MUL, module.constants().getConstant(r)); offset.setName("ioffset0"); entryBlock.instructions().add(offset); ioffsets.add(offset); } else { ichannels = new ArrayList<>(preds.size()); for (int chanIdx = 0; chanIdx < preds.size(); ++chanIdx) { Worker<?, ?> p = preds.get(chanIdx); Token t = new Token(p, w); if (workers.contains(p)) { assert !buffers.containsKey(t) : "BufferData created for internal buffer"; Value localBuffer = localBuffers.get(new Token(p, w)); assert localBuffer != null : "Local buffer needed before created"; ichannels.add(localBuffer); ioffsets.add(module.constants().getConstant(0)); } else { ichannels.add(getReaderBuffer(t)); int r = w.getPopRates().get(chanIdx).max() * internalSchedule.getExecutions(w); BinaryInst offset = new BinaryInst(multiple, BinaryInst.Operation.MUL, module.constants().getConstant(r)); offset.setName("ioffset"+chanIdx); entryBlock.instructions().add(offset); ioffsets.add(offset); } } } Pair<Value, List<Instruction>> ichannelArray = createChannelArray(ichannels); ichannelArray.first.setName("ichannels_"+wid); entryBlock.instructions().addAll(ichannelArray.second); Pair<Value, List<Instruction>> ioffsetArray = createIntArray(ioffsets); ioffsetArray.first.setName("ioffsets_"+wid); entryBlock.instructions().addAll(ioffsetArray.second); Pair<Value, List<Instruction>> iincrementArray = createIntArray(Collections.<Value>nCopies(ioffsets.size(), module.constants().getConstant(1))); iincrementArray.first.setName("iincrements_"+wid); entryBlock.instructions().addAll(iincrementArray.second); //Output buffers List<Worker<?, ?>> succs = (List<Worker<?, ?>>)Workers.getSuccessors(w); List<Value> ochannels; List<Value> ooffsets = new ArrayList<>(); if (succs.isEmpty()) { ochannels = ImmutableList.<Value>of(getWriterBuffer(Token.createOverallOutputToken(w))); int r = w.getPushRates().get(0).max() * internalSchedule.getExecutions(w); BinaryInst offset = new BinaryInst(multiple, BinaryInst.Operation.MUL, module.constants().getConstant(r)); offset.setName("ooffset0"); entryBlock.instructions().add(offset); ooffsets.add(offset); } else { ochannels = new ArrayList<>(preds.size()); for (int chanIdx = 0; chanIdx < succs.size(); ++chanIdx) { Worker<?, ?> s = succs.get(chanIdx); Token t = new Token(w, s); if (workers.contains(s)) { assert buffers.containsKey(t) : "BufferData created for internal buffer"; Value localBuffer = localBuffers.get(new Token(w, s)); assert localBuffer != null : "Local buffer needed before created"; ochannels.add(localBuffer); ooffsets.add(module.constants().getConstant(0)); } else { ochannels.add(getWriterBuffer(t)); int r = w.getPushRates().get(chanIdx).max() * internalSchedule.getExecutions(w); BinaryInst offset0 = new BinaryInst(multiple, BinaryInst.Operation.MUL, module.constants().getConstant(r)); //Leave room to copy the excess peeks in front when //it's time to flip. BinaryInst offset = new BinaryInst(offset0, BinaryInst.Operation.ADD, module.constants().getConstant(buffers.get(t).excessPeeks)); offset.setName("ooffset"+chanIdx); entryBlock.instructions().add(offset0); entryBlock.instructions().add(offset); ooffsets.add(offset); } } } Pair<Value, List<Instruction>> ochannelArray = createChannelArray(ochannels); ochannelArray.first.setName("ochannels_"+wid); entryBlock.instructions().addAll(ochannelArray.second); Pair<Value, List<Instruction>> ooffsetArray = createIntArray(ooffsets); ooffsetArray.first.setName("ooffsets_"+wid); entryBlock.instructions().addAll(ooffsetArray.second); Pair<Value, List<Instruction>> oincrementArray = createIntArray(Collections.<Value>nCopies(ooffsets.size(), module.constants().getConstant(1))); oincrementArray.first.setName("oincrements_"+wid); entryBlock.instructions().addAll(oincrementArray.second); for (int i = 0; i < internalSchedule.getExecutions(w); ++i) { CallInst ci = new CallInst(workerWorkMethods.get(w), ichannelArray.first, ioffsetArray.first, iincrementArray.first, ochannelArray.first, ooffsetArray.first, oincrementArray.first); entryBlock.instructions().add(ci); } } entryBlock.instructions().add(new ReturnInst(module.types().getVoidType())); } private Field getReaderBuffer(Token t) { return blobKlass.getField(buffers.get(t).readerBufferFieldName); } private Field getWriterBuffer(Token t) { return blobKlass.getField(buffers.get(t).writerBufferFieldName); } private Pair<Value, List<Instruction>> createChannelArray(List<Value> channels) { ImmutableList.Builder<Instruction> insts = ImmutableList.builder(); NewArrayInst nai = new NewArrayInst(module.types().getArrayType(Object[][].class), module.constants().getConstant(channels.size())); insts.add(nai); for (int i = 0; i < channels.size(); ++i) { Value toStore = channels.get(i); //If the value is a field, load it first. if (toStore.getType() instanceof FieldType) { LoadInst li = new LoadInst((Field)toStore); insts.add(li); toStore = li; } ArrayStoreInst asi = new ArrayStoreInst(nai, module.constants().getConstant(i), toStore); insts.add(asi); } return new Pair<Value, List<Instruction>>(nai, insts.build()); } private Pair<Value, List<Instruction>> createIntArray(List<Value> ints) { ImmutableList.Builder<Instruction> insts = ImmutableList.builder(); NewArrayInst nai = new NewArrayInst(module.types().getArrayType(int[].class), module.constants().getConstant(ints.size())); insts.add(nai); for (int i = 0; i < ints.size(); ++i) { Value toStore = ints.get(i); ArrayStoreInst asi = new ArrayStoreInst(nai, module.constants().getConstant(i), toStore); insts.add(asi); } return new Pair<Value, List<Instruction>>(nai, insts.build()); } private void mapIOInfo() { ImmutableMap.Builder<Worker<?, ?>, ImmutableSortedSet<IOInfo>> inputIOs = ImmutableMap.builder(), outputIOs = ImmutableMap.builder(); for (Worker<?, ?> w : workers) { ImmutableSortedSet.Builder<IOInfo> inputs = ImmutableSortedSet.orderedBy(IOInfo.TOKEN_SORT), outputs = ImmutableSortedSet.orderedBy(IOInfo.TOKEN_SORT); for (IOInfo info : ioinfo) if (w.equals(info.downstream())) inputs.add(info); else if (w.equals(info.upstream())) outputs.add(info); inputIOs.put(w, inputs.build()); outputIOs.put(w, outputs.build()); } this.inputIOs = inputIOs.build(); this.outputIOs = outputIOs.build(); } } /** * Holds information about buffers. This class is used both during * compilation and at runtime, so it doesn't directly refer to the Compiler * or IR-level constructs, to ensure they can be garbage collected when * compilation finishes. */ private static final class BufferData implements Comparable<BufferData> { /** * The Token for the edge this buffer is on. */ public final Token token; /** * The names of the reader and writer buffers. The reader buffer is the * one initially filled with data items for peeking purposes. * * The overall input buffer has no writer buffer; the overall output * buffer has no reader buffer. */ public final String readerBufferFieldName, writerBufferFieldName; /** * The buffer capacity. */ public final int capacity; /** * The buffer initial size. This is generally less than the capacity * for intracore buffers introduced by peeking. Intercore buffers * always get filled to capacity. */ public final int initialSize; /** * The number of items peeked at but not popped; that is, the number of * unconsumed items in the reader buffer that must be copied to the * front of the writer buffer when flipping buffers. */ public final int excessPeeks; private BufferData(Token token, String readerBufferFieldName, String writerBufferFieldName, int capacity, int initialSize, int excessPeeks) { this.token = token; this.readerBufferFieldName = readerBufferFieldName; this.writerBufferFieldName = writerBufferFieldName; this.capacity = capacity; this.initialSize = initialSize; this.excessPeeks = excessPeeks; assert readerBufferFieldName != null || token.isOverallOutput() : this; assert writerBufferFieldName != null || token.isOverallInput() : this; assert capacity >= 0 : this; assert initialSize >= 0 && initialSize <= capacity : this; assert excessPeeks >= 0 && excessPeeks <= capacity : this; } @Override public int compareTo(BufferData other) { return token.compareTo(other.token); } @Override public String toString() { return String.format("[%s: r: %s, w: %s, init: %d, max: %d, peeks: %d]", token, readerBufferFieldName, writerBufferFieldName, initialSize, capacity, excessPeeks); } } private static final class CompilerBlobHost implements Blob { private final ImmutableSet<Worker<?, ?>> workers; private final Configuration configuration; private final ImmutableMap<Token, BufferData> bufferData; private final ImmutableMap<Worker<?, ?>, Integer> initSchedule; private final ImmutableMap<Token, Integer> initScheduleReqs; private final ImmutableSortedSet<Token> inputTokens, outputTokens, internalTokens; private final ImmutableMap<Token, Integer> minimumBufferSize; private final Class<?> blobClass; private final ImmutableMap<String, MethodHandle> blobClassMethods, blobClassFieldGetters, blobClassFieldSetters; private final Runnable[] runnables; private final SwitchPoint sp1 = new SwitchPoint(), sp2 = new SwitchPoint(); private final CyclicBarrier barrier; private ImmutableMap<Token, Buffer> buffers; private ImmutableMap<Token, Channel<Object>> channelMap; private volatile Runnable drainCallback; private volatile DrainData drainData; public CompilerBlobHost(Set<Worker<?, ?>> workers, Configuration configuration, Class<?> blobClass, List<BufferData> bufferData, Map<Worker<?, ?>, Integer> initSchedule) { this.workers = ImmutableSet.copyOf(workers); this.configuration = configuration; this.initSchedule = ImmutableMap.copyOf(initSchedule); this.blobClass = blobClass; ImmutableMap.Builder<Token, BufferData> bufferDataBuilder = ImmutableMap.builder(); for (BufferData d : bufferData) bufferDataBuilder.put(d.token, d); this.bufferData = bufferDataBuilder.build(); ImmutableSet<IOInfo> ioinfo = IOInfo.externalEdges(workers); ImmutableMap.Builder<Token, Integer> initScheduleReqsBuilder = ImmutableMap.builder(); for (IOInfo info : ioinfo) { if (!info.isInput()) continue; Worker<?, ?> worker = info.downstream(); int index = info.getDownstreamChannelIndex(); int popRate = worker.getPopRates().get(index).max(); int peekRate = worker.getPeekRates().get(index).max(); int excessPeeks = Math.max(0, peekRate - popRate); int required = popRate * initSchedule.get(worker) + this.bufferData.get(info.token()).initialSize; initScheduleReqsBuilder.put(info.token(), required); } this.initScheduleReqs = initScheduleReqsBuilder.build(); ImmutableSortedSet.Builder<Token> inputTokensBuilder = ImmutableSortedSet.naturalOrder(), outputTokensBuilder = ImmutableSortedSet.naturalOrder(); ImmutableMap.Builder<Token, Integer> minimumBufferSizeBuilder = ImmutableMap.builder(); for (IOInfo info : ioinfo) if (info.isInput()) { inputTokensBuilder.add(info.token()); BufferData data = this.bufferData.get(info.token()); minimumBufferSizeBuilder.put(info.token(), Math.max(initScheduleReqs.get(info.token()), data.capacity)); } else { outputTokensBuilder.add(info.token()); //TODO: request enough for one or more steady-states worth of output? //We still have to support partial writes but we can give an //efficiency hint here. Perhaps autotunable fraction? minimumBufferSizeBuilder.put(info.token(), 1); } this.inputTokens = inputTokensBuilder.build(); this.outputTokens = outputTokensBuilder.build(); this.minimumBufferSize = minimumBufferSizeBuilder.build(); ImmutableSortedSet.Builder<Token> internalTokensBuilder = ImmutableSortedSet.naturalOrder(); for (IOInfo info : IOInfo.internalEdges(workers)) internalTokensBuilder.add(info.token()); this.internalTokens = internalTokensBuilder.build(); MethodHandles.Lookup lookup = MethodHandles.lookup(); ImmutableMap.Builder<String, MethodHandle> methodBuilder = ImmutableMap.builder(), fieldGetterBuilder = ImmutableMap.builder(), fieldSetterBuilder = ImmutableMap.builder(); try { java.lang.reflect.Method[] methods = blobClass.getDeclaredMethods(); Arrays.sort(methods, new Comparator<java.lang.reflect.Method>() { @Override public int compare(java.lang.reflect.Method o1, java.lang.reflect.Method o2) { return o1.getName().compareTo(o2.getName()); } }); for (java.lang.reflect.Method m : methods) { m.setAccessible(true); methodBuilder.put(m.getName(), lookup.unreflect(m)); } java.lang.reflect.Field[] fields = blobClass.getDeclaredFields(); Arrays.sort(fields, new Comparator<java.lang.reflect.Field>() { @Override public int compare(java.lang.reflect.Field o1, java.lang.reflect.Field o2) { return o1.getName().compareTo(o2.getName()); } }); for (java.lang.reflect.Field f : fields) { f.setAccessible(true); fieldGetterBuilder.put(f.getName(), lookup.unreflectGetter(f)); fieldSetterBuilder.put(f.getName(), lookup.unreflectSetter(f)); } } catch (IllegalAccessException | SecurityException ex) { throw new AssertionError(ex); } this.blobClassMethods = methodBuilder.build(); this.blobClassFieldGetters = fieldGetterBuilder.build(); this.blobClassFieldSetters = fieldSetterBuilder.build(); final java.lang.invoke.MethodType voidNoArgs = java.lang.invoke.MethodType.methodType(void.class); MethodHandle nop = MethodHandles.identity(Void.class).bindTo(null).asType(voidNoArgs); MethodHandle mainLoop, doInit, doAdjustBuffers, newAssertionError; try { mainLoop = lookup.findVirtual(CompilerBlobHost.class, "mainLoop", java.lang.invoke.MethodType.methodType(void.class, MethodHandle.class)).bindTo(this); doInit = lookup.findVirtual(CompilerBlobHost.class, "doInit", voidNoArgs).bindTo(this); doAdjustBuffers = lookup.findVirtual(CompilerBlobHost.class, "doAdjustBuffers", voidNoArgs).bindTo(this); newAssertionError = lookup.findConstructor(AssertionError.class, java.lang.invoke.MethodType.methodType(void.class, Object.class)); } catch (IllegalAccessException | NoSuchMethodException ex) { throw new AssertionError(ex); } List<MethodHandle> coreWorkHandles = new ArrayList<>(); for (Map.Entry<String, MethodHandle> methods : blobClassMethods.entrySet()) if (methods.getKey().startsWith("corework")) coreWorkHandles.add(methods.getValue()); this.runnables = new Runnable[coreWorkHandles.size()]; for (int i = 0; i < runnables.length; ++i) { MethodHandle mainNop = mainLoop.bindTo(nop); MethodHandle mainCorework = mainLoop.bindTo(coreWorkHandles.get(i)); MethodHandle overall = sp1.guardWithTest(mainNop, sp2.guardWithTest(mainCorework, nop)); runnables[i] = MethodHandleProxies.asInterfaceInstance(Runnable.class, overall); } MethodHandle thrower = MethodHandles.throwException(void.class, AssertionError.class); MethodHandle doThrowAE = MethodHandles.filterReturnValue(newAssertionError.bindTo("Can't happen! Barrier action reached after draining?"), thrower); MethodHandle barrierAction = sp1.guardWithTest(doInit, sp2.guardWithTest(doAdjustBuffers, doThrowAE)); this.barrier = new CyclicBarrier(runnables.length, MethodHandleProxies.asInterfaceInstance(Runnable.class, barrierAction)); } @Override public Set<Worker<?, ?>> getWorkers() { return workers; } @Override public ImmutableSet<Token> getInputs() { return inputTokens; } @Override public ImmutableSet<Token> getOutputs() { return outputTokens; } @Override public int getMinimumBufferCapacity(Token token) { return minimumBufferSize.get(token); } @Override public void installBuffers(Map<Token, Buffer> buffers) { ImmutableMap.Builder<Token, Buffer> buffersBuilder = ImmutableMap.builder(); for (Token t : getInputs()) buffersBuilder.put(t, buffers.get(t)); for (Token t : getOutputs()) buffersBuilder.put(t, buffers.get(t)); this.buffers = buffersBuilder.build(); } @Override public int getCoreCount() { return runnables.length; } @Override public Runnable getCoreCode(int core) { return runnables[core]; } @Override public void drain(Runnable callback) { drainCallback = callback; } @Override public DrainData getDrainData() { return drainData; } private void mainLoop(MethodHandle corework) throws Throwable { corework.invoke(); try { barrier.await(); } catch (BrokenBarrierException ex) { return; } catch (InterruptedException ex) { Thread.currentThread().interrupt(); return; } } private void doInit() throws Throwable { //Create channels. ImmutableSet<IOInfo> allEdges = IOInfo.allEdges(workers); ImmutableMap.Builder<Token, Channel<Object>> channelMapBuilder = ImmutableMap.builder(); for (IOInfo i : allEdges) { Channel<Object> c = new ArrayChannel<>(); if (i.upstream() != null && !i.isInput()) addOrSet(Workers.getOutputChannels(i.upstream()), i.getUpstreamChannelIndex(), c); if (i.downstream() != null && !i.isOutput()) addOrSet(Workers.getInputChannels(i.downstream()), i.getDownstreamChannelIndex(), c); channelMapBuilder.put(i.token(), c); } this.channelMap = channelMapBuilder.build(); //Fill input channels. for (IOInfo i : allEdges) { if (!i.isInput()) continue; int required = initScheduleReqs.get(i.token()); Channel<Object> channel = channelMap.get(i.token()); Buffer buffer = buffers.get(i.token()); Object[] data = new Object[required]; //These are the first reads we do, so we can't "waste" our //interrupt here. while (!buffer.readAll(data)) if (isDraining()) { doDrain(false, ImmutableList.<Token>of()); return; } for (Object datum : data) channel.push(datum); } //Work workers in topological order. for (Worker<?, ?> worker : Workers.topologicalSort(workers)) { int iterations = initSchedule.get(worker); for (int i = 0; i < iterations; ++i) Workers.doWork(worker); } //Flush output (if any was generated?). for (Token output : getOutputs()) { Channel<Object> channel = channelMap.get(output); Buffer buffer = buffers.get(output); while (!channel.isEmpty()) { Object obj = channel.pop(); while (!buffer.write(obj)) /* deliberate empty statement */; } } //Move buffered items from channels to buffers. for (Map.Entry<Token, Channel<Object>> entry : channelMap.entrySet()) { Token token = entry.getKey(); Channel<Object> channel = entry.getValue(); BufferData data = bufferData.get(token); assert channel.size() == data.initialSize : String.format("%s: expected %d, got %d", token, data.initialSize, channel.size()); if (data.readerBufferFieldName == null) { assert data.initialSize == 0; continue; } Object[] objs = Iterables.toArray(channel, Object.class); Object[] buffer = (Object[])blobClassFieldGetters.get(data.readerBufferFieldName).invokeExact(); System.arraycopy(objs, 0, buffer, 0, objs.length); while (!channel.isEmpty()) channel.pop(); } //TODO: Move state to fields. SwitchPoint.invalidateAll(new SwitchPoint[]{sp1}); } private void doAdjustBuffers() throws Throwable { //Flush output buffers. for (Token t : getOutputs()) { String fieldName = bufferData.get(t).writerBufferFieldName; Object[] data = (Object[])blobClassFieldGetters.get(fieldName).invokeExact(); Buffer buffer = buffers.get(t); int written = 0; while (written < data.length) written += buffer.write(data, written, data.length - written); } //Copy unconsumed peek data, then flip buffers. for (Token t : internalTokens) { BufferData data = bufferData.get(t); Object[] reader = (Object[])blobClassFieldGetters.get(data.readerBufferFieldName).invokeExact(); Object[] writer = (Object[])blobClassFieldGetters.get(data.writerBufferFieldName).invokeExact(); if (data.excessPeeks > 0) System.arraycopy(reader, reader.length - data.excessPeeks, writer, 0, data.excessPeeks); blobClassFieldSetters.get(data.readerBufferFieldName).invokeExact(writer); blobClassFieldSetters.get(data.writerBufferFieldName).invokeExact(reader); } //Fill input buffers (draining-aware). ImmutableList<Token> inputList = getInputs().asList(); for (int i = 0; i < inputList.size(); ++i) { Token t = inputList.get(i); Object[] data = (Object[])blobClassFieldGetters.get(bufferData.get(t).readerBufferFieldName).invokeExact(); Buffer buffer = buffers.get(t); if (isDraining()) { //While draining, we can trust size() exactly, so we can //check before proceeding to avoid wasting the interrupt. if (buffer.size() >= data.length) { boolean mustSucceed = buffer.readAll(data); assert mustSucceed : "size() lies"; } else { doDrain(true, inputList.subList(0, i)); return; } } else while (!buffer.readAll(data)) if (isDraining()) { doDrain(true, inputList.subList(0, i)); return; } } } /** * * @param nonInputReaderBuffersLive true iff non-input reader buffers * are live (basically, true if we're draining from doAdjustBuffers, * false if from doInit) */ private void doDrain(boolean nonInputReaderBuffersLive, List<Token> additionalLiveBuffers) throws Throwable { //We already have channels installed from initialization; we just //have to fill them if our internal buffers are live. (If we're //draining during init some of the input channels are already //primed with data -- that's okay.) ImmutableSet.Builder<Token> live = ImmutableSet.builder(); if (nonInputReaderBuffersLive) live.addAll(internalTokens); live.addAll(additionalLiveBuffers); for (Token t : live.build()) { BufferData data = bufferData.get(t); if (data != null) { Channel<Object> c = channelMap.get(t); assert c.isEmpty() : "data left in internal channel after init"; Object[] buf = (Object[])blobClassFieldGetters.get(data.readerBufferFieldName).invokeExact(); for (Object o : buf) c.push(o); } } //TODO: Move state into worker fields. //Create an interpreter and use it to drain stuff. //TODO: hack. Make a proper Interpreter interface for this use case. List<ChannelFactory> universe = Arrays.<ChannelFactory>asList(new ChannelFactory() { @Override @SuppressWarnings("unchecked") public <E> Channel<E> makeChannel(Worker<?, E> upstream, Worker<E, ?> downstream) { if (upstream == null) return (Channel<E>)channelMap.get(Token.createOverallInputToken(downstream)); if (downstream == null) return (Channel<E>)channelMap.get(Token.createOverallOutputToken(upstream)); return (Channel<E>)channelMap.get(new Token(upstream, downstream)); } @Override public boolean equals(Object o) { return o != null && getClass() == o.getClass(); } @Override public int hashCode() { return 10; } }); Configuration config = Configuration.builder().addParameter(new Configuration.SwitchParameter<>("channelFactory", ChannelFactory.class, universe.get(0), universe)).build(); Blob interp = new Interpreter.InterpreterBlobFactory().makeBlob(workers, config, 1); interp.installBuffers(buffers); Runnable interpCode = interp.getCoreCode(0); final AtomicBoolean interpFinished = new AtomicBoolean(); interp.drain(new Runnable() { @Override public void run() { interpFinished.set(true); } }); while (!interpFinished.get()) interpCode.run(); this.drainData = interp.getDrainData(); SwitchPoint.invalidateAll(new SwitchPoint[]{sp1, sp2}); drainCallback.run(); //TODO: null out blob class fields to permit GC. } private boolean isDraining() { return drainCallback != null; } private static void addOrSet(List list, int i, Object obj) { if (i < list.size()) list.set(i, obj); else { assert i == 0; list.add(obj); } } } public static void main(String[] args) throws Throwable { OneToOneElement<Integer, Integer> graph = new Identity<>();//new Splitjoin<>(new RoundrobinSplitter<Integer>(), new RoundrobinJoiner<Integer>(), new Identity<Integer>(), new Identity<Integer>()); ConnectWorkersVisitor cwv = new ConnectWorkersVisitor(); graph.visit(cwv); Set<Worker<?, ?>> workers = Workers.getAllWorkersInGraph(cwv.getSource()); Configuration config = new CompilerBlobFactory().getDefaultConfiguration(workers); int maxNumCores = 1; Compiler compiler = new Compiler(workers, config, maxNumCores); Blob blob = compiler.compile(); Map<Token, Buffer> buffers = new HashMap<>(); for (Token t : blob.getInputs()) { Buffer buf = Buffers.queueBuffer(new ArrayDeque<>(), Integer.MAX_VALUE); for (int i = 0; i < 1000; ++i) buf.write(i); buffers.put(t, buf); } for (Token t : blob.getOutputs()) buffers.put(t, Buffers.queueBuffer(new ArrayDeque<>(), Integer.MAX_VALUE)); blob.installBuffers(buffers); final AtomicBoolean drained = new AtomicBoolean(); blob.drain(new Runnable() { @Override public void run() { drained.set(true); } }); Runnable r = blob.getCoreCode(0); Buffer b = buffers.get(blob.getOutputs().iterator().next()); while (!drained.get()) { r.run(); Object o; while ((o = b.read()) != null) System.out.println(o); } System.out.println(blob.getDrainData()); } }
package edu.nyu.cs.omnidroid.tests; import android.app.Activity; import android.os.Bundle; import android.widget.Toast; import edu.nyu.cs.omnidroid.util.*; /** * Test the Application Configuration File * * @author acase * */ public class TestAppConfig extends Activity { /* * (non-Javadoc) * * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); AGParser ag = new AGParser(this.getApplicationContext()); ag.delete_all(); ag.write("Application:SMS"); ag.write("PkgName:edu.nyu.cs.omnidroid"); ag.write("ListenerClass:edu.nyu.cs.omnidroid.external.catcherapp.SMSListener"); ag.write("EventName:SMS_RECEIVED,SMS_RECEIVED"); ag.write("Filters:S_Name,S_Ph_No,Text,Location"); ag.write("EventName:SMS_SENT,SENT SMS"); ag.write("Filters:R_Name,R_Ph_no,Text"); ag.write("ActionName: SMS_SEND,SEND SMS"); ag.write("URIFields:R_NAME,R_Ph_No,Text"); ag.write("ContentMap:"); ag.write("S_Name,SENDER NAME,STRING"); ag.write("R_Name,RECEIVER NAME,STRING"); ag.write("S_Ph_No,SENDER PHONE NUMBER,INT"); ag.write("R_Ph_No,RECEIVER PHONE NUMBER,INT"); ag.write("Text,Text,STRING"); ag.write("Location,SMS Number,INT"); Toast.makeText(getApplicationContext(), "Population Test App Config File", 5).show(); this.finish(); } }
package org.yakindu.sct.ui.editor.validation; import java.util.Arrays; import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.workspace.util.WorkspaceSynchronizer; import org.eclipse.xtext.validation.CheckType; import org.eclipse.xtext.validation.Issue; import org.yakindu.sct.model.sgraph.ui.validation.ISctIssueCreator; import org.yakindu.sct.model.sgraph.ui.validation.SCTIssue; import org.yakindu.sct.model.sgraph.ui.validation.SCTMarkerType; import org.yakindu.sct.ui.editor.validation.IValidationIssueStore; import org.yakindu.sct.ui.editor.validation.IResourceChangeToIssueProcessor.ResourceDeltaToIssueResult; import com.google.common.base.Predicate; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import com.google.common.collect.Sets.SetView; import com.google.inject.Inject; /** * Maintains the list of current visible issues based on persistent markers and * live validation results. * * @author Johannes Dicks - Initial contribution and API */ public class DefaultValidationIssueStore implements IValidationIssueStore, IResourceChangeListener { @Inject private ISctIssueCreator issueCreator; @Inject private IResourceChangeToIssueProcessor resourceChangeToIssues; protected final List<IValidationIssueStoreListener> listener; protected Multimap<String, SCTIssue> visibleIssues; protected boolean connected = false; protected Resource connectedResource; public DefaultValidationIssueStore() { listener = Lists.newArrayList(); visibleIssues = ArrayListMultimap.create(); } @Override public void addIssueStoreListener(IValidationIssueStoreListener newListener) { synchronized (this.listener) { this.listener.add(newListener); } } @Override public void removeIssueStoreListener(IValidationIssueStoreListener oldListener) { synchronized (listener) { listener.remove(oldListener); } } protected void notifyListeners() { synchronized (listener) { for (IValidationIssueStoreListener iResourceIssueStoreListener : listener) { iResourceIssueStoreListener.issuesChanged(); } } } protected void notifyListeners(String semanticURI) { synchronized (listener) { for (IValidationIssueStoreListener iResourceIssueStoreListener : listener) { if (semanticURI.equals(iResourceIssueStoreListener.getSemanticURI())) { iResourceIssueStoreListener.issuesChanged(); } } } } @Override public void connect(Resource resource) { if (connected) { throw new IllegalStateException("Issue store is already connected to a resource"); } connectedResource = resource; IFile file = WorkspaceSynchronizer.getFile(resource); if ((file != null) && file.isAccessible()) { ResourcesPlugin.getWorkspace().addResourceChangeListener(this); connected = true; } initFromPersistentMarkers(); } protected synchronized void initFromPersistentMarkers() { Multimap<String, SCTIssue> newVisibleIssues = ArrayListMultimap.create(); List<IMarker> markers = getMarkersOfConnectedResource(); for (IMarker iMarker : markers) { SCTIssue issue = issueCreator.createFromMarker(iMarker, iMarker.getAttribute(SCTMarkerType.SEMANTIC_ELEMENT_ID, "")); newVisibleIssues.put(issue.getSemanticURI(), issue); } synchronized (visibleIssues) { visibleIssues.clear(); visibleIssues.putAll(newVisibleIssues); } notifyListeners(); } protected List<IMarker> getMarkersOfConnectedResource() { List<IMarker> markers = Lists.newArrayList(); try { IFile file = WorkspaceSynchronizer.getFile(connectedResource); if ((file != null) && file.isAccessible()) { markers.addAll( Arrays.asList(file.findMarkers(SCTMarkerType.SUPERTYPE, true, IResource.DEPTH_INFINITE))); } } catch (CoreException e) { e.printStackTrace(); } return markers; } @Override public void disconnect(Resource resource) { IFile file = WorkspaceSynchronizer.getFile(resource); if ((file != null) && file.isAccessible()) { ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); connected = false; connectedResource = null; synchronized (listener) { listener.clear(); } } } @Override public synchronized void processIssues(List<Issue> issues, IProgressMonitor monitor) { final Multimap<String, SCTIssue> newVisibleIssues = ArrayListMultimap.create(); for (Issue issue : issues) { if (issue instanceof SCTIssue) { String semanticURI = ((SCTIssue) issue).getSemanticURI(); newVisibleIssues.put(semanticURI, (SCTIssue) issue); } } final Multimap<String, SCTIssue> oldVisibleIssues = ArrayListMultimap.create(); synchronized (visibleIssues) { oldVisibleIssues.putAll(visibleIssues); // normal and expensive checks will not be executed by the live // validation, so persistent markers have to be copied Iterable<SCTIssue> persistentIssues = Iterables.filter(visibleIssues.values(), new Predicate<SCTIssue>() { public boolean apply(SCTIssue input) { return input.getType() == CheckType.NORMAL || input.getType() == CheckType.EXPENSIVE; } }); for (SCTIssue sctIssue : persistentIssues) { newVisibleIssues.put(sctIssue.getSemanticURI(), sctIssue); } visibleIssues.clear(); visibleIssues.putAll(newVisibleIssues); } SetView<String> changes = Sets.symmetricDifference(oldVisibleIssues.keySet(), newVisibleIssues.keySet()); for (String semanticElementID : changes) { notifyListeners(semanticElementID); } } @Override public synchronized List<SCTIssue> getIssues(String uri) { List<SCTIssue> result = Lists.newArrayList(); synchronized (visibleIssues) { Iterables.addAll(result, visibleIssues.get(uri)); } return result; } @Override public void resourceChanged(IResourceChangeEvent event) { if ((IResourceChangeEvent.POST_CHANGE != event.getType())) { return; } ResourceDeltaToIssueResult markerChangeResult = null; synchronized (visibleIssues) { markerChangeResult = resourceChangeToIssues.process(event, connectedResource, visibleIssues); if (markerChangeResult != null) visibleIssues = markerChangeResult.getIssues(); } if (markerChangeResult != null) for (String elementID : markerChangeResult.getChangedElementIDs()) { notifyListeners(elementID); } } }
/** * SpawningScreen * * Class representing the screen that allows to determine spawning conditions, * or spawn new entities during a simulation. * * @author Willy McHie * Wheaton College, CSCI 335, Spring 2013 */ package edu.wheaton.simulator.gui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingConstants; import sun.management.resources.agent_zh_TW; public class SpawningScreen extends Screen { //TODO how do we handle if spawn are set, and then the grid is made smaller, // and some of the spawns are now out of bounds? delete those fields? //TODO figure out where and how to store spawning information private String[] entities; private ArrayList<JComboBox> entityTypes; private ArrayList<JComboBox> spawnPatterns; //TODO temporary placeholder private String[] spawnOptions = {"Random", "Clustered"}; private ArrayList<JTextField> xLocs; private ArrayList<JTextField> yLocs; private ArrayList<JTextField> numbers; private ArrayList<JButton> deleteButtons; private ArrayList<JPanel> subPanels; private JButton addSpawnButton; private JPanel listPanel; private Component glue; private static final long serialVersionUID = 6312784326472662829L; //TODO does not read existing entities public SpawningScreen(final ScreenManager sm) { super(sm); this.setLayout(new BorderLayout()); entities = new String[0]; JLabel label = new JLabel("Spawning"); label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); label.setPreferredSize(new Dimension(300, 150)); JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); listPanel = new JPanel(); listPanel.setLayout(new BoxLayout(listPanel, BoxLayout.Y_AXIS)); JPanel labelsPanel = new JPanel(); labelsPanel.setLayout(new BoxLayout(labelsPanel, BoxLayout.X_AXIS)); //TODO mess with sizes of labels to line up with components JLabel entityLabel = new JLabel("Entity Type"); entityLabel.setPreferredSize(new Dimension(200, 30)); JLabel patternLabel = new JLabel("Spawn Pattern"); patternLabel.setPreferredSize(new Dimension(270, 30)); JLabel xLabel = new JLabel("x Loc."); xLabel.setPreferredSize(new Dimension(100, 30)); JLabel yLabel = new JLabel("Y Loc."); yLabel.setPreferredSize(new Dimension(100, 30)); JLabel numberLabel = new JLabel("Number"); numberLabel.setPreferredSize(new Dimension(330, 30)); labelsPanel.add(Box.createHorizontalGlue()); labelsPanel.add(entityLabel); entityLabel.setHorizontalAlignment(SwingConstants.CENTER); labelsPanel.add(Box.createHorizontalGlue()); labelsPanel.add(patternLabel); patternLabel.setHorizontalAlignment(SwingConstants.CENTER); labelsPanel.add(Box.createHorizontalGlue()); labelsPanel.add(xLabel); labelsPanel.add(yLabel); labelsPanel.add(numberLabel); labelsPanel.add(Box.createHorizontalGlue()); mainPanel.add(labelsPanel); mainPanel.add(listPanel); labelsPanel.setAlignmentX(CENTER_ALIGNMENT); entityTypes = new ArrayList<JComboBox>(); spawnPatterns = new ArrayList<JComboBox>(); entityTypes.add(new JComboBox(entities)); xLocs = new ArrayList<JTextField>(); yLocs = new ArrayList<JTextField>(); numbers = new ArrayList<JTextField>(); deleteButtons = new ArrayList<JButton>(); subPanels = new ArrayList<JPanel>(); entityTypes.get(0).setMaximumSize(new Dimension(250, 30)); addSpawnButton = new JButton("Add Spawn"); addSpawnButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ addSpawn(); } }); listPanel.add(addSpawnButton); addSpawnButton.setAlignmentX(CENTER_ALIGNMENT); glue = Box.createVerticalGlue(); listPanel.add(glue); addSpawn(); System.out.println(deleteButtons.size()); JPanel buttonPanel = new JPanel(); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { sm.update(sm.getScreen("Edit Simulation")); } }); JButton finishButton = new JButton("Finish"); finishButton.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ArrayList<SpawnCondition> conditions = sm.getSpawnConditions(); conditions.clear(); for (int i = 0; i < entityTypes.size(); i++) { SpawnCondition condition = new SpawnCondition(sm.getFacade().getPrototype( ((String) entityTypes.get(i).getSelectedItem())), Integer.parseInt(xLocs.get(i).getText()), Integer .parseInt(yLocs.get(i).getText()), Integer .parseInt(numbers.get(i).getText()), (String) spawnPatterns.get(i).getSelectedItem()); sm.getSpawnConditions().add(condition); } sm.update(sm.getScreen("Edit Simulation")); } }); buttonPanel.add(cancelButton); buttonPanel.add(finishButton); this.add(label, BorderLayout.NORTH); this.add(listPanel, BorderLayout.CENTER); this.add(buttonPanel, BorderLayout.SOUTH); } public void reset() { entityTypes.clear(); spawnPatterns.clear(); xLocs.clear(); yLocs.clear(); numbers.clear(); subPanels.clear(); deleteButtons.clear(); listPanel.removeAll(); addSpawn(); } @Override public void load() { reset(); entities = sm.getFacade().prototypeNames().toArray(entities); ArrayList<SpawnCondition> spawnConditions = sm.getSpawnConditions(); System.out.println(deleteButtons.size()); for (int i = 0; i < spawnConditions.size(); i++) { addSpawn(); entityTypes.get(i).setSelectedItem(spawnConditions.get(i).prototype.toString()); spawnPatterns.get(i).setSelectedItem(spawnConditions.get(i).pattern); xLocs.get(i).setText(spawnConditions.get(i).x + ""); yLocs.get(i).setText(spawnConditions.get(i).y + ""); numbers.get(i).setText(spawnConditions.get(i).number + ""); } } private void addSpawn() { JPanel newPanel = new JPanel(); newPanel.setLayout( new BoxLayout(newPanel, BoxLayout.X_AXIS) ); JComboBox newBox = new JComboBox(entities); newBox.setMaximumSize(new Dimension(250, 30)); entityTypes.add(newBox); JComboBox newSpawnType = new JComboBox(spawnOptions); newSpawnType.setMaximumSize(new Dimension(250, 30)); spawnPatterns.add(newSpawnType); JTextField newXLoc = new JTextField(10); newXLoc.setMaximumSize(new Dimension(100, 30)); xLocs.add(newXLoc); JTextField newYLoc = new JTextField(10); newYLoc.setMaximumSize(new Dimension(100, 30)); yLocs.add(newYLoc); JTextField newNumber = new JTextField(10); newNumber.setMaximumSize(new Dimension(100, 30)); numbers.add(newNumber); JButton newButton = new JButton("Delete"); newButton.addActionListener(new DeleteListener()); deleteButtons.add(newButton); newButton.setActionCommand( deleteButtons.indexOf(newButton) + "" ); newPanel.add(newBox); newPanel.add(newSpawnType); newPanel.add(newXLoc); newPanel.add(newYLoc); newPanel.add(newNumber); newPanel.add(newButton); subPanels.add(newPanel); listPanel.add(newPanel); listPanel.add(addSpawnButton); listPanel.add(glue); listPanel.validate(); repaint(); } private void deleteSpawn(int n) { entityTypes.remove(n); spawnPatterns.remove(n); xLocs.remove(n); yLocs.remove(n); numbers.remove(n); deleteButtons.remove(n); for (int i = n; i < deleteButtons.size(); i++) { deleteButtons.get(i).setActionCommand(i + ""); } listPanel.remove(subPanels.get(n)); subPanels.remove(n); listPanel.validate(); repaint(); } private class DeleteListener implements ActionListener { @Override public void actionPerformed(ActionEvent e){ String action = e.getActionCommand(); deleteSpawn(Integer.parseInt(action)); } } }
/* Open Source Software - may be modified and shared by FRC teams. The code */ /* the project. */ package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.*; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj.DriverStationLCD.Line; //import edu.wpi.first.wpilibj.RobotDrive; //import edu.wpi.first.wpilibj.SimpleRobot; //import edu.wpi.first.wpilibj.templates.Shooter; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the SimpleRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Team3373 extends SimpleRobot{ /** * This function is called once each time the robot enters autonomous mode. */ int StageOneMotorPWM = 1; //Declares channel of StageOne PWM int StageTwoMotorPWM = 2; //Declares channel of StageTwo PWM Talon StageOneTalon = new Talon(1, 1); //Creates instance of StageOne PWM Talon StageTwoTalon = new Talon(1, 2); //Creates instance of StageTwo PWM DriverStationLCD LCD = DriverStationLCD.getInstance(); //SmartDashboard smartDashboard; Joystick shootStick = new Joystick(2); Shooter objShooter = new Shooter(this); //Deadband objDeadband = new Deadband(); Timer robotTimer = new Timer(); boolean shootA; boolean shootB; boolean shootX; boolean shootY; boolean shootRB; boolean shootLB; boolean shootBack; boolean shootStart; boolean test; double shootLX = shootStick.getRawAxis(1); double shootLY = shootStick.getRawAxis(2); double shootTriggers = shootStick.getRawAxis(3); double shootRX = shootStick.getRawAxis(4); double shootRY = shootStick.getRawAxis(5); double shootDP = shootStick.getRawAxis(6); double ShooterSpeedStage2 = 0.1;//was StageTwoTalon.get() double percentageScaler = 0.5; double ShooterSpeedStage1 = ShooterSpeedStage2 * percentageScaler;//was StageOneTalon.get() double ShooterSpeedMax = 5300.0; double ShooterSpeedAccel = 250; double stageOneScaler = .5; //What stage one is multiplied by in order to make it a pecentage of stage 2 double PWMMax = 1; //maximum voltage sent to motor double MaxScaler = PWMMax/5300; double ShooterSpeedScale = MaxScaler * ShooterSpeedMax; //Scaler for voltage to RPM. Highly experimental!! double currentRPMT2 = StageTwoTalon.get()*ShooterSpeedScale; double currentRPMT1 = currentRPMT2*stageOneScaler; double target; double RPMModifier = 250; double idle = 1 * ShooterSpeedScale; double off = 0; double Scaler = 5936; double change; double startTime = 9000000; double backTime = 90000000; double aTime = 900000000; double bTime = 900000000; boolean flagA; boolean flagB; boolean flagX; boolean flagY; boolean flagStart; boolean flagBack; boolean flagBack2; public Team3373(){ } public void autonomous() { for (int i = 0; i < 4; i++) { } } /** * This function is called once each time the robot enters operator control. */ public void operatorControl() { robotTimer.start(); while (isOperatorControl() & isDisabled()){ objShooter.shootInit(); } flagA = true; flagB = true; flagX = true; flagY = true; flagStart = true; flagBack = true; flagBack2 = false; while (isOperatorControl() & isEnabled()){ shootA = shootStick.getRawButton(1); shootB = shootStick.getRawButton(2); shootX = shootStick.getRawButton(3); shootY = shootStick.getRawButton(4); shootRB = shootStick.getRawButton(5); shootLB = shootStick.getRawButton(6); shootBack = shootStick.getRawButton(7); shootStart = shootStick.getRawButton(8); shootLX = shootStick.getRawAxis(1); shootLY = shootStick.getRawAxis(2); shootTriggers = shootStick.getRawAxis(3); shootRX = shootStick.getRawAxis(4); shootRY = shootStick.getRawAxis(5); shootDP = shootStick.getRawAxis(6); if (robotTimer.get() >= startTime + 1) { StageOneTalon.set(ShooterSpeedStage1); StageTwoTalon.set(ShooterSpeedStage2); } //Shooter objShooter = new Shooter(); //objShooter.shooterPrint(); //objShooter.Start(); if (shootStart && flagStart) { startTime = robotTimer.get(); flagStart = false; } else if (shootA && flagA){//increases stage 2 aTime = robotTimer.get(); if (robotTimer.get() >= aTime + 1){ ShooterSpeedStage2 += 0.1; ShooterSpeedStage1 = ShooterSpeedStage2 * percentageScaler; StageOneTalon.set(ShooterSpeedStage1); StageTwoTalon.set(ShooterSpeedStage2); } if (ShooterSpeedStage2 >= 1) { ShooterSpeedStage2 = 1; } flagA = false; } else if (shootB && flagB){//decrease stage 2 bTime = robotTimer.get(); if (robotTimer.get() >= bTime + 1) { ShooterSpeedStage2 -= 0.1; ShooterSpeedStage1 = ShooterSpeedStage2 * percentageScaler; StageOneTalon.set(ShooterSpeedStage1); StageTwoTalon.set(ShooterSpeedStage2); } if (ShooterSpeedStage2 <= 0) { ShooterSpeedStage2 = 0; } flagB = false; } else if (shootX && flagX && !flagBack){//increases percentage between Stage1 and Stage2 percentageScaler += 0.05; if (percentageScaler >= 1) { percentageScaler = 1; } ShooterSpeedStage1 = ShooterSpeedStage2 * percentageScaler; StageOneTalon.set(ShooterSpeedStage1); StageTwoTalon.set(ShooterSpeedStage2); flagX = false; } else if (shootY && flagY){//decreases percentage between Stage1 and Stage2 percentageScaler -= 0.05; if (percentageScaler <= 0 ) { percentageScaler = 0; } ShooterSpeedStage1 = ShooterSpeedStage2 * percentageScaler; StageOneTalon.set(ShooterSpeedStage1); StageTwoTalon.set(ShooterSpeedStage2); flagY = false; } else if (flagBack2 && flagBack){//turns off backTime = robotTimer.get(); if (robotTimer.get() >= backTime + .05){ ShooterSpeedStage2 -= 0.1; ShooterSpeedStage1 = ShooterSpeedStage2 * percentageScaler; } if (ShooterSpeedStage2 == 0){ flagBack = false; } ShooterSpeedStage2 = .1; ShooterSpeedStage1 = ShooterSpeedStage2 * percentageScaler; } if (shootBack && flagBack){ flagBack2 = true; } else if (!shootA && !flagA) { //toggles flagA = true; } else if (!shootB && !flagB){ flagB = true; }else if (!shootX && !flagX){ flagX = true; }else if (!shootY && !flagY){ flagY = true; } else if (!shootStart && !flagStart){ flagStart = true; }else if (!shootBack && !flagBack && ShooterSpeedStage2 == 0){ flagBack = true; flagBack2 = false; } //try {Thread.sleep(1000);} catch(Exception e){} //String percentage = Double.toString(); double speedOne = StageOneTalon.get(); String speed1 = Double.toString(speedOne); double speedTwo = StageTwoTalon.get(); String speed2 = Double.toString(speedTwo); LCD.println(Line.kUser3, 1, ((StageOneTalon.get()/StageTwoTalon.get()) *100) + " %"); LCD.println(Line.kUser4, 1,"S1:" + speed1); LCD.println(Line.kUser5, 1,"S2:" + speed2); LCD.println(Line.kUser1, 1, "RPM1: " + (speedOne * Scaler)); LCD.println(Line.kUser2, 1, "RPM2: " + (speedTwo * Scaler)); LCD.updateLCD(); /*if (shootA & !flagA) { //increases speed objShooter.speedChange(); LCD.println(Line.kUser2, 1, "Pressing A"); LCD.updateLCD(); flagA = true; } if (!shootA & flagA) { //if a is not pressed and it has been pressed set it to false flagA = false; } if (shootB & !flagB) { //decreases speed objShooter.speedChange(); LCD.println(Line.kUser2, 1, "Pressing B"); LCD.updateLCD(); flagB = true; } if (!shootB & flagB) { //if b is not pressed and it has been pressed set it to false flagB = false; } if (shootX & stageOneScaler <= 100 & !flagX){ stageOneScaler += 0.05; //changes stage1 percentage of stage2 adds 5% LCD.println(Line.kUser6, 1, "Adding 5% to Stage One Percentile"); LCD.updateLCD(); flagX = true; } if (!shootX & flagX) { //if x is not pressed and it has been pressed set it to false flagX = false; } if (shootY & !flagY){ objShooter.percentageSubtract(); LCD.println(Line.kUser2, 1, "Pressing Y"); LCD.updateLCD(); }*/ String currentTime = Double.toString(robotTimer.get()); LCD.println(Line.kUser6, 1, currentTime); } } }
package com.matthewtamlin.spyglass.processors.code_generation; import com.matthewtamlin.spyglass.processors.annotation_utils.CallHandlerAnnotationUtil; import com.matthewtamlin.spyglass.processors.annotation_utils.ValueHandlerAnnotationUtil; import com.matthewtamlin.spyglass.processors.grouper.TypeGrouper; import com.matthewtamlin.spyglass.processors.util.TypeUtil; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.HashSet; import java.util.Set; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.VariableElement; import javax.lang.model.util.Elements; import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkEachElementIsNotNull; import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull; import static com.matthewtamlin.spyglass.processors.annotation_utils.CallHandlerAnnotationUtil.hasCallHandlerAnnotation; import static com.matthewtamlin.spyglass.processors.annotation_utils.DefaultAnnotationUtil.hasDefaultAnnotation; import static com.matthewtamlin.spyglass.processors.annotation_utils.UseAnnotationUtil.hasUseAnnotation; import static com.matthewtamlin.spyglass.processors.annotation_utils.ValueHandlerAnnotationUtil.hasValueHandlerAnnotation; import static javax.lang.model.element.Modifier.PUBLIC; public class CompanionClassGenerator { private final CallerComponentGenerator callerComponentGenerator; private final InvocationLiteralGenerator invocationLiteralGenerator; public CompanionClassGenerator(final Elements elementUtil) { checkNotNull(elementUtil, "Argument \'elementUtil\' cannot be null."); callerComponentGenerator = new CallerComponentGenerator(elementUtil); invocationLiteralGenerator = new InvocationLiteralGenerator(elementUtil); } public JavaFile generateCompanionFromElements(final Set<ExecutableElement> methods) { checkNotNull(methods, "Argument \'methods\' cannot be null."); checkEachElementIsNotNull(methods, "Argument \'methods\' cannot contain null elements."); if (methods.isEmpty()) { throw new IllegalArgumentException("Argument \'methods\' cannot be empty."); } if (TypeGrouper.groupByEnclosingType(methods).size() != 1) { throw new IllegalArgumentException("All elements in argument \'methods\' must belong to the same class."); } final Set<TypeSpec> callers = new HashSet<>(); for (final ExecutableElement method : methods) { callers.add(generateCallerSpec(method)); } return null; } private TypeSpec generateCallerSpec(final ExecutableElement method) { if (hasCallHandlerAnnotation(method)) { return generateCallerForCallHandlerCase(method); } else if (hasValueHandlerAnnotation(method)) { return hasDefaultAnnotation(method) ? generateCallerForValueHandlerWithDefaultCase(method) : generateCallerForValueHandlerWithoutDefaultCase(method); } else { throw new IllegalArgumentException("Argument \'method\' has neither a value handler annotation nor a call" + " handler annotation."); } } private TypeSpec generateCallerForCallHandlerCase(final ExecutableElement e) { /* General structure * * new Caller { * public void callMethod(T target, Context context, TypedArray attrs) { * if (shouldCallMethod(attrs) { * // Variable implementation, generated by invocationLiteralGenerator * target.<generated method call> * } * } * * public boolean shouldCallMethod(TypedArray attrs) { * // Variable implementation, generated by callerComponentGenerator * <generated boolean with return> * } * } */ final TypeName targetType = TypeName.get(TypeUtil.getEnclosingType(e).asType()); final AnnotationMirror callHandlerAnno = CallHandlerAnnotationUtil.getCallHandlerAnnotationMirror(e); final MethodSpec shouldCallMethod = callerComponentGenerator.generateShouldCallMethodSpecFor(callHandlerAnno); final MethodSpec callMethod = getEmptyCallMethodSpec(targetType) .addCode(CodeBlock .builder() .beginControlFlow("if ($N(attrs))", shouldCallMethod) .addStatement("$L.$L", "target", invocationLiteralGenerator.generateLiteralWithoutExtraArg(e)) .endControlFlow() .build()) .build(); return getEmptyAnonymousCallerSpec(targetType) .addMethod(callMethod) .addMethod(shouldCallMethod) .build(); } private TypeSpec generateCallerForValueHandlerWithoutDefaultCase(final ExecutableElement e) { /* General structure * * new Caller { * public void callMethod(T target, Context context, TypedArray attrs) { * * if (valueIsAvailable(attrs) { * V value = (V) getValue(attrs); * * // Variable implementation, generated by invocationLiteralGenerator * target.<generated method call using "value"> * } * } * * public void valueIsAvailable(TypedArray attrs) { * // Variable implementation, generated by callerComponentGenerator * <generated boolean with return> * } * * public V getValue(TypedArray attrs) { * // Variable implementation, generated by callerComponentGenerator * <generated code with return> * } * } */ final TypeName targetType = TypeName.get(TypeUtil.getEnclosingType(e).asType()); final TypeName nonUseParamType = getTypeNameOfNonUseParameter(e); final AnnotationMirror valueHandlerAnno = ValueHandlerAnnotationUtil.getValueHandlerAnnotationMirror(e); final MethodSpec valueIsAvailable = callerComponentGenerator.generateValueIsAvailableSpecFor(valueHandlerAnno); final MethodSpec getValue = callerComponentGenerator.generateGetValueSpecFor(valueHandlerAnno); final MethodSpec callMethod = getEmptyCallMethodSpec(targetType) .addCode(CodeBlock .builder() .beginControlFlow("if ($N(attrs))", valueIsAvailable) .addStatement("$T value = ($T) $N(attrs)", nonUseParamType, nonUseParamType, getValue) .addStatement( "$L.$L", "target", invocationLiteralGenerator.generateLiteralWithExtraArg(e, "value")) .endControlFlow() .build()) .build(); return getEmptyAnonymousCallerSpec(targetType) .addMethod(callMethod) .addMethod(valueIsAvailable) .addMethod(getValue) .build(); } private TypeSpec generateCallerForValueHandlerWithDefaultCase(final ExecutableElement e) { /* General structure * * new Caller { * public void callMethod(T target, Context context, TypedArray attrs) { * V value = valueIsAvailable(attrs) ? (V) getValue(attrs) : (V) getDefault(attrs); * * // Variable implementation, generated by invocationLiteralGenerator * target.<generated method call using "value"> * } * * public void valueIsAvailable(TypedArray attrs) { * // Variable implementation, generated by callerComponentGenerator * <generated boolean with return> * } * * public V getValue(TypedArray attrs) { * // Variable implementation, generated by callerComponentGenerator * <generated code with return> * } * * public V getDefault(Context context, TypedArray attrs) { * // Variable implementation, generated by callerComponentGenerator * <generated code with return> * } * } */ final TypeName targetType = TypeName.get(TypeUtil.getEnclosingType(e).asType()); final TypeName nonUseParamType = getTypeNameOfNonUseParameter(e); final AnnotationMirror valueHandler = ValueHandlerAnnotationUtil.getValueHandlerAnnotationMirror(e); final MethodSpec valueIsAvailable = callerComponentGenerator.generateValueIsAvailableSpecFor(valueHandler); final MethodSpec getValue = callerComponentGenerator.generateGetValueSpecFor(valueHandler); final MethodSpec getDefault = callerComponentGenerator.generateGetDefaultValueSpecFor(valueHandler); final MethodSpec callMethod = getEmptyCallMethodSpec(targetType) .addCode(CodeBlock .builder() .addStatement( "$1T value = $2N(attrs) ? ($1T) $3N(attrs) : ($1T) $4N(context, attrs)", nonUseParamType, valueIsAvailable, getValue, getDefault) .addStatement( "target.$L", invocationLiteralGenerator.generateLiteralWithExtraArg(e, "value")) .build()) .build(); return getEmptyAnonymousCallerSpec(targetType) .addMethod(callMethod) .addMethod(valueIsAvailable) .addMethod(getValue) .addMethod(getDefault) .build(); } private TypeSpec.Builder getEmptyAnonymousCallerSpec(final TypeName targetType) { final ClassName genericCaller = ClassName.get(CallerDef.PACKAGE, CallerDef.INTERFACE_NAME); final TypeName specificCaller = ParameterizedTypeName.get(genericCaller, targetType); return TypeSpec .anonymousClassBuilder("") .addSuperinterface(specificCaller); } private MethodSpec.Builder getEmptyCallMethodSpec(final TypeName targetType) { return MethodSpec .methodBuilder(CallerDef.METHOD_NAME) .returns(void.class) .addModifiers(PUBLIC) .addParameter(targetType, "target") .addParameter(AndroidClassNames.CONTEXT, "context") .addParameter(AndroidClassNames.TYPED_ARRAY, "attrs"); } private TypeName getTypeNameOfNonUseParameter(final ExecutableElement e) { for (final VariableElement parameter : e.getParameters()) { if (!hasUseAnnotation(parameter)) { return ClassName.get(parameter.asType()); } } throw new RuntimeException("No non-use argument found."); } }
package com.jetbrains.edu.learning.courseGeneration; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; import com.jetbrains.edu.EduNames; import com.jetbrains.edu.courseFormat.Course; import com.jetbrains.edu.courseFormat.Lesson; import com.jetbrains.edu.courseFormat.Task; import com.jetbrains.edu.courseFormat.TaskFile; import com.jetbrains.edu.learning.StudyTaskManager; import com.jetbrains.edu.learning.StudyUtils; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.List; import java.util.Map; public class StudyGenerator { private StudyGenerator() { } private static final Logger LOG = Logger.getInstance(StudyGenerator.class.getName()); /** * Creates task files in its task folder in project user created * * @param taskDir project directory of task which task file belongs to * @param resourceRoot directory where original task file stored * @throws IOException */ public static void createTaskFile(@NotNull final VirtualFile taskDir, @NotNull final File resourceRoot, @NotNull final String name) throws IOException { String systemIndependentName = FileUtil.toSystemIndependentName(name); final int index = systemIndependentName.lastIndexOf("/"); if (index > 0) { systemIndependentName = systemIndependentName.substring(index + 1); } File resourceFile = new File(resourceRoot, name); File fileInProject = new File(taskDir.getPath(), systemIndependentName); FileUtil.copy(resourceFile, fileInProject); } /** * Creates task directory in its lesson folder in project user created * * @param lessonDir project directory of lesson which task belongs to * @param resourceRoot directory where original task file stored * @throws IOException */ public static void createTask(@NotNull final Task task, @NotNull final VirtualFile lessonDir, @NotNull final File resourceRoot, @NotNull final Project project) throws IOException { VirtualFile taskDir = lessonDir.createChildDirectory(project, EduNames.TASK + Integer.toString(task.getIndex())); File newResourceRoot = new File(resourceRoot, taskDir.getName()); int i = 0; for (Map.Entry<String, TaskFile> taskFile : task.getTaskFiles().entrySet()) { TaskFile taskFileContent = taskFile.getValue(); taskFileContent.setIndex(i); i++; createTaskFile(taskDir, newResourceRoot, taskFile.getKey()); } File[] filesInTask = newResourceRoot.listFiles(); if (filesInTask != null) { for (File file : filesInTask) { String fileName = file.getName(); if (!task.isTaskFile(fileName)) { File resourceFile = new File(newResourceRoot, fileName); File fileInProject = new File(taskDir.getCanonicalPath(), fileName); FileUtil.copy(resourceFile, fileInProject); if (!StudyUtils.isTestsFile(project, fileName) && !EduNames.TASK_HTML.equals(fileName)) { StudyTaskManager.getInstance(project).addInvisibleFiles(FileUtil.toSystemIndependentName(fileInProject.getPath())); } } } } } /** * Creates lesson directory in its course folder in project user created * * @param courseDir project directory of course * @param resourceRoot directory where original lesson stored * @throws IOException */ public static void createLesson(@NotNull final Lesson lesson, @NotNull final VirtualFile courseDir, @NotNull final File resourceRoot, @NotNull final Project project) throws IOException { if (EduNames.PYCHARM_ADDITIONAL.equals(lesson.getName())) return; String lessonDirName = EduNames.LESSON + Integer.toString(lesson.getIndex()); VirtualFile lessonDir = courseDir.createChildDirectory(project, lessonDirName); final List<Task> taskList = lesson.getTaskList(); for (int i = 1; i <= taskList.size(); i++) { Task task = taskList.get(i - 1); task.setIndex(i); createTask(task, lessonDir, new File(resourceRoot, lessonDir.getName()), project); } } /** * Creates course directory in project user created * * @param baseDir project directory * @param resourceRoot directory where original course is stored */ public static void createCourse(@NotNull final Course course, @NotNull final VirtualFile baseDir, @NotNull final File resourceRoot, @NotNull final Project project) { try { final List<Lesson> lessons = course.getLessons(); for (int i = 1; i <= lessons.size(); i++) { Lesson lesson = lessons.get(i - 1); lesson.setIndex(i); createLesson(lesson, baseDir, resourceRoot, project); } baseDir.createChildDirectory(project, EduNames.SANDBOX_DIR); File[] files = resourceRoot.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return !name.contains(EduNames.LESSON) && !name.equals(EduNames.COURSE_META_FILE) && !name.equals(EduNames.HINTS); } }); for (File file : files) { FileUtil.copy(file, new File(baseDir.getPath(), file.getName())); } } catch (IOException e) { LOG.error(e); } } }
package org.eclipse.che.selenium.core.client; import static com.google.common.base.Charsets.UTF_8; import static com.google.common.io.Resources.getResource; import static com.google.common.io.Resources.toByteArray; import static java.lang.String.format; import static java.nio.file.Files.createFile; import static java.nio.file.Files.write; import static java.util.Optional.ofNullable; import static org.eclipse.che.dto.server.DtoFactory.getInstance; import static org.eclipse.che.selenium.core.project.ProjectTemplates.PLAIN_JAVA; import com.google.common.io.Resources; import com.google.inject.Inject; import com.google.inject.Singleton; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.eclipse.che.api.core.model.workspace.config.ProjectConfig; import org.eclipse.che.api.core.rest.HttpJsonRequestFactory; import org.eclipse.che.api.workspace.shared.dto.ProjectConfigDto; import org.eclipse.che.api.workspace.shared.dto.SourceStorageDto; import org.eclipse.che.commons.lang.IoUtil; import org.eclipse.che.commons.lang.ZipUtils; import org.eclipse.che.selenium.core.provider.TestWorkspaceAgentApiEndpointUrlProvider; /** * @author Musienko Maxim * @author Mykola Morhun */ @Singleton public class TestProjectServiceClient { private static final String BEARER_TOKEN_PREFIX = "Bearer "; private final TestMachineServiceClient machineServiceClient; private final HttpJsonRequestFactory requestFactory; private final TestWorkspaceAgentApiEndpointUrlProvider workspaceAgentApiEndpointUrlProvider; @Inject public TestProjectServiceClient( TestMachineServiceClient machineServiceClient, HttpJsonRequestFactory requestFactory, TestWorkspaceAgentApiEndpointUrlProvider workspaceAgentApiEndpointUrlProvider) { this.machineServiceClient = machineServiceClient; this.requestFactory = requestFactory; this.workspaceAgentApiEndpointUrlProvider = workspaceAgentApiEndpointUrlProvider; } /** Set type for existing project on vfs */ public void setProjectType(String workspaceId, String template, String projectName) throws Exception { InputStream in = getClass().getResourceAsStream("/templates/project/" + template); String json = IoUtil.readAndCloseQuietly(in); ProjectConfigDto project = getInstance().createDtoFromJson(json, ProjectConfigDto.class); project.setName(projectName); requestFactory .fromUrl(workspaceAgentApiEndpointUrlProvider.get(workspaceId) + "project/" + projectName) .usePutMethod() .setAuthorizationHeader( BEARER_TOKEN_PREFIX + machineServiceClient.getMachineApiToken(workspaceId)) .setBody(project) .request(); } /** Delete resource. */ public void deleteResource(String workspaceId, String path) throws Exception { requestFactory .fromUrl(workspaceAgentApiEndpointUrlProvider.get(workspaceId) + "project/" + path) .setAuthorizationHeader( BEARER_TOKEN_PREFIX + machineServiceClient.getMachineApiToken(workspaceId)) .useDeleteMethod() .request(); } public void createFolder(String workspaceId, String folder) throws Exception { String url = workspaceAgentApiEndpointUrlProvider.get(workspaceId) + "project/folder/" + folder; requestFactory .fromUrl(url) .setAuthorizationHeader( BEARER_TOKEN_PREFIX + machineServiceClient.getMachineApiToken(workspaceId)) .usePostMethod() .request(); } /** Import zip project from file system into user workspace. */ public void importZipProject( String workspaceId, Path zipFile, String projectName, String template) throws Exception { String url = workspaceAgentApiEndpointUrlProvider.get(workspaceId) + "project/import/" + projectName; // createFolder(workspaceId, projectName); HttpURLConnection httpConnection = null; try { httpConnection = (HttpURLConnection) new URL(url).openConnection(); httpConnection.setRequestMethod("POST"); httpConnection.setRequestProperty("Content-Type", "application/zip"); httpConnection.addRequestProperty( "Authorization", BEARER_TOKEN_PREFIX + machineServiceClient.getMachineApiToken(workspaceId)); httpConnection.setDoOutput(true); try (OutputStream outputStream = httpConnection.getOutputStream()) { Files.copy(zipFile, outputStream); if (httpConnection.getResponseCode() != 201) { throw new RuntimeException( "Cannot deploy requested project using ProjectServiceClient REST API. Server response " + httpConnection.getResponseCode() + " " + IoUtil.readStream(httpConnection.getErrorStream()) + "REST url: " + url); } } } finally { ofNullable(httpConnection).ifPresent(HttpURLConnection::disconnect); } setProjectType(workspaceId, template, projectName); } /** Import project from file system into a user workspace */ public void importProject( String workspaceId, Path sourceFolder, String projectName, String template) throws Exception { if (!Files.exists(sourceFolder)) { throw new IOException(format("%s not found", sourceFolder)); } if (!Files.isDirectory(sourceFolder)) { throw new IOException(format("%s not a directory", sourceFolder)); } Path zip = Files.createTempFile("project", projectName); if (PLAIN_JAVA.equals(template)) { Path tmpDir = Files.createTempDirectory("TestProject"); Path dotClasspath = createFile(tmpDir.resolve(".classpath")); Path dotProject = Files.createFile(tmpDir.resolve(".project")); write( dotProject, format( Resources.toString(getResource("projects/jdt-ls-project-files/project"), UTF_8), projectName) .getBytes()); write(dotClasspath, toByteArray(getResource("projects/jdt-ls-project-files/classpath"))); ZipUtils.zipFiles( zip.toFile(), sourceFolder.toFile(), dotClasspath.toFile(), dotProject.toFile()); } else { ZipUtils.zipFiles(zip.toFile(), sourceFolder.toFile()); } importZipProject(workspaceId, zip, projectName, template); } /** Import project from file system into a user workspace */ public void importProject( String workspaceId, String projectName, String location, String type, Map<String, String> parameters) throws Exception { SourceStorageDto source = getInstance().createDto(SourceStorageDto.class); source.setLocation(location); source.setType(type); source.setParameters(parameters); importProject(workspaceId, projectName, source); } /** Import project from file system into a user workspace */ public void importProject(String workspaceId, String projectName, SourceStorageDto source) throws Exception { requestFactory .fromUrl( workspaceAgentApiEndpointUrlProvider.get(workspaceId) + "project/import/" + projectName) .usePostMethod() .setAuthorizationHeader(machineServiceClient.getMachineApiToken(workspaceId)) .setBody(source) .request(); } /** Creates file in the project. */ public void createFileInProject( String workspaceId, String parentFolder, String fileName, String content) throws Exception { String apiRESTUrl = workspaceAgentApiEndpointUrlProvider.get(workspaceId) + "project/file/" + parentFolder + "?name=" + fileName; HttpURLConnection httpConnection = null; try { httpConnection = (HttpURLConnection) new URL(apiRESTUrl).openConnection(); httpConnection.setRequestMethod("POST"); httpConnection.setRequestProperty("Content-Type", "text/plain"); httpConnection.addRequestProperty( "Authorization", BEARER_TOKEN_PREFIX + machineServiceClient.getMachineApiToken(workspaceId)); httpConnection.setDoOutput(true); try (OutputStream output = httpConnection.getOutputStream()) { output.write(content.getBytes("UTF-8")); if (httpConnection.getResponseCode() != 201) { throw new RuntimeException( "Cannot create requested content in the current project: " + apiRESTUrl + " something went wrong " + httpConnection.getResponseCode() + IoUtil.readStream(httpConnection.getErrorStream())); } } } finally { ofNullable(httpConnection).ifPresent(HttpURLConnection::disconnect); } } public ProjectConfigDto getFirstProject(String workspaceId) throws Exception { String apiUrl = workspaceAgentApiEndpointUrlProvider.get(workspaceId) + "project"; return requestFactory .fromUrl(apiUrl) .setAuthorizationHeader( BEARER_TOKEN_PREFIX + machineServiceClient.getMachineApiToken(workspaceId)) .request() .asList(ProjectConfigDto.class) .get(0); } /** Updates file content. */ public void updateFile(String workspaceId, String pathToFile, String content) throws Exception { String url = workspaceAgentApiEndpointUrlProvider.get(workspaceId) + "project/file/" + pathToFile; HttpURLConnection httpConnection = null; try { httpConnection = (HttpURLConnection) new URL(url).openConnection(); httpConnection.setRequestMethod("PUT"); httpConnection.setRequestProperty("Content-Type", "text/plain"); httpConnection.addRequestProperty( "Authorization", BEARER_TOKEN_PREFIX + machineServiceClient.getMachineApiToken(workspaceId)); httpConnection.setDoOutput(true); try (OutputStream output = httpConnection.getOutputStream()) { output.write(content.getBytes("UTF-8")); if (httpConnection.getResponseCode() != 200) { throw new RuntimeException( "Cannot update content in the current file: " + url + " something went wrong " + httpConnection.getResponseCode() + IoUtil.readStream(httpConnection.getErrorStream())); } } } finally { ofNullable(httpConnection).ifPresent(HttpURLConnection::disconnect); } } public boolean checkProjectType(String wokspaceId, String projectName, String projectType) throws Exception { return getProject(wokspaceId, projectName).getType().equals(projectType); } public boolean checkProjectLanguage(String workspaceId, String projectName, String language) throws Exception { return getProject(workspaceId, projectName).getAttributes().get("language").contains(language); } public boolean checkProjectLanguage( String workspaceId, String projectName, List<String> languages) throws Exception { return getProject(workspaceId, projectName) .getAttributes() .get("language") .containsAll(languages); } public List<String> getExternalLibraries(String workspaceId, String projectName) throws Exception { return requestFactory .fromUrl( workspaceAgentApiEndpointUrlProvider.get(workspaceId) + "java/navigation/libraries") .useGetMethod() .addQueryParam("projectpath", "/" + projectName) .request() .asList(ProjectConfigDto.class) .stream() .map(e -> e.getName()) .collect(Collectors.toList()); } private ProjectConfig getProject(String workspaceId, String projectName) throws Exception { return requestFactory .fromUrl(workspaceAgentApiEndpointUrlProvider.get(workspaceId) + "project/" + projectName) .useGetMethod() .setAuthorizationHeader( BEARER_TOKEN_PREFIX + machineServiceClient.getMachineApiToken(workspaceId)) .request() .asDto(ProjectConfigDto.class); } }
package org.sagebionetworks.repo.manager; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.util.List; import java.util.Properties; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.Message.RecipientType; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; import org.apache.commons.net.util.Base64; import org.apache.http.entity.ContentType; import org.sagebionetworks.StackConfiguration; import org.sagebionetworks.repo.model.message.multipart.Attachment; import org.sagebionetworks.repo.model.message.multipart.MessageBody; import org.sagebionetworks.schema.adapter.JSONObjectAdapterException; import org.sagebionetworks.schema.adapter.org.json.EntityFactory; import com.amazonaws.services.simpleemail.model.RawMessage; import com.amazonaws.services.simpleemail.model.SendRawEmailRequest; /* * If sender is null then the 'notification email address' is used * If unsubscribeLink is null then no such link is added. * */ public class SendRawEmailRequestBuilder { private String recipientEmail=null; private String subject=null; private String to=null; private String cc=null; private String bcc=null; private String body=null; private BodyType bodyType=null; private String senderDisplayName=null; private String senderUserName=null; private String notificationUnsubscribeEndpoint=null; private String userId=null; public enum BodyType{JSON, PLAIN_TEXT, HTML}; public SendRawEmailRequestBuilder withRecipientEmail(String recipientEmail) { this.recipientEmail=recipientEmail; return this; } public SendRawEmailRequestBuilder withSubject(String subject) { this.subject=subject; return this; } public SendRawEmailRequestBuilder withTo(String to) { this.to=to; return this; } public SendRawEmailRequestBuilder withCc(String cc) { this.cc=cc; return this; } public SendRawEmailRequestBuilder withBcc(String bcc) { this.bcc=bcc; return this; } public SendRawEmailRequestBuilder withBody(String body, BodyType bodyType) { this.body=body; this.bodyType=bodyType; return this; } public SendRawEmailRequestBuilder withSenderDisplayName(String senderDisplayName) { this.senderDisplayName=senderDisplayName; return this; } public SendRawEmailRequestBuilder withSenderUserName(String senderUserName) { this.senderUserName=senderUserName; return this; } public SendRawEmailRequestBuilder withNotificationUnsubscribeEndpoint(String notificationUnsubscribeEndpoint) { this.notificationUnsubscribeEndpoint=notificationUnsubscribeEndpoint; return this; } public SendRawEmailRequestBuilder withUserId(String userId) { this.userId=userId; return this; } public SendRawEmailRequest build() { String source = EmailUtils.createSource(senderDisplayName, senderUserName); // Create the subject and body of the message if (subject == null) subject = ""; String unsubscribeLink = null; if (notificationUnsubscribeEndpoint==null) { notificationUnsubscribeEndpoint = StackConfiguration.getDefaultPortalNotificationEndpoint(); } if (userId!=null) { unsubscribeLink = EmailUtils. createOneClickUnsubscribeLink(notificationUnsubscribeEndpoint, userId); } MimeMultipart multipart; switch (bodyType) { case JSON: multipart = createEmailBodyFromJSON(body, unsubscribeLink); break; case PLAIN_TEXT: multipart = createEmailBodyFromText(body, ContentType.TEXT_PLAIN, unsubscribeLink); break; case HTML: multipart = createEmailBodyFromText(body, ContentType.TEXT_HTML, unsubscribeLink); break; default: throw new IllegalStateException("Unexpected type "+bodyType); } Properties props = new Properties(); // sets SMTP server properties props.setProperty("mail.transport.protocol", "aws"); Session mailSession = Session.getInstance(props); ByteArrayOutputStream out = new ByteArrayOutputStream(); try { MimeMessage msg = new MimeMessage(mailSession); msg.setFrom(new InternetAddress(source)); msg.setRecipient( Message.RecipientType.TO, new InternetAddress(recipientEmail)); if (subject!=null) msg.setSubject(subject); // note: setSubject will encode non-ascii characters for us if (to!=null) msg.setRecipients(RecipientType.TO, to); if (cc!=null) msg.setRecipients(RecipientType.CC, cc); if (bcc!=null) msg.setRecipients(RecipientType.BCC, bcc); msg.setContent(multipart); msg.writeTo(out); } catch (AddressException e) { throw new RuntimeException(e); } catch (MessagingException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } RawMessage rawMessage = new RawMessage(); rawMessage.setData(ByteBuffer.wrap(out.toByteArray())); // Assemble the email SendRawEmailRequest request = new SendRawEmailRequest() .withSource(source) .withRawMessage(rawMessage) .withDestinations(recipientEmail); return request; } public static MimeMultipart createEmailBodyFromJSON(String messageBodyString, String unsubscribeLink) { try { MessageBody messageBody = null; boolean canDeserializeJSON = false; try { messageBody = EntityFactory.createEntityFromJSONString(messageBodyString, MessageBody.class); canDeserializeJSON=true; } catch (JSONObjectAdapterException e) { canDeserializeJSON = false; // just send the content as plain text } MimeMultipart mp = new MimeMultipart("related"); if (canDeserializeJSON) { String plain = messageBody.getPlain(); String html = messageBody.getHtml(); List<Attachment> attachments = messageBody.getAttachments(); if (html!=null || plain!=null) { MimeBodyPart alternativeBodyPart = new MimeBodyPart(); MimeMultipart alternativeMultiPart = new MimeMultipart("alternative"); alternativeBodyPart.setContent(alternativeMultiPart); if (html!=null) { BodyPart part = new MimeBodyPart(); part.setContent(EmailUtils.createEmailBodyFromHtml(html, unsubscribeLink), ContentType.TEXT_HTML.getMimeType()); alternativeMultiPart.addBodyPart(part); } else if (plain!=null) { BodyPart part = new MimeBodyPart(); part.setContent(EmailUtils.createEmailBodyFromText(plain, unsubscribeLink), ContentType.TEXT_PLAIN.getMimeType()); alternativeMultiPart.addBodyPart(part); } mp.addBodyPart(alternativeBodyPart); } if (attachments!=null) { for (Attachment attachment : attachments) { MimeBodyPart part = new MimeBodyPart(); String content = attachment.getContent(); String contentType = attachment.getContent_type(); // CloudMailIn doesn't provide the Content-Transfer-Encoding // header, so we assume it's base64 encoded, which is the norm byte[] contentBytes; try { contentBytes = Base64.decodeBase64(content); } catch (Exception e) { contentBytes = content.getBytes(); } if (contentType.toLowerCase().startsWith("text")) { part.setContent(new String(contentBytes), contentType); } else { part.setContent(contentBytes, contentType); } if (attachment.getDisposition()!=null) part.setDisposition(attachment.getDisposition()); if (attachment.getContent_id()!=null) part.setContentID(attachment.getContent_id()); if (attachment.getFile_name()!=null) part.setFileName(attachment.getFile_name()); if (attachment.getSize()!=null) part.setHeader("size", attachment.getSize()); if (attachment.getUrl()!=null) part.setHeader("url", attachment.getUrl()); mp.addBodyPart(part); } } } else { BodyPart part = new MimeBodyPart(); part.setContent(EmailUtils.createEmailBodyFromText(messageBodyString, unsubscribeLink), ContentType.TEXT_PLAIN.getMimeType()); mp.addBodyPart(part); } return mp; } catch (MessagingException e) { throw new RuntimeException(e); } } public static MimeMultipart createEmailBodyFromText(String messageBodyString, ContentType contentType, String unsubscribeLink) { MimeMultipart mp = new MimeMultipart("related"); try { BodyPart part = new MimeBodyPart(); if (contentType.getMimeType().equals(ContentType.TEXT_HTML.getMimeType())) { part.setContent(EmailUtils.createEmailBodyFromHtml(messageBodyString, unsubscribeLink), ContentType.TEXT_HTML.getMimeType()); } else if (contentType.getMimeType().equals(ContentType.TEXT_PLAIN.getMimeType())) { StringBuilder sb = new StringBuilder("<html>\n<body>\n"); sb.append("<div style=\"white-space: pre-wrap;\">\n"); sb.append(EmailUtils.createEmailBodyFromHtml(messageBodyString, unsubscribeLink)); sb.append("\n</div>"); sb.append("\n</body>\n</html>\n"); part.setContent(sb.toString(), ContentType.TEXT_HTML.getMimeType()); } else { throw new IllegalArgumentException("Unexpected mime type for text: "+contentType.getMimeType()); } mp.addBodyPart(part); } catch (MessagingException e) { throw new RuntimeException(e); } return mp; } }
package org.rstudio.studio.client.workbench.views.source.editors.text.ace; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.rstudio.core.client.HandlerRegistrations; import org.rstudio.core.client.JsVector; import org.rstudio.core.client.JsVectorInteger; import org.rstudio.core.client.ListUtil; import org.rstudio.core.client.StringUtil; import org.rstudio.core.client.regex.Pattern; import org.rstudio.studio.client.workbench.views.source.editors.text.AceEditor; import org.rstudio.studio.client.workbench.views.source.editors.text.events.DocumentChangedEvent; import org.rstudio.studio.client.workbench.views.source.editors.text.events.EditorModeChangedEvent; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.event.logical.shared.AttachEvent; import com.google.gwt.user.client.Timer; public class AceBackgroundHighlighter implements EditorModeChangedEvent.Handler, DocumentChangedEvent.Handler, AttachEvent.Handler { private static class HighlightPattern { public HighlightPattern(String begin, String end) { this.begin = Pattern.create(begin, ""); this.end = Pattern.create(end, ""); } public Pattern begin; public Pattern end; } private class Worker { public Worker() { timer_ = new Timer() { @Override public void run() { work(); } }; } private void work() { // determine range to update int n = editor_.getRowCount(); int startRow = row_; int endRow = Math.min(startRow + CHUNK_SIZE, editor_.getRowCount()); activeHighlightPattern_ = findActiveHighlightPattern(startRow); // first, update local background state for each row for (int row = startRow; row < endRow; row++) { // determine what state this row is in int state = computeState(row); // if there's been no change, bail boolean isConsistentState = rowStates_.isSet(row) && rowPatterns_.isSet(row) && (rowStates_.get(row) == state) && (rowPatterns_.get(row) == activeHighlightPattern_); if (isConsistentState) break; // update state for this row rowStates_.set(row, state); rowPatterns_.set(row, activeHighlightPattern_); } // then, notify Ace and perform actual rendering of markers for (int row = startRow; row < endRow; row++) { int state = rowStates_.get(row); // don't show background highlighting if this // chunk lies within a fold AceFold fold = session_.getFoldAt(row, 0); if (fold != null) continue; int marker = markerIds_.get(row, 0); // bail early if no action is necessary boolean isConsistentState = (state == STATE_TEXT && marker == 0) || (state != STATE_TEXT && marker != 0); if (isConsistentState) continue; // clear a pre-existing marker if necessary if (marker != 0) { session_.removeMarker(marker); markerIds_.set(row, 0); } // if this is a non-text state, then draw a marker if (state != STATE_TEXT) { int markerId = session_.addMarker( Range.create(row, 0, row, Integer.MAX_VALUE), MARKER_CLASS, MARKER_TYPE, false); markerIds_.set(row, markerId); } } // update worker state and reschedule if there's // more work to be done row_ = endRow; if (endRow != n) timer_.schedule(DELAY_MS); } public void start(int row) { row_ = Math.min(row, row_); timer_.schedule(0); } private final Timer timer_; private int row_; private static final int DELAY_MS = 5; private static final int CHUNK_SIZE = 200; } public AceBackgroundHighlighter(AceEditor editor) { editor_ = editor; session_ = editor.getSession(); highlightPatterns_ = new ArrayList<HighlightPattern>(); handlers_ = new HandlerRegistrations( editor.addEditorModeChangedHandler(this), editor.addDocumentChangedHandler(this), editor.addAttachHandler(this)); int n = editor.getRowCount(); rowStates_ = JavaScriptObject.createArray(n).cast(); rowPatterns_ = JavaScriptObject.createArray(n).cast(); markerIds_ = JavaScriptObject.createArray(n).cast(); worker_ = new Worker(); refreshHighlighters(); } @Override public void onEditorModeChanged(EditorModeChangedEvent event) { clearMarkers(); clearRowState(); refreshHighlighters(); synchronizeFrom(0); } @Override public void onDocumentChanged(DocumentChangedEvent event) { AceDocumentChangeEventNative nativeEvent = event.getEvent(); String action = nativeEvent.getAction(); Range range = nativeEvent.getRange(); int startRow = range.getStart().getRow(); int endRow = range.getEnd().getRow(); // NOTE: this will need to change with the next version of Ace, // as the layout of document changed events will have changed there rowStates_.unset(startRow); rowPatterns_.unset(startRow); if (action.startsWith("insert")) { int newlineCount = endRow - startRow; rowStates_.insert(startRow, JsVectorInteger.ofLength(newlineCount)); rowPatterns_.insert(startRow, JsVector.<HighlightPattern>ofLength(newlineCount)); } else if (action.startsWith("remove")) { int newlineCount = endRow - startRow; if (newlineCount > 0) { rowStates_.remove(startRow, newlineCount); rowPatterns_.remove(startRow,newlineCount); } } synchronizeFrom(startRow); } @Override public void onAttachOrDetach(AttachEvent event) { if (!event.isAttached()) { handlers_.removeHandler(); } } HighlightPattern selectBeginPattern(String line) { for (HighlightPattern pattern : highlightPatterns_) if (pattern.begin.test(line)) return pattern; return null; } private HighlightPattern findActiveHighlightPattern(int startRow) { for (int row = startRow; row >= 0; row { // check for a cached highlight pattern HighlightPattern pattern = rowPatterns_.get(row); if (pattern != null) return pattern; // no pattern available; re-compute based on current state int state = rowStates_.get(row); switch (state) { case STATE_TEXT: break; case STATE_CHUNK_START: String line = editor_.getLine(row); return selectBeginPattern(line); case STATE_CHUNK_BODY: case STATE_CHUNK_END: default: continue; } } return null; } private int computeState(int row) { String line = editor_.getLine(row); int state = (row > 0) ? rowStates_.get(row - 1, STATE_TEXT) : STATE_TEXT; switch (state) { case STATE_TEXT: case STATE_CHUNK_END: { HighlightPattern pattern = selectBeginPattern(line); if (pattern != null) { activeHighlightPattern_ = pattern; return STATE_CHUNK_START; } return STATE_TEXT; } case STATE_CHUNK_START: case STATE_CHUNK_BODY: { assert activeHighlightPattern_ != null : "Unexpected null highlight pattern"; if (activeHighlightPattern_.end.test(line)) { activeHighlightPattern_ = null; return STATE_CHUNK_END; } return STATE_CHUNK_BODY; } } // shouldn't be reached return STATE_TEXT; } private void synchronizeFrom(int startRow) { // if this row has no state, then we need to look // back until we find a row with cached state while (startRow > 0 && !rowStates_.isSet(startRow - 1)) startRow // start the worker that will update ace worker_.start(startRow); } private void refreshHighlighters() { highlightPatterns_.clear(); String modeId = editor_.getModeId(); if (StringUtil.isNullOrEmpty(modeId)) return; if (HIGHLIGHT_PATTERN_REGISTRY.containsKey(modeId)) { highlightPatterns_.addAll(HIGHLIGHT_PATTERN_REGISTRY.get(modeId)); } } private void clearRowState() { rowStates_.fill(0); rowPatterns_.fill((HighlightPattern) null); } private void clearMarkers() { for (int i = 0, n = markerIds_.length(); i < n; i++) { int markerId = markerIds_.get(i); if (markerId != 0) session_.removeMarker(markerId); } markerIds_.fill(0); } private static List<HighlightPattern> cStyleHighlightPatterns() { return ListUtil.create( new HighlightPattern( "^\\s*[/][*}{3,}\\s*[Rr]\\s*$", "^\\s*[*]+[/]") ); } private static List<HighlightPattern> htmlStyleHighlightPatterns() { return ListUtil.create( new HighlightPattern( "^<!--\\s*begin[.]rcode\\s*(?:.*)", "^\\s*end[.]rcode\\s* ); } private static List<HighlightPattern> sweaveHighlightPatterns() { return ListUtil.create( new HighlightPattern( "<<(.*?)>>", "^\\s*@\\s*$") ); } private static final List<HighlightPattern> rMarkdownHighlightPatterns() { return ListUtil.create( // code chunks new HighlightPattern( "^(?:[ ]{4})?`{3,}\\s*\\{.*\\}\\s*$", "^(?:[ ]{4})?`{3,}\\s*$"), // latex blocks new HighlightPattern( "^[$][$]\\s*$", "^[$][$]\\s*$") ); } private final AceEditor editor_; private final EditSession session_; private HighlightPattern activeHighlightPattern_; private final List<HighlightPattern> highlightPatterns_; private final HandlerRegistrations handlers_; private final JsVectorInteger rowStates_; private final JsVectorInteger markerIds_; private final JsVector<HighlightPattern> rowPatterns_; private final Worker worker_; private static final String MARKER_CLASS = "ace_foreign_line background_highlight"; private static final String MARKER_TYPE = "fullLine"; private static final Map<String, List<HighlightPattern>> HIGHLIGHT_PATTERN_REGISTRY; static { HIGHLIGHT_PATTERN_REGISTRY = new HashMap<String, List<HighlightPattern>>(); HIGHLIGHT_PATTERN_REGISTRY.put("mode/rmarkdown", rMarkdownHighlightPatterns()); HIGHLIGHT_PATTERN_REGISTRY.put("mode/c_cpp", cStyleHighlightPatterns()); HIGHLIGHT_PATTERN_REGISTRY.put("mode/sweave", sweaveHighlightPatterns()); HIGHLIGHT_PATTERN_REGISTRY.put("mode/rhtml", htmlStyleHighlightPatterns()); } private static final int STATE_TEXT = 0; private static final int STATE_CHUNK_START = 1; private static final int STATE_CHUNK_BODY = 2; private static final int STATE_CHUNK_END = 3; }
package org.carlspring.strongbox.io; import java.nio.file.FileSystem; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.Paths; import java.nio.file.spi.FileSystemProvider; import org.carlspring.strongbox.storage.repository.Repository; /** * {@link RepositoryFileSystem} is a wrapper under concrete Storage {@link FileSystem}. <br> * The {@link RepositoryFileSystem} root is the {@link Repository}'s base directory. * * @author Sergey Bespalov */ public class RepositoryFileSystem extends FileSystemWrapper { private Repository repository; private FileSystemProvider fileSystemProvider; public RepositoryFileSystem(Repository repository, FileSystem storageFileSystem, FileSystemProvider provider) { super(storageFileSystem); this.repository = repository; this.fileSystemProvider = provider; } public RepositoryFileSystem(Repository repository, FileSystem storageFileSystem) { this(repository, storageFileSystem, new RepositoryFileSystemProvider(storageFileSystem.provider())); } public Repository getRepository() { return repository; } public FileSystemProvider provider() { return fileSystemProvider; } public RepositoryPath getRootDirectory() { Path root = Paths.get(repository.getBasedir()); FileSystem rootFileSystem = root.getFileSystem(); return new RepositoryPath(root, new RepositoryFileSystem(repository, rootFileSystem, new RepositoryFileSystemProvider(rootFileSystem.provider()))); } public RepositoryPath getTrashPath() { return getRootDirectory().resolve(".trash"); } public RepositoryPath getTempPath() { return getRootDirectory().resolve(".temp"); } public Path getPath(String first, String... more) { throw new UnsupportedOperationException(); } public PathMatcher getPathMatcher(String syntaxAndPattern) { throw new UnsupportedOperationException(); } }
// Authors: // * Simos Gerasimou (University of York) // This file is part of EvoChecker. package evochecker; import java.util.ArrayList; import java.util.List; import _main.Experiment; import evochecker.auxiliary.Utility; import evochecker.genetic.GenotypeFactory; import evochecker.genetic.genes.AbstractGene; import evochecker.genetic.genes.RegionGene; import evochecker.genetic.jmetal.GeneticProblemPSY; import evochecker.genetic.jmetal.metaheuristics.NSGAIIRegion_Settings; import evochecker.genetic.jmetal.metaheuristics.RandomSearchRegion_Settings; import evochecker.parser.ParserEngine; import evochecker.parser.ParserEnginePrismPSY; import evochecker.prism.Property; import jmetal.core.Algorithm; import jmetal.core.Problem; import jmetal.core.SolutionSet; /** * Main EvoChecker class * @author sgerasimou * */ public class EvoChecker { /** properties list*/ private List<Property> propertyList; /** problem trying to solve*/ private Problem problem; /** problem genes*/ private List<AbstractGene> genes = new ArrayList<AbstractGene>(); /** parser engine handler*/ private ParserEngine parserEngine; /** model filename*/ private String modelFilename; /** property filename*/ private String propertiesFilename; /** algorithm to be executed*/ private Algorithm algorithm; /** * Main * @param args */ public static void main(String[] args) { long start = System.currentTimeMillis(); try { //instantiate evochecker EvoChecker evoChecker = new EvoChecker(); //initialise problem evoChecker.initializeProblem(); //initialise algorithm evoChecker.initialiseAlgorithm(); //execute evoChecker.execute(); //close down evoChecker.closeDown(); } catch (Exception e) { e.printStackTrace(); } long end = System.currentTimeMillis(); System.err.println("Time:\t" + (end - start)/1000); } /** * Initialise the problem and the properties associated with the problem * Note that in the next iteration of this code, * the initialisation should be done by reading the properties file * @throws Exception */ private void initializeProblem() throws Exception { //1 Get model and properties filenames modelFilename = Utility.getProperty("MODEL_TEMPLATE_FILE"); propertiesFilename = Utility.getProperty("PROPERTIES_FILE"); //2) parse model template parserEngine = new ParserEnginePrismPSY(modelFilename, propertiesFilename); //3) create chromosome genes = GenotypeFactory.createChromosome(parserEngine.getEvolvableList()); //4) create (gene,evolvable element) pairs parserEngine.createMapping(); //5) create properties list propertyList = new ArrayList<Property>(); //Google // propertyList.add(new Property(true)); // propertyList.add(new Property(true)); // propertyList.add(new Property(false)); // int numOfConstraints = 1; // Cluster // propertyList.add(new Property(true)); // propertyList.add(new Property(true)); // propertyList.add(new Property(false)); // int numOfConstraints = 1; // Buffer propertyList.add(new Property(true)); propertyList.add(new Property(false)); int numOfConstraints = 0; //6) instantiate the problem problem = new GeneticProblemPSY(genes, propertyList, parserEngine, numOfConstraints, "GeneticProblem"); } /** * initialise algorithm * @throws Exception */ private void initialiseAlgorithm() throws Exception{ String algorithmStr = Utility.getProperty("ALGORITHM").toUpperCase(); if (algorithmStr != null){ if (algorithmStr.equals("NSGAII")){ NSGAIIRegion_Settings nsgaiiSettings = new NSGAIIRegion_Settings(problem.getName(), problem); algorithm = nsgaiiSettings.configure(); } else if (algorithmStr.equals("RANDOM")){ RandomSearchRegion_Settings rsSettings = new RandomSearchRegion_Settings(problem.getName(), problem); algorithm = rsSettings.configure(); } else throw new Exception("Algorithm not recognised"); } } /** * Make finalisations of algorithm */ private void closeDown(){ } /** * Execute * @throws Exception */ private void execute() throws Exception{ // Execute the Algorithm SolutionSet population = algorithm.execute(); //Print results to console System.out.println(" System.out.println("SOLUTIONS: \t" + population.size()); List<Double> regionsRadii = new ArrayList<Double>(); for (AbstractGene gene : genes){ if (gene instanceof RegionGene) regionsRadii.add(((RegionGene)gene).getRegionRadius()); } String tolerance = Utility.getProperty("TOLERANCE").replace(".", ""); String leniency = Utility.getProperty("LENIENCY").replace(".", ""); int run = Experiment.getRun(); String outputFileEnd = tolerance +"_"+ leniency +"_"+ run; //Store results population.printObjectivesToFile("data/FUN_"+ outputFileEnd); population.printVariablesToFile("data/VAR_"+ outputFileEnd); Utility.printVariableRegionsToFile("data/VAR_REGION_"+ outputFileEnd, population, false, regionsRadii); Utility.printObjectiveRegionsToFile("data/FUN_REGION_"+ outputFileEnd, population, false, propertyList); // Utility.printVariableRegionsToFile("data/VAR_REGION_"+tolerance, population, false); // Utility.printVariableRegionsToFile2("data/VAR_REGION2_"+tolerance, population, false); } }
package org.shipkit.internal.gradle.versionupgrade; import org.gradle.api.Action; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.Task; import org.gradle.api.specs.Spec; import org.shipkit.gradle.configuration.ShipkitConfiguration; import org.shipkit.gradle.exec.ShipkitExecTask; import org.shipkit.gradle.git.GitPushTask; import org.shipkit.internal.gradle.configuration.ShipkitConfigurationPlugin; import org.shipkit.internal.gradle.git.GitConfigPlugin; import org.shipkit.internal.gradle.git.GitOriginPlugin; import org.shipkit.internal.gradle.git.GitUrlInfo; import org.shipkit.internal.gradle.git.domain.PullRequest; import org.shipkit.internal.gradle.git.tasks.GitCheckOutTask; import org.shipkit.internal.gradle.git.tasks.GitPullTask; import org.shipkit.internal.gradle.util.GitUtil; import org.shipkit.internal.gradle.util.TaskMaker; import org.shipkit.internal.util.IncubatingWarning; import static org.shipkit.internal.gradle.configuration.DeferredConfiguration.deferredConfiguration; import static org.shipkit.internal.gradle.exec.ExecCommandFactory.execCommand; /** * BEWARE! This plugin is in incubating state, so its API may change in the future! * The plugin applies following plugins: * * <ul> * <li>{@link ShipkitConfigurationPlugin}</li> * <li>{@link GitOriginPlugin}</li> * <li>{@link GitConfigPlugin}</li> * </ul> * * and adds following tasks: * * <ul> * <li>checkoutBaseBranch - checkouts base branch - the branch to which version upgrade should be applied through pull request</li> * <li>pullUpstream - syncs the fork on which we perform version upgrade with the upstream repo</li> * <li>findOpenPullRequest - finds an open pull request with version upgrade if it exists</li> * <li>checkoutVersionBranch - checkouts version branch where version will be upgraded. A new branch or the head branch for open pull request</li> * <li>replaceVersion - replaces version in build file, using dependency pattern</li> * <li>commitVersionUpgrade - commits replaced version</li> * <li>pushVersionUpgrade - pushes the commit to the version branch</li> * <li>createPullRequest - creates a pull request between base and version branches if there is no open pull request for this dependency already</li> * <li>mergePullRequest - wait for status checks defined for pull request and in case of success merge it to base branch. Task is executed only if there was no previously opened pull request. If createPullRequest task is skipped, mergePullRequest is also skipped and pull request needs to be merged manually. If no checks defined, pull request also needs to be merged manually</li> * <li>performVersionUpgrade - task aggregating all of the above</li> * </ul> * * Plugin should be used in client projects that want to have automated version upgrades of some other dependency, that use the producer version of this plugin. * Project with the producer plugin applied would then clone a fork of client project and run './gradlew performVersionUpgrade -Pdependency=${group:name:version}' on it. * * Example of plugin usage: * * Configure your 'shipkit.gradle' file like here: * * apply plugin: 'org.shipkit.upgrade-dependency' * * upgradeDependency { * baseBranch = 'release/2.x' * buildFile = file('build.gradle') * } * * and then call it: * * ./gradlew performVersionUpgrade -Pdependency=org.shipkit:shipkit:1.2.3 */ public class UpgradeDependencyPlugin implements Plugin<Project> { public static final String CHECKOUT_BASE_BRANCH = "checkoutBaseBranch"; public static final String PULL_UPSTREAM = "pullUpstream"; public static final String FIND_OPEN_PULL_REQUEST = "findOpenPullRequest"; public static final String CHECKOUT_VERSION_BRANCH = "checkoutVersionBranch"; public static final String REPLACE_VERSION = "replaceVersion"; public static final String COMMIT_VERSION_UPGRADE = "commitVersionUpgrade"; public static final String PUSH_VERSION_UPGRADE = "pushVersionUpgrade"; public static final String CREATE_PULL_REQUEST = "createPullRequest"; public static final String PERFORM_VERSION_UPGRADE = "performVersionUpgrade"; public static final String MERGE_PULL_REQUEST = "mergePullRequest"; public static final String DEPENDENCY_PROJECT_PROPERTY = "dependency"; private UpgradeDependencyExtension upgradeDependencyExtension; @Override public void apply(final Project project) { IncubatingWarning.warn("upgrade-dependency plugin"); final GitOriginPlugin gitOriginPlugin = project.getRootProject().getPlugins().apply(GitOriginPlugin.class); final ShipkitConfiguration conf = project.getPlugins().apply(ShipkitConfigurationPlugin.class).getConfiguration(); project.getPlugins().apply(GitConfigPlugin.class); upgradeDependencyExtension = project.getExtensions().create("upgradeDependency", UpgradeDependencyExtension.class); // set defaults upgradeDependencyExtension.setBuildFile(project.file("build.gradle")); upgradeDependencyExtension.setBaseBranch("master"); String dependency = (String) project.findProperty(DEPENDENCY_PROJECT_PROPERTY); new DependencyNewVersionParser(dependency).fillVersionUpgradeExtension(upgradeDependencyExtension); TaskMaker.task(project, CHECKOUT_BASE_BRANCH, GitCheckOutTask.class, new Action<GitCheckOutTask>() { @Override public void execute(final GitCheckOutTask task) { task.setDescription("Checks out the base branch."); deferredConfiguration(project, new Runnable() { @Override public void run() { task.setRev(upgradeDependencyExtension.getBaseBranch()); } }); } }); TaskMaker.task(project, PULL_UPSTREAM, GitPullTask.class, new Action<GitPullTask>() { @Override public void execute(final GitPullTask task) { task.setDescription("Performs git pull from upstream repository."); task.mustRunAfter(CHECKOUT_BASE_BRANCH); task.setDryRun(conf.isDryRun()); deferredConfiguration(project, new Runnable() { @Override public void run() { task.setRev(upgradeDependencyExtension.getBaseBranch()); } }); gitOriginPlugin.provideOriginRepo(task, new Action<String>() { public void execute(String originRepo) { GitUrlInfo info = new GitUrlInfo(conf); task.setUrl(info.getGitUrl()); task.setSecretValue(info.getWriteToken()); } }); } }); final FindOpenPullRequestTask findOpenPullRequestTask = TaskMaker.task(project, FIND_OPEN_PULL_REQUEST, FindOpenPullRequestTask.class, new Action<FindOpenPullRequestTask>() { @Override public void execute(final FindOpenPullRequestTask task) { task.setDescription("Find an open pull request with version upgrade, if such exists."); task.mustRunAfter(PULL_UPSTREAM); task.setGitHubApiUrl(conf.getGitHub().getApiUrl()); task.setAuthToken(conf.getLenient().getGitHub().getReadOnlyAuthToken()); task.setUpstreamRepositoryName(conf.getGitHub().getRepository()); task.setVersionBranchRegex(getVersionBranchName( upgradeDependencyExtension.getDependencyName(), ReplaceVersionTask.VERSION_REGEX)); } }); TaskMaker.task(project, CHECKOUT_VERSION_BRANCH, GitCheckOutTask.class, new Action<GitCheckOutTask>() { public void execute(final GitCheckOutTask task) { task.setDescription("Creates a new version branch and checks it out."); task.mustRunAfter(FIND_OPEN_PULL_REQUEST); findOpenPullRequestTask.provideOpenPullRequest(task, new Action<PullRequest>() { @Override public void execute(PullRequest pullRequest) { String ref = null; if (pullRequest != null) { ref = pullRequest.getRef(); // don't create a new branch if there is already a branch with open pull request with version upgrade task.setNewBranch(false); } else { task.setNewBranch(true); } task.setRev(getCurrentVersionBranchName(upgradeDependencyExtension.getDependencyName(), upgradeDependencyExtension.getNewVersion(), ref)); } }); } }); final ReplaceVersionTask replaceVersionTask = TaskMaker.task(project, REPLACE_VERSION, ReplaceVersionTask.class, new Action<ReplaceVersionTask>() { @Override public void execute(final ReplaceVersionTask task) { task.setDescription("Replaces dependency version in build file."); task.mustRunAfter(CHECKOUT_VERSION_BRANCH); deferredConfiguration(project, new Runnable() { @Override public void run() { task.setDependencyGroup(upgradeDependencyExtension.getDependencyGroup()); task.setNewVersion(upgradeDependencyExtension.getNewVersion()); task.setDependencyName(upgradeDependencyExtension.getDependencyName()); task.setBuildFile(upgradeDependencyExtension.getBuildFile()); } }); } }); TaskMaker.task(project, COMMIT_VERSION_UPGRADE, ShipkitExecTask.class, new Action<ShipkitExecTask>() { @Override public void execute(final ShipkitExecTask exec) { exec.setDescription("Commits updated build file."); exec.mustRunAfter(REPLACE_VERSION); exec.dependsOn(GitConfigPlugin.SET_EMAIL_TASK, GitConfigPlugin.SET_USER_TASK); deferredConfiguration(project, new Runnable() { @Override public void run() { String message = String.format("%s version upgraded to %s", upgradeDependencyExtension.getDependencyName(), upgradeDependencyExtension.getNewVersion()); exec.execCommand(execCommand("Committing build file", "git", "commit", "--author", GitUtil.getGitGenericUserNotation(conf.getGit().getUser(), conf.getGit().getEmail()), "-m", message, upgradeDependencyExtension.getBuildFile().getAbsolutePath())); } }); exec.onlyIf(wasBuildFileUpdatedSpec(replaceVersionTask)); } }); TaskMaker.task(project, PUSH_VERSION_UPGRADE, GitPushTask.class, new Action<GitPushTask>() { @Override public void execute(final GitPushTask task) { task.setDescription("Pushes updated config file to an update branch."); task.mustRunAfter(COMMIT_VERSION_UPGRADE); task.setDryRun(conf.isDryRun()); gitOriginPlugin.provideOriginRepo(task, new Action<String>() { public void execute(String originRepo) { GitUrlInfo info = new GitUrlInfo(conf); task.setUrl(info.getGitUrl()); task.setSecretValue(info.getWriteToken()); } }); findOpenPullRequestTask.provideOpenPullRequest(task, new Action<PullRequest>() { @Override public void execute(PullRequest pullRequest) { String ref = null; if (pullRequest != null) { ref = pullRequest.getRef(); } task.getTargets().add(getCurrentVersionBranchName(upgradeDependencyExtension.getDependencyName(), upgradeDependencyExtension.getNewVersion(), ref)); } }); task.onlyIf(wasBuildFileUpdatedSpec(replaceVersionTask)); } }); final CreatePullRequestTask createPullRequestTask = TaskMaker.task(project, CREATE_PULL_REQUEST, CreatePullRequestTask.class, new Action<CreatePullRequestTask>() { @Override public void execute(final CreatePullRequestTask task) { task.setDescription("Creates a pull request from branch with version upgraded to master"); task.mustRunAfter(PUSH_VERSION_UPGRADE); task.setGitHubApiUrl(conf.getGitHub().getApiUrl()); task.setDryRun(conf.isDryRun()); task.setAuthToken(conf.getLenient().getGitHub().getWriteAuthToken()); task.setPullRequestTitle(getPullRequestTitle(upgradeDependencyExtension)); task.setPullRequestDescription(getPullRequestDescription(upgradeDependencyExtension)); task.setUpstreamRepositoryName(conf.getGitHub().getRepository()); gitOriginPlugin.provideOriginRepo(task, new Action<String>() { @Override public void execute(String originRepoName) { task.setForkRepositoryName(originRepoName); } }); findOpenPullRequestTask.provideOpenPullRequest(task, new Action<PullRequest>() { @Override public void execute(PullRequest openPullRequestBranch) { //TODO consider using Optional. This null check is duplicated String ref = openPullRequestBranch == null? null : openPullRequestBranch.getRef(); task.setVersionBranch(getCurrentVersionBranchName(upgradeDependencyExtension.getDependencyName(), upgradeDependencyExtension.getNewVersion(), ref)); } }); deferredConfiguration(project, new Runnable() { @Override public void run() { task.setBaseBranch(upgradeDependencyExtension.getBaseBranch()); } }); task.onlyIf(wasOpenPullRequestNotFound(findOpenPullRequestTask)); task.onlyIf(wasBuildFileUpdatedSpec(replaceVersionTask)); } }); TaskMaker.task(project, MERGE_PULL_REQUEST, MergePullRequestTask.class, new Action<MergePullRequestTask>() { @Override public void execute(final MergePullRequestTask task) { task.setDescription("Merge pull request when all checks will be passed"); task.mustRunAfter(CREATE_PULL_REQUEST); task.setGitHubApiUrl(conf.getGitHub().getApiUrl()); task.setDryRun(conf.isDryRun()); task.setAuthToken(conf.getLenient().getGitHub().getWriteAuthToken()); task.setBaseBranch(upgradeDependencyExtension.getBaseBranch()); task.setUpstreamRepositoryName(conf.getGitHub().getRepository()); gitOriginPlugin.provideOriginRepo(task, new Action<String>() { @Override public void execute(String originRepoName) { task.setForkRepositoryName(originRepoName); } }); createPullRequestTask.provideCreatedPullRequest(task, new Action<PullRequest>() { @Override public void execute(PullRequest pullRequest) { if (pullRequest != null) { setPullRequestDataToTask(pullRequest, task); } } }); deferredConfiguration(project, new Runnable() { @Override public void run() { task.setBaseBranch(upgradeDependencyExtension.getBaseBranch()); } }); task.onlyIf(wasOpenPullRequestNotFound(findOpenPullRequestTask)); task.onlyIf(wasBuildFileUpdatedSpec(replaceVersionTask)); } }); //TODO: WW add validation for the case when 'dependency' property is not provided TaskMaker.task(project, PERFORM_VERSION_UPGRADE, new Action<Task>() { @Override public void execute(Task task) { task.setDescription("Checkouts new version branch, updates Shipkit dependency in config file, commits and pushes."); task.dependsOn(CHECKOUT_BASE_BRANCH); task.dependsOn(FIND_OPEN_PULL_REQUEST); task.dependsOn(PULL_UPSTREAM); task.dependsOn(CHECKOUT_VERSION_BRANCH); task.dependsOn(REPLACE_VERSION); task.dependsOn(COMMIT_VERSION_UPGRADE); task.dependsOn(PUSH_VERSION_UPGRADE); task.dependsOn(CREATE_PULL_REQUEST); task.dependsOn(MERGE_PULL_REQUEST); } }); } private void setPullRequestDataToTask(PullRequest pullRequest, MergePullRequestTask task) { task.setVersionBranch(getCurrentVersionBranchName(upgradeDependencyExtension.getDependencyName(), upgradeDependencyExtension.getNewVersion(), pullRequest.getRef())); task.setPullRequestSha(pullRequest.getSha()); task.setPullRequestUrl(pullRequest.getUrl()); } static String getCurrentVersionBranchName(String dependencyName, String version, String openPullRequestBranch) { if (openPullRequestBranch != null) { return openPullRequestBranch; } return getVersionBranchName(dependencyName, version); } private String getPullRequestDescription(UpgradeDependencyExtension versionUpgrade) { return String.format("This pull request was automatically created by Shipkit's" + " 'org.shipkit.upgrade-downstream' Gradle plugin (http://shipkit.org)." + " Please merge it so that you are using fresh version of '%s' dependency.", versionUpgrade.getDependencyName()); } private String getPullRequestTitle(UpgradeDependencyExtension versionUpgrade) { return String.format("Version of %s upgraded to %s", versionUpgrade.getDependencyName(), versionUpgrade.getNewVersion()); } private Spec<Task> wasBuildFileUpdatedSpec(final ReplaceVersionTask replaceVersionTask) { return new Spec<Task>() { @Override public boolean isSatisfiedBy(Task element) { return replaceVersionTask.isBuildFileUpdated(); } }; } private Spec<Task> wasOpenPullRequestNotFound(final FindOpenPullRequestTask findOpenPullRequestTask) { return new Spec<Task>() { @Override public boolean isSatisfiedBy(Task task) { return findOpenPullRequestTask.getPullRequest() == null; } }; } private static String getVersionBranchName(String dependencyName, String newVersion) { return "upgrade-" + dependencyName + "-to-" + newVersion; } public UpgradeDependencyExtension getUpgradeDependencyExtension() { return upgradeDependencyExtension; } }
package com.nike.wingtips.zipkin2.util; import com.nike.wingtips.Span; import com.nike.wingtips.Span.SpanPurpose; import com.nike.wingtips.Span.TimestampedAnnotation; import com.nike.wingtips.TraceAndSpanIdGenerator; import org.apache.commons.codec.digest.DigestUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.concurrent.TimeUnit; import zipkin2.Endpoint; @SuppressWarnings("WeakerAccess") public class WingtipsToZipkinSpanConverterDefaultImpl implements WingtipsToZipkinSpanConverter { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private static final String SANITIZED_ID_LOG_MSG = "Detected invalid ID format. orig_id={}, sanitized_id={}"; protected final boolean enableIdSanitization; public WingtipsToZipkinSpanConverterDefaultImpl() { // Disable ID sanitization by default - this should be something that users consciously opt-in for. this(false); } public WingtipsToZipkinSpanConverterDefaultImpl(boolean enableIdSanitization) { this.enableIdSanitization = enableIdSanitization; } @Override public zipkin2.Span convertWingtipsSpanToZipkinSpan(Span wingtipsSpan, Endpoint zipkinEndpoint) { long durationMicros = TimeUnit.NANOSECONDS.toMicros(wingtipsSpan.getDurationNanos()); String spanId = sanitizeIdIfNecessary(wingtipsSpan.getSpanId(), false); String traceId = sanitizeIdIfNecessary(wingtipsSpan.getTraceId(), true); String parentId = sanitizeIdIfNecessary(wingtipsSpan.getParentSpanId(), false); final zipkin2.Span.Builder spanBuilder = zipkin2.Span .newBuilder() .id(spanId) .name(wingtipsSpan.getSpanName()) .parentId(parentId) .traceId(traceId) .timestamp(wingtipsSpan.getSpanStartTimeEpochMicros()) .duration(durationMicros) .localEndpoint(zipkinEndpoint) .kind(determineZipkinKind(wingtipsSpan)); // Iterate over existing wingtips tags and add them to the zipkin builder. for (Map.Entry<String, String> tagEntry : wingtipsSpan.getTags().entrySet()) { spanBuilder.putTag(tagEntry.getKey(), tagEntry.getValue()); } if (!spanId.equals(wingtipsSpan.getSpanId())) { spanBuilder.putTag("invalid.span_id", wingtipsSpan.getSpanId()); } if (!traceId.equals(wingtipsSpan.getTraceId())) { spanBuilder.putTag("invalid.trace_id", wingtipsSpan.getTraceId()); } if (parentId != null && !parentId.equals(wingtipsSpan.getParentSpanId())) { spanBuilder.putTag("invalid.parent_id", wingtipsSpan.getParentSpanId()); } // Iterate over existing wingtips annotations and add them to the zipkin builder. for (TimestampedAnnotation wingtipsAnnotation : wingtipsSpan.getTimestampedAnnotations()) { spanBuilder.addAnnotation(wingtipsAnnotation.getTimestampEpochMicros(), wingtipsAnnotation.getValue()); } return spanBuilder.build(); } @SuppressWarnings("WeakerAccess") protected zipkin2.Span.Kind determineZipkinKind(Span wingtipsSpan) { SpanPurpose wtsp = wingtipsSpan.getSpanPurpose(); // Clunky if checks necessary to avoid code coverage gaps with a switch statement // due to unreachable default case. :( if (SpanPurpose.SERVER == wtsp) { return zipkin2.Span.Kind.SERVER; } else if (SpanPurpose.CLIENT == wtsp) { return zipkin2.Span.Kind.CLIENT; } else if (SpanPurpose.LOCAL_ONLY == wtsp || SpanPurpose.UNKNOWN == wtsp) { // No Zipkin Kind associated with these SpanPurposes. return null; } else { // This case should technically be impossible, but in case it happens we'll log a warning and default to // no Zipkin kind. logger.warn("Unhandled SpanPurpose type: {}", String.valueOf(wtsp)); return null; } } protected String sanitizeIdIfNecessary(final String originalId, final boolean allow128Bit) { if (!enableIdSanitization) { return originalId; } if (originalId == null) { return null; } if (isAllowedNumChars(originalId, allow128Bit)) { if (isLowerHex(originalId)) { // Already lowerhex with correct number of chars, no modifications needed. return originalId; } else if (isHex(originalId, true)) { // It wasn't lowerhex, but it is hex and it is the correct number of chars. // We can trivially convert to valid lowerhex by lowercasing the ID. String sanitizedId = originalId.toLowerCase(); logger.info(SANITIZED_ID_LOG_MSG, originalId, sanitizedId); return sanitizedId; } } // If the originalId can be parsed as a long, then its sanitized ID is the lowerhex representation of that long. Long originalIdAsRawLong = attemptToConvertToLong(originalId); if (originalIdAsRawLong != null) { String sanitizedId = TraceAndSpanIdGenerator.longToUnsignedLowerHexString(originalIdAsRawLong); logger.info(SANITIZED_ID_LOG_MSG, originalId, sanitizedId); return sanitizedId; } // If the originalId can be parsed as a UUID and is allowed to be 128 bit, // then its sanitized ID is that UUID with the dashes ripped out and forced lowercase. if (allow128Bit) { String sanitizedId = attemptToConvertFromUuid(originalId); if (sanitizedId != null) { logger.info(SANITIZED_ID_LOG_MSG, originalId, sanitizedId); return sanitizedId; } } // No convenient/sensible conversion to a valid lowerhex ID was found. // Do a SHA256 hash of the original ID to get a (deterministic) valid sanitized lowerhex ID that can be // converted to a long, but only take the number of characters we're allowed to take. Truncation // of a SHA digest like this is specifically allowed by the SHA algorithm - see Section 7 // ("TRUNCATION OF A MESSAGE DIGEST") here: int allowedNumChars = allow128Bit ? 32 : 16; String sanitizedId = DigestUtils.sha256Hex(originalId).toLowerCase().substring(0, allowedNumChars); logger.info(SANITIZED_ID_LOG_MSG, originalId, sanitizedId); return sanitizedId; } protected boolean isLowerHex(String id) { return isHex(id, false); } /** * Copied from {@link zipkin2.Span#validateHex(String)} and slightly modified. * * @param id The ID to check for hexadecimal conformity. * @param allowUppercase Pass true to allow uppercase A-F letters, false to force lowercase-hexadecimal check * (only a-f letters allowed). * * @return true if the given id is hexadecimal, false if there are any characters that are not hexadecimal, with * the {@code allowUppercase} parameter determining whether uppercase hex characters are allowed. */ protected boolean isHex(String id, boolean allowUppercase) { for (int i = 0, length = id.length(); i < length; i++) { char c = id.charAt(i); if ((c < '0' || c > '9') && (c < 'a' || c > 'f')) { // Not 0-9, and not a-f. So it's not lowerhex. If we don't allow uppercase then we can return false. if (!allowUppercase) { return false; } else if (c < 'A' || c > 'F') { // Uppercase is allowed but it's not A-F either, so we still have to return false. return false; } // If we reach here inside this if-block, then it's an uppercase A-F and allowUppercase is true, so // do nothing and move onto the next character. } } return true; } protected boolean isAllowedNumChars(final String id, final boolean allow128Bit) { if (allow128Bit) { return id.length() <= 16 || id.length() == 32; } else { return id.length() <= 16; } } protected Long attemptToConvertToLong(final String id) { try { return Long.valueOf(id); } catch (final NumberFormatException nfe) { return null; } } protected String attemptToConvertFromUuid(String originalId) { if (originalId == null) { return null; } if (originalId.length() == 36) { // 36 chars - might be a UUID. Rip out the dashes and check to see if it's a valid 128 bit ID. String noDashesAndLowercase = stripDashesAndConvertToLowercase(originalId); if (noDashesAndLowercase.length() == 32 && isLowerHex(noDashesAndLowercase)) { // 32 chars and lowerhex - it's now a valid 128 bit ID. return noDashesAndLowercase;//.toLowerCase(); } } // It wasn't a UUID, so return null. return null; } protected String stripDashesAndConvertToLowercase(String orig) { if (orig == null) { return null; } StringBuilder sb = new StringBuilder(orig.length()); for (int i = 0; i < orig.length(); i++) { char nextChar = orig.charAt(i); if (nextChar != '-') { sb.append(Character.toLowerCase(nextChar)); } } return sb.toString(); } }
package org.xwiki.test.wysiwyg; import org.xwiki.test.wysiwyg.framework.AbstractWysiwygTestCase; import org.xwiki.test.wysiwyg.framework.XWikiExplorer; /** * Test for the Wysiwyg editing features when editing as a regular user, not an admin. */ public class RegularUserTest extends AbstractWysiwygTestCase { /** * The object used to assert the state of the XWiki Explorer tree. */ private final XWikiExplorer explorer = new XWikiExplorer(this); /** * {@inheritDoc}. Override to login as a regular user (and create the user if necessary). */ @Override protected void login() { loginAndRegisterUser("Pokemon", "Pokemon", false); } public void testWikiLinkSearchedPageHidesTechnicalSpaces() { openDialog("Link", "Wiki Page..."); waitForStepToLoad("xSelectorAggregatorStep"); clickTab("Search"); waitForStepToLoad("xPagesSearch"); // Check the results list: Blog, Main and Sandbox are present. checkSpaceInSearchResults("Blog", true); checkSpaceInSearchResults("Main", true); checkSpaceInSearchResults("Sandbox", true); // Check the results list: ColorThemes, Panels, Scheduler, Stats, XWiki are not present. checkSpaceInSearchResults("ColorThemes", false); checkSpaceInSearchResults("Panels", false); checkSpaceInSearchResults("Scheduler", false); checkSpaceInSearchResults("Stats", false); checkSpaceInSearchResults("XWiki", false); closeDialog(); } /** * Helper method to test if a space appears in the search results or not. * * @param spaceName the name of the space to test whether it is returned among the search results or not * @param present {@code true} if the space is expected in the search results, {@code false} otherwise */ private void checkSpaceInSearchResults(String spaceName, boolean expected) { typeInInput("Type a keyword to search for a wiki page", spaceName + ".WebHome"); clickButtonWithText("Search"); // We have to look for the new page selector inside the search panel because it is also present on the recent // pages panel (which is hidden, but still present in DOM, while the search tab is selected). String newPageSelector = "//div[contains(@class, 'xPagesSearch')]" + "//div[contains(@class, 'xListItem')]" + "//div[contains(@class, 'xNewPagePreview')]"; // Wait for the search results. The list is cleared (including the new page selector) as soon as we click the // search button and is refilled when the search results are received. The new page selector is (re)added after // the list is filled with the search results. waitForElement(newPageSelector); // Check if the desired element is there or not, but look precisely inside the search panel. String pageInListLocator = "//div[contains(@class, 'xPagesSearch')]" + "//div[contains(@class, 'xListItem')]" + "//div[. = '" + String.format(LinkTest.PAGE_LOCATION, spaceName, "WebHome") + "']"; if (expected) { assertElementPresent(pageInListLocator); } else { assertElementNotPresent(pageInListLocator); } } /** * Test that upon selecting the wiki page to create a link to from all the pages in the wiki, with the tree * explorer, the technical spaces are not displayed to the regular user to choose from. */ public void testWikiLinkAllPagesPageHidesTechnicalSpaces() { String currentSpace = getClass().getSimpleName(); String currentPage = getName(); // Save the current page so that it appears in the tree. clickEditSaveAndContinue(); openDialog("Link", "Wiki Page..."); waitForStepToLoad("xSelectorAggregatorStep"); clickTab("All pages"); waitForStepToLoad("xExplorerPanel"); explorer.waitForPageSelected(currentSpace, currentPage); // Now the tree is loaded. Check the list of spaces. // Blog, Main and Sandbox must be present. explorer.selectNewPageIn("Blog"); explorer.selectNewPageIn("Main"); explorer.selectNewPageIn("Sandbox"); // ColorThemes, Panels, Scheduler, Stats and XWiki shouldn't be present. explorer.lookupEntity("ColorThemes."); explorer.waitForNoneSelected(); explorer.lookupEntity("Panels."); explorer.waitForNoneSelected(); explorer.lookupEntity("Scheduler."); explorer.waitForNoneSelected(); explorer.lookupEntity("Stats."); explorer.waitForNoneSelected(); explorer.lookupEntity("XWiki."); explorer.waitForNoneSelected(); closeDialog(); } /** * Test that upon selecting an image from all the images in the wiki, the technical spaces are not listed in the * space selector for the regular user to choose from. */ public void testImageSelectorHidesTechnicalSpaces() { String currentSpace = getClass().getSimpleName(); // Save the current page so that it appears in the tree. clickEditSaveAndContinue(); openDialog(ImageTest.MENU_IMAGE, ImageTest.MENU_INSERT_ATTACHED_IMAGE); waitForStepToLoad("xSelectorAggregatorStep"); clickTab("All pages"); waitForStepToLoad("xImagesExplorer"); // wait for the current space to load in the selector to be sure the spaces list is loaded waitForElement(ImageTest.SPACE_SELECTOR + "/option[@value=\"" + currentSpace + "\"]"); // check the spaces: Blog, Main, Sandbox are present assertElementPresent(ImageTest.SPACE_SELECTOR + "/option[@value=\"Blog\"]"); assertElementPresent(ImageTest.SPACE_SELECTOR + "/option[@value=\"Main\"]"); assertElementPresent(ImageTest.SPACE_SELECTOR + "/option[@value=\"Sandbox\"]"); // check the spaces: ColorThemes, Panels, Scheduler, Stats, XWiki are not present assertElementNotPresent(ImageTest.SPACE_SELECTOR + "/option[@value=\"ColorThemes\"]"); assertElementNotPresent(ImageTest.SPACE_SELECTOR + "/option[@value=\"Panels\"]"); assertElementNotPresent(ImageTest.SPACE_SELECTOR + "/option[@value=\"Scheduler\"]"); assertElementNotPresent(ImageTest.SPACE_SELECTOR + "/option[@value=\"Stats\"]"); // TODO: XWiki space should not be listed but currently there are few pages in this space that are not marked as // hidden/technical. Update this check as soon as the XWiki space is completely hidden. assertElementPresent(ImageTest.SPACE_SELECTOR + "/option[@value=\"XWiki\"]"); closeDialog(); } protected void waitForStepToLoad(String name) {
package com.xpn.xwiki.doc; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import org.apache.commons.lang3.StringUtils; import org.xwiki.bridge.DocumentAccessBridge; import org.xwiki.bridge.DocumentModelBridge; import org.xwiki.component.annotation.Component; import org.xwiki.context.Execution; import org.xwiki.model.EntityType; import org.xwiki.model.reference.AttachmentReference; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.DocumentReferenceResolver; import org.xwiki.model.reference.EntityReferenceSerializer; import org.xwiki.model.reference.ObjectPropertyReference; import org.xwiki.model.reference.ObjectReference; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.BaseProperty; import com.xpn.xwiki.objects.classes.PropertyClass; import com.xpn.xwiki.user.api.XWikiRightService; /** * Exposes methods for accessing Document data. This is temporary until we remodel the Model classes and the Document * services. The implementation is inside the old core, and not in a component because it has dependencies on the old * core. * * @version $Id$ * @since 1.6M1 */ @Component @Singleton public class DefaultDocumentAccessBridge implements DocumentAccessBridge { /** Execution context handler, needed for accessing the XWikiContext. */ @Inject private Execution execution; /** * Used to resolve a string into a proper Document Reference using the current document's reference to fill the * blanks, except for the page name for which the default page name is used instead. */ @Inject @Named("currentmixed") private DocumentReferenceResolver<String> currentMixedDocumentReferenceResolver; /** * Used to serialize full reference of current user. */ @Inject private EntityReferenceSerializer<String> defaultEntityReferenceSerializer; private XWikiContext getContext() { return (XWikiContext) this.execution.getContext().getProperty("xwikicontext"); } @Override @Deprecated public DocumentModelBridge getDocument(String documentReference) throws Exception { XWikiContext xcontext = getContext(); return xcontext.getWiki().getDocument(documentReference, xcontext).getTranslatedDocument(xcontext); } @Override public DocumentModelBridge getDocument(DocumentReference documentReference) throws Exception { XWikiContext xcontext = getContext(); return xcontext.getWiki().getDocument(documentReference, xcontext).getTranslatedDocument(xcontext); } @Override public DocumentReference getCurrentDocumentReference() { XWikiDocument currentDocument = null; XWikiContext context = getContext(); if (context != null) { currentDocument = context.getDoc(); } return currentDocument == null ? null : currentDocument.getDocumentReference(); } @Override @Deprecated public String getDocumentContent(String documentReference) throws Exception { XWikiContext xcontext = getContext(); return getDocumentContent(documentReference, xcontext.getLanguage()); } @Override public String getDocumentContentForDefaultLanguage(DocumentReference documentReference) throws Exception { XWikiContext xcontext = getContext(); return xcontext.getWiki().getDocument(documentReference, xcontext).getContent(); } @Override @Deprecated public String getDocumentContentForDefaultLanguage(String documentReference) throws Exception { XWikiContext xcontext = getContext(); return xcontext.getWiki().getDocument(documentReference, xcontext).getContent(); } @Override public String getDocumentContent(DocumentReference documentReference, String language) throws Exception { XWikiContext xcontext = getContext(); String originalRev = (String) xcontext.get("rev"); try { xcontext.remove("rev"); return xcontext.getWiki().getDocument(documentReference, xcontext).getTranslatedContent(language, xcontext); } finally { if (originalRev != null) { xcontext.put("rev", originalRev); } } } @Override @Deprecated public String getDocumentContent(String documentReference, String language) throws Exception { XWikiContext xcontext = getContext(); String originalRev = (String) xcontext.get("rev"); try { xcontext.remove("rev"); return xcontext.getWiki().getDocument(documentReference, xcontext).getTranslatedContent(language, xcontext); } finally { if (originalRev != null) { xcontext.put("rev", originalRev); } } } @Override public boolean exists(DocumentReference documentReference) { return getContext().getWiki().exists(documentReference, getContext()); } @Override @Deprecated public boolean exists(String documentReference) { return getContext().getWiki().exists(documentReference, getContext()); } @Override public void setDocumentContent(DocumentReference documentReference, String content, String editComment, boolean isMinorEdit) throws Exception { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); doc.setContent(content); saveDocument(doc, editComment, isMinorEdit); } @Override @Deprecated public void setDocumentContent(String documentReference, String content, String editComment, boolean isMinorEdit) throws Exception { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); doc.setContent(content); saveDocument(doc, editComment, isMinorEdit); } @Override @Deprecated public String getDocumentSyntaxId(String documentReference) throws Exception { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); return doc.getSyntaxId(); } @Override public void setDocumentSyntaxId(DocumentReference documentReference, String syntaxId) throws Exception { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); doc.setSyntaxId(syntaxId); saveDocument(doc, String.format("Changed document syntax from [%s] to [%s].", doc.getSyntax(), syntaxId), true); } @Override @Deprecated public void setDocumentSyntaxId(String documentReference, String syntaxId) throws Exception { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); String oldSyntaxId = doc.getSyntaxId(); doc.setSyntaxId(syntaxId); saveDocument(doc, String.format("Changed document syntax from [%s] to [%s].", oldSyntaxId, syntaxId), true); } @Override public void setDocumentParentReference(DocumentReference documentReference, DocumentReference parentReference) throws Exception { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); doc.setParentReference(parentReference); saveDocument(doc, String.format("Changed document parent to [%s].", this.defaultEntityReferenceSerializer.serialize(parentReference)), true); } @Override public void setDocumentTitle(DocumentReference documentReference, String title) throws Exception { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); doc.setTitle(title); saveDocument(doc, String.format("Changed document title to [%s].", title), true); } @Override public int getObjectNumber(DocumentReference documentReference, DocumentReference classReference, String propertyName, String valueToMatch) { try { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); BaseObject object = doc.getXObject(classReference, propertyName, valueToMatch, false); return object != null ? object.getNumber() : -1; } catch (XWikiException e) { return -1; } } @Override public Object getProperty(ObjectPropertyReference objectPropertyReference) { try { DocumentReference documentReference = (DocumentReference) objectPropertyReference.extractReference(EntityType.DOCUMENT); ObjectReference objectReference = (ObjectReference) objectPropertyReference.extractReference(EntityType.OBJECT); XWikiContext xcontext = getContext(); return ((BaseProperty) xcontext.getWiki().getDocument(documentReference, xcontext) .getXObject(objectReference).get(objectPropertyReference.getName())).getValue(); } catch (Exception e) { return null; } } @Override public Object getProperty(ObjectReference objectReference, String propertyName) { try { DocumentReference documentReference = (DocumentReference) objectReference.extractReference(EntityType.DOCUMENT); XWikiContext xcontext = getContext(); return ((BaseProperty) xcontext.getWiki().getDocument(documentReference, xcontext) .getXObject(objectReference).get(propertyName)).getValue(); } catch (Exception e) { return null; } } @Override public Object getProperty(String documentReference, String className, int objectNumber, String propertyName) { try { XWikiContext xcontext = getContext(); return ((BaseProperty) xcontext.getWiki().getDocument(documentReference, xcontext) .getObject(className, objectNumber).get(propertyName)).getValue(); } catch (Exception ex) { return null; } } @Override @Deprecated public Object getProperty(String documentReference, String className, String propertyName) { Object value; try { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); BaseObject object = doc.getObject(className); BaseProperty property = (BaseProperty) object.get(propertyName); value = property.getValue(); } catch (Exception ex) { value = null; } return value; } @Override public Object getProperty(DocumentReference documentReference, DocumentReference classReference, String propertyName) { Object value; try { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); BaseObject object = doc.getXObject(classReference); BaseProperty property = (BaseProperty) object.get(propertyName); value = property.getValue(); } catch (Exception ex) { value = null; } return value; } @Override public Object getProperty(DocumentReference documentReference, DocumentReference classReference, int objectNumber, String propertyName) { Object value; try { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); BaseObject object = doc.getXObject(classReference, objectNumber); BaseProperty property = (BaseProperty) object.get(propertyName); value = property.getValue(); } catch (Exception ex) { value = null; } return value; } @Override public Object getProperty(String documentReference, String propertyName) { try { XWikiContext xcontext = getContext(); return ((BaseProperty) xcontext.getWiki().getDocument(documentReference, xcontext) .getFirstObject(propertyName, xcontext).get(propertyName)).getValue(); } catch (Exception ex) { return null; } } @Override public List<Object> getProperties(String documentReference, String className) { List<Object> result; try { XWikiContext xcontext = getContext(); result = new ArrayList<Object>(xcontext.getWiki().getDocument(documentReference, xcontext) .getObject(className).getFieldList()); } catch (Exception ex) { result = Collections.emptyList(); } return result; } @Override public String getPropertyType(String className, String propertyName) throws Exception { XWikiContext xcontext = getContext(); PropertyClass pc = xcontext.getWiki().getPropertyClassFromName(className + "_" + propertyName, xcontext); if (pc == null) { return null; } else { return pc.newProperty().getClass().getName(); } } @Override public boolean isPropertyCustomMapped(String className, String property) throws Exception { XWikiContext xcontext = getContext(); if (!xcontext.getWiki().hasCustomMappings()) { return false; } List<String> lst = xcontext.getWiki().getClass(className, xcontext).getCustomMappingPropertyList(xcontext); return lst != null && lst.contains(property); } /** * {@inheritDoc} * * @see org.xwiki.bridge.DocumentAccessBridge#setProperty(java.lang.String, java.lang.String, java.lang.String, * java.lang.Object) */ @Override @Deprecated public void setProperty(String documentReference, String className, String propertyName, Object propertyValue) throws Exception { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); BaseObject obj = doc.getObject(className, true, xcontext); if (obj != null) { obj.set(propertyName, propertyValue, xcontext); saveDocument(doc, String.format("Property [%s] set.", propertyName), true); } } @Override public void setProperty(DocumentReference documentReference, DocumentReference classReference, String propertyName, Object propertyValue) throws Exception { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); BaseObject obj = doc.getXObject(classReference, true, xcontext); if (obj != null) { obj.set(propertyName, propertyValue, xcontext); saveDocument(doc, String.format("Property [%s] set.", propertyName), true); } } @Override @Deprecated public byte[] getAttachmentContent(String documentReference, String attachmentFilename) throws Exception { XWikiContext xcontext = getContext(); return xcontext.getWiki().getDocument(documentReference, xcontext).getAttachment(attachmentFilename) .getContent(xcontext); } @Override public InputStream getAttachmentContent(AttachmentReference attachmentReference) throws Exception { XWikiContext xcontext = getContext(); XWikiDocument attachmentDocument = xcontext.getWiki().getDocument(attachmentReference.getDocumentReference(), xcontext); return new ByteArrayInputStream(attachmentDocument.getAttachment(attachmentReference.getName()).getContent( xcontext)); } @Override public void setAttachmentContent(AttachmentReference attachmentReference, byte[] attachmentData) throws Exception { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(attachmentReference.getDocumentReference(), xcontext); XWikiAttachment attachment = doc.getAttachment(attachmentReference.getName()); if (attachment == null) { attachment = new XWikiAttachment(); doc.getAttachmentList().add(attachment); doc.setComment("Add new attachment " + attachmentReference.getName()); } else { doc.setComment("Update attachment " + attachmentReference.getName()); } attachment.setContent(attachmentData); attachment.setFilename(attachmentReference.getName()); attachment.setAuthor(getCurrentUser()); attachment.setDoc(doc); doc.setAuthorReference(getContext().getUserReference()); if (doc.isNew()) { doc.setCreatorReference(getContext().getUserReference()); } doc.saveAttachmentContent(attachment, xcontext); } @Override @Deprecated public void setAttachmentContent(String documentReference, String attachmentFilename, byte[] attachmentData) throws Exception { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); XWikiAttachment attachment = doc.getAttachment(attachmentFilename); if (attachment == null) { attachment = new XWikiAttachment(); doc.getAttachmentList().add(attachment); doc.setComment("Add new attachment " + attachmentFilename); } else { doc.setComment("Update attachment " + attachmentFilename); } attachment.setContent(attachmentData); attachment.setFilename(attachmentFilename); attachment.setAuthor(getCurrentUser()); attachment.setDoc(doc); doc.setAuthor(getCurrentUser()); if (doc.isNew()) { doc.setCreator(getCurrentUser()); } doc.saveAttachmentContent(attachment, xcontext); } @Override public List<AttachmentReference> getAttachmentReferences(DocumentReference documentReference) throws Exception { XWikiContext xcontext = getContext(); List<XWikiAttachment> attachments = xcontext.getWiki().getDocument(documentReference, xcontext).getAttachmentList(); List<AttachmentReference> attachmentReferences = new ArrayList<AttachmentReference>(attachments.size()); for (XWikiAttachment attachment : attachments) { attachmentReferences.add(attachment.getReference()); } return attachmentReferences; } @Override public String getAttachmentVersion(AttachmentReference attachmentReference) throws Exception { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(attachmentReference.getDocumentReference(), xcontext); XWikiAttachment attachment = doc.getAttachment(attachmentReference.getName()); return attachment == null ? null : attachment.getVersion(); } @Override public String getDocumentURL(DocumentReference documentReference, String action, String queryString, String anchor) { return getDocumentURL(documentReference, action, queryString, anchor, false); } @Override public String getDocumentURL(final DocumentReference documentReference, final String action, final String queryString, final String anchor, final boolean isFullURL) { if (documentReference == null) { return this.getDocumentURL(this.getContext().getDoc().getDocumentReference(), action, queryString, anchor, isFullURL); } if (isFullURL) { return this .getContext() .getURLFactory() .createExternalURL(documentReference.getLastSpaceReference().getName(), documentReference.getName(), action, queryString, anchor, documentReference.getWikiReference().getName(), this.getContext()) .toString(); } else { return this.getContext().getWiki() .getURL(documentReference, action, queryString, anchor, this.getContext()); } } @Override @Deprecated public String getURL(String documentReference, String action, String queryString, String anchor) { XWikiContext xcontext = getContext(); // If the document name is empty then use the current document String computedDocumentName = documentReference; if (StringUtils.isEmpty(documentReference)) { computedDocumentName = xcontext.getDoc().getFullName(); } return xcontext.getWiki().getURL(computedDocumentName, action, queryString, anchor, xcontext); } @Override @Deprecated public String getAttachmentURL(String documentReference, String attachmentName) { XWikiContext xcontext = getContext(); String attachmentURL; try { attachmentURL = xcontext.getWiki().getAttachmentURL( documentReference == null ? xcontext.getDoc().getFullName() : documentReference, attachmentName, xcontext); } catch (XWikiException e) { // This cannot happen. There's a bug in the definition of XWiki.getAttachmentURL: it says it can generate // an exception but in fact no exception is raised in the current implementation. throw new RuntimeException("Failed to get attachment URL", e); } return attachmentURL; } @Override public String getAttachmentURL(AttachmentReference attachmentReference, boolean isFullURL) { return getAttachmentURL(attachmentReference, null, isFullURL); } @Override public String getAttachmentURL(AttachmentReference attachmentReference, String queryString, boolean isFullURL) { String url; if (isFullURL) { XWikiContext xcontext = getContext(); url = xcontext.getURLFactory().createAttachmentURL(attachmentReference.getName(), attachmentReference.getDocumentReference().getLastSpaceReference().getName(), attachmentReference.getDocumentReference().getName(), "download", queryString, attachmentReference.getDocumentReference().getWikiReference().getName(), xcontext).toString(); } else { XWikiContext xcontext = getContext(); String documentReference = this.defaultEntityReferenceSerializer.serialize(attachmentReference.getDocumentReference()); if (documentReference == null) { documentReference = xcontext.getDoc().getFullName(); } String fileName = attachmentReference.getName(); try { url = xcontext.getWiki().getAttachmentURL(documentReference, fileName, queryString, xcontext); } catch (XWikiException e) { // This cannot happen. There's a bug in the definition of XWiki.getAttachmentURL: it says it can // generate an exception but in fact no exception is raised in the current implementation. throw new RuntimeException("Failed to get attachment URL", e); } } return url; } @Override @Deprecated public List<String> getAttachmentURLs(DocumentReference documentReference, boolean isFullURL) throws Exception { List<String> urls = new ArrayList<String>(); for (AttachmentReference attachmentReference : getAttachmentReferences(documentReference)) { urls.add(getAttachmentURL(attachmentReference, isFullURL)); } return urls; } @Override public boolean isDocumentViewable(DocumentReference documentReference) { return hasRight(documentReference, "view"); } @Override @Deprecated public boolean isDocumentViewable(String documentReference) { return hasRight(documentReference, "view"); } @Override @Deprecated public boolean isDocumentEditable(String documentReference) { return hasRight(documentReference, "edit"); } @Override public boolean isDocumentEditable(DocumentReference documentReference) { return hasRight(documentReference, "edit"); } @Override public boolean hasProgrammingRights() { XWikiContext xcontext = getContext(); return xcontext.getWiki().getRightService().hasProgrammingRights(xcontext); } @Override @Deprecated public String getCurrentUser() { DocumentReference userReference = getContext().getUserReference(); // Make sure to always return the full reference of the user if (userReference != null) { return this.defaultEntityReferenceSerializer.serialize(userReference); } else { return XWikiRightService.GUEST_USER_FULLNAME; } } @Override public DocumentReference getCurrentUserReference() { return getContext().getUserReference(); } @Override public void setCurrentUser(String userName) { getContext().setUser(userName); } @Override public String getDefaultEncoding() { return getContext().getWiki().getEncoding(); } @Override public void popDocumentFromContext(Map<String, Object> backupObjects) { XWikiDocument.restoreContext(backupObjects, getContext()); } @Override @Deprecated public void pushDocumentInContext(Map<String, Object> backupObjects, String documentReference) throws Exception { XWikiContext xcontext = getContext(); // Backup current context state XWikiDocument.backupContext(backupObjects, xcontext); // Make sure to get the current XWikiContext after ExcutionContext clone xcontext = getContext(); // Change context document xcontext.getWiki().getDocument(documentReference, xcontext).setAsContextDoc(xcontext); } @Override public void pushDocumentInContext(Map<String, Object> backupObjects, DocumentReference documentReference) throws Exception { XWikiContext xcontext = getContext(); // Backup current context state XWikiDocument.backupContext(backupObjects, xcontext); // Make sure to get the current XWikiContext after ExcutionContext clone xcontext = getContext(); // Change context document xcontext.getWiki().getDocument(documentReference, xcontext).setAsContextDoc(xcontext); } @Override public String getCurrentWiki() { XWikiContext xcontext = getContext(); return xcontext.getDatabase(); } /** * Utility method for checking access rights of the current user on a target document. * * @param documentReference the reference of the document * @param right Access right requested. * @return True if the current user has the given access right, false otherwise. */ private boolean hasRight(DocumentReference documentReference, String right) { return hasRight(this.defaultEntityReferenceSerializer.serialize(documentReference), right); } /** * Utility method for checking access rights of the current user on a target document. * * @param documentReference the reference of the document * @param right Access right requested. * @return True if the current user has the given access right, false otherwise. */ private boolean hasRight(String documentReference, String right) { boolean hasRight = false; XWikiContext xcontext = getContext(); try { hasRight = xcontext.getWiki().getRightService() .hasAccessLevel(right, xcontext.getUser(), documentReference, xcontext); } catch (XWikiException e) { // Do nothing } return hasRight; } /** * Utility method for saving an {@link XWikiDocument}. This method takes care of setting authors and creators * appropriately. * * @param doc the {@link XWikiDocument} to be saved. * @param comment the edit comment. * @param isMinorEdit if the change in document is minor. * @throws Exception if an error occurs while saving the document. */ private void saveDocument(XWikiDocument doc, String comment, boolean isMinorEdit) throws Exception { doc.setAuthorReference(getContext().getUserReference()); if (doc.isNew()) { doc.setCreatorReference(getContext().getUserReference()); } getContext().getWiki().saveDocument(doc, comment, isMinorEdit, getContext()); } }
package com.xpn.xwiki.doc; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Provider; import javax.inject.Singleton; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.xwiki.bridge.DocumentAccessBridge; import org.xwiki.bridge.DocumentModelBridge; import org.xwiki.component.annotation.Component; import org.xwiki.model.EntityType; import org.xwiki.model.reference.AttachmentReference; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.DocumentReferenceResolver; import org.xwiki.model.reference.EntityReference; import org.xwiki.model.reference.EntityReferenceSerializer; import org.xwiki.model.reference.LocalDocumentReference; import org.xwiki.model.reference.ObjectPropertyReference; import org.xwiki.model.reference.ObjectReference; import org.xwiki.security.authorization.ContextualAuthorizationManager; import org.xwiki.security.authorization.Right; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.BaseProperty; import com.xpn.xwiki.objects.classes.PropertyClass; import com.xpn.xwiki.user.api.XWikiRightService; /** * Exposes methods for accessing Document data. This is temporary until we remodel the Model classes and the Document * services. The implementation is inside the old core, and not in a component because it has dependencies on the old * core. * * @version $Id$ * @since 1.6M1 */ @Component @Singleton public class DefaultDocumentAccessBridge implements DocumentAccessBridge { private static final LocalDocumentReference USERCLASS_REFERENCE = new LocalDocumentReference("XWiki", "XWikiUsers"); @Inject private Provider<XWikiContext> contextProvider; @Inject @Named("readonly") private Provider<XWikiContext> readonlyContextProvider; /** * Used to resolve a string into a proper Document Reference using the current document's reference to fill the * blanks, except for the page name for which the default page name is used instead. */ @Inject @Named("currentmixed") private DocumentReferenceResolver<String> currentMixedDocumentReferenceResolver; /** * Used to serialize full reference of current user. */ @Inject private EntityReferenceSerializer<String> defaultEntityReferenceSerializer; /** * Used to convert a Document Reference to string (compact form without the wiki part if it matches the current * wiki). */ @Inject @Named("compactwiki") private EntityReferenceSerializer<String> compactWikiEntityReferenceSerializer; @Inject private Provider<ContextualAuthorizationManager> authorizationProvider; @Inject private Logger logger; private XWikiContext getContext() { return this.contextProvider.get(); } @Override public DocumentReference getDocumentReference(EntityReference entityReference) { XWikiContext context = getContext(); if (context != null) { return context.getWiki().getDocumentReference(entityReference, context); } else { return null; } } @Override @Deprecated public DocumentModelBridge getDocument(String documentReference) throws Exception { XWikiContext xcontext = getContext(); return xcontext.getWiki().getDocument(documentReference, xcontext).getTranslatedDocument(xcontext); } @Override @Deprecated public DocumentModelBridge getDocument(DocumentReference documentReference) throws Exception { return getTranslatedDocumentInstance(documentReference); } @Override public DocumentModelBridge getDocumentInstance(DocumentReference documentReference) throws Exception { XWikiContext xcontext = getContext(); return xcontext.getWiki().getDocument(documentReference, xcontext); } @Override public DocumentModelBridge getDocumentInstance(EntityReference reference) throws Exception { XWikiContext xcontext = getContext(); return xcontext.getWiki().getDocument(reference, xcontext); } @Override public DocumentModelBridge getTranslatedDocumentInstance(DocumentReference documentReference) throws Exception { XWikiContext xcontext = getContext(); return xcontext.getWiki().getDocument(documentReference, xcontext).getTranslatedDocument(xcontext); } @Override public DocumentModelBridge getTranslatedDocumentInstance(EntityReference entityReference) throws Exception { XWikiContext xcontext = getContext(); return xcontext.getWiki().getDocument(entityReference, xcontext).getTranslatedDocument(xcontext); } @Override public DocumentReference getCurrentDocumentReference() { XWikiDocument currentDocument = null; XWikiContext context = getContext(); if (context != null) { currentDocument = context.getDoc(); } return currentDocument == null ? null : currentDocument.getDocumentReference(); } @Override @Deprecated public String getDocumentContent(String documentReference) throws Exception { XWikiContext xcontext = getContext(); return getDocumentContent(documentReference, xcontext.getLanguage()); } @Override public String getDocumentContentForDefaultLanguage(DocumentReference documentReference) throws Exception { XWikiContext xcontext = getContext(); return xcontext.getWiki().getDocument(documentReference, xcontext).getContent(); } @Override @Deprecated public String getDocumentContentForDefaultLanguage(String documentReference) throws Exception { XWikiContext xcontext = getContext(); return xcontext.getWiki().getDocument(documentReference, xcontext).getContent(); } @Override public String getDocumentContent(DocumentReference documentReference, String language) throws Exception { XWikiContext xcontext = getContext(); String originalRev = (String) xcontext.get("rev"); try { xcontext.remove("rev"); return xcontext.getWiki().getDocument(documentReference, xcontext).getTranslatedContent(language, xcontext); } finally { if (originalRev != null) { xcontext.put("rev", originalRev); } } } @Override @Deprecated public String getDocumentContent(String documentReference, String language) throws Exception { XWikiContext xcontext = getContext(); String originalRev = (String) xcontext.get("rev"); try { xcontext.remove("rev"); return xcontext.getWiki().getDocument(documentReference, xcontext).getTranslatedContent(language, xcontext); } finally { if (originalRev != null) { xcontext.put("rev", originalRev); } } } @Override public boolean exists(DocumentReference documentReference) { XWikiContext context = getContext(); if (context != null) { return context.getWiki().exists(documentReference, context); } else { return false; } } @Override @Deprecated public boolean exists(String documentReference) { XWikiContext context = getContext(); if (context != null) { return context.getWiki().exists(documentReference, context); } else { return false; } } @Override public void setDocumentContent(DocumentReference documentReference, String content, String editComment, boolean isMinorEdit) throws Exception { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); doc.setContent(content); saveDocument(doc, editComment, isMinorEdit); } @Override @Deprecated public void setDocumentContent(String documentReference, String content, String editComment, boolean isMinorEdit) throws Exception { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); doc.setContent(content); saveDocument(doc, editComment, isMinorEdit); } @Override @Deprecated public String getDocumentSyntaxId(String documentReference) throws Exception { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); return doc.getSyntaxId(); } @Override public void setDocumentSyntaxId(DocumentReference documentReference, String syntaxId) throws Exception { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); doc.setSyntaxId(syntaxId); saveDocument(doc, String.format("Changed document syntax from [%s] to [%s].", doc.getSyntax(), syntaxId), true); } @Override @Deprecated public void setDocumentSyntaxId(String documentReference, String syntaxId) throws Exception { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); String oldSyntaxId = doc.getSyntaxId(); doc.setSyntaxId(syntaxId); saveDocument(doc, String.format("Changed document syntax from [%s] to [%s].", oldSyntaxId, syntaxId), true); } @Override public void setDocumentParentReference(DocumentReference documentReference, DocumentReference parentReference) throws Exception { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); doc.setParent(this.compactWikiEntityReferenceSerializer.serialize(parentReference, doc.getDocumentReference())); saveDocument(doc, String.format("Changed document parent to [%s].", this.defaultEntityReferenceSerializer.serialize(parentReference)), true); } @Override public void setDocumentTitle(DocumentReference documentReference, String title) throws Exception { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); doc.setTitle(title); saveDocument(doc, String.format("Changed document title to [%s].", title), true); } @Override public int getObjectNumber(DocumentReference documentReference, DocumentReference classReference, String propertyName, String valueToMatch) { try { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); BaseObject object = doc.getXObject(classReference, propertyName, valueToMatch, false); return object != null ? object.getNumber() : -1; } catch (XWikiException e) { return -1; } } @Override public Object getProperty(ObjectPropertyReference objectPropertyReference) { ObjectReference objectReference = (ObjectReference) objectPropertyReference.extractReference(EntityType.OBJECT); return getProperty(objectReference, objectPropertyReference.getName()); } @Override public Object getProperty(ObjectReference objectReference, String propertyName) { Object value = null; try { XWikiContext xcontext = getContext(); if (xcontext != null && xcontext.getWiki() != null) { DocumentReference documentReference = (DocumentReference) objectReference.extractReference(EntityType.DOCUMENT); XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); BaseObject object = doc.getXObject(objectReference); if (object != null) { BaseProperty property = (BaseProperty) object.get(propertyName); if (property != null) { value = property.getValue(); } } } } catch (Exception e) { this.logger.error("Failed to get property", e); } return value; } @Override public Object getProperty(String documentReference, String className, int objectNumber, String propertyName) { Object value = null; try { XWikiContext xcontext = getContext(); if (xcontext != null && xcontext.getWiki() != null) { XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); BaseObject object = doc.getObject(className, objectNumber); if (object != null) { BaseProperty property = (BaseProperty) object.get(propertyName); if (property != null) { value = property.getValue(); } } } } catch (Exception e) { this.logger.error("Failed to get property", e); } return value; } @Override @Deprecated public Object getProperty(String documentReference, String className, String propertyName) { Object value = null; try { XWikiContext xcontext = getContext(); if (xcontext != null && xcontext.getWiki() != null) { XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); BaseObject object = doc.getObject(className); if (object != null) { BaseProperty property = (BaseProperty) object.get(propertyName); if (property != null) { value = property.getValue(); } } } } catch (Exception e) { this.logger.error("Failed to get property", e); } return value; } @Override public Object getProperty(DocumentReference documentReference, DocumentReference classReference, String propertyName) { Object value = null; try { XWikiContext xcontext = getContext(); if (xcontext != null && xcontext.getWiki() != null) { XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); BaseObject object = doc.getXObject(classReference); if (object != null) { BaseProperty property = (BaseProperty) object.get(propertyName); if (property != null) { value = property.getValue(); } } } } catch (Exception e) { this.logger.error("Failed to get property", e); } return value; } @Override public Object getProperty(DocumentReference documentReference, DocumentReference classReference, int objectNumber, String propertyName) { Object value = null; try { XWikiContext xcontext = getContext(); if (xcontext != null && xcontext.getWiki() != null) { XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); BaseObject object = doc.getXObject(classReference, objectNumber); if (object != null) { BaseProperty property = (BaseProperty) object.get(propertyName); if (property != null) { value = property.getValue(); } } } } catch (Exception e) { this.logger.error("Failed to get property", e); } return value; } @Override public Object getProperty(String documentReference, String propertyName) { Object value = null; try { XWikiContext xcontext = getContext(); if (xcontext != null && xcontext.getWiki() != null) { XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); BaseObject object = doc.getFirstObject(propertyName, xcontext); if (object != null) { BaseProperty property = (BaseProperty) object.get(propertyName); if (property != null) { value = property.getValue(); } } } } catch (Exception e) { this.logger.error("Failed to get property", e); } return value; } @Override public List<Object> getProperties(String documentReference, String className) { List<Object> result; try { XWikiContext xcontext = getContext(); result = new ArrayList<Object>( xcontext.getWiki().getDocument(documentReference, xcontext).getObject(className).getFieldList()); } catch (Exception ex) { result = Collections.emptyList(); } return result; } @Override public String getPropertyType(String className, String propertyName) throws Exception { XWikiContext xcontext = getContext(); PropertyClass pc = null; try { pc = (PropertyClass) xcontext.getWiki().getDocument(className, xcontext).getXClass().get(propertyName); } catch (XWikiException e) { this.logger.warn("Failed to get document [{}]. Root cause: [{}]", className, ExceptionUtils.getRootCauseMessage(e)); } return pc == null ? null : pc.newProperty().getClass().getName(); } @Override public boolean isPropertyCustomMapped(String className, String property) throws Exception { XWikiContext xcontext = getContext(); if (!xcontext.getWiki().hasCustomMappings()) { return false; } List<String> lst = xcontext.getWiki().getClass(className, xcontext).getCustomMappingPropertyList(xcontext); return lst != null && lst.contains(property); } @Override @Deprecated public void setProperty(String documentReference, String className, String propertyName, Object propertyValue) throws Exception { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); BaseObject obj = doc.getObject(className, true, xcontext); if (obj != null) { obj.set(propertyName, propertyValue, xcontext); saveDocument(doc, String.format("Property [%s] set.", propertyName), true); } } @Override public void setProperty(DocumentReference documentReference, DocumentReference classReference, String propertyName, Object propertyValue) throws Exception { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); BaseObject obj = doc.getXObject(classReference, true, xcontext); if (obj != null) { obj.set(propertyName, propertyValue, xcontext); saveDocument(doc, String.format("Property [%s] set.", propertyName), true); } } @Override @Deprecated public byte[] getAttachmentContent(String documentReference, String attachmentFilename) throws Exception { XWikiContext xcontext = getContext(); return xcontext.getWiki().getDocument(documentReference, xcontext).getAttachment(attachmentFilename) .getContent(xcontext); } @Override public InputStream getAttachmentContent(AttachmentReference attachmentReference) throws Exception { XWikiContext xcontext = getContext(); XWikiDocument attachmentDocument = xcontext.getWiki().getDocument(attachmentReference.getDocumentReference(), xcontext); return new ByteArrayInputStream( attachmentDocument.getAttachment(attachmentReference.getName()).getContent(xcontext)); } @Override public void setAttachmentContent(AttachmentReference attachmentReference, byte[] attachmentData) throws Exception { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(attachmentReference.getDocumentReference(), xcontext); setAttachmentContent(doc, attachmentReference.getName(), attachmentData, xcontext); } @Override @Deprecated public void setAttachmentContent(String documentReference, String attachmentFilename, byte[] attachmentData) throws Exception { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext); setAttachmentContent(doc, attachmentFilename, attachmentData, xcontext); } private void setAttachmentContent(XWikiDocument doc, String attachmentFilename, byte[] attachmentData, XWikiContext xcontext) throws Exception { if (doc.getAttachment(attachmentFilename) == null) { doc.setComment("Add new attachment " + attachmentFilename); } else { doc.setComment("Update attachment " + attachmentFilename); } doc.setAttachment(attachmentFilename, new ByteArrayInputStream(attachmentData != null ? attachmentData : new byte[0]), xcontext); doc.setAuthorReference(getCurrentUserReference()); if (doc.isNew()) { doc.setCreatorReference(getCurrentUserReference()); } xcontext.getWiki().saveDocument(doc, xcontext); } @Override public List<AttachmentReference> getAttachmentReferences(DocumentReference documentReference) throws Exception { XWikiContext xcontext = getContext(); List<XWikiAttachment> attachments = xcontext.getWiki().getDocument(documentReference, xcontext).getAttachmentList(); List<AttachmentReference> attachmentReferences = new ArrayList<AttachmentReference>(attachments.size()); for (XWikiAttachment attachment : attachments) { attachmentReferences.add(attachment.getReference()); } return attachmentReferences; } @Override public String getAttachmentVersion(AttachmentReference attachmentReference) throws Exception { XWikiContext xcontext = getContext(); XWikiDocument doc = xcontext.getWiki().getDocument(attachmentReference.getDocumentReference(), xcontext); XWikiAttachment attachment = doc.getAttachment(attachmentReference.getName()); return attachment == null ? null : attachment.getVersion(); } @Override public String getDocumentURL(DocumentReference documentReference, String action, String queryString, String anchor) { return getDocumentURL(documentReference, action, queryString, anchor, false); } @Override public String getDocumentURL(final DocumentReference documentReference, final String action, final String queryString, final String anchor, final boolean isFullURL) { if (documentReference == null) { return this.getDocumentURL(this.getContext().getDoc().getDocumentReference(), action, queryString, anchor, isFullURL); } if (isFullURL) { return this.getContext().getURLFactory() .createExternalURL(extractSpacesFromDocumentReference(documentReference), documentReference.getName(), action, queryString, anchor, documentReference.getWikiReference().getName(), this.getContext()) .toString(); } else { return this.getContext().getWiki().getURL(documentReference, action, queryString, anchor, this.getContext()); } } @Override public String getDocumentURL(EntityReference entityReference, String action, String queryString, String anchor) { return getDocumentURL(entityReference, action, queryString, anchor, false); } @Override public String getDocumentURL(EntityReference entityReference, String action, String queryString, String anchor, boolean isFullURL) { XWikiContext xcontext = getContext(); DocumentReference documentReference = xcontext.getWiki().getDocumentReference(entityReference, xcontext); return getDocumentURL(documentReference, action, queryString, anchor, isFullURL); } @Override @Deprecated public String getURL(String documentReference, String action, String queryString, String anchor) { XWikiContext xcontext = getContext(); // If the document name is empty then use the current document String computedDocumentName = documentReference; if (StringUtils.isEmpty(documentReference)) { computedDocumentName = xcontext.getDoc().getFullName(); } return xcontext.getWiki().getURL(computedDocumentName, action, queryString, anchor, xcontext); } @Override @Deprecated public String getAttachmentURL(String documentReference, String attachmentName) { XWikiContext xcontext = getContext(); String attachmentURL; try { attachmentURL = xcontext.getWiki().getAttachmentURL( documentReference == null ? xcontext.getDoc().getFullName() : documentReference, attachmentName, xcontext); } catch (XWikiException e) { // This cannot happen. There's a bug in the definition of XWiki.getAttachmentURL: it says it can generate // an exception but in fact no exception is raised in the current implementation. throw new RuntimeException("Failed to get attachment URL", e); } return attachmentURL; } @Override public String getAttachmentURL(AttachmentReference attachmentReference, boolean isFullURL) { return getAttachmentURL(attachmentReference, null, isFullURL); } @Override public String getAttachmentURL(AttachmentReference attachmentReference, String queryString, boolean isFullURL) { String url; if (isFullURL) { XWikiContext xcontext = getContext(); url = xcontext.getURLFactory() .createAttachmentURL(attachmentReference.getName(), extractSpacesFromDocumentReference(attachmentReference.getDocumentReference()), attachmentReference.getDocumentReference().getName(), "download", queryString, attachmentReference.getDocumentReference().getWikiReference().getName(), xcontext) .toString(); } else { XWikiContext xcontext = getContext(); String documentReference = this.defaultEntityReferenceSerializer.serialize(attachmentReference.getDocumentReference()); if (documentReference == null) { documentReference = xcontext.getDoc().getFullName(); } String fileName = attachmentReference.getName(); try { url = xcontext.getWiki().getAttachmentURL(documentReference, fileName, queryString, xcontext); } catch (XWikiException e) { // This cannot happen. There's a bug in the definition of XWiki.getAttachmentURL: it says it can // generate an exception but in fact no exception is raised in the current implementation. throw new RuntimeException("Failed to get attachment URL", e); } } return url; } @Override @Deprecated public List<String> getAttachmentURLs(DocumentReference documentReference, boolean isFullURL) throws Exception { List<String> urls = new ArrayList<String>(); for (AttachmentReference attachmentReference : getAttachmentReferences(documentReference)) { urls.add(getAttachmentURL(attachmentReference, isFullURL)); } return urls; } @Override public boolean isDocumentViewable(DocumentReference documentReference) { return hasRight(documentReference, "view"); } @Override @Deprecated public boolean isDocumentViewable(String documentReference) { return hasRight(documentReference, "view"); } @Override @Deprecated public boolean isDocumentEditable(String documentReference) { return hasRight(documentReference, "edit"); } @Override public boolean isDocumentEditable(DocumentReference documentReference) { return hasRight(documentReference, "edit"); } @Override public boolean hasProgrammingRights() { return this.authorizationProvider.get().hasAccess(Right.PROGRAM); } @Override @Deprecated public String getCurrentUser() { DocumentReference userReference = getContext().getUserReference(); // Make sure to always return the full reference of the user if (userReference != null) { return this.defaultEntityReferenceSerializer.serialize(userReference); } else { return XWikiRightService.GUEST_USER_FULLNAME; } } @Override public DocumentReference getCurrentUserReference() { XWikiContext xcontext = getContext(); return xcontext != null ? xcontext.getUserReference() : null; } @Override public boolean isAdvancedUser() { return isAdvancedUser(getCurrentUserReference()); } @Override public boolean isAdvancedUser(EntityReference userReference) { boolean advanced = false; if (!XWikiRightService.isGuest(userReference)) { advanced = true; if (!XWikiRightService.isSuperAdmin(userReference)) { XWikiContext xcontext = getContext(); try { XWikiDocument userDocument = xcontext.getWiki().getDocument(userReference, xcontext); advanced = StringUtils.equals(userDocument.getStringValue(USERCLASS_REFERENCE, "usertype"), "Advanced"); } catch (XWikiException e) { this.logger.error("Failed to get document", e); } } } return advanced; } @Override public void setCurrentUser(String userName) { getContext().setUser(userName); } @Override public String getDefaultEncoding() { return getContext().getWiki().getEncoding(); } @Override public void popDocumentFromContext(Map<String, Object> backupObjects) { XWikiDocument.restoreContext(backupObjects, getContext()); } @Override @Deprecated public void pushDocumentInContext(Map<String, Object> backupObjects, String documentReference) throws Exception { XWikiContext xcontext = getContext(); // Backup current context state XWikiDocument.backupContext(backupObjects, xcontext); // Make sure to get the current XWikiContext after ExcutionContext clone xcontext = getContext(); // Change context document xcontext.getWiki().getDocument(documentReference, xcontext).setAsContextDoc(xcontext); } @Override public void pushDocumentInContext(Map<String, Object> backupObjects, DocumentReference documentReference) throws Exception { pushDocumentInContext(backupObjects, getDocumentInstance(documentReference)); } @Override public void pushDocumentInContext(Map<String, Object> backupObjects, DocumentModelBridge document) throws Exception { XWikiContext xcontext = getContext(); // Backup current context state XWikiDocument.backupContext(backupObjects, xcontext); // Make sure to get the current XWikiContext after ExcutionContext clone xcontext = getContext(); // Change context document ((XWikiDocument) document).setAsContextDoc(xcontext); } @Override public String getCurrentWiki() { XWikiContext xcontext = getContext(); return xcontext != null ? xcontext.getWikiId() : null; } @Override public DocumentReference getCurrentAuthorReference() { XWikiContext xcontext = this.readonlyContextProvider.get(); return xcontext != null ? xcontext.getAuthorReference() : null; } /** * Utility method for checking access rights of the current user on a target document. * * @param documentReference the reference of the document * @param right Access right requested. * @return True if the current user has the given access right, false otherwise. */ private boolean hasRight(DocumentReference documentReference, String right) { return hasRight(this.defaultEntityReferenceSerializer.serialize(documentReference), right); } /** * Utility method for checking access rights of the current user on a target document. * * @param documentReference the reference of the document * @param right Access right requested. * @return True if the current user has the given access right, false otherwise. */ private boolean hasRight(String documentReference, String right) { boolean hasRight = false; XWikiContext xcontext = getContext(); try { hasRight = xcontext.getWiki().getRightService().hasAccessLevel(right, xcontext.getUser(), documentReference, xcontext); } catch (XWikiException e) { // Do nothing } return hasRight; } /** * Utility method for saving an {@link XWikiDocument}. This method takes care of setting authors and creators * appropriately. * * @param doc the {@link XWikiDocument} to be saved. * @param comment the edit comment. * @param isMinorEdit if the change in document is minor. * @throws Exception if an error occurs while saving the document. */ private void saveDocument(XWikiDocument doc, String comment, boolean isMinorEdit) throws Exception { doc.setAuthorReference(getContext().getUserReference()); if (doc.isNew()) { doc.setCreatorReference(getContext().getUserReference()); } getContext().getWiki().saveDocument(doc, comment, isMinorEdit, getContext()); } private String extractSpacesFromDocumentReference(DocumentReference reference) { // Extract and escape the spaces portion of the passed reference to pass to the old createURL() API which // unfortunately doesn't accept a DocumentReference... EntityReference spaceReference = reference.getLastSpaceReference().removeParent(reference.getWikiReference()); return this.defaultEntityReferenceSerializer.serialize(spaceReference); } }
package com.hubspot.singularity.scheduler; import com.google.inject.Inject; import com.hubspot.mesos.JavaUtils; import com.hubspot.mesos.client.MesosClient; import com.hubspot.mesos.json.MesosMasterStateObject; import com.hubspot.singularity.MachineState; import com.hubspot.singularity.SingularityAgent; import com.hubspot.singularity.SingularityDeleteResult; import com.hubspot.singularity.config.SingularityConfiguration; import com.hubspot.singularity.data.AgentManager; import com.hubspot.singularity.data.InactiveAgentManager; import com.hubspot.singularity.helpers.MesosUtils; import com.hubspot.singularity.mesos.SingularityAgentAndRackManager; import com.hubspot.singularity.mesos.SingularityMesosScheduler; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.TimeUnit; import javax.inject.Singleton; import org.apache.mesos.v1.Protos.MasterInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public class SingularityAgentReconciliationPoller extends SingularityLeaderOnlyPoller { private static final Logger LOG = LoggerFactory.getLogger( SingularityAgentReconciliationPoller.class ); private final AgentManager agentManager; private final SingularityConfiguration configuration; private final SingularityAgentAndRackManager agentAndRackManager; private final MesosClient mesosClient; private final SingularityMesosScheduler mesosScheduler; private final InactiveAgentManager inactiveAgentManager; @Inject SingularityAgentReconciliationPoller( SingularityConfiguration configuration, AgentManager agentManager, SingularityAgentAndRackManager agentAndRackManager, MesosClient mesosClient, SingularityMesosScheduler mesosScheduler, InactiveAgentManager inactiveAgentManager ) { super(configuration.getReconcileAgentsEveryMinutes(), TimeUnit.MINUTES); this.agentManager = agentManager; this.configuration = configuration; this.agentAndRackManager = agentAndRackManager; this.mesosClient = mesosClient; this.mesosScheduler = mesosScheduler; this.inactiveAgentManager = inactiveAgentManager; } @Override public void runActionOnPoll() { refereshAgentsAndRacks(); checkInactiveAgents(); inactiveAgentManager.cleanInactiveAgentsList( System.currentTimeMillis() - TimeUnit.HOURS.toMillis(configuration.getCleanInactiveHostListEveryHours()) ); clearOldAgentHistory(); } private void refereshAgentsAndRacks() { try { Optional<MasterInfo> maybeMasterInfo = mesosScheduler.getMaster(); if (maybeMasterInfo.isPresent()) { final String uri = mesosClient.getMasterUri( MesosUtils.getMasterHostAndPort(maybeMasterInfo.get()) ); MesosMasterStateObject state = mesosClient.getMasterState(uri); agentAndRackManager.loadAgentsAndRacksFromMaster(state, false); } } catch (Exception e) { LOG.error("Could not refresh agent data", e); } } private void checkInactiveAgents() { final long start = System.currentTimeMillis(); // filter dead and missing on startup agents for cleanup List<SingularityAgent> deadAgents = agentManager.getObjectsFiltered( MachineState.DEAD ); LOG.debug("Found {} dead agents", deadAgents.size()); List<SingularityAgent> missingOnStartupAgents = agentManager.getObjectsFiltered( MachineState.MISSING_ON_STARTUP ); LOG.debug("Found {} agents missing on startup", missingOnStartupAgents.size()); List<SingularityAgent> decommissionedAgents = agentManager.getObjectsFiltered( MachineState.DECOMMISSIONED ); LOG.debug("Found {} agents decommissioned", decommissionedAgents.size()); List<SingularityAgent> inactiveAgents = new ArrayList<>(); inactiveAgents.addAll(deadAgents); inactiveAgents.addAll(missingOnStartupAgents); inactiveAgents.addAll(decommissionedAgents); if (inactiveAgents.isEmpty()) { LOG.trace("No inactive agents"); return; } int deleted = 0; final long maxDuration = TimeUnit.HOURS.toMillis( configuration.getDeleteDeadAgentsAfterHours() ); for (SingularityAgent inactiveAgent : inactiveAgents) { final long duration = System.currentTimeMillis() - inactiveAgent.getCurrentState().getTimestamp(); if (duration > maxDuration) { SingularityDeleteResult result = agentManager.deleteObject(inactiveAgent.getId()); inactiveAgentManager.cleanInactiveAgent(inactiveAgent.getHost()); // delete agent from inactive list too deleted++; LOG.info( "Removing inactive agent {} ({}) after {} (max {})", inactiveAgent.getId(), result, JavaUtils.durationFromMillis(duration), JavaUtils.durationFromMillis(maxDuration) ); } } LOG.debug( "Checked {} inactive agents, deleted {} in {}", inactiveAgents.size(), deleted, JavaUtils.duration(start) ); } private void clearOldAgentHistory() { for (SingularityAgent singularityAgent : agentManager.getObjects()) { agentManager.clearOldHistory(singularityAgent.getId()); } } }
package com.beancore.ui; import java.awt.BorderLayout; import java.awt.Container; import java.io.IOException; import javax.swing.ImageIcon; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextPane; import com.beancore.config.Config; import com.beancore.util.FileUtil; public class HelpDialog extends JFrame { private static final long serialVersionUID = 1L; private JTextPane helpContentTextPane; private JScrollPane scrollPane; public HelpDialog() { this.initComponent(); } private void initComponent() { this.helpContentTextPane = new JTextPane(); this.helpContentTextPane.setEditable(false); this.helpContentTextPane.setContentType("text/html;charset=utf-8"); try { this.helpContentTextPane.setText(FileUtil.readFileToString(Config.HELP_FILE_PATH)); } catch (IOException e) { e.printStackTrace(); } this.scrollPane = new JScrollPane(this.helpContentTextPane); this.scrollPane.setAutoscrolls(true); Container c = this.getContentPane(); c.add(this.scrollPane, BorderLayout.CENTER); this.setTitle("Help"); this.setIconImage(new ImageIcon(Config.LOGO_IMG).getImage()); this.setSize(Config.HELP_DIALOG_WIDTH, Config.HELP_DIALOG_HEIGHT); this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); } }
package com.antoniocappiello.curriculumvitae.espresso; import android.content.Context; import android.content.Intent; import android.support.test.InstrumentationRegistry; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.test.suitebuilder.annotation.LargeTest; import com.antoniocappiello.curriculumvitae.App; import com.antoniocappiello.curriculumvitae.R; import com.antoniocappiello.curriculumvitae.model.Category; import com.antoniocappiello.curriculumvitae.presenter.webapi.WebApi; import com.antoniocappiello.curriculumvitae.presenter.webapi.WebApiService; import com.antoniocappiello.curriculumvitae.view.CategoryActivity; import com.antoniocappiello.curriculumvitae.view.MainActivity; import com.google.gson.JsonElement; import com.orhanobut.logger.Logger; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import javax.inject.Inject; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; @LargeTest @RunWith(AndroidJUnit4.class) public class CategoryActivityPersonalInfoTest { @Rule public ActivityTestRule<CategoryActivity> activityTestRule = new ActivityTestRule<CategoryActivity>(CategoryActivity.class) { @Override protected Intent getActivityIntent() { Context targetContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); Intent result = new Intent(targetContext, MainActivity.class); result.putExtra(CategoryActivity.CATEGORY, Category.PERSONAL_INFO); return result; } }; @Inject WebApiService mWebApiService; @Before public void setUp() { mWebApiService = ((App) activityTestRule.getActivity().getApplication()) .appComponent() .webApiService(); } @Test public void correctPersonalInfoTextIsDisplayed() { JsonElement data = mWebApiService.readAboutMe().toBlocking().first(); onView(withId(R.id.content_text_view)).check(matches(withText(data.toString()))); } }
package de.fau.amos.virtualledger.android.views.savings.add; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.OnClick; import de.fau.amos.virtualledger.R; import de.fau.amos.virtualledger.android.dagger.App; import de.fau.amos.virtualledger.android.data.BankingDataManager; import de.fau.amos.virtualledger.android.data.SyncStatus; import de.fau.amos.virtualledger.android.model.SavingsAccount; import de.fau.amos.virtualledger.dtos.BankAccess; import de.fau.amos.virtualledger.dtos.BankAccount; public class AddSavingsAccountAccountsFragment extends AddSavingsAccountPage { @SuppressWarnings("unused") private static final String TAG = AddSavingsAccountAccountsFragment.class.getSimpleName(); private BankAccountSelectedListener bankAccountSelectedListener; private BankAccount bankAccount; private BankAccountAdapter adapter; @Inject BankingDataManager bankingDataManager; @OnClick(R.id.add_savings_account_button_accounts) public void onClickChooseAccountsButton() { //TODO } @Nullable @Override public View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable final Bundle savedInstanceState) { ((App) getActivity().getApplication()).getNetComponent().inject(this); final View view = inflater.inflate(R.layout.saving_accounts_add_fragment_accounts, container, false); ButterKnife.bind(this, view); return view; } @Override public void fillInData(final SavingsAccount addSavingsAccountResult) { //TODO } @NonNull private ArrayList<BankAccount> getBankAccounts() { ArrayList<BankAccount> allBankAccounts = new ArrayList<>(); List<BankAccess> accesses = new ArrayList<>(); if(bankingDataManager.getSyncStatus() == SyncStatus.SYNCED) { try { accesses = bankingDataManager.getBankAccesses(); } catch (Exception e) { logger().info(TAG + " could not get bank accesses"); } for(BankAccess bankAccess: accesses) { allBankAccounts.addAll(bankAccess.getBankaccounts()); } } return allBankAccounts; } private Logger logger() { return Logger.getLogger(this.getClass().getCanonicalName()); } }
package org.ovirt.engine.core.bll; import org.ovirt.engine.core.common.queries.GetAllRelevantQuotasForStorageParameters; public class GetAllRelevantQuotasForStorageQuery<P extends GetAllRelevantQuotasForStorageParameters> extends QueriesCommandBase<P> { public GetAllRelevantQuotasForStorageQuery(P parameters) { super(parameters); } @Override protected void executeQueryCommand() { getQueryReturnValue().setReturnValue(getDbFacade() .getQuotaDAO() .getAllRelevantQuotasForStorage(getParameters().getStorageId())); } }
package dk.statsbiblioteket.medieplatform.autonomous; import dk.statsbiblioteket.util.Strings; import org.slf4j.Logger; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; /** This class collects the result of a run of a component. */ public class ResultCollector { private static Logger log = org.slf4j.LoggerFactory.getLogger(ResultCollector.class); private Result resultStructure; private boolean preservable = true; private Integer maxResults; private int resultCount; private Failure lastFailure; /** * * @param tool * @param version * @param maxResults The maximum number of results to collect. If null then unlimited results may be collected. */ public ResultCollector(String tool, String version, Integer maxResults) { resultStructure = new ObjectFactory().createResult(); setSuccess(true); resultStructure.setFailures(new Failures()); resultStructure.setTool(tool); resultStructure.setVersion(version); setTimestamp(new Date()); this.maxResults = maxResults; resultCount = 0; } /** * This method is marked as deprecated. Use the alternative constructor where the maximum number of allowable * results is explicitly specified. * @param tool * @param version */ @Deprecated public ResultCollector(String tool, String version) { this(tool, version, null); } /** * This flag controls whether or not the result collecter contains results that should be preserved. Default * true. If set to false, the result will not be preserved and thus the event will never have happened in * the event framework */ public boolean isPreservable() { return preservable; } /** * This flag controls whether or not the result collecter contains results that should be preserved. Default * true. If set to false, the result will not be preserved and thus the event will never have happened in * the event framework */ public void setPreservable(boolean preservable) { this.preservable = preservable; } /** * Get the success value of the execution * * @return the success */ public boolean isSuccess() { return "Success".equals(resultStructure.getOutcome()); } /** * Set the success Value of the execution * * @param success the sucesss */ private void setSuccess(boolean success) { resultStructure.setOutcome(success ? "Success" : "Failure"); } /** * Add a specific failure to the result collector. All these parameters must be non-null and non-empty * * @param reference the reference to the file/object that caused the failure * @param type the type of failure * @param component the component that failed * @param description Description of the failure. */ public void addFailure(String reference, String type, String component, String description) { addFailure(reference, type, component, description, new String[]{}); } /** * Add a specific failure to the result collector. All these parameters, except the last, must be non-null and non-empty * * @param reference the reference to the file/object that caused the failure * @param type the type of failure * @param component the component that failed * @param description Description of the failure. * @param details additional details, can be null */ public void addFailure(String reference, String type, String component, String description, String... details) { resultCount++; //The count of the current failure, starting at 1. log.info( "Adding failure for " + "resource '{}' " + "of type '{}' " + "from component '{}' " + "with description '{}' " + "and details '{}'", reference, type, component, description, Strings.join(details, "\n")); List<Failure> list = resultStructure.getFailures().getFailure(); Failure failure = new Failure(); failure.setFilereference(reference); failure.setType(type); failure.setComponent(component); failure.setDescription(description); if (details != null && details.length > 0) { Details xmlDetails = new Details(); xmlDetails.getContent().add(Strings.join(Arrays.asList(details), "\n")); failure.setDetails(xmlDetails); } if (maxResults == null || resultCount < maxResults) { list.add(failure); } else { Details currentDetails = failure.getDetails(); if (currentDetails == null) { currentDetails = new Details(); } currentDetails.getContent().add(0, description); failure.setDetails(currentDetails); failure.setDescription("The number of results (" + resultCount + ") exceeded the maximum number that can be" + " collected (" + maxResults + ")."); lastFailure = failure; } setSuccess(false); } /** * Merge the failures from this ResultCollector into the given result collector. The maxResults specified in the * "that" argument is respected. * * @param that the result collector to merge into * * @return that */ public ResultCollector mergeInto(ResultCollector that) { for (Failure failure : getFailures()) { ArrayList<String> details = new ArrayList<>(); if (failure.getDetails() != null) { for (Object content : failure.getDetails().getContent()) { details.add(content.toString()); } } that.addFailure( failure.getFilereference(), failure.getType(), failure.getComponent(), failure.getDescription(), details.toArray(new String[details.size()])); if (that.getTimestamp().before(this.getTimestamp())) { that.setTimestamp(this.getTimestamp()); } } return that; } /** * Get the list of failures. This method is only meant to be used for merging purposes * * @return the failures */ private List<Failure> getFailures() { return Collections.unmodifiableList( resultStructure.getFailures().getFailure()); } /** Return the report as xml */ public String toReport() { if (lastFailure != null) { resultStructure.getFailures().getFailure().add(lastFailure); } try { JAXBContext context = JAXBContext.newInstance(ObjectFactory.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); StringWriter writer = new StringWriter(); marshaller.marshal(resultStructure, writer); return writer.toString(); } catch (JAXBException e) { return null; } } /** * The timestamp of the event * * @return */ public Date getTimestamp() { return resultStructure.getDate().toGregorianCalendar().getTime(); } /** * Timestamp the event that this is the result of * * @param timestamp */ public void setTimestamp(Date timestamp) { resultStructure.setDate(format(timestamp)); } private XMLGregorianCalendar format(Date date) { GregorianCalendar c = new GregorianCalendar(); c.setTime(date); XMLGregorianCalendar date2 = null; try { date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c); } catch (DatatypeConfigurationException e) { throw new Error(e); } return date2; } }
package gov.nih.nci.caadapter.ui.specification.hsm; import gov.nih.nci.caadapter.common.Log; import gov.nih.nci.caadapter.common.util.Config; import gov.nih.nci.caadapter.common.util.GeneralUtilities; import gov.nih.nci.caadapter.hl7.datatype.Attribute; import gov.nih.nci.caadapter.hl7.datatype.Datatype; import gov.nih.nci.caadapter.hl7.datatype.DatatypeBaseObject; import gov.nih.nci.caadapter.hl7.datatype.DatatypeParserUtil; //import gov.nih.nci.caadapter.hl7.mif.CMETRef; import gov.nih.nci.caadapter.hl7.mif.MIFAssociation; import gov.nih.nci.caadapter.hl7.mif.MIFAttribute; import gov.nih.nci.caadapter.hl7.mif.MIFClass; import gov.nih.nci.caadapter.hl7.mif.MIFCardinality; import gov.nih.nci.caadapter.hl7.mif.MIFUtil; import javax.swing.JTabbedPane; import javax.swing.JTextField; import javax.swing.JComponent; import javax.swing.JComboBox; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JLabel; import javax.swing.JButton; import javax.swing.JOptionPane; import javax.swing.BorderFactory; import javax.swing.text.JTextComponent; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreePath; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Insets; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Iterator; import java.util.List; public class HSMNodePropertiesPane extends JPanel implements ActionListener { /** * Logging constant used to identify source of log entry, that could be later used to create * logging mechanism to uniquely identify the logged class. */ private static final String LOGID = "$RCSfile: HSMNodePropertiesPane.java,v $"; public static String RCSID = "$Header: /share/content/gforge/caadapter/caadapter/components/userInterface/src/gov/nih/nci/caadapter/ui/specification/hsm/HSMNodePropertiesPane.java,v 1.18 2007-10-31 20:38:17 wangeug Exp $"; private static final String APPLY_BUTTON_COMMAND_NAME = "Apply"; private static final String APPLY_BUTTON_COMMAND_MNEMONIC = "A"; private static final String RESET_BUTTON_COMMAND_NAME = "Reset"; private static final String RESET_BUTTON_COMMAND_MNEMONIC = "R"; private static final String COMBO_BOX_DEFAULT_BLANK_CHOICE = ""; private Color defaultEditableFieldBackgroundColor = null; private JTextField elementNameField; private JTextField elementTypeField; private JTextField elementParentField; private JTextField cardinalityField; private JTextField mandatoryField; private JTextField conformanceField; private JTextField abstractField; private JComboBox dataTypeField; private JTextField hl7DefaultValueField; private JTextField hl7DomainField; private JTextField codingStrengthField; private JTextField cmetField; private JTextField userDefaultValueField; private DatatypeBaseObject seletedBaseObject; private HSMPanel parentPanel; /** * Creates a new <code>JPanel</code> with a double buffer * and a flow layout. */ public HSMNodePropertiesPane(HSMPanel parent) { this.parentPanel = parent; initialize(); } private void initialize() { this.setLayout(new BorderLayout()); this.add(getCenterComponent(), BorderLayout.CENTER); this.add(getSouthComponent(), BorderLayout.SOUTH); } private JComponent getCenterComponent() { JScrollPane scrollPane = new JScrollPane(); scrollPane.setBorder(BorderFactory.createTitledBorder("HL7 v3 Specification Properties")); JPanel centerPanel = new JPanel(new GridBagLayout()); Insets insets = new Insets(5, 5, 5, 5); int posY = 0; JLabel elementNameLabel = new JLabel("Element Name:"); centerPanel.add(elementNameLabel, new GridBagConstraints(0, posY, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, insets, 0, 0)); elementNameField = new JTextField(); Dimension fieldDimension = new Dimension(elementNameLabel.getPreferredSize().width, elementNameField.getPreferredSize().height); //first time set the editable field background color defaultEditableFieldBackgroundColor = elementNameField.getBackground(); elementNameField.setEditable(false); elementNameField.setBackground(Config.DEFAULT_READ_ONLY_BACK_GROUND_COLOR); elementNameField.setPreferredSize(fieldDimension);//titleLabel.getPreferredSize()); centerPanel.add(elementNameField, new GridBagConstraints(1, posY, 1, 1, 1.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, insets, 0, 0)); posY++; JLabel elementTypeLabel = new JLabel("Element Type:"); centerPanel.add(elementTypeLabel, new GridBagConstraints(0, posY, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, insets, 0, 0)); elementTypeField = new JTextField(); elementTypeField.setEditable(false); elementTypeField.setBackground(Config.DEFAULT_READ_ONLY_BACK_GROUND_COLOR); centerPanel.add(elementTypeField, new GridBagConstraints(1, posY, 1, 1, 1.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, insets, 0, 0)); posY++; JLabel elementParentLabel = new JLabel("Element Parent:"); centerPanel.add(elementParentLabel, new GridBagConstraints(0, posY, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, insets, 0, 0)); elementParentField = new JTextField(); elementParentField.setEditable(false); elementParentField.setBackground(Config.DEFAULT_READ_ONLY_BACK_GROUND_COLOR); centerPanel.add(elementParentField, new GridBagConstraints(1, posY, 1, 1, 1.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, insets, 0, 0)); posY++; JLabel cardinalityLabel = new JLabel("Cardinality:"); centerPanel.add(cardinalityLabel, new GridBagConstraints(0, posY, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, insets, 0, 0)); cardinalityField = new JTextField(); cardinalityField.setEditable(false); cardinalityField.setBackground(Config.DEFAULT_READ_ONLY_BACK_GROUND_COLOR); centerPanel.add(cardinalityField, new GridBagConstraints(1, posY, 1, 1, 1.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, insets, 0, 0)); posY++; JLabel mandatoryLabel = new JLabel("Mandatory:"); centerPanel.add(mandatoryLabel, new GridBagConstraints(0, posY, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, insets, 0, 0)); mandatoryField = new JTextField(); mandatoryField.setEditable(false); mandatoryField.setBackground(Config.DEFAULT_READ_ONLY_BACK_GROUND_COLOR); centerPanel.add(mandatoryField, new GridBagConstraints(1, posY, 1, 1, 1.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, insets, 0, 0)); posY++; JLabel conformanceLabel = new JLabel("Conformance:"); centerPanel.add(conformanceLabel, new GridBagConstraints(0, posY, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, insets, 0, 0)); conformanceField = new JTextField(); conformanceField.setEditable(false); conformanceField.setBackground(Config.DEFAULT_READ_ONLY_BACK_GROUND_COLOR); centerPanel.add(conformanceField, new GridBagConstraints(1, posY, 1, 1, 1.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, insets, 0, 0)); posY++; // JLabel rimSourceLabel = new JLabel("RIM Source:"); // centerPanel.add(rimSourceLabel, new GridBagConstraints(0, posY, 1, 1, 0.0, 0.0, // GridBagConstraints.WEST, GridBagConstraints.NONE, insets, 0, 0)); // rimSourceField = new JTextField(); // rimSourceField.setEditable(false); // rimSourceField.setBackground(Config.DEFAULT_READ_ONLY_BACK_GROUND_COLOR); // centerPanel.add(rimSourceField, new GridBagConstraints(1, posY, 1, 1, 1.0, 0.0, // GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, insets, 0, 0)); posY++; JLabel abstractLabel = new JLabel("Abstract:"); centerPanel.add(abstractLabel, new GridBagConstraints(0, posY, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, insets, 0, 0)); abstractField = new JTextField(); abstractField.setEditable(false); abstractField.setBackground(Config.DEFAULT_READ_ONLY_BACK_GROUND_COLOR); centerPanel.add(abstractField, new GridBagConstraints(1, posY, 1, 1, 1.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, insets, 0, 0)); posY++; JLabel dataTypeLabel = new JLabel("Data Type:"); centerPanel.add(dataTypeLabel, new GridBagConstraints(0, posY, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, insets, 0, 0)); dataTypeField = new JComboBox(); dataTypeField.setPreferredSize(new Dimension(fieldDimension.width + 4, fieldDimension.height + 2));//titleLabel.getPreferredSize()); centerPanel.add(dataTypeField, new GridBagConstraints(1, posY, 1, 1, 1.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, insets, 0, 0)); posY++; JLabel hl7DefaultValueLabel = new JLabel("HL7 Default Value:"); centerPanel.add(hl7DefaultValueLabel, new GridBagConstraints(0, posY, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, insets, 0, 0)); hl7DefaultValueField = new JTextField(); hl7DefaultValueField.setEditable(false); hl7DefaultValueField.setBackground(Config.DEFAULT_READ_ONLY_BACK_GROUND_COLOR); centerPanel.add(hl7DefaultValueField, new GridBagConstraints(1, posY, 1, 1, 1.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, insets, 0, 0)); posY++; JLabel hl7DomainLabel = new JLabel("HL7 Domain:"); centerPanel.add(hl7DomainLabel, new GridBagConstraints(0, posY, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, insets, 0, 0)); hl7DomainField = new JTextField(); hl7DomainField.setEditable(false); hl7DomainField.setBackground(Config.DEFAULT_READ_ONLY_BACK_GROUND_COLOR); centerPanel.add(hl7DomainField, new GridBagConstraints(1, posY, 1, 1, 1.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, insets, 0, 0)); posY++; JLabel codingStrengthLabel = new JLabel("Coding Strength:"); centerPanel.add(codingStrengthLabel, new GridBagConstraints(0, posY, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, insets, 0, 0)); codingStrengthField = new JTextField(); codingStrengthField.setEditable(false); codingStrengthField.setBackground(Config.DEFAULT_READ_ONLY_BACK_GROUND_COLOR); centerPanel.add(codingStrengthField, new GridBagConstraints(1, posY, 1, 1, 1.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, insets, 0, 0)); posY++; JLabel cmetLabel = new JLabel("CMET:"); centerPanel.add(cmetLabel, new GridBagConstraints(0, posY, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, insets, 0, 0)); cmetField = new JTextField(); cmetField.setEditable(false); cmetField.setBackground(Config.DEFAULT_READ_ONLY_BACK_GROUND_COLOR); centerPanel.add(cmetField, new GridBagConstraints(1, posY, 1, 1, 1.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, insets, 0, 0)); posY++; JLabel userDefaultValueLabel = new JLabel("User-defined Default Value:"); centerPanel.add(userDefaultValueLabel, new GridBagConstraints(0, posY, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, insets, 0, 0)); userDefaultValueField = new JTextField(); centerPanel.add(userDefaultValueField, new GridBagConstraints(1, posY, 1, 1, 1.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, insets, 0, 0)); posY++; scrollPane.getViewport().setView(centerPanel); return scrollPane; } private JComponent getSouthComponent() { JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING)); JButton applyButton = new JButton(APPLY_BUTTON_COMMAND_NAME); applyButton.setMnemonic(APPLY_BUTTON_COMMAND_MNEMONIC.charAt(0)); applyButton.addActionListener(this); JButton resetButton = new JButton(RESET_BUTTON_COMMAND_NAME); resetButton.setMnemonic(RESET_BUTTON_COMMAND_MNEMONIC.charAt(0)); resetButton.addActionListener(this); buttonPanel.add(applyButton); buttonPanel.add(resetButton); return buttonPanel; } /** * Invoked when an action occurs. */ public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (APPLY_BUTTON_COMMAND_NAME.equals(command)) { //Log.logInfo(this, "To Implement Apply Command..."); applyUserChanges(); } else if (RESET_BUTTON_COMMAND_NAME.equals(command)) { //Log.logInfo(this, "To Implement Reset Command..."); reloadData(); } } public DatatypeBaseObject getDatatypeObject(boolean fromUI) { if (fromUI) {//synchronize from UI. if (seletedBaseObject instanceof MIFAttribute) { //set selected concrete class MIFAttribute mifAttr=(MIFAttribute)seletedBaseObject; if (mifAttr.getDatatype()!=null&&mifAttr.getDatatype().isAbstract()) mifAttr.setConcreteDatatype(DatatypeParserUtil.getDatatype((String)dataTypeField.getSelectedItem())); if (userDefaultValueField.isEditable()) mifAttr.setDefaultValue(userDefaultValueField.getText()); } else if (seletedBaseObject instanceof Attribute) { //set default value Attribute updtdDatatypeAttr=(Attribute)seletedBaseObject; updtdDatatypeAttr.setDefaultValue(userDefaultValueField.getText()); //update the concrete datatype if it is an abstract Datatype dtType=updtdDatatypeAttr.getReferenceDatatype(); String slctdTypeName=(String)dataTypeField.getSelectedItem(); if (dtType!=null&&!slctdTypeName.equalsIgnoreCase("")) { if (dtType.isAbstract() ||(!dtType.getName().equals(slctdTypeName))) updtdDatatypeAttr.setReferenceDatatype(DatatypeParserUtil.getDatatype(slctdTypeName)); } } } return seletedBaseObject; } /** * Called by outsiders to trigger change check * * @param treeNode */ public boolean setDisplayData(DefaultMutableTreeNode treeNode) { if (isDataChanged()) { int userChoice = JOptionPane.showConfirmDialog(parentPanel, "This HL7 v3 specification has been changed in this properties panel. Would you like to apply the changes?", "Question", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (userChoice == JOptionPane.YES_OPTION) { applyUserChanges(); } else if (userChoice == JOptionPane.CANCEL_OPTION) {//stay where user is at, abort the attemption to move to different node. return false; } } setDisplayData(treeNode, true); Component parentCom=this.getParent(); if (parentCom instanceof JTabbedPane) { JTabbedPane parentTab=(JTabbedPane)parentCom; parentTab.setSelectedComponent(this); } return true; } /** * Interim between the public setDisplayData() and the setHl7V3Meta() so as to check if treeNode is null and its user object is MetaObject. * @param treeNode * @param refresh */ private void setDisplayData(DefaultMutableTreeNode treeNode, boolean refresh) { if (treeNode == null) {//no need to update return; } Object userObj = treeNode.getUserObject(); if (!(userObj instanceof DatatypeBaseObject)) { Log.logWarning(this,"Invalid data type being selectd:"+userObj.getClass().getName()); return; } DatatypeBaseObject userDatatypeObj=(DatatypeBaseObject)userObj; if (refresh || !GeneralUtilities.areEqual(this.seletedBaseObject, userDatatypeObj)) { this.seletedBaseObject = userDatatypeObj; clearAndEditableFields(false); elementNameField.setText(seletedBaseObject.getName()); //set parent name form xmlPath String parentXmlPath=userDatatypeObj.getParentXmlPath();//xmlPath.substring(0, xmlPath.lastIndexOf(".")); elementParentField.setText(parentXmlPath); if (userDatatypeObj instanceof Attribute ) { //userDefaultValue is editable Attribute dtAttr=(Attribute)userDatatypeObj; elementTypeField.setText("Data Type Field"); cardinalityField.setText(new MIFCardinality(dtAttr.getMin(), dtAttr.getMax()).toString()); if (dtAttr.isOptional()) mandatoryField.setText("N"); else mandatoryField.setText("Y"); //conformance is not present if (dtAttr.getType()!=null&&DatatypeParserUtil.isAbstractDatatypeWithName(dtAttr.getType())) { abstractField.setText("Y"); Datatype dtRefClass=dtAttr.getReferenceDatatype(); // if (dtAttr.isEnabled()) dataTypeField.setEditable(true); List<String> subClassList=DatatypeParserUtil.findSubclassListWithTypeName(dtAttr.getType()); if (subClassList!=null) { dataTypeField.addItem(COMBO_BOX_DEFAULT_BLANK_CHOICE); for(String subName:subClassList) { if (!subName.equals(dtAttr.getType())) dataTypeField.addItem(subName); if(dtRefClass!=null&&subName.equals(dtRefClass.getName())) dataTypeField.setSelectedItem(subName); } } else dataTypeField.addItem("No subclass is found"); } else abstractField.setText("N"); dataTypeField.addItem(dtAttr.getType()); if (dtAttr.getReferenceDatatype()==null) setEditableField(userDefaultValueField, dtAttr.isEnabled()); else if (dtAttr.getReferenceDatatype().isSimple()) setEditableField(userDefaultValueField, dtAttr.isEnabled()); //HL7 default is not present //HL7 Domain is not present //code strength is not present //cmet is not present userDefaultValueField.setText(dtAttr.getDefaultValue()); } else if (userDatatypeObj instanceof MIFAttribute ) { // dataTypeField is editable if the MIFAttribute is Abstract MIFAttribute mifAttr=(MIFAttribute)userDatatypeObj; elementTypeField.setText("Attribute"); cardinalityField.setText(new MIFCardinality(mifAttr.getMinimumMultiplicity(), mifAttr.getMaximumMultiplicity()).toString()); if (mifAttr.isMandatory()) mandatoryField.setText("Y"); else mandatoryField.setText("N"); conformanceField.setText(mifAttr.getConformance()); Datatype mifAttrDataType=mifAttr.getDatatype(); //the pre-defined type is always the first elemnt if (mifAttrDataType!=null&&mifAttrDataType.isAbstract()) { Datatype subClass=mifAttr.getConcreteDatatype(); dataTypeField.setEditable(true); abstractField.setText("Y"); List<String> subClassList=DatatypeParserUtil.findSubclassListWithTypeName(mifAttr.getType()); if (subClassList!=null) { dataTypeField.addItem(COMBO_BOX_DEFAULT_BLANK_CHOICE); for(String subName:subClassList) { if (!subName.equals(mifAttr.getType())) dataTypeField.addItem(subName); if(subClass!=null&&subName.equals(subClass.getName())) dataTypeField.setSelectedItem(subName); } } else dataTypeField.addItem("No subclass is found"); } else { abstractField.setText("N"); dataTypeField.addItem(mifAttr.getType()); } //use fixedValue as default value if available hl7DefaultValueField.setText(mifAttr.findHL7DefaultValueProperty()); hl7DomainField.setText(mifAttr.findDomainNameOidProperty());//.getDomainName()); codingStrengthField.setText(mifAttr.getCodingStrength()); userDefaultValueField.setText(mifAttr.getDefaultValue()); if (MIFUtil.isEditableMIFAttributeDefault(mifAttr)) setEditableField(userDefaultValueField,true); } else if (userDatatypeObj instanceof MIFClass ) { MIFClass mifClass=(MIFClass)userDatatypeObj; elementTypeField.setText("Clone"); //set 1..1 cardinality to root node if (mifClass.getParentXmlPath()==null ||mifClass.getParentXmlPath().equals("")) { cardinalityField.setText(new MIFCardinality(1, 1).toString()); mandatoryField.setText("Y"); } else { //here is a MIFClass selected for a ChoiceAssociation //find the cardinality from parent association DefaultMutableTreeNode parentNode =(DefaultMutableTreeNode)treeNode.getParent(); MIFAssociation parentMifAssc=(MIFAssociation)parentNode.getUserObject(); cardinalityField.setText(new MIFCardinality(parentMifAssc.getMaximumMultiplicity(), parentMifAssc.getMaximumMultiplicity()).toString()); if (parentMifAssc.isMandatory()) mandatoryField.setText("Y"); else mandatoryField.setText("N"); conformanceField.setText(parentMifAssc.getConformance()); } //Abstract is not present // dataTypeField.addItem(mifClass.getName()); // dataTypeField.setEditable(false); if (mifClass.isReference())//.getReferenceName()!=null) { cmetField.setText(mifClass.getName()); // hl7DomainField.setText(mifClass.getName()); } // hl7DefaultValueField.setText(mifAttr.getFixedValue()); // codingStrengthField.setText(mifAttr.getCodingStrength()); // userDefaultValueField.setText(mifAttr.getDefaultValue()); } else if (userDatatypeObj instanceof MIFAssociation ) { MIFAssociation mifAssc=(MIFAssociation)userDatatypeObj; elementTypeField.setText("Clone"); cardinalityField.setText(new MIFCardinality(mifAssc.getMinimumMultiplicity(), mifAssc.getMaximumMultiplicity()).toString()); if (mifAssc.isMandatory()) mandatoryField.setText("Y"); else mandatoryField.setText("N"); conformanceField.setText(mifAssc.getConformance()); // abstractField.setText(mifAssc.getMifClass().isDynamic()); //Abstract is not presentt MIFClass asscClass=mifAssc.getMifClass(); // if(asscClass.getChoices().isEmpty()) // dataTypeField.addItem(asscClass.getName()); if (asscClass.isReference())//.getReferenceName()!=null) { cmetField.setText(asscClass.getName());//.getReferenceName()); // hl7DomainField.setText(asscClass.getName()); } // hl7DefaultValueField.setText(""); // codingStrengthField.setText(""); // userDefaultValueField.setText(""); } else Log.logWarning(this,"Invalid data type being selectd:"+userDatatypeObj.getClass().getName()); } } private void clearAndEditableFields(boolean editableValue) { //clear fields elementNameField.setText(""); elementTypeField.setText(""); elementParentField.setText(""); cardinalityField.setText(""); mandatoryField.setText(""); conformanceField.setText(""); abstractField.setText(""); dataTypeField.removeAllItems(); hl7DefaultValueField.setText(""); hl7DomainField.setText(""); codingStrengthField.setText(""); cmetField.setText(""); userDefaultValueField.setText(""); //alter the editability display status setEditableField(dataTypeField, editableValue); setEditableField(userDefaultValueField, editableValue); } private void setEditableField(JComponent component, boolean editableValue) { if(component instanceof JTextComponent) { ((JTextComponent) component).setEditable(editableValue); } else if(component instanceof JComboBox) { ((JComboBox) component).setEditable(editableValue); } if(editableValue) { component.setBackground(defaultEditableFieldBackgroundColor); } else { component.setBackground(Config.DEFAULT_READ_ONLY_BACK_GROUND_COLOR); } } public boolean isDataChanged() { if (this.seletedBaseObject == null) { return false; } boolean result = false; if (seletedBaseObject instanceof MIFClass) { result=false; } else if (seletedBaseObject instanceof MIFAssociation) { result=false; } else if (seletedBaseObject instanceof MIFAttribute) { //check the selected concreted class MIFAttribute mifAttr=(MIFAttribute)seletedBaseObject; Datatype mifAttrDataType=mifAttr.getDatatype(); //the pre-defined type is always the first elemnt if (mifAttrDataType!=null&&mifAttrDataType.isAbstract()) { //compare the selected concrete class Datatype subClass=mifAttr.getConcreteDatatype(); if (subClass==null) result=!GeneralUtilities.areEqual(subClass, dataTypeField.getSelectedItem(), true); else result = !GeneralUtilities.areEqual(subClass.getName(), dataTypeField.getSelectedItem(), true); } else if (userDefaultValueField.isEditable()) { //check the default value result=!GeneralUtilities.areEqual(mifAttr.getDefaultValue(), userDefaultValueField.getText().trim(), true); } } else if (seletedBaseObject instanceof Attribute) { //check the default value Attribute mifDatatypeAttr=(Attribute)seletedBaseObject; result=!GeneralUtilities.areEqual(mifDatatypeAttr.getDefaultValue(), userDefaultValueField.getText(), true); Datatype attrDataType=mifDatatypeAttr.getReferenceDatatype(); String slectdDt=(String)dataTypeField.getSelectedItem(); if (slectdDt==null||slectdDt.equalsIgnoreCase("")) return result; if (attrDataType!=null&&attrDataType.isAbstract()) { //compare the selected concrete class result = !GeneralUtilities.areEqual(attrDataType.getName(), dataTypeField.getSelectedItem(), true); } } return result; } /** * Following handle some button actions */ private void applyUserChanges() { DatatypeBaseObject userDatatypeObj= this.getDatatypeObject(true);//getHl7V3Meta(true); parentPanel.getController().updateCurrentNodeWithUserObject(userDatatypeObj); //explicitly redisplay the property pane, because user could continue to work on it parentPanel.setPropertiesPaneVisible(true); } /** * Reload the data. */ public void reloadData() { // Object targetNode = getDatatypeObject(false); TreePath treePath=parentPanel.getTree().getSelectionPath(); DefaultMutableTreeNode slctdNode = (DefaultMutableTreeNode) treePath.getLastPathComponent(); this.setDisplayData(slctdNode,true); } }
package br.net.mirante.singular.form.wicket.mapper.attachment.single; import br.net.mirante.singular.form.SInstance; import br.net.mirante.singular.form.SingularFormException; import br.net.mirante.singular.form.type.core.attachment.SIAttachment; import br.net.mirante.singular.form.wicket.IAjaxUpdateListener; import br.net.mirante.singular.form.wicket.enums.ViewMode; import br.net.mirante.singular.form.wicket.mapper.ControlsFieldComponentAbstractMapper; import br.net.mirante.singular.form.wicket.mapper.attachment.DownloadLink; import br.net.mirante.singular.form.wicket.mapper.attachment.DownloadSupportedBehavior; import br.net.mirante.singular.util.wicket.bootstrap.layout.BSWellBorder; import br.net.mirante.singular.util.wicket.bootstrap.layout.TemplatePanel; import org.apache.wicket.Component; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; public class AttachmentMapper extends ControlsFieldComponentAbstractMapper { @Override @SuppressWarnings("unchecked") public Component appendInput() { final FileUploadPanel container = new FileUploadPanel("container", (IModel<SIAttachment>) model, ViewMode.EDITION); formGroup.appendDiv(container); return container.getUploadField(); } @Override public void addAjaxUpdate(Component component, IModel<SInstance> model, IAjaxUpdateListener listener) { } @Override public String getReadOnlyFormattedText(IModel<? extends SInstance> model) { throw new SingularFormException("Este metodo não deve ser acessado, para download utilizar appendReadOnlyInput"); } @Override @SuppressWarnings("unchecked") public Component appendReadOnlyInput() { String markup = ""; markup += " <div wicket:id='well'> "; markup += " <div stype='min-height: 20px; white-space: pre-wrap; word-wrap: break-word;'> "; markup += " <i class='fa fa-file'></i> "; markup += " <a wicket:id='downloadLink'></a> "; markup += " </div> "; markup += " </div> "; final BSWellBorder well = BSWellBorder.small("well"); final TemplatePanel panel = new TemplatePanel("_readOnlyAttachment", markup); final DownloadSupportedBehavior downloadSupportedBehavior = new DownloadSupportedBehavior(model); final DownloadLink downloadLink = new DownloadLink("downloadLink", (IModel<SIAttachment>) model, downloadSupportedBehavior); panel.add(downloadSupportedBehavior); well.add(downloadLink); panel.add(well); formGroup.appendTag("div", panel); return panel; } }
package org.eclipse.persistence.internal.jpa.jpql; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import org.eclipse.persistence.exceptions.JPQLException; import org.eclipse.persistence.expressions.Expression; import org.eclipse.persistence.internal.jpa.jpql.spi.JavaManagedTypeProvider; import org.eclipse.persistence.internal.sessions.AbstractSession; import org.eclipse.persistence.jpa.jpql.EclipseLinkJPQLQueryHelper; import org.eclipse.persistence.jpa.jpql.JPQLQueryProblem; import org.eclipse.persistence.jpa.jpql.JPQLQueryProblemMessages; import org.eclipse.persistence.jpa.jpql.JPQLQueryProblemResourceBundle; import org.eclipse.persistence.jpa.jpql.parser.AbstractExpressionVisitor; import org.eclipse.persistence.jpa.jpql.parser.ConditionalExpressionBNF; import org.eclipse.persistence.jpa.jpql.parser.DefaultEclipseLinkJPQLGrammar; import org.eclipse.persistence.jpa.jpql.parser.DeleteStatement; import org.eclipse.persistence.jpa.jpql.parser.JPQLExpression; import org.eclipse.persistence.jpa.jpql.parser.JPQLGrammar; import org.eclipse.persistence.jpa.jpql.parser.SelectStatement; import org.eclipse.persistence.jpa.jpql.parser.UpdateStatement; import org.eclipse.persistence.jpa.jpql.spi.IManagedTypeProvider; import org.eclipse.persistence.jpa.jpql.spi.java.JavaQuery; import org.eclipse.persistence.queries.DatabaseQuery; import org.eclipse.persistence.queries.DeleteAllQuery; import org.eclipse.persistence.queries.JPAQueryBuilder; import org.eclipse.persistence.queries.ObjectLevelReadQuery; import org.eclipse.persistence.queries.ReadAllQuery; import org.eclipse.persistence.queries.ReportQuery; import org.eclipse.persistence.queries.UpdateAllQuery; /** * The default implementation used to parse a JPQL query into a {@link DatabaseQuery}. It uses * {@link JPQLExpression} to parse the JPQL query. * * @see EclipseLinkJPQLQueryHelper * @see JPQLExpression * * @version 2.4 * @since 2.3 * @author John Bracken * @author Pascal Filion */ @SuppressWarnings("nls") public final class HermesParser implements JPAQueryBuilder { /** * Indicates whether this query builder should have validation mode on for JPQL queries. */ private boolean validateQueries; /** * Creates a new <code>HermesParser</code>. */ public HermesParser() { this(true); } /** * Creates a new {@link HermesParser}. * * @param validateQueries Determines whether JPQL queries should be validated before creating the * {@link Expression Expression} */ public HermesParser(boolean validateQueries) { super(); this.validateQueries = validateQueries; } /** * Registers the input parameters derived from the JPQL expression with the {@link DatabaseQuery}. * * @param queryContext The {@link JPQLQueryContext} containing the information about the JPQL query * @param databaseQuery The EclipseLink {@link DatabaseQuery} where the input parameter types are added */ private void addArguments(JPQLQueryContext queryContext, DatabaseQuery databaseQuery) { for (Map.Entry<String, Class<?>> inputParameters : queryContext.inputParameters()) { databaseQuery.addArgument(inputParameters.getKey().substring(1), inputParameters.getValue()); } } private IManagedTypeProvider buildProvider(AbstractSession session) { return new JavaManagedTypeProvider(session); } /** * {@inheritDoc} */ public DatabaseQuery buildQuery(String jpqlQuery, AbstractSession session) { return populateQueryImp(jpqlQuery, null, session); } /** * {@inheritDoc} */ public Expression buildSelectionCriteria(String entityName, String selectionCriteria, AbstractSession session) { // Create the parsed tree representation of the selection criteria JPQLExpression jpqlExpression = new JPQLExpression( selectionCriteria, jpqlGrammar(), ConditionalExpressionBNF.ID, validateQueries ); // Caches the info and add a virtual range variable declaration JPQLQueryContext queryContext = new JPQLQueryContext(); queryContext.cache(session, null, jpqlExpression, selectionCriteria); queryContext.addRangeVariableDeclaration(entityName, "this"); // Validate the query // Note: Currently turned off, I need to tweak validation to support JPQL fragment // validate(jpqlExpression, session, selectionCriteria); // Create the Expression representing the selection criteria return queryContext.buildExpression(jpqlExpression.getQueryStatement()); } private JPQLGrammar jpqlGrammar() { return DefaultEclipseLinkJPQLGrammar.instance(); } /** * Creates and throws a {@link JPQLException} indicating the problems with the JPQL query. * * @param queryContext The {@link JPQLQueryContext} containing the information about the JPQL query * @param problems The {@link JPQLQueryProblem problems} found in the JPQL query that are * translated into an exception * @param messageKey The key used to retrieve the localized message */ private void logProblems(JPQLQueryContext queryContext, List<JPQLQueryProblem> problems, String messageKey) { ResourceBundle bundle = ResourceBundle.getBundle(JPQLQueryProblemResourceBundle.class.getName()); StringBuilder sb = new StringBuilder(); for (int index = 0, count = problems.size(); index < count; index++) { JPQLQueryProblem problem = problems.get(index); // Create the localized message String message = bundle.getString(problem.getMessageKey()); message = MessageFormat.format(message, (Object[]) problem.getMessageArguments()); // Append the description sb.append("\n"); sb.append("["); sb.append(problem.getStartPosition()); sb.append(", "); sb.append(problem.getEndPosition()); sb.append("] "); sb.append(message); } String errorMessage = bundle.getString(messageKey); errorMessage = MessageFormat.format(errorMessage, queryContext.getJPQLQuery(), sb); throw new JPQLException(errorMessage); } /** * {@inheritDoc} */ public void populateQuery(String jpqlQuery, DatabaseQuery query, AbstractSession session) { populateQueryImp(jpqlQuery, query, session); } private DatabaseQuery populateQueryImp(String jpqlQuery, DatabaseQuery query, AbstractSession session) { // Parse the JPQL query JPQLExpression jpqlExpression = new JPQLExpression(jpqlQuery, jpqlGrammar(), validateQueries); // Create the context JPQLQueryContext queryContext = new JPQLQueryContext(); queryContext.cache(session, query, jpqlExpression, jpqlQuery); // Validate the query validate(queryContext, jpqlExpression, session, jpqlQuery); // Create the DatabaseQuery DatabaseQueryVisitor visitor = new DatabaseQueryVisitor(queryContext); jpqlExpression.accept(visitor); // Add the input parameter types to the DatabaseQuery if (query == null) { query = queryContext.getDatabaseQuery(); addArguments(queryContext, query); } return query; } /** * Grammatically and semantically validates the JPQL query. If the query is not valid, then an * exception will be thrown. */ private void validate(JPQLQueryContext queryContext, JPQLExpression expression, AbstractSession session, String jpqlQuery) { if (validateQueries) { List<JPQLQueryProblem> problems = new ArrayList<JPQLQueryProblem>(); // Create the helper EclipseLinkJPQLQueryHelper queryHelper = new EclipseLinkJPQLQueryHelper(jpqlGrammar()); queryHelper.setJPQLExpression(expression); queryHelper.setQuery(new JavaQuery(buildProvider(session), jpqlQuery)); // Validate the query using the grammar queryHelper.validateGrammar(expression, problems); if (!problems.isEmpty()) { logProblems(queryContext, problems, JPQLQueryProblemMessages.HermesParser_GrammarValidator_ErrorMessage); problems.clear(); } // Now validate the semantic of the query queryHelper.validateSemantic(expression, problems); if (!problems.isEmpty()) { logProblems(queryContext, problems, JPQLQueryProblemMessages.HermesParser_SemanticValidator_ErrorMessage); } } } /** * This visitor traverses the parsed tree and create the right EclipseLink query and populates it. */ private class DatabaseQueryVisitor extends AbstractExpressionVisitor { private final JPQLQueryContext queryContext; DatabaseQueryVisitor(JPQLQueryContext queryContext) { super(); this.queryContext = queryContext; } private ReadAllQuery buildReadAllQuery(SelectStatement expression) { ReadAllQueryBuilder visitor = new ReadAllQueryBuilder(queryContext); expression.accept(visitor); return visitor.query; } /** * {@inheritDoc} */ @Override public void visit(DeleteStatement expression) { DeleteAllQuery query = queryContext.getDatabaseQuery(); // Create and prepare the query if (query == null) { query = new DeleteAllQuery(); queryContext.setDatabasQuery(query); } query.setJPQLString(queryContext.getJPQLQuery()); query.setSession(queryContext.getSession()); query.setShouldDeferExecutionInUOW(false); // Now populate it DeleteQueryVisitor visitor = new DeleteQueryVisitor(queryContext); visitor.query = query; expression.accept(visitor); } /** * {@inheritDoc} */ @Override public void visit(JPQLExpression expression) { expression.getQueryStatement().accept(this); } /** * {@inheritDoc} */ @Override public void visit(SelectStatement expression) { ObjectLevelReadQuery query = queryContext.getDatabaseQuery(); // Create and prepare the query if (query == null) { query = buildReadAllQuery(expression); queryContext.setDatabasQuery(query); } query.setJPQLString(queryContext.getJPQLQuery()); // Now populate it if (query.isReportQuery()) { queryContext.populateReportQuery(expression, (ReportQuery) query); } else { ObjectLevelReadQueryVisitor visitor = new ObjectLevelReadQueryVisitor(queryContext); visitor.query = query; expression.accept(visitor); } } /** * {@inheritDoc} */ @Override public void visit(UpdateStatement expression) { UpdateAllQuery query = queryContext.getDatabaseQuery(); // Create and prepare the query if (query == null) { query = new UpdateAllQuery(); queryContext.setDatabasQuery(query); } query.setJPQLString(queryContext.getJPQLQuery()); query.setSession(queryContext.getSession()); query.setShouldDeferExecutionInUOW(false); // Now populate it UpdateQueryVisitor visitor = new UpdateQueryVisitor(queryContext); visitor.query = query; expression.accept(visitor); } } }