answer
stringlengths
17
10.2M
package be.ibridge.kettle.job.entry.mail; import java.nio.charset.Charset; import java.util.ArrayList; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.events.FocusListener; 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.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.Props; import be.ibridge.kettle.core.ResultFile; import be.ibridge.kettle.core.WindowProperty; import be.ibridge.kettle.core.widget.LabelText; import be.ibridge.kettle.core.widget.LabelTextVar; import be.ibridge.kettle.core.widget.TextVar; import be.ibridge.kettle.job.dialog.JobDialog; import be.ibridge.kettle.job.entry.JobEntryDialogInterface; import be.ibridge.kettle.job.entry.JobEntryInterface; import be.ibridge.kettle.trans.step.BaseStepDialog; import be.ibridge.kettle.trans.step.textfileinput.VariableButtonListenerFactory; /** * Dialog that allows you to edit a JobEntryMail object. * * @author Matt * @since 19-06-2003 */ public class JobEntryMailDialog extends Dialog implements JobEntryDialogInterface { private LabelText wName; private FormData fdName; private LabelTextVar wDestination; private LabelTextVar wDestinationCc; private LabelTextVar wDestinationBCc; private FormData fdDestination; private FormData fdDestinationCc; private FormData fdDestinationBCc; private LabelTextVar wServer; private FormData fdServer; private LabelTextVar wPort; private FormData fdPort; private Label wlUseAuth; private Button wUseAuth; private FormData fdlUseAuth, fdUseAuth; private Label wlUseSecAuth; private Button wUseSecAuth; private FormData fdlUseSecAuth, fdUseSecAuth; private LabelTextVar wAuthUser; private FormData fdAuthUser; private LabelTextVar wAuthPass; private FormData fdAuthPass; private LabelTextVar wReply; private FormData fdReply; private LabelTextVar wSubject; private FormData fdSubject; private Label wlAddDate; private Button wAddDate; private FormData fdlAddDate, fdAddDate; private Label wlIncludeFiles; private Button wIncludeFiles; private FormData fdlIncludeFiles, fdIncludeFiles; private Label wlTypes; private List wTypes; private FormData fdlTypes, fdTypes; private Label wlZipFiles; private Button wZipFiles; private FormData fdlZipFiles, fdZipFiles; private LabelTextVar wZipFilename; private FormData fdZipFilename; private LabelTextVar wPerson; private FormData fdPerson; private LabelTextVar wPhone; private FormData fdPhone; private Label wlComment; private Text wComment; private FormData fdlComment, fdComment; private Label wlOnlyComment, wlUseHTML; private Button wOnlyComment, wUseHTML; private FormData fdlOnlyComment, fdOnlyComment, fdlUseHTML, fdUseHTML; private Label wlEncoding; private CCombo wEncoding; private FormData fdlEncoding, fdEncoding; private Button wOK, wCancel; private Listener lsOK, lsCancel; private Shell shell; private SelectionAdapter lsDef; private JobEntryMail jobEntry; private boolean backupDate, backupChanged; private Props props; private Display display; private boolean gotEncodings = false; public JobEntryMailDialog(Shell parent, JobEntryMail jobEntry) { super(parent, SWT.NONE); props = Props.getInstance(); this.jobEntry = jobEntry; } public JobEntryInterface open() { Shell parent = getParent(); display = parent.getDisplay(); shell = new Shell(parent, props.getJobsDialogStyle()); props.setLook(shell); JobDialog.setShellImage(shell, jobEntry); ModifyListener lsMod = new ModifyListener() { public void modifyText(ModifyEvent e) { jobEntry.setChanged(); } }; backupChanged = jobEntry.hasChanged(); backupDate = jobEntry.getIncludeDate(); FormLayout formLayout = new FormLayout(); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout(formLayout); shell.setText(Messages.getString("JobMail.Header")); int middle = props.getMiddlePct(); int margin = Const.MARGIN; // Name line wName = new LabelText(shell, Messages.getString("JobMail.NameOfEntry.Label"), Messages .getString("JobMail.NameOfEntry.Tooltip")); wName.addModifyListener(lsMod); fdName = new FormData(); fdName.top = new FormAttachment(0, 0); fdName.left = new FormAttachment(0, 0); fdName.right = new FormAttachment(100, 0); wName.setLayoutData(fdName); // Destination line wDestination = new LabelTextVar(shell, Messages .getString("JobMail.DestinationAddress.Label"), Messages .getString("JobMail.DestinationAddress.Tooltip")); wDestination.addModifyListener(lsMod); fdDestination = new FormData(); fdDestination.left = new FormAttachment(0, 0); fdDestination.top = new FormAttachment(wName, margin); fdDestination.right = new FormAttachment(100, 0); wDestination.setLayoutData(fdDestination); // Destination Cc wDestinationCc = new LabelTextVar(shell, Messages .getString("JobMail.DestinationAddressCc.Label"), Messages .getString("JobMail.DestinationAddressCc.Tooltip")); wDestinationCc.addModifyListener(lsMod); fdDestinationCc = new FormData(); fdDestinationCc.left = new FormAttachment(0, 0); fdDestinationCc.top = new FormAttachment(wDestination, margin); fdDestinationCc.right = new FormAttachment(100, 0); wDestinationCc.setLayoutData(fdDestinationCc); // Destination BCc wDestinationBCc = new LabelTextVar(shell, Messages .getString("JobMail.DestinationAddressBCc.Label"), Messages .getString("JobMail.DestinationAddressBCc.Tooltip")); wDestinationBCc.addModifyListener(lsMod); fdDestinationBCc = new FormData(); fdDestinationBCc.left = new FormAttachment(0, 0); fdDestinationBCc.top = new FormAttachment(wDestinationCc, margin); fdDestinationBCc.right = new FormAttachment(100, 0); wDestinationBCc.setLayoutData(fdDestinationBCc); // Server line wServer = new LabelTextVar(shell, Messages.getString("JobMail.SMTPServer.Label"), Messages .getString("JobMail.SMTPServer.Tooltip")); wServer.addModifyListener(lsMod); fdServer = new FormData(); fdServer.left = new FormAttachment(0, 0); fdServer.top = new FormAttachment(wDestinationBCc, margin); fdServer.right = new FormAttachment(100, 0); wServer.setLayoutData(fdServer); // Port line wPort = new LabelTextVar(shell, Messages.getString("JobMail.Port.Label"), Messages .getString("JobMail.Port.Tooltip")); wPort.addModifyListener(lsMod); fdPort = new FormData(); fdPort.left = new FormAttachment(0, 0); fdPort.top = new FormAttachment(wServer, margin); fdPort.right = new FormAttachment(100, 0); wPort.setLayoutData(fdPort); // Include Files? wlUseAuth = new Label(shell, SWT.RIGHT); wlUseAuth.setText(Messages.getString("JobMail.UseAuthentication.Label")); props.setLook(wlUseAuth); fdlUseAuth = new FormData(); fdlUseAuth.left = new FormAttachment(0, 0); fdlUseAuth.top = new FormAttachment(wPort, margin); fdlUseAuth.right = new FormAttachment(middle, -margin); wlUseAuth.setLayoutData(fdlUseAuth); wUseAuth = new Button(shell, SWT.CHECK); props.setLook(wUseAuth); fdUseAuth = new FormData(); fdUseAuth.left = new FormAttachment(middle, margin); fdUseAuth.top = new FormAttachment(wPort, margin); fdUseAuth.right = new FormAttachment(100, 0); wUseAuth.setLayoutData(fdUseAuth); wUseAuth.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { jobEntry.setChanged(); setFlags(); } }); // AuthUser line wAuthUser = new LabelTextVar(shell, Messages.getString("JobMail.AuthenticationUser.Label"), Messages.getString("JobMail.AuthenticationUser.Tooltip")); wAuthUser.addModifyListener(lsMod); fdAuthUser = new FormData(); fdAuthUser.left = new FormAttachment(0, 0); fdAuthUser.top = new FormAttachment(wUseAuth, margin); fdAuthUser.right = new FormAttachment(100, 0); wAuthUser.setLayoutData(fdAuthUser); // AuthPass line wAuthPass = new LabelTextVar(shell, Messages .getString("JobMail.AuthenticationPassword.Label"), Messages .getString("JobMail.AuthenticationPassword.Tooltip")); wAuthPass.setEchoChar('*'); wAuthPass.addModifyListener(lsMod); fdAuthPass = new FormData(); fdAuthPass.left = new FormAttachment(0, 0); fdAuthPass.top = new FormAttachment(wAuthUser, margin); fdAuthPass.right = new FormAttachment(100, 0); wAuthPass.setLayoutData(fdAuthPass); // Use authentication? wlUseSecAuth = new Label(shell, SWT.RIGHT); wlUseSecAuth.setText(Messages.getString("JobMail.UseSecAuthentication.Label")); props.setLook(wlUseSecAuth); fdlUseSecAuth = new FormData(); fdlUseSecAuth.left = new FormAttachment(0, 0); fdlUseSecAuth.top = new FormAttachment(wAuthPass, margin); fdlUseSecAuth.right = new FormAttachment(middle, -margin); wlUseSecAuth.setLayoutData(fdlUseSecAuth); wUseSecAuth = new Button(shell, SWT.CHECK); props.setLook(wUseSecAuth); fdUseSecAuth = new FormData(); fdUseSecAuth.left = new FormAttachment(middle, margin); fdUseSecAuth.top = new FormAttachment(wAuthPass, margin); fdUseSecAuth.right = new FormAttachment(100, 0); wUseSecAuth.setLayoutData(fdUseSecAuth); wUseSecAuth.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { jobEntry.setChanged(); setFlags(); } }); // Reply line wReply = new LabelTextVar(shell, Messages.getString("JobMail.ReplyAddress.Label"), Messages .getString("JobMail.ReplyAddress.Tooltip")); wReply.addModifyListener(lsMod); fdReply = new FormData(); fdReply.left = new FormAttachment(0, 0); fdReply.top = new FormAttachment(wUseSecAuth, margin); fdReply.right = new FormAttachment(100, 0); wReply.setLayoutData(fdReply); // Subject line wSubject = new LabelTextVar(shell, Messages.getString("JobMail.Subject.Label"), Messages .getString("JobMail.Subject.Tooltip")); wSubject.addModifyListener(lsMod); fdSubject = new FormData(); fdSubject.left = new FormAttachment(0, 0); fdSubject.top = new FormAttachment(wReply, margin); fdSubject.right = new FormAttachment(100, 0); wSubject.setLayoutData(fdSubject); // Add date to logfile name? wlAddDate = new Label(shell, SWT.RIGHT); wlAddDate.setText(Messages.getString("JobMail.IncludeDate.Label")); props.setLook(wlAddDate); fdlAddDate = new FormData(); fdlAddDate.left = new FormAttachment(0, 0); fdlAddDate.top = new FormAttachment(wSubject, margin); fdlAddDate.right = new FormAttachment(middle, -margin); wlAddDate.setLayoutData(fdlAddDate); wAddDate = new Button(shell, SWT.CHECK); props.setLook(wAddDate); fdAddDate = new FormData(); fdAddDate.left = new FormAttachment(middle, margin); fdAddDate.top = new FormAttachment(wSubject, margin); fdAddDate.right = new FormAttachment(100, 0); wAddDate.setLayoutData(fdAddDate); wAddDate.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { jobEntry.setChanged(); } }); // Include Files? wlIncludeFiles = new Label(shell, SWT.RIGHT); wlIncludeFiles.setText(Messages.getString("JobMail.AttachFiles.Label")); props.setLook(wlIncludeFiles); fdlIncludeFiles = new FormData(); fdlIncludeFiles.left = new FormAttachment(0, 0); fdlIncludeFiles.top = new FormAttachment(wAddDate, margin); fdlIncludeFiles.right = new FormAttachment(middle, -margin); wlIncludeFiles.setLayoutData(fdlIncludeFiles); wIncludeFiles = new Button(shell, SWT.CHECK); props.setLook(wIncludeFiles); fdIncludeFiles = new FormData(); fdIncludeFiles.left = new FormAttachment(middle, margin); fdIncludeFiles.top = new FormAttachment(wAddDate, margin); fdIncludeFiles.right = new FormAttachment(100, 0); wIncludeFiles.setLayoutData(fdIncludeFiles); wIncludeFiles.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { jobEntry.setChanged(); setFlags(); } }); // Include Files? wlTypes = new Label(shell, SWT.RIGHT); wlTypes.setText(Messages.getString("JobMail.SelectFileTypes.Label")); props.setLook(wlTypes); fdlTypes = new FormData(); fdlTypes.left = new FormAttachment(0, 0); fdlTypes.top = new FormAttachment(wIncludeFiles, margin); fdlTypes.right = new FormAttachment(middle, -margin); wlTypes.setLayoutData(fdlTypes); wTypes = new List(shell, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); props.setLook(wTypes); fdTypes = new FormData(); fdTypes.left = new FormAttachment(middle, margin); fdTypes.top = new FormAttachment(wIncludeFiles, margin); fdTypes.bottom = new FormAttachment(wIncludeFiles, margin + 150); fdTypes.right = new FormAttachment(100, 0); wTypes.setLayoutData(fdTypes); for (int i = 0; i < ResultFile.getAllTypeDesc().length; i++) { wTypes.add(ResultFile.getAllTypeDesc()[i]); } // Zip Files? wlZipFiles = new Label(shell, SWT.RIGHT); wlZipFiles.setText(Messages.getString("JobMail.ZipFiles.Label")); props.setLook(wlZipFiles); fdlZipFiles = new FormData(); fdlZipFiles.left = new FormAttachment(0, 0); fdlZipFiles.top = new FormAttachment(wTypes, margin); fdlZipFiles.right = new FormAttachment(middle, -margin); wlZipFiles.setLayoutData(fdlZipFiles); wZipFiles = new Button(shell, SWT.CHECK); props.setLook(wZipFiles); fdZipFiles = new FormData(); fdZipFiles.left = new FormAttachment(middle, margin); fdZipFiles.top = new FormAttachment(wTypes, margin); fdZipFiles.right = new FormAttachment(100, 0); wZipFiles.setLayoutData(fdZipFiles); wZipFiles.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { jobEntry.setChanged(); setFlags(); } }); // ZipFilename line wZipFilename = new LabelTextVar(shell, Messages.getString("JobMail.ZipFilename.Label"), Messages.getString("JobMail.ZipFilename.Tooltip")); wZipFilename.addModifyListener(lsMod); fdZipFilename = new FormData(); fdZipFilename.left = new FormAttachment(0, 0); fdZipFilename.top = new FormAttachment(wZipFiles, margin); fdZipFilename.right = new FormAttachment(100, 0); wZipFilename.setLayoutData(fdZipFilename); // ZipFilename line wPerson = new LabelTextVar(shell, Messages.getString("JobMail.ContactPerson.Label"), Messages.getString("JobMail.ContactPerson.Tooltip")); wPerson.addModifyListener(lsMod); fdPerson = new FormData(); fdPerson.left = new FormAttachment(0, 0); fdPerson.top = new FormAttachment(wZipFilename, margin); fdPerson.right = new FormAttachment(100, 0); wPerson.setLayoutData(fdPerson); // Phone line wPhone = new LabelTextVar(shell, Messages.getString("JobMail.ContactPhone.Label"), Messages .getString("JobMail.ContactPhone.Tooltip")); wPhone.addModifyListener(lsMod); fdPhone = new FormData(); fdPhone.left = new FormAttachment(0, 0); fdPhone.top = new FormAttachment(wPerson, margin); fdPhone.right = new FormAttachment(100, 0); wPhone.setLayoutData(fdPhone); // Some buttons wOK = new Button(shell, SWT.PUSH); wOK.setText(Messages.getString("System.Button.OK")); wCancel = new Button(shell, SWT.PUSH); wCancel.setText(Messages.getString("System.Button.Cancel")); BaseStepDialog.positionBottomButtons(shell, new Button[] { wOK, wCancel }, margin, null); // Only send the comment in the mail body wlOnlyComment = new Label(shell, SWT.RIGHT); wlOnlyComment.setText(Messages.getString("JobMail.OnlyCommentInBody.Label")); props.setLook(wlOnlyComment); fdlOnlyComment = new FormData(); fdlOnlyComment.left = new FormAttachment(0, 0); fdlOnlyComment.bottom = new FormAttachment(wOK, -margin * 2); fdlOnlyComment.right = new FormAttachment(middle, -margin); wlOnlyComment.setLayoutData(fdlOnlyComment); wOnlyComment = new Button(shell, SWT.CHECK); props.setLook(wOnlyComment); fdOnlyComment = new FormData(); fdOnlyComment.left = new FormAttachment(middle, margin); fdOnlyComment.bottom = new FormAttachment(wOK, -margin * 2); fdOnlyComment.right = new FormAttachment(100, 0); wOnlyComment.setLayoutData(fdOnlyComment); wOnlyComment.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { jobEntry.setChanged(); } }); // Encoding wlEncoding=new Label(shell, SWT.RIGHT); wlEncoding.setText(Messages.getString("JobMail.Encoding.Label")); props.setLook(wlEncoding); fdlEncoding=new FormData(); fdlEncoding.left = new FormAttachment(0, 0); fdlEncoding.bottom = new FormAttachment(wOnlyComment, -margin); fdlEncoding.right= new FormAttachment(middle, -margin); wlEncoding.setLayoutData(fdlEncoding); wEncoding=new CCombo(shell, SWT.BORDER | SWT.READ_ONLY); wEncoding.setEditable(true); props.setLook(wEncoding); wEncoding.addModifyListener(lsMod); fdEncoding=new FormData(); fdEncoding.left = new FormAttachment(middle, margin); fdEncoding.bottom = new FormAttachment(wOnlyComment,-margin); fdEncoding.right= new FormAttachment(100, 0); wEncoding.setLayoutData(fdEncoding); wEncoding.addFocusListener(new FocusListener() { public void focusLost(org.eclipse.swt.events.FocusEvent e) { } public void focusGained(org.eclipse.swt.events.FocusEvent e) { Cursor busy = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT); shell.setCursor(busy); setEncodings(); shell.setCursor(null); busy.dispose(); } } ); // HTML format ? wlUseHTML = new Label(shell, SWT.RIGHT); wlUseHTML.setText(Messages.getString("JobMail.UseHTMLInBody.Label")); props.setLook(wlUseHTML); fdlUseHTML = new FormData(); fdlUseHTML.left = new FormAttachment(0, 0); fdlUseHTML.bottom = new FormAttachment(wEncoding, -margin ); fdlUseHTML.right = new FormAttachment(middle, -margin); wlUseHTML.setLayoutData(fdlUseHTML); wUseHTML = new Button(shell, SWT.CHECK); props.setLook(wUseHTML); fdUseHTML = new FormData(); fdUseHTML.left = new FormAttachment(middle, margin); fdUseHTML.bottom = new FormAttachment(wEncoding, -margin ); fdUseHTML.right = new FormAttachment(100, 0); wUseHTML.setLayoutData(fdUseHTML); wUseHTML.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { SetEnabledEncoding(); jobEntry.setChanged(); } }); // Comment line wlComment = new Label(shell, SWT.RIGHT); wlComment.setText(Messages.getString("JobMail.Comment.Label")); props.setLook(wlComment); fdlComment = new FormData(); fdlComment.left = new FormAttachment(0, 0); fdlComment.top = new FormAttachment(wPhone, margin); fdlComment.right = new FormAttachment(middle, margin); wlComment.setLayoutData(fdlComment); wComment = new Text(shell, SWT.MULTI | SWT.LEFT | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); props.setLook(wComment); wComment.addModifyListener(lsMod); fdComment = new FormData(); fdComment.left = new FormAttachment(middle, margin); fdComment.top = new FormAttachment(wPhone, margin); fdComment.right = new FormAttachment(100, 0); fdComment.bottom = new FormAttachment(wUseHTML, -margin); wComment.setLayoutData(fdComment); SelectionAdapter lsVar = VariableButtonListenerFactory.getSelectionAdapter(shell, wComment); wComment.addKeyListener(TextVar.getControlSpaceKeyListener(wComment, lsVar)); // Add listeners lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } }; lsOK = new Listener() { public void handleEvent(Event e) { ok(); } }; wOK.addListener(SWT.Selection, lsOK); wCancel.addListener(SWT.Selection, lsCancel); lsDef = new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } }; wName.addSelectionListener(lsDef); wServer.addSelectionListener(lsDef); wSubject.addSelectionListener(lsDef); wDestination.addSelectionListener(lsDef); wDestinationCc.addSelectionListener(lsDef); wDestinationBCc.addSelectionListener(lsDef); wReply.addSelectionListener(lsDef); wPerson.addSelectionListener(lsDef); wPhone.addSelectionListener(lsDef); wZipFilename.addSelectionListener(lsDef); // Detect [X] or ALT-F4 or something that kills this window... shell.addShellListener(new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } }); // BaseStepDialog.setTraverseOrder(new Control[] {wName, wDestination, wServer, wUseAuth, // wAuthUser, wAuthPass, wReply, // wSubject, wAddDate, wIncludeFiles, wTypes, wZipFiles, wZipFilename, wPerson, wPhone, // wComment, wOK, wCancel }); getData(); SetEnabledEncoding(); BaseStepDialog.setSize(shell); shell.open(); props.setDialogSize(shell, "JobMailDialogSize"); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } return jobEntry; } private void SetEnabledEncoding () { wEncoding.setEnabled(wUseHTML.getSelection()); wlEncoding.setEnabled(wUseHTML.getSelection()); } protected void setFlags() { wlTypes.setEnabled(wIncludeFiles.getSelection()); wTypes.setEnabled(wIncludeFiles.getSelection()); wlZipFiles.setEnabled(wIncludeFiles.getSelection()); wZipFiles.setEnabled(wIncludeFiles.getSelection()); wZipFilename.setEnabled(wIncludeFiles.getSelection() && wZipFiles.getSelection()); wAuthUser.setEnabled(wUseAuth.getSelection()); wAuthPass.setEnabled(wUseAuth.getSelection()); wUseSecAuth.setEnabled(wUseAuth.getSelection()); } public void dispose() { WindowProperty winprop = new WindowProperty(shell); props.setScreen(winprop); shell.dispose(); } public void getData() { if (jobEntry.getName() != null) wName.setText(jobEntry.getName()); if (jobEntry.getDestination() != null) wDestination.setText(jobEntry.getDestination()); if (jobEntry.getDestinationCc() != null) wDestinationCc.setText(jobEntry.getDestinationCc()); if (jobEntry.getDestinationBCc() != null) wDestinationBCc.setText(jobEntry.getDestinationBCc()); if (jobEntry.getServer() != null) wServer.setText(jobEntry.getServer()); if (jobEntry.getPort() != null) wPort.setText(jobEntry.getPort()); if (jobEntry.getReplyAddress() != null) wReply.setText(jobEntry.getReplyAddress()); if (jobEntry.getSubject() != null) wSubject.setText(jobEntry.getSubject()); if (jobEntry.getContactPerson() != null) wPerson.setText(jobEntry.getContactPerson()); if (jobEntry.getContactPhone() != null) wPhone.setText(jobEntry.getContactPhone()); if (jobEntry.getComment() != null) wComment.setText(jobEntry.getComment()); wAddDate.setSelection(jobEntry.getIncludeDate()); wIncludeFiles.setSelection(jobEntry.isIncludingFiles()); if (jobEntry.getFileType() != null) { int types[] = jobEntry.getFileType(); wTypes.setSelection(types); } wZipFiles.setSelection(jobEntry.isZipFiles()); if (jobEntry.getZipFilename() != null) wZipFilename.setText(jobEntry.getZipFilename()); wUseAuth.setSelection(jobEntry.isUsingAuthentication()); wUseSecAuth.setSelection(jobEntry.isUsingSecureAuthentication()); if (jobEntry.getAuthenticationUser() != null) wAuthUser.setText(jobEntry.getAuthenticationUser()); if (jobEntry.getAuthenticationPassword() != null) wAuthPass.setText(jobEntry.getAuthenticationPassword()); wOnlyComment.setSelection(jobEntry.isOnlySendComment()); wUseHTML.setSelection(jobEntry.isUseHTML()); if (jobEntry.getEncoding()!=null) { wEncoding.setText(""+jobEntry.getEncoding()); }else { wEncoding.setText("UTF-8"); } setFlags(); } private void cancel() { jobEntry.setChanged(backupChanged); jobEntry.setIncludeDate(backupDate); jobEntry = null; dispose(); } private void ok() { jobEntry.setName(wName.getText()); jobEntry.setDestination(wDestination.getText()); jobEntry.setDestinationCc(wDestinationCc.getText()); jobEntry.setDestinationBCc(wDestinationBCc.getText()); jobEntry.setServer(wServer.getText()); jobEntry.setPort(wPort.getText()); jobEntry.setReplyAddress(wReply.getText()); jobEntry.setSubject(wSubject.getText()); jobEntry.setContactPerson(wPerson.getText()); jobEntry.setContactPhone(wPhone.getText()); jobEntry.setComment(wComment.getText()); jobEntry.setIncludeDate(wAddDate.getSelection()); jobEntry.setIncludingFiles(wIncludeFiles.getSelection()); jobEntry.setFileType(wTypes.getSelectionIndices()); jobEntry.setZipFilename(wZipFilename.getText()); jobEntry.setZipFiles(wZipFiles.getSelection()); jobEntry.setAuthenticationUser(wAuthUser.getText()); jobEntry.setAuthenticationPassword(wAuthPass.getText()); jobEntry.setUsingAuthentication(wUseAuth.getSelection()); jobEntry.setUsingSecureAuthentication(wUseSecAuth.getSelection()); jobEntry.setOnlySendComment(wOnlyComment.getSelection()); jobEntry.setUseHTML(wUseHTML.getSelection()); jobEntry.setEncoding(wEncoding.getText()); dispose(); } private void setEncodings() { // Encoding of the text file: if (!gotEncodings) { gotEncodings = true; wEncoding.removeAll(); ArrayList values = new ArrayList(Charset.availableCharsets().values()); for (int i=0;i<values.size();i++) { Charset charSet = (Charset)values.get(i); wEncoding.add( charSet.displayName() ); } // Now select the default! String defEncoding = Const.getEnvironmentVariable("file.encoding", "UTF-8"); int idx = Const.indexOfString(defEncoding, wEncoding.getItems() ); if (idx>=0) wEncoding.select( idx ); } } }
package chameleon.core.type.inheritance; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.log4j.Logger; import org.rejuse.association.SingleAssociation; import org.rejuse.logic.ternary.Ternary; import chameleon.core.declaration.Signature; import chameleon.core.element.ChameleonProgrammerException; import chameleon.core.element.Element; import chameleon.core.element.ElementImpl; import chameleon.core.lookup.DeclarationSelector; import chameleon.core.lookup.LookupException; import chameleon.core.member.Member; import chameleon.core.type.Type; import chameleon.core.type.TypeReference; import chameleon.core.validation.BasicProblem; import chameleon.core.validation.Valid; import chameleon.core.validation.VerificationResult; import chameleon.oo.language.ObjectOrientedLanguage; public abstract class InheritanceRelation<E extends InheritanceRelation> extends ElementImpl<E,Type> { private static Logger logger = Logger.getLogger("lookup.inheritance"); public Logger lookupLogger() { return logger; } public abstract E clone(); public InheritanceRelation(TypeReference ref) { setSuperClassReference(ref); } public List<? extends Element> children() { List<Element> result = new ArrayList<Element>(); result.add(superClassReference()); return result; } /** * Return the inherited class. * @return * @throws LookupException */ /*@ @ public behavior @ @ post \result == superClassReference().getType(); @*/ public Type superClass() throws LookupException { lookupLogger().debug("Inheritance relation of class "+parent().getFullyQualifiedName()+" is going to look up super class " + superClassReference().getName()); Type result = null; try { result = superClassReference().getType(); } catch(NullPointerException exc) { if(superClassReference() == null) { throw new ChameleonProgrammerException("trying to get the super class of an inheritance relation that points to null in class" + parent().getFullyQualifiedName(),exc); } else { throw exc; } } if(result != null) { return result; } else { throw new LookupException("Superclass is null",superClassReference()); } } /** * Return the inherited type, if this relation also introduces a subtype relation. * @return * @throws LookupException */ /*@ @ public behavior @ @ post \result == null || \result == superClass(); @*/ public abstract Type superType() throws LookupException; /** * Return a reference to the inherited class. * @return */ public TypeReference superClassReference() { return _superClass.getOtherEnd(); } /*@ @ public behavior @ @ post superClassReference() == ref; @*/ public void setSuperClassReference(TypeReference ref) { if(ref != null) { _superClass.connectTo(ref.parentLink()); } else { _superClass.connectTo(null); } } /** * Return the set of members inherited through this inheritance relation. * @param <M> * @param <S> * @param <F> * @param kind * @return * @throws LookupException */ public <M extends Member<M,? super Type,S,F>, S extends Signature<S,M>, F extends Member<? extends Member,? super Type,S,F>> void accumulateInheritedMembers(final Class<M> kind, List<M> current) throws LookupException { final List<M> potential = potentiallyInheritedMembers(kind); removeNonMostSpecificMembers(current, potential); } public <M extends Member<M,? super Type,S,F>, S extends Signature<S,M>, F extends Member<? extends Member,? super Type,S,F>> void accumulateInheritedMembers(DeclarationSelector<M> selector, List<M> current) throws LookupException { final List<M> potential = potentiallyInheritedMembers(selector); removeNonMostSpecificMembers(current, potential); } private <M extends Member<M,? super Type,S,F>, S extends Signature<S,M>, F extends Member<? extends Member,? super Type,S,F>> void removeNonMostSpecificMembers(List<M> current, final List<M> potential) throws LookupException { final List<M> toAdd = new ArrayList<M>(); for(M m: potential) { boolean add = true; Iterator<M> iterCurrent = current.iterator(); while(add && iterCurrent.hasNext()) { M alreadyInherited = iterCurrent.next(); // Remove the already inherited member if potentially inherited member m overrides or hides it. if((alreadyInherited != m) && (m.overrides(alreadyInherited) || m.canImplement(alreadyInherited) || m.hides(alreadyInherited))) { iterCurrent.remove(); } if(add == true && ((alreadyInherited == m) || alreadyInherited.overrides(m) || alreadyInherited.equivalentTo(m) || alreadyInherited.canImplement(m) || alreadyInherited.hides(m))) { add = false; } } if(add == true) { toAdd.add(m); } } current.addAll(toAdd); } public <M extends Member<M,? super Type,S,F>, S extends Signature<S,M>, F extends Member<? extends Member,? super Type,S,F>> List<M> potentiallyInheritedMembers(final Class<M> kind) throws LookupException { List<M> superMembers = superClass().members(kind); removeNonInheritableMembers(superMembers); return superMembers; } public <M extends Member<M, ? super Type, S, F>, S extends Signature<S, M>, F extends Member<?, ? super Type, S, F>> List<M> potentiallyInheritedMembers( final DeclarationSelector<M> selector) throws LookupException { List<M> superMembers = superClass().members(selector); removeNonInheritableMembers(superMembers); return superMembers; } /** * Remove members that are not inheritable. */ /*@ @ public behavior @ @ (\forall M m; members.contains(m); \old(members()).contains(m) && m.is(language(ObjectOrientedLanguage.class).INHERITABLE == Ternary.TRUE); @*/ private <M extends Member<M, ? super Type, S, F>, S extends Signature<S, M>, F extends Member<?, ? super Type, S, F>> void removeNonInheritableMembers(List<M> members) throws LookupException { Iterator<M> superIter = members.iterator(); while(superIter.hasNext()) { M member = superIter.next(); Ternary temp = member.is(language(ObjectOrientedLanguage.class).INHERITABLE); if (temp == Ternary.UNKNOWN) { temp = member.is(language(ObjectOrientedLanguage.class).INHERITABLE); throw new LookupException("For one of the members of super type " + superClass().getFullyQualifiedName() + " it is unknown whether it is inheritable or not. Member type: " + member.getClass().getName()); } else { if (temp == Ternary.FALSE) { superIter.remove(); } } } } // public <M extends Member<M,? super Type,S,F>, S extends Signature<S,M>, F extends Member<? extends Member,? super Type,S,F>> // M transform(M member) throws MetamodelException { // M result = member.clone(); // // 1) SUBSTITUTE GENERIC PARAMETERS, OR USE TRICK CONTAINER? // // 1.a) WE NEED A TRICK CONTAINER (The superclass) IN WHICH THE PARAMETERS ARE SUBSTITUTED private SingleAssociation<InheritanceRelation,TypeReference> _superClass = new SingleAssociation<InheritanceRelation, TypeReference>(this); }
package com.dmdirc.commandparser.commands.channel; import com.dmdirc.Topic; import com.dmdirc.commandparser.BaseCommandInfo; import com.dmdirc.commandparser.CommandArguments; import com.dmdirc.commandparser.CommandInfo; import com.dmdirc.commandparser.CommandType; import com.dmdirc.commandparser.commands.Command; import com.dmdirc.commandparser.commands.CommandOptions; import com.dmdirc.commandparser.commands.ExternalCommand; import com.dmdirc.commandparser.commands.context.ChannelCommandContext; import com.dmdirc.commandparser.commands.context.CommandContext; import com.dmdirc.events.ChannelGotTopicEvent; import com.dmdirc.events.ChannelNoTopicEvent; import com.dmdirc.interfaces.CommandController; import com.dmdirc.interfaces.Connection; import com.dmdirc.interfaces.GroupChat; import com.dmdirc.interfaces.GroupChatUser; import com.dmdirc.interfaces.User; import com.dmdirc.interfaces.WindowModel; import java.util.Optional; import javax.annotation.Nonnull; import javax.inject.Inject; /** * The show topic command shows the user the current topic. */ @CommandOptions(allowOffline = false) public class ShowTopic extends Command implements ExternalCommand { /** A command info object for this command. */ public static final CommandInfo INFO = new BaseCommandInfo("topic", "topic - displays the current topic\ntopic <newtopic> - sets the channel topic", CommandType.TYPE_CHANNEL); /** * Creates a new instance of this command. * * @param controller The controller to use for command information. */ @Inject public ShowTopic(final CommandController controller) { super(controller); } @Override public void execute(@Nonnull final WindowModel origin, final CommandArguments args, final CommandContext context) { final GroupChat channel = ((ChannelCommandContext) context).getGroupChat(); if (args.getArguments().length == 0) { final Optional<Topic> topic = channel.getCurrentTopic(); if (topic.isPresent()) { final User user = topic .flatMap(Topic::getClient) .map(GroupChatUser::getUser) .orElse(null); channel.getEventBus().publishAsync( new ChannelGotTopicEvent(channel, topic.get(), user)); } else { channel.getEventBus().publishAsync( new ChannelNoTopicEvent(channel)); } } else { channel.setTopic(args.getArgumentsAsString()); } } @Override public void execute(final WindowModel origin, final Connection connection, final String channel, final boolean isSilent, final CommandArguments args) { if (args.getArguments().length == 0) { connection.getParser().get().sendRawMessage("TOPIC " + channel); } else { connection.getParser().get().sendRawMessage("TOPIC " + channel + " :" + args. getArgumentsAsString()); } } }
package edu.washington.escience.myria.accessmethod; import java.util.Iterator; import edu.washington.escience.myria.DbException; import edu.washington.escience.myria.MyriaConstants; import edu.washington.escience.myria.RelationKey; import edu.washington.escience.myria.Schema; import edu.washington.escience.myria.TupleBatch; /** * Interface for Database Access Methods. * * @author valmeida * */ public abstract class AccessMethod { /** * Factory. * * @param dbms the DBMS * @param connectionInfo the connection info * @param readOnly the flag for read-only * @return the object of type AccessMethod * @throws DbException if anything goes wrong on connecting */ public static AccessMethod of(final String dbms, final ConnectionInfo connectionInfo, final Boolean readOnly) throws DbException { switch (dbms) { case MyriaConstants.STORAGE_SYSTEM_SQLITE: return new SQLiteAccessMethod((SQLiteInfo) connectionInfo, readOnly); case MyriaConstants.STORAGE_SYSTEM_MONETDB: case MyriaConstants.STORAGE_SYSTEM_MYSQL: case MyriaConstants.STORAGE_SYSTEM_VERTICA: return new JdbcAccessMethod((JdbcInfo) connectionInfo, readOnly); } return null; } /** * Connects with the database. * * @param connectionInfo connection information * @param readOnly whether read-only connection or not * @throws DbException if there is an error making the connection. */ abstract void connect(final ConnectionInfo connectionInfo, final Boolean readOnly) throws DbException; /** * Sets the connection to be read-only or writable. * * @param readOnly whether read-only connection or not * @throws DbException if there is an error making the connection. */ abstract void setReadOnly(final Boolean readOnly) throws DbException; /** * Insert the tuples in this TupleBatch into the database. * * @param insertString the insert statement. * @param tupleBatch the tupleBatch to be inserted * @throws DbException if there is an error inserting the tuples. */ public abstract void tupleBatchInsert(final String insertString, final TupleBatch tupleBatch) throws DbException; /** * Runs a query and expose the results as an Iterator<TupleBatch>. * * @param queryString the query * @param schema the output schema (with SQLite we are not able to reconstruct the schema from the API) * @return an Iterator<TupleBatch> containing the results. * @throws DbException if there is an error getting tuples. */ public abstract Iterator<TupleBatch> tupleBatchIteratorFromQuery(final String queryString, final Schema schema) throws DbException; /** * Executes a DDL command. * * @param ddlCommand the DDL command * @throws DbException if there is an error in the database. */ abstract void execute(final String ddlCommand) throws DbException; /** * Closes the database connection. * * @throws DbException if there is an error in the database. */ public abstract void close() throws DbException; /** * Perform some initialization steps for the specific database system. * * @throws DbException if there is an error in the database. */ public void init() throws DbException { } /** * Generates the insert statement string for a relation in the database. * * @param schema the relation schema * @param relationKey the relation name * @return the insert statement string */ public abstract String insertStatementFromSchema(Schema schema, RelationKey relationKey); /** * Generates the create table statement string for a relation in the database. * * @param schema the relation schema * @param relationKey the relation name * @return the create table statement string */ public abstract String createStatementFromSchema(Schema schema, RelationKey relationKey); /** * Creates a table into the database. * * @param relationKey the relation name * @param schema the relation schema * @param overwriteTable a flag to overwrite the table or not * @throws DbException if anything goes wrong */ public abstract void createTable(RelationKey relationKey, Schema schema, boolean overwriteTable) throws DbException; }
package com.frc2013.rmr662.manipulator; import com.frc2013.rmr662.main.TeleopMode; import com.frc2013.rmr662.system.generic.Component; import com.frc2013.rmr662.wrappers.Button; import com.frc2013.rmr662.wrappers.RMRSolenoid; import edu.wpi.first.wpilibj.DoubleSolenoid; import edu.wpi.first.wpilibj.Joystick; public class PneumaticManipulator extends Component { // Constants private static final int WING_CHANNEL_EXTEND = 2; private static final int WING_CHANNEL_RETRACT = 3; private static final int DUMPER_CHANNEL = 1; private static final int TILT_CHANNEL_EXTEND = 4; private static final int TILT_CHANNEL_RETRACT = 5; private static final int WING_BUTTON = 5; private static final int DUMPER_BUTTON = 3; private static final int TILT_BUTTON = 1; // Fields private final Joystick controller; private final Button tiltButton; private final DoubleSolenoid winglenoid; private boolean wingTarget = false; private boolean wingState = false; private final RMRSolenoid dumplenoid; private boolean dumpState = false; private final DoubleSolenoid tiltlenoid; // Constructor public PneumaticManipulator() { winglenoid = new DoubleSolenoid(WING_CHANNEL_EXTEND, WING_CHANNEL_RETRACT); dumplenoid = new RMRSolenoid(DUMPER_CHANNEL, false); tiltlenoid = new DoubleSolenoid(TILT_CHANNEL_EXTEND, TILT_CHANNEL_RETRACT); controller = new Joystick(TeleopMode.XBOX_JOYSTICK_PORT); tiltButton = new Button(controller, TILT_BUTTON); } // Implemented (from superclass) methods protected void onBegin() { winglenoid.set(DoubleSolenoid.Value.kOff); tiltlenoid.set(DoubleSolenoid.Value.kReverse); dumplenoid.set(false); } protected void update() { // Called repeatedly // Wing wingTarget = controller.getRawButton(WING_BUTTON); if (wingTarget && !wingState) { winglenoid.set(DoubleSolenoid.Value.kForward); wingState = true; } else if (!wingTarget && wingState) { winglenoid.set(DoubleSolenoid.Value.kReverse); wingState = false; } // Dumping boolean dumperTarget = controller.getRawButton(DUMPER_BUTTON); if (dumpState != dumperTarget) { dumplenoid.set(dumperTarget); dumpState = dumperTarget; } // Tilt if (tiltButton.wasPressed()) { // Toggle piston state DoubleSolenoid.Value currentState = tiltlenoid.get(); if (currentState == DoubleSolenoid.Value.kForward) { tiltlenoid.set(DoubleSolenoid.Value.kReverse); } else { tiltlenoid.set(DoubleSolenoid.Value.kForward); } } } protected void onEnd() { // Called when robot is disabled. // Be sure to set hardware elements to safe states. dumplenoid.set(false); dumplenoid.free(); tiltlenoid.free(); winglenoid.free(); } }
package com.firebase.ui; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.firebase.client.Firebase; import com.firebase.client.Query; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public abstract class FirebaseRecyclerViewAdapter<T, VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> { Class<T> mModelClass; protected int mModelLayout; Class<VH> mViewHolderClass; FirebaseArray mSnapshots; /** * @param modelClass Firebase will marshall the data at a location into an instance of a class that you provide * @param modelLayout This is the layout used to represent a single item in the list. You will be responsible for populating an * instance of the corresponding view with the data from an instance of modelClass. * @param viewHolderClass The class that hold references to all sub-views in an instance modelLayout. * @param ref The Firebase location to watch for data changes. Can also be a slice of a location, using some * combination of <code>limit()</code>, <code>startAt()</code>, and <code>endAt()</code> */ public FirebaseRecyclerViewAdapter(Class<T> modelClass, int modelLayout, Class<VH> viewHolderClass, Query ref) { mModelClass = modelClass; mModelLayout = modelLayout; mViewHolderClass = viewHolderClass; mSnapshots = new FirebaseArray(ref); mSnapshots.setOnChangedListener(new FirebaseArray.OnChangedListener() { @Override public void onChanged(EventType type, int index, int oldIndex) { switch (type) { case Added: notifyItemInserted(index); break; case Changed: notifyItemChanged(index); break; case Removed: notifyItemRemoved(index); break; case Moved: notifyItemMoved(oldIndex, index); break; default: throw new IllegalStateException("Incomplete case statement"); } } }); } /** * @param modelClass Firebase will marshall the data at a location into an instance of a class that you provide * @param modelLayout This is the layout used to represent a single item in the list. You will be responsible for populating an * instance of the corresponding view with the data from an instance of modelClass. * @param viewHolderClass The class that hold references to all sub-views in an instance modelLayout. * @param ref The Firebase location to watch for data changes. Can also be a slice of a location, using some * combination of <code>limit()</code>, <code>startAt()</code>, and <code>endAt()</code> */ public FirebaseRecyclerViewAdapter(Class<T> modelClass, int modelLayout, Class<VH> viewHolderClass, Firebase ref) { this(modelClass, modelLayout, viewHolderClass, (Query)ref); } public void cleanup() { mSnapshots.cleanup(); } @Override public int getItemCount() { return mSnapshots.getCount(); } public T getItem(int position) { return mSnapshots.getItem(position).getValue(mModelClass); } public Firebase getRef(int position) { return mSnapshots.getItem(position).getRef(); } @Override public long getItemId(int position) { return mSnapshots.getItem(position).getKey().hashCode(); } @Override public VH onCreateViewHolder(ViewGroup parent, int viewType) { ViewGroup view = (ViewGroup) LayoutInflater.from(parent.getContext()).inflate(mModelLayout, parent, false); try { Constructor<VH> constructor = mViewHolderClass.getConstructor(View.class); return constructor.newInstance(view); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } @Override public void onBindViewHolder(VH viewHolder, int i) { T model = getItem(i); populateViewHolder(viewHolder, model); } abstract public void populateViewHolder(VH viewHolder, T model); }
package com.mebigfatguy.fbcontrib.collect; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.bcel.Constants; import org.apache.bcel.classfile.AnnotationEntry; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import com.mebigfatguy.fbcontrib.utils.CollectionUtils; import com.mebigfatguy.fbcontrib.utils.QMethod; import com.mebigfatguy.fbcontrib.utils.SignatureBuilder; import com.mebigfatguy.fbcontrib.utils.SignatureUtils; import com.mebigfatguy.fbcontrib.utils.UnmodifiableSet; import com.mebigfatguy.fbcontrib.utils.Values; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.BytecodeScanningDetector; import edu.umd.cs.findbugs.NonReportingDetector; import edu.umd.cs.findbugs.OpcodeStack; import edu.umd.cs.findbugs.ba.ClassContext; /** * a first pass detector to collect various statistics used in second pass detectors. */ public class CollectStatistics extends BytecodeScanningDetector implements NonReportingDetector { private static final Set<String> COMMON_METHOD_SIG_PREFIXES = UnmodifiableSet.create( //@formatter:off new SignatureBuilder().withMethodName(Values.CONSTRUCTOR).toString(), new SignatureBuilder().withMethodName("toString").withReturnType(Values.SLASHED_JAVA_LANG_STRING).toString(), new SignatureBuilder().withMethodName("hashCode").withReturnType(Values.SIG_PRIMITIVE_INT).toString(), "clone()", "values()", new SignatureBuilder().withMethodName("main").withParamTypes(Values.SIG_ARRAY_PREFIX + Values.SLASHED_JAVA_LANG_STRING).toString() //@formatter:on ); private int numMethodCalls; private boolean modifiesState; private boolean classHasAnnotation; private OpcodeStack stack; private Map<QMethod, Set<CalledMethod>> selfCallTree; private QMethod curMethod; /** * constructs a CollectStatistics detector which clears the singleton that holds the statistics for all classes parsed in the first pass. * * @param bugReporter * unused, but required by reflection contract */ public CollectStatistics(BugReporter bugReporter) { Statistics.getStatistics().clear(); } /** * implements the visitor to collect statistics on this class * * @param classContext * the currently class */ @Override public void visitClassContext(ClassContext classContext) { try { JavaClass cls = classContext.getJavaClass(); AnnotationEntry[] annotations = cls.getAnnotationEntries(); classHasAnnotation = !CollectionUtils.isEmpty(annotations); stack = new OpcodeStack(); selfCallTree = new HashMap<>(); super.visitClassContext(classContext); performModifyStateClosure(classContext.getJavaClass()); } finally { stack = null; selfCallTree = null; curMethod = null; } } @Override public void visitCode(Code obj) { numMethodCalls = 0; modifiesState = false; byte[] code = obj.getCode(); if (code == null) { return; } stack.resetForMethodEntry(this); curMethod = null; super.visitCode(obj); String clsName = getClassName(); Method method = getMethod(); int accessFlags = method.getAccessFlags(); MethodInfo mi = Statistics.getStatistics().addMethodStatistics(clsName, getMethodName(), getMethodSig(), accessFlags, obj.getLength(), numMethodCalls); if (clsName.contains("$") || ((accessFlags & (ACC_ABSTRACT | ACC_INTERFACE | ACC_ANNOTATION)) != 0)) { mi.addCallingAccess(Constants.ACC_PUBLIC); } else if ((accessFlags & Constants.ACC_PRIVATE) == 0) { if (isAssociationedWithAnnotations(method)) { mi.addCallingAccess(Constants.ACC_PUBLIC); } else { String methodSig = getMethodName() + getMethodSig(); for (String sig : COMMON_METHOD_SIG_PREFIXES) { if (methodSig.startsWith(sig)) { mi.addCallingAccess(Constants.ACC_PUBLIC); break; } } } } mi.setModifiesState(modifiesState); } @Override public void sawOpcode(int seen) { try { switch (seen) { case INVOKEVIRTUAL: case INVOKEINTERFACE: case INVOKESPECIAL: case INVOKESTATIC: case INVOKEDYNAMIC: numMethodCalls++; if (seen != INVOKESTATIC) { int numParms = SignatureUtils.getNumParameters(getSigConstantOperand()); if (stack.getStackDepth() > numParms) { OpcodeStack.Item itm = stack.getStackItem(numParms); if (itm.getRegisterNumber() == 0) { Set<CalledMethod> calledMethods; if (curMethod == null) { curMethod = new QMethod(getMethodName(), getMethodSig()); calledMethods = new HashSet<>(); selfCallTree.put(curMethod, calledMethods); } else { calledMethods = selfCallTree.get(curMethod); } calledMethods.add(new CalledMethod(new QMethod(getNameConstantOperand(), getSigConstantOperand()), seen == INVOKESPECIAL)); } } } break; case PUTSTATIC: case PUTFIELD: modifiesState = true; break; default: break; } } finally { stack.sawOpcode(this, seen); } } private void performModifyStateClosure(JavaClass cls) { boolean foundNewCall = true; Statistics statistics = Statistics.getStatistics(); String clsName = cls.getClassName(); while (foundNewCall && !selfCallTree.isEmpty()) { foundNewCall = false; Iterator<Map.Entry<QMethod, Set<CalledMethod>>> callerIt = selfCallTree.entrySet().iterator(); while (callerIt.hasNext()) { Map.Entry<QMethod, Set<CalledMethod>> callerEntry = callerIt.next(); QMethod caller = callerEntry.getKey(); MethodInfo callerMi = statistics.getMethodStatistics(clsName, caller.getMethodName(), caller.getSignature()); if (callerMi == null) { // odd, shouldn't happen foundNewCall = true; } else if (callerMi.getModifiesState()) { foundNewCall = true; } else { for (CalledMethod calledMethod : callerEntry.getValue()) { if (calledMethod.isSuper) { callerMi.setModifiesState(true); foundNewCall = true; break; } else { MethodInfo calleeMi = statistics.getMethodStatistics(clsName, calledMethod.callee.getMethodName(), calledMethod.callee.getSignature()); if (calleeMi == null) { // a super or sub class probably implements this method so just assume it modifies state callerMi.setModifiesState(true); foundNewCall = true; break; } if (calleeMi.getModifiesState()) { callerMi.setModifiesState(true); foundNewCall = true; break; } } } } if (foundNewCall) { callerIt.remove(); } } } selfCallTree.clear(); } private boolean isAssociationedWithAnnotations(Method m) { if (classHasAnnotation) { return true; } return !CollectionUtils.isEmpty(m.getAnnotationEntries()); } /** * represents a method that is called, and whether it is in the super class */ static class CalledMethod { private QMethod callee; private boolean isSuper; public CalledMethod(QMethod c, boolean s) { callee = c; isSuper = s; } @Override public int hashCode() { return callee.hashCode() & (isSuper ? 0 : 1); } @Override public boolean equals(Object obj) { if (!(obj instanceof CalledMethod)) { return false; } CalledMethod that = (CalledMethod) obj; return (isSuper == that.isSuper) && callee.equals(that.callee); } } }
package liquibase.logging.core; import liquibase.logging.LogLevel; import liquibase.util.StringUtils; import java.text.DateFormat; import java.util.Date; public class DefaultLogger extends AbstractLogger { private String name = "liquibase"; public DefaultLogger() { String passedLevel = System.getProperty("liquibase.defaultlogger.level"); if (passedLevel == null) { setLogLevel(LogLevel.INFO); } else { setLogLevel(passedLevel); } } public int getPriority() { return 1; } public void setName(String name) { this.name = name; } public void setLogLevel(String logLevel, String logFile) { setLogLevel(logLevel); } public void severe(String message) { if (getLogLevel().compareTo(LogLevel.SEVERE) <=0) { print(LogLevel.SEVERE, message); } } protected void print(LogLevel logLevel, String message) { if (StringUtils.trimToNull(message) == null) { return; } System.err.println(logLevel+" "+DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(new Date())+ ":"+name + ": " + message); } public void severe(String message, Throwable e) { if (getLogLevel().compareTo(LogLevel.SEVERE) <=0) { print(LogLevel.SEVERE, message); e.printStackTrace(); } } public void warning(String message) { if (getLogLevel().compareTo(LogLevel.WARNING) <=0) { print(LogLevel.WARNING, message); } } public void warning(String message, Throwable e) { if (getLogLevel().compareTo(LogLevel.WARNING) <=0) { print(LogLevel.WARNING, message); e.printStackTrace(); } } public void info(String message) { if (getLogLevel().compareTo(LogLevel.INFO) <=0) { print(LogLevel.INFO, message); } } public void info(String message, Throwable e) { if (getLogLevel().compareTo(LogLevel.INFO) <=0) { print(LogLevel.INFO, message); e.printStackTrace(); } } public void debug(String message) { if (getLogLevel().compareTo(LogLevel.DEBUG) <=0) { print(LogLevel.DEBUG, message); } } public void debug(String message, Throwable e) { if (getLogLevel().compareTo(LogLevel.DEBUG) <=0) { print(LogLevel.DEBUG, message); e.printStackTrace(); } } }
package com.sc2mafia.mafiaplusplus.event; import java.util.EventObject; import com.sc2mafia.mafiaplusplus.Player; public class SystemMessageEvent extends EventObject { private static final long serialVersionUID = -4971767742918062990L; Player[] receivers; String message; public SystemMessageEvent(Object source, Player[] receivers, String message) { super(source); this.receivers = receivers; this.message = message; } public Player[] getReceiver() { return receivers; } public String getMessage() { return message; } }
package com.facebook.litho.processor; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.Name; import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Types; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.facebook.common.internal.ImmutableList; import com.facebook.litho.annotations.Event; import com.facebook.litho.annotations.FromEvent; import com.facebook.litho.annotations.OnCreateInitialState; import com.facebook.litho.annotations.OnCreateTreeProp; import com.facebook.litho.annotations.OnEvent; import com.facebook.litho.annotations.OnLoadStyle; import com.facebook.litho.annotations.OnUpdateState; import com.facebook.litho.annotations.Param; import com.facebook.litho.annotations.Prop; import com.facebook.litho.annotations.PropDefault; import com.facebook.litho.annotations.ResType; import com.facebook.litho.annotations.State; import com.facebook.litho.annotations.TreeProp; import com.facebook.litho.javapoet.JPUtil; import com.facebook.litho.processor.GetTreePropsForChildrenMethodBuilder.CreateTreePropMethodData; import com.facebook.litho.specmodels.model.ClassNames; import com.facebook.litho.specmodels.model.PropDefaultModel; import com.facebook.litho.specmodels.processor.PropDefaultsExtractor; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.TypeVariableName; import com.squareup.javapoet.WildcardTypeName; import static com.facebook.litho.processor.Utils.capitalize; import static com.facebook.litho.processor.Visibility.PRIVATE; import static com.facebook.litho.specmodels.generator.GeneratorConstants.DELEGATE_FIELD_NAME; import static com.facebook.litho.specmodels.generator.GeneratorConstants.SPEC_INSTANCE_NAME; import static java.util.Arrays.asList; import static javax.lang.model.type.TypeKind.ARRAY; import static javax.lang.model.type.TypeKind.DECLARED; import static javax.lang.model.type.TypeKind.DOUBLE; import static javax.lang.model.type.TypeKind.FLOAT; import static javax.lang.model.type.TypeKind.TYPEVAR; import static javax.lang.model.type.TypeKind.VOID; public class Stages { public static final String IMPL_CLASS_NAME_SUFFIX = "Impl"; private static final String INNER_IMPL_BUILDER_CLASS_NAME = "Builder"; private static final String STATE_UPDATE_IMPL_NAME_SUFFIX = "StateUpdate"; public static final String STATE_CONTAINER_IMPL_NAME_SUFFIX = "StateContainerImpl"; public static final String STATE_CONTAINER_IMPL_MEMBER = "mStateContainerImpl"; private static final String REQUIRED_PROPS_NAMES = "REQUIRED_PROPS_NAMES"; private static final String REQUIRED_PROPS_COUNT = "REQUIRED_PROPS_COUNT"; private static final int ON_STYLE_PROPS = 1; private static final int ON_CREATE_INITIAL_STATE = 1; private final boolean mSupportState; public enum StaticFlag { STATIC, NOT_STATIC } public enum StyleableFlag { STYLEABLE, NOT_STYLEABLE } // Using these names in props might cause conflicts with the method names in the // component's generated layout builder class so we trigger a more user-friendly // error if the component tries to use them. This list should be kept in sync // with BaseLayoutBuilder. private static final String[] RESERVED_PROP_NAMES = new String[] { "withLayout", "key", "loadingEventHandler", }; private static final Class<Annotation>[] TREE_PROP_ANNOTATIONS = new Class[] { TreeProp.class, }; private static final Class<Annotation>[] PROP_ANNOTATIONS = new Class[] { Prop.class, }; private static final Class<Annotation>[] STATE_ANNOTATIONS = new Class[] { State.class, }; private final ProcessingEnvironment mProcessingEnv; private final TypeElement mSourceElement; private final String mQualifiedClassName; private final Class<Annotation>[] mStageAnnotations; private final Class<Annotation>[] mInterStagePropAnnotations; private final Class<Annotation>[] mParameterAnnotations; private final TypeSpec.Builder mClassTypeSpec; private final List<TypeVariableName> mTypeVariables; private final List<TypeElement> mEventDeclarations; private final Map<String, String> mPropJavadocs; private final String mSimpleClassName; private String mSourceDelegateAccessorName = DELEGATE_FIELD_NAME; private List<VariableElement> mProps; private List<VariableElement> mOnCreateInitialStateDefinedProps; private ImmutableList<PropDefaultModel> mPropDefaults; private List<VariableElement> mTreeProps; private final Map<String, VariableElement> mStateMap = new LinkedHashMap<>(); // Map of name to VariableElement, for members of the inner implementation class, in order private LinkedHashMap<String, VariableElement> mImplMembers; private List<Parameter> mImplParameters; private final Map<String, TypeMirror> mExtraStateMembers; // List of methods that have @OnEvent on it. private final List<ExecutableElement> mOnEventMethods; // List of methods annotated with @OnUpdateState. private final List<ExecutableElement> mOnUpdateStateMethods; private final List<ExecutableElement> mOnCreateTreePropsMethods; // List of methods that define stages (e.g. OnCreateLayout) private List<ExecutableElement> mStages; public TypeElement getSourceElement() { return mSourceElement; } public Stages( ProcessingEnvironment processingEnv, TypeElement sourceElement, String qualifiedClassName, Class<Annotation>[] stageAnnotations, Class<Annotation>[] interStagePropAnnotations, TypeSpec.Builder typeSpec, List<TypeVariableName> typeVariables, boolean supportState, Map<String, TypeMirror> extraStateMembers, List<TypeElement> eventDeclarations, Map<String, String> propJavadocs) { mProcessingEnv = processingEnv; mSourceElement = sourceElement; mQualifiedClassName = qualifiedClassName; mStageAnnotations = stageAnnotations; mInterStagePropAnnotations = interStagePropAnnotations; mClassTypeSpec = typeSpec; mTypeVariables = typeVariables; mEventDeclarations = eventDeclarations; mPropJavadocs = propJavadocs; final List<Class<Annotation>> parameterAnnotations = new ArrayList<>(); parameterAnnotations.addAll(asList(PROP_ANNOTATIONS)); parameterAnnotations.addAll(asList(STATE_ANNOTATIONS)); parameterAnnotations.addAll(asList(mInterStagePropAnnotations)); parameterAnnotations.addAll(asList(TREE_PROP_ANNOTATIONS)); mParameterAnnotations = parameterAnnotations.toArray( new Class[parameterAnnotations.size()]); mSupportState = supportState; mSimpleClassName = Utils.getSimpleClassName(mQualifiedClassName); mOnEventMethods = Utils.getAnnotatedMethods(mSourceElement, OnEvent.class); mOnUpdateStateMethods = Utils.getAnnotatedMethods(mSourceElement, OnUpdateState.class); mOnCreateTreePropsMethods = Utils.getAnnotatedMethods(mSourceElement, OnCreateTreeProp.class); mExtraStateMembers = extraStateMembers; validateOnEventMethods(); populatePropDefaults(); populateStages(); validateAnnotatedParameters(); populateOnCreateInitialStateDefinedProps(); populateProps(); populateTreeProps(); if (mSupportState) { populateStateMap(); } validatePropDefaults(); populateImplMembers(); populateImplParameters(); validateStyleOutputs(); } private boolean isInterStagePropAnnotationValidInStage( Class<? extends Annotation> interStageProp, Class<? extends Annotation> stage) { final int interStagePropIndex = asList(mInterStagePropAnnotations).indexOf(interStageProp); final int stageIndex = asList(mStageAnnotations).indexOf(stage); if (interStagePropIndex < 0 || stageIndex < 0) { throw new IllegalArgumentException(); // indicates bug in the annotation processor } // This logic relies on the fact that there are prop annotations for each stage (except for // some number at the end) return interStagePropIndex < stageIndex; } private boolean doesInterStagePropAnnotationMatchStage( Class<? extends Annotation> interStageProp, Class<? extends Annotation> stage) { final int interStagePropIndex = asList(mInterStagePropAnnotations).indexOf(interStageProp); // Null stage is allowed and indicates prop int stageIndex = -1; if (stage != null) { stageIndex = asList(mStageAnnotations).indexOf(stage); if (interStagePropIndex < 0 || stageIndex < 0) { throw new IllegalArgumentException(); // indicates bug in the annotation processor } } return interStagePropIndex == stageIndex; } private void validateOnEventMethods() { final Map<String, Boolean> existsMap = new HashMap<>(); for (ExecutableElement element : mOnEventMethods) { if (existsMap.containsKey(element.getSimpleName().toString())) { throw new ComponentsProcessingException( element, "@OnEvent declared methods must have unique names"); } final DeclaredType eventClass = Utils.getAnnotationParameter( mProcessingEnv, element, OnEvent.class, "value"); final TypeMirror returnType = Utils.getAnnotationParameter( mProcessingEnv, eventClass.asElement(), Event.class, "returnType"); if (!mProcessingEnv.getTypeUtils().isSameType(element.getReturnType(), returnType)) { throw new ComponentsProcessingException( element, "Method " + element.getSimpleName() + " must return " + returnType + ", since that is what " + eventClass + " expects."); } final List<? extends VariableElement> parameters = Utils.getEnclosedFields((TypeElement) eventClass.asElement()); for (VariableElement v : Utils.getParametersWithAnnotation(element, FromEvent.class)) { boolean hasMatchingParameter = false; for (VariableElement parameter : parameters) { if (parameter.getSimpleName().equals(v.getSimpleName()) && parameter.asType().toString().equals(v.asType().toString())) { hasMatchingParameter = true; break; } } if (!hasMatchingParameter) { throw new ComponentsProcessingException( v, v.getSimpleName() + " of this type is not a member of " + eventClass); } return; } existsMap.put(element.getSimpleName().toString(), true); } } /** * Ensures that the declared events don't clash with the predefined ones. */ private void validateEventDeclarations() { for (TypeElement eventDeclaration : mEventDeclarations) { final Event eventAnnotation = eventDeclaration.getAnnotation(Event.class); if (eventAnnotation == null) { throw new ComponentsProcessingException( eventDeclaration, "Events must be declared with the @Event annotation, event is: " + eventDeclaration); } final List<? extends VariableElement> fields = Utils.getEnclosedFields(eventDeclaration); for (VariableElement field : fields) { if (!field.getModifiers().contains(Modifier.PUBLIC) || field.getModifiers().contains(Modifier.FINAL)) { throw new ComponentsProcessingException( field, "Event fields must be declared as public non-final"); } } } } private void validateStyleOutputs() { final ExecutableElement delegateMethod = Utils.getAnnotatedMethod( mSourceElement, OnLoadStyle.class); if (delegateMethod == null) { return; } final List<? extends VariableElement> parameters = delegateMethod.getParameters(); if (parameters.size() < ON_STYLE_PROPS) { throw new ComponentsProcessingException( delegateMethod, "The @OnLoadStyle method should have an ComponentContext" + "followed by Output parameters matching component create."); } final TypeName firstParamType = ClassName.get(parameters.get(0).asType()); if (!firstParamType.equals(ClassNames.COMPONENT_CONTEXT)) { throw new ComponentsProcessingException( parameters.get(0), "The first argument of the @OnLoadStyle method should be an ComponentContext."); } for (int i = ON_STYLE_PROPS, size = parameters.size(); i < size; i++) { final VariableElement v = parameters.get(i); final TypeMirror outputType = Utils.getGenericTypeArgument(v.asType(), ClassNames.OUTPUT); if (outputType == null) { throw new ComponentsProcessingException( parameters.get(i), "The @OnLoadStyle method should have only have Output arguments matching " + "component create."); } final Types typeUtils = mProcessingEnv.getTypeUtils(); final String name = v.getSimpleName().toString(); boolean matchesProp = false; for (Element prop : mProps) { if (!prop.getSimpleName().toString().equals(name)) { continue; } matchesProp = true; if (!typeUtils.isAssignable(prop.asType(), outputType)) { throw new ComponentsProcessingException( v, "Searching for prop \"" + name + "\" of type " + ClassName.get(outputType) + " but found prop with the same name of type " + ClassName.get(prop.asType())); } } if (!matchesProp) { throw new ComponentsProcessingException( v, "Output named '" + v.getSimpleName() + "' does not match any prop " + "in the component."); } } } private void validateAnnotatedParameters() { final List<PrintableException> exceptions = new ArrayList<>(); final Map<String, VariableElement> variableNameToElementMap = new HashMap<>(); final Map<String, Class<? extends Annotation>> outputVariableToStage = new HashMap<>(); for (Class<? extends Annotation> stageAnnotation : mStageAnnotations) { final ExecutableElement stage = Utils.getAnnotatedMethod( mSourceElement, stageAnnotation); if (stage == null) { continue; } // Enforce #5: getSpecDefinedParameters will verify that parameters don't have duplicate // annotations for (VariableElement v : getSpecDefinedParameters(stage)) { try { final String variableName = v.getSimpleName().toString(); final Annotation interStagePropAnnotation = getInterStagePropAnnotation(v); final boolean isOutput = Utils.getGenericTypeArgument(v.asType(), ClassNames.OUTPUT) != null; if (isOutput) { outputVariableToStage.put(variableName, stageAnnotation); } // Enforce if (interStagePropAnnotation != null) { final Class<? extends Annotation> outputStage = outputVariableToStage.get(variableName); if (!doesInterStagePropAnnotationMatchStage( interStagePropAnnotation.annotationType(), outputStage)) { throw new ComponentsProcessingException( v, "Inter-stage prop declaration is incorrect, the same name and type must be " + "used in every method where the inter-stage prop is declared."); } } // Enforce if (interStagePropAnnotation != null && !isInterStagePropAnnotationValidInStage( interStagePropAnnotation.annotationType(), stageAnnotation)) { throw new ComponentsProcessingException( v, "Inter-stage create must refer to previous stages."); } final VariableElement existingType = variableNameToElementMap.get(variableName); if (existingType != null && !isSameType(existingType.asType(), v.asType())) { // We have a type mis-match. This is allowed, provided that the previous type is an // outputand the new type is an prop, and the type argument of the output matches the // prop. In the future, we may want to allow stages to modify outputs from previous // stages, but for now we disallow it. // Enforce #1 and #2 if ((getInterStagePropAnnotation(v) == null || Utils.getGenericTypeArgument(existingType.asType(), ClassNames.OUTPUT) == null) && Utils.getGenericTypeArgument(existingType.asType(), ClassNames.DIFF) == null) { throw new ComponentsProcessingException( v, "Inconsistent type for '" + variableName + "': '" + existingType.asType() + "' and '" + v.asType() + "'"); } } else if (existingType == null) { // We haven't see a parameter with this name yet. Therefore it must be either @Prop, // @State or an output. final boolean isFromProp = getParameterAnnotation(v, PROP_ANNOTATIONS) != null; final boolean isFromState = getParameterAnnotation(v, STATE_ANNOTATIONS) != null; final boolean isFromTreeProp = getParameterAnnotation(v, TREE_PROP_ANNOTATIONS) != null; if (isFromState && !mSupportState) { throw new ComponentsProcessingException( v, "State is not supported in this kind of Spec."); } if (!isFromProp && !isFromState && !isOutput && !isFromTreeProp) { throw new ComponentsProcessingException( v, "Inter-stage prop declared without source."); } } // Enforce final Prop propAnnotation = v.getAnnotation(Prop.class); if (propAnnotation != null) { for (String reservedPropName : RESERVED_PROP_NAMES) { if (reservedPropName.equals(variableName)) { throw new ComponentsProcessingException( v, "'" + reservedPropName + "' is a reserved prop name used by " + "the component's layout builder. Please use another name."); } } // Enforce final boolean hasDefaultValue = hasDefaultValue(v); if (hasDefaultValue && !propAnnotation.optional()) { throw new ComponentsProcessingException( v, "Prop is not optional but has a declared default value."); } // Enforce if (existingType != null) { final Prop existingPropAnnotation = existingType.getAnnotation(Prop.class); if (existingPropAnnotation != null) { if (!hasSameAnnotations(v, existingType)) { throw new ComponentsProcessingException( v, "The prop '" + variableName + "' is configured differently for different " + "methods. Ensure each instance of this prop is declared identically."); } } } // Enforce TypeName typeName; try { typeName = ClassName.get(v.asType()); } catch (IllegalArgumentException e) { throw new ComponentsProcessingException( v, "Prop type does not exist"); } // Enforce final List<ClassName> illegalPropTypes = Arrays.asList( ClassNames.COMPONENT_LAYOUT, ClassNames.COMPONENT_LAYOUT_BUILDER, ClassNames.COMPONENT_LAYOUT_CONTAINER_BUILDER, ClassNames.COMPONENT_BUILDER, ClassNames.COMPONENT_BUILDER_WITH_LAYOUT, ClassNames.REFERENCE_BUILDER); if (illegalPropTypes.contains(typeName)) { throw new ComponentsProcessingException( v, "Props may not be declared with the following types:" + illegalPropTypes); } } variableNameToElementMap.put(variableName, v); } catch (PrintableException e) { exceptions.add(e); } } } if (!exceptions.isEmpty()) { throw new MultiPrintableException(exceptions); } } private boolean hasSameAnnotations(VariableElement v1, VariableElement v2) { final List<? extends AnnotationMirror> v1Annotations = v1.getAnnotationMirrors(); final List<? extends AnnotationMirror> v2Annotations = v2.getAnnotationMirrors(); if (v1Annotations.size() != v2Annotations.size()) { return false; } final int count = v1Annotations.size(); for (int i = 0; i < count; i++) { final AnnotationMirror a1 = v1Annotations.get(i); final AnnotationMirror a2 = v2Annotations.get(i); // Some object in this hierarchy don't implement equals correctly. // They do however produce very nice strings representations which we can compare instead. if (!a1.toString().equals(a2.toString())) { return false; } } return true; } public void validateStatic() { validateStaticFields(); validateStaticMethods(); } private void validateStaticFields() { for (Element element : mSourceElement.getEnclosedElements()) { if (element.getKind() == ElementKind.FIELD && !element.getModifiers().contains(Modifier.STATIC)) { throw new ComponentsProcessingException( element, "Field " + element.getSimpleName() + " in " + mSourceElement.getQualifiedName() + " must be static"); } } } private void validateStaticMethods() { for (Class<? extends Annotation> stageAnnotation : mStageAnnotations) { final ExecutableElement stage = Utils.getAnnotatedMethod( mSourceElement, stageAnnotation); if (stage != null && !stage.getModifiers().contains(Modifier.STATIC)) { throw new ComponentsProcessingException( stage, "Method " + stage.getSimpleName() + " in " + mSourceElement.getQualifiedName() + " must be static"); } } } /** * Gather a list of VariableElement that are the props to this component */ private void populateProps() { // We use a linked hash map to guarantee iteration order final LinkedHashMap<String, VariableElement> variableNameToElementMap = new LinkedHashMap<>(); for (ExecutableElement stage : mStages) { for (VariableElement v : getProps(stage)) { // Validation unnecessary - already handled by validateAnnotatedParameters final String variableName = v.getSimpleName().toString(); variableNameToElementMap.put(variableName, v); } } mProps = new ArrayList<>(variableNameToElementMap.values()); addCreateInitialStateDefinedProps(mProps); } /** * Gather a list of VariableElement that are the state to this component */ private void populateStateMap() { // We use a linked hash map to guarantee iteration order final LinkedHashMap<String, VariableElement> variableNameToElementMap = new LinkedHashMap<>(); for (ExecutableElement stage : mStages) { for (VariableElement v : getState(stage)) { final String variableName = v.getSimpleName().toString(); if (mStateMap.containsKey(variableName)) { VariableElement existingType = mStateMap.get(variableName); final State existingPropAnnotation = existingType.getAnnotation(State.class); if (existingPropAnnotation != null) { if (!hasSameAnnotations(v, existingType)) { throw new ComponentsProcessingException( v, "The state '" + variableName + "' is configured differently for different " + "methods. Ensure each instance of this state is declared identically."); } } } mStateMap.put( variableName, v); } } } private void populateTreeProps() { final LinkedHashMap<String, VariableElement> variableNameToElementMap = new LinkedHashMap<>(); for (ExecutableElement stage : mStages) { for (VariableElement v : Utils.getParametersWithAnnotation(stage, TreeProp.class)) { final String variableName = v.getSimpleName().toString(); variableNameToElementMap.put(variableName, v); } } mTreeProps = new ArrayList<>(variableNameToElementMap.values()); } /** * Get the list of stages (OnInflate, OnMeasure, OnMount) that are defined for this component. */ private void populateStages() { mStages = new ArrayList<>(); for (Class<Annotation> stageAnnotation : mStageAnnotations) { final ExecutableElement stage = Utils.getAnnotatedMethod( mSourceElement, stageAnnotation); if (stage != null) { mStages.add(stage); } } if (mOnEventMethods != null) { mStages.addAll(mOnEventMethods); } mStages.addAll(mOnCreateTreePropsMethods); } /** * @param prop The prop to determine if it has a default or not. * @return Returns true if the prop has a default, false otherwise. */ private boolean hasDefaultValue(VariableElement prop) { final String name = prop.getSimpleName().toString(); final TypeName type = TypeName.get(prop.asType()); for (PropDefaultModel propDefault : mPropDefaults) { if (propDefault.mName.equals(name) && propDefault.mType.equals(type)) { return true; } } return false; } /** * Fail if any elements that exist in mPropDefaults do not exist in mProps. */ private void validatePropDefaults() { for (PropDefaultModel propDefault : mPropDefaults) { final ImmutableList<Modifier> modifiers = propDefault.mModifiers; if (!modifiers.contains(Modifier.STATIC) || !modifiers.contains(Modifier.FINAL) || modifiers.contains(Modifier.PRIVATE)) { throw new RuntimeException( "Defaults for props (fields annotated with " + PropDefault.class + ") must be " + "non-private, static, and final. This is not the case for " + propDefault.mName); } if (!hasValidNameAndType(propDefault)) { throw new RuntimeException( "Prop defaults (fields annotated with " + PropDefault.class + ") should have the " + "same name and type as the prop that they set the default for. This is not the " + "case for " + propDefault.mName); } } } /** * @return true if the given prop default matches the name and type of a prop, false otherwise. */ private boolean hasValidNameAndType(PropDefaultModel propDefault) { for (VariableElement prop : mProps) { if (prop.getSimpleName().toString().equals(propDefault.mName) && TypeName.get(prop.asType()).equals(propDefault.mType)) { return true; } } return false; } /** * Gather a list of parameters from the given element that are props to this component. */ private static List<VariableElement> getProps(ExecutableElement element) { return Utils.getParametersWithAnnotation(element, Prop.class); } /** * Gather a list of parameters from the given element that are state to this component. */ private static List<VariableElement> getState(ExecutableElement element) { return Utils.getParametersWithAnnotation(element, State.class); } /** * Gather a list of parameters from the given element that are defined by the spec. That is, they * aren't one of the parameters predefined for a given method. For example, OnCreateLayout has a * predefined parameter of type LayoutContext. Spec-defined parameters are annotated with one of * our prop annotations or are of type {@link com.facebook.litho.Output}. */ private List<VariableElement> getSpecDefinedParameters(ExecutableElement element) { return getSpecDefinedParameters(element, true); } private List<VariableElement> getSpecDefinedParameters( ExecutableElement element, boolean shouldIncludeOutputs) { final ArrayList<VariableElement> specDefinedParameters = new ArrayList<>(); for (VariableElement v : element.getParameters()) { final boolean isAnnotatedParameter = getParameterAnnotation(v) != null; final boolean isInterStageOutput = Utils.getGenericTypeArgument(
package gov.nih.nci.ncicb.cadsr.loader.persister; import gov.nih.nci.ncicb.cadsr.dao.*; import gov.nih.nci.ncicb.cadsr.domain.*; import gov.nih.nci.ncicb.cadsr.loader.ElementsLists; import gov.nih.nci.ncicb.cadsr.loader.util.*; import gov.nih.nci.ncicb.cadsr.loader.defaults.UMLDefaults; import org.apache.log4j.Logger; import java.util.*; /** * * @author <a href="mailto:chris.ludet@oracle.com">Christophe Ludet</a> */ public class OcRecPersister extends UMLPersister { private static Logger logger = Logger.getLogger(OcRecPersister.class.getName()); public OcRecPersister() { } public void persist() throws PersisterException { ObjectClassRelationship ocr = DomainObjectFactory.newObjectClassRelationship(); List<ObjectClassRelationship> ocrs = elements.getElements(ocr); if (ocrs != null) { for (ListIterator it = ocrs.listIterator(); it.hasNext();) { ocr = (ObjectClassRelationship) it.next(); ocr.setContext(defaults.getContext()); ocr.setAudit(defaults.getAudit()); ocr.setVersion(defaults.getVersion()); ocr.setWorkflowStatus(defaults.getWorkflowStatus()); String sourcePackage = getPackageName(ocr.getSource()); String targetPackage = getPackageName(ocr.getTarget()); ocr.setPreferredDefinition(new OCRDefinitionBuilder().buildDefinition(ocr)); if ((ocr.getLongName() == null) || (ocr.getLongName().length() == 0)) { logger.debug("No Role name for association. Generating one"); ocr.setLongName(new OCRRoleNameBuilder().buildRoleName(ocr)); } List<ObjectClass> ocs = elements. getElements(DomainObjectFactory.newObjectClass()); ObjectClass sOcr = ocr.getSource(); socr: for(AlternateName an : sOcr.getAlternateNames()) { if(an.getType().equals(AlternateName.TYPE_CLASS_FULL_NAME)) { ocr.setSource(LookupUtil.lookupObjectClass(an)); break socr; } } ObjectClass tOcr = ocr.getTarget(); tocr: for(AlternateName an : tOcr.getAlternateNames()) { if(an.getType().equals(AlternateName.TYPE_CLASS_FULL_NAME)) { ocr.setTarget(LookupUtil.lookupObjectClass(an)); break tocr; } } // logger.info(PropertyAccessor // .getProperty("created.association")); LogUtil.logAc(ocr, logger); logger.info(PropertyAccessor .getProperty("source.role", ocr.getSourceRole())); logger.info(PropertyAccessor .getProperty("source.class", ocr.getSource().getLongName())); logger.info(PropertyAccessor.getProperty ("source.cardinality", new Object[] {new Integer(ocr.getSourceLowCardinality()), new Integer(ocr.getSourceHighCardinality())})); logger.info(PropertyAccessor .getProperty("target.role", ocr.getTargetRole())); logger.info(PropertyAccessor .getProperty("target.class", ocr.getTarget().getLongName())); logger.info(PropertyAccessor.getProperty ("target.cardinality", new Object[] {new Integer(ocr.getTargetLowCardinality()), new Integer(ocr.getTargetHighCardinality())})); logger.info(PropertyAccessor.getProperty ("direction", ocr.getDirection())); logger.info(PropertyAccessor.getProperty ("type", ocr.getType())); // check if association already exists ObjectClassRelationship ocr2 = DomainObjectFactory.newObjectClassRelationship(); ocr2.setSource(ocr.getSource()); ocr2.setSourceRole(ocr.getSourceRole()); ocr2.setTarget(ocr.getTarget()); ocr2.setTargetRole(ocr.getTargetRole()); ocr2.setDirection(ocr.getDirection()); ocr2.setSourceLowCardinality(ocr.getSourceLowCardinality()); ocr2.setSourceHighCardinality(ocr.getSourceHighCardinality()); ocr2.setTargetLowCardinality(ocr.getTargetLowCardinality()); ocr2.setTargetHighCardinality(ocr.getTargetHighCardinality()); List eager = new ArrayList(); eager.add(EagerConstants.AC_CS_CSI); List l = objectClassRelationshipDAO.find(ocr2, eager); // boolean found = false; // if (l.size() > 0) { // for (Iterator it2 = l.iterator(); it2.hasNext();) { // ocr2 = (ObjectClassRelationship) it2.next(); // List acCsCsis = (List) ocr2.getAcCsCsis(); // for (Iterator it3 = acCsCsis.iterator(); it3.hasNext();) { // AdminComponentClassSchemeClassSchemeItem acCsCsi = (AdminComponentClassSchemeClassSchemeItem) it3.next(); // if (acCsCsi.getCsCsi().getCs().getLongName().equals(defaults.getProjectCs().getLongName())) { // found = true; // logger.debug("Association with same classification already found"); if (l.size() > 0) { logger.info(PropertyAccessor.getProperty("existed.association")); ocr = (ObjectClassRelationship)l.get(0); } else { // ocr.setPreferredName( // ocr.getSource().getPublicId() + "-" + // ocr.getSource().getVersion() + ":" + // ocr.getTarget().getPublicId() + "-" + // ocr.getTarget().getVersion() ocr.setId(objectClassRelationshipDAO.create(ocr)); // addProjectCs(ocr); logger.info(PropertyAccessor.getProperty("created.association")); } addPackageClassification(ocr, sourcePackage); addPackageClassification(ocr, targetPackage); } } } }
package com.wakatime.intellij.plugin; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.event.DocumentListener; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.vfs.VirtualFile; public class CustomDocumentListener implements DocumentListener { @Override public void beforeDocumentChange(DocumentEvent documentEvent) { } @Override public void documentChanged(DocumentEvent documentEvent) { final FileDocumentManager instance = FileDocumentManager.getInstance(); final VirtualFile file = instance.getFile(documentEvent.getDocument()); if (file != null && !file.getUrl().startsWith("mock: final String currentFile = file.getPath(); final long currentTime = System.currentTimeMillis() / 1000; if ((!currentFile.equals(WakaTime.lastFile) || WakaTime.enoughTimePassed(currentTime)) && !currentFile.contains("/.idea/workspace.xml")) { WakaTime.logFile(currentFile, false); WakaTime.lastFile = currentFile; WakaTime.lastTime = currentTime; } } } }
package nallar.tickthreading.minecraft; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumSet; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.google.common.base.Charsets; import com.google.common.io.Files; import cpw.mods.fml.common.IPlayerTracker; import cpw.mods.fml.common.IScheduledTickHandler; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.TickType; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLServerStartingEvent; import cpw.mods.fml.common.network.NetworkMod; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.TickRegistry; import cpw.mods.fml.relauncher.Side; import nallar.collections.IntSet; import nallar.reporting.LeakDetector; import nallar.reporting.Metrics; import nallar.tickthreading.Log; import nallar.tickthreading.minecraft.commands.Command; import nallar.tickthreading.minecraft.commands.DumpCommand; import nallar.tickthreading.minecraft.commands.ProfileCommand; import nallar.tickthreading.minecraft.commands.TPSCommand; import nallar.tickthreading.minecraft.commands.TicksCommand; import nallar.tickthreading.minecraft.entitylist.EntityList; import nallar.tickthreading.minecraft.entitylist.LoadedEntityList; import nallar.tickthreading.minecraft.entitylist.LoadedTileEntityList; import nallar.tickthreading.minecraft.profiling.EntityTickProfiler; import nallar.tickthreading.minecraft.profiling.Timings; import nallar.tickthreading.util.CollectionsUtil; import nallar.tickthreading.util.LocationUtil; import nallar.tickthreading.util.PatchUtil; import nallar.tickthreading.util.ReflectUtil; import nallar.tickthreading.util.TableFormatter; import nallar.tickthreading.util.VersionUtil; import nallar.tickthreading.util.contextaccess.ContextAccess; import net.minecraft.command.ServerCommandManager; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.network.NetServerHandler; import net.minecraft.network.packet.PacketCount; import net.minecraft.server.MinecraftServer; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraft.world.chunk.Chunk; import net.minecraftforge.common.Configuration; import net.minecraftforge.common.DimensionManager; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.EventPriority; import net.minecraftforge.event.ForgeSubscribe; import net.minecraftforge.event.entity.living.LivingFallEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.world.WorldEvent; @SuppressWarnings ("WeakerAccess") @Mod (modid = "TickThreading", name = "TickThreading", version = "@MOD_VERSION@", acceptedMinecraftVersions = "[@MC_VERSION@]") @NetworkMod (clientSideRequired = false, serverSideRequired = false) public class TickThreading { @Mod.Instance public static TickThreading instance; private static final int loadedEntityFieldIndex = 0; private static final int loadedTileEntityFieldIndex = 2; final Map<World, TickManager> managers = new LinkedHashMap<World, TickManager>(); private final Runtime runtime = Runtime.getRuntime(); private final IntSet worlds = new IntSet(); public String messageDeadlockDetected = "The server appears to have frozen and will restart soon if it does not recover. :("; public String messageDeadlockRecovered = "The server has recovered and will not need to restart. :)"; public String messageDeadlockSavingExiting = "The server is saving the world and restarting - be right back!"; private String profilingFileName = "world/computer/<computer id>/profile.txt"; public boolean exitOnDeadlock = false; public boolean requireOpForTicksCommand = true; public boolean requireOpForProfileCommand = true; public boolean shouldLoadSpawn = false; public boolean concurrentNetworkTicks = false; public boolean antiCheatKick = false; public boolean antiCheatNotify = false; public boolean cleanWorlds = true; public boolean allowWorldUnloading = true; public boolean requireOpForDumpCommand = true; public boolean enableFastMobSpawning = true; public boolean enableBugWarningMessage = true; public boolean concurrentMovementUpdates = true; public boolean rateLimitChunkUpdates = true; public int saveInterval = 180; public int deadLockTime = 35; public int chunkCacheSize = 2000; public int chunkGCInterval = 1200; public int maxEntitiesPerPlayer = 1000; public float mobSpawningMultiplier = 1; private int tickThreads = 0; int regionSize = 16; private int profilingInterval = 0; private int maxItemsPerChunk = 0; private boolean profilingJson = false; public boolean variableTickRate = true; private DeadLockDetector deadLockDetector; private HashSet<Integer> disabledFastMobSpawningDimensions = new HashSet<Integer>(); private boolean waitForEntityTickCompletion = true; private int targetTPS = 20; private final LeakDetector leakDetector = new LeakDetector(1800); public static int recentSpawnedItems; private int lastMaxItemWarnedTime; static { new Metrics("TickThreading", VersionUtil.TTVersionNumber()); } public TickThreading() { Log.LOGGER.getLevel(); // Force log class to load try { PatchUtil.writePatchRunners(); } catch (IOException e) { Log.severe("Failed to write patch runners", e); } List<File> filesToCheck = LocationUtil.getJarLocations(); if (PatchUtil.shouldPatch(filesToCheck)) { Log.severe("TickThreading is disabled, because your server has not been patched" + " or the patches are out of date" + "\nTo patch your server, simply run the PATCHME.bat/sh file in your server directory" + "\n\nAlso, make a full backup of your server if you haven't already!" + "\n\nFiles checked for patches: " + CollectionsUtil.join(filesToCheck)); Log.flush(); Runtime.getRuntime().halt(1); } ContextAccess.$.getContext(0); } @Mod.Init public void init(FMLInitializationEvent event) { MinecraftForge.EVENT_BUS.register(this); initPeriodicProfiling(); if (!enableBugWarningMessage) { return; } GameRegistry.registerPlayerTracker(new LoginWarningHandler()); } private void initPeriodicProfiling() { final int profilingInterval = this.profilingInterval; if (profilingInterval == 0) { return; } TickRegistry.registerScheduledTickHandler(new ProfilingScheduledTickHandler(profilingInterval, MinecraftServer.getServer().getFile(profilingFileName), profilingJson), Side.SERVER); } @SuppressWarnings ("FieldRepeatedlyAccessedInMethod") @Mod.PreInit public void preInit(FMLPreInitializationEvent event) { Configuration config = new Configuration(event.getSuggestedConfigurationFile()); config.load(); String GENERAL = Configuration.CATEGORY_GENERAL; TicksCommand.name = config.get(GENERAL, "ticksCommandName", TicksCommand.name, "Name of the command to be used for performance stats. Defaults to ticks.").getString(); TPSCommand.name = config.get(GENERAL, "tpsCommandName", TPSCommand.name, "Name of the command to be used for TPS reports.").getString(); ProfileCommand.name = config.get(GENERAL, "profileCommandName", ProfileCommand.name, "Name of the command to be used for profiling reports.").getString(); DumpCommand.name = config.get(GENERAL, "dumpCommandName", DumpCommand.name, "Name of the command to be used for profiling reports.").getString(); messageDeadlockDetected = config.get(GENERAL, "messageDeadlockDetected", messageDeadlockDetected, "The message to be displayed if a deadlock is detected. (Only sent if exitOnDeadlock is on)").getString(); messageDeadlockRecovered = config.get(GENERAL, "messageDeadlockRecovered", messageDeadlockRecovered, "The message to be displayed if the server recovers from an apparent deadlock. (Only sent if exitOnDeadlock is on)").getString(); messageDeadlockSavingExiting = config.get(GENERAL, "messageDeadlockSavingExiting", messageDeadlockSavingExiting, "The message to be displayed when the server attempts to save and stop after a deadlock. (Only sent if exitOnDeadlock is on)").getString(); tickThreads = config.get(GENERAL, "tickThreads", tickThreads, "number of threads to use to tick. 0 = automatic").getInt(tickThreads); regionSize = config.get(GENERAL, "regionSize", regionSize, "width/length of tick regions, specified in blocks. Should be a power of 2 (eg: 16/32)").getInt(regionSize); saveInterval = config.get(GENERAL, "saveInterval", saveInterval, "Time between auto-saves, in ticks.").getInt(saveInterval); deadLockTime = config.get(GENERAL, "deadLockTime", deadLockTime, "The time(seconds) of being frozen which will trigger the DeadLockDetector. Set to 1 to instead detect lag spikes.").getInt(deadLockTime); chunkCacheSize = Math.max(100, config.get(GENERAL, "chunkCacheSize", chunkCacheSize, "Number of unloaded chunks to keep cached. Replacement for Forge's dormant chunk cache, which tends to break. Minimum size of 100").getInt(chunkCacheSize)); chunkGCInterval = config.get(GENERAL, "chunkGCInterval", chunkGCInterval, "Interval between chunk garbage collections in ticks").getInt(chunkGCInterval); targetTPS = config.get(GENERAL, "targetTPS", targetTPS, "TPS the server should try to run at.").getInt(targetTPS); maxItemsPerChunk = config.get(GENERAL, "maxItemsPerChunk", maxItemsPerChunk, "Maximum number of entity items allowed per chunk. 0 = no limit.").getInt(maxItemsPerChunk); maxEntitiesPerPlayer = config.get(GENERAL, "maxEntitiesPerPlayer", maxEntitiesPerPlayer, "If more entities than this are loaded per player in a world, mob spawning will be disabled in that world.").getInt(maxEntitiesPerPlayer); mobSpawningMultiplier = (float) config.get(GENERAL, "mobSpawningMultiplier", mobSpawningMultiplier, "Mob spawning multiplier. Default is 1, can be a decimal.").getDouble(mobSpawningMultiplier); variableTickRate = config.get(GENERAL, "variableRegionTickRate", variableTickRate, "Allows tick rate to vary per region so that each region uses at most 50ms on average per tick.").getBoolean(variableTickRate); exitOnDeadlock = config.get(GENERAL, "exitOnDeadlock", exitOnDeadlock, "If the server should shut down when a deadlock is detected").getBoolean(exitOnDeadlock); enableFastMobSpawning = config.get(GENERAL, "enableFastMobSpawning", enableFastMobSpawning, "If enabled, TT's alternative mob spawning implementation will be used.").getBoolean(enableFastMobSpawning); requireOpForTicksCommand = config.get(GENERAL, "requireOpsForTicksCommand", requireOpForTicksCommand, "If a player must be opped to use /ticks").getBoolean(requireOpForTicksCommand); requireOpForProfileCommand = config.get(GENERAL, "requireOpsForProfileCommand", requireOpForProfileCommand, "If a player must be opped to use /profile").getBoolean(requireOpForProfileCommand); requireOpForDumpCommand = config.get(GENERAL, "requireOpsForDumpCommand", requireOpForDumpCommand, "If a player must be opped to use /dump").getBoolean(requireOpForDumpCommand); shouldLoadSpawn = config.get(GENERAL, "shouldLoadSpawn", shouldLoadSpawn, "Whether chunks within 200 blocks of world spawn points should always be loaded.").getBoolean(shouldLoadSpawn); waitForEntityTickCompletion = config.get(GENERAL, "waitForEntityTickCompletion", waitForEntityTickCompletion, "Whether we should wait until all Tile/Entity tick threads are finished before moving on with world tick. False = experimental, but may improve performance.").getBoolean(waitForEntityTickCompletion); concurrentNetworkTicks = config.get(GENERAL, "concurrentNetworkTicks", concurrentNetworkTicks, "Whether network ticks should be ran in a separate thread from the main minecraft thread. This is likely to be very buggy, especially with mods doing custom networking such as IC2!").getBoolean(concurrentNetworkTicks); concurrentMovementUpdates = config.get(GENERAL, "concurrentMovementUpdates", concurrentMovementUpdates, "Whether movement updates should be processed asynchronously. Improves performance, but may cause spontaneous fall damage in some (still not sure what) situations.").getBoolean(concurrentMovementUpdates); antiCheatKick = config.get(GENERAL, "antiCheatKick", antiCheatKick, "Whether to kick players for detected cheating").getBoolean(antiCheatKick); antiCheatNotify = config.get(GENERAL, "antiCheatNotify", antiCheatNotify, "Whether to notify admins if TT anti-cheat detects cheating").getBoolean(antiCheatNotify); cleanWorlds = config.get(GENERAL, "cleanWorlds", cleanWorlds, "Whether to clean worlds on unload - this should fix some memory leaks due to mods holding on to world objects").getBoolean(cleanWorlds); allowWorldUnloading = config.get(GENERAL, "allowWorldUnloading", allowWorldUnloading, "Whether worlds should be allowed to unload.").getBoolean(allowWorldUnloading); enableBugWarningMessage = config.get(GENERAL, "enableBugWarningMessage", enableBugWarningMessage, "Whether to enable warning if there are severe known compatibility issues with the current TT build you are using and your installed mods. Highly recommend leaving this enabled, if you disable it chances are you'll get users experiencing these issues annoying mod authors, which I really don't want to happen.").getBoolean(enableBugWarningMessage); profilingInterval = config.get(GENERAL, "profilingInterval", profilingInterval, "Interval, in minutes, to record profiling information to disk. 0 = never. Recommended >= 2.").getInt(); profilingFileName = config.get(GENERAL, "profilingFileName", profilingFileName, "Location to store profiling information to, relative to the server folder. For example, why not store it in a computercraft computer's folder?").getString(); profilingJson = config.get(GENERAL, "profilingJson", profilingJson, "Whether to write periodic profiling in JSON format").getBoolean(profilingJson); rateLimitChunkUpdates = config.get(GENERAL, "rateLimitChunkUpdates", rateLimitChunkUpdates, "Whether to prevent repeated chunk updates which can cause rendering issues and disconnections for slow clients/connections.").getBoolean(rateLimitChunkUpdates); config.save(); int[] disabledDimensions = config.get(GENERAL, "disableFastMobSpawningDimensions", new int[]{-1, 1}, "List of dimensions not to enable fast spawning in.").getIntList(); disabledFastMobSpawningDimensions = new HashSet<Integer>(disabledDimensions.length); for (int disabledDimension : disabledDimensions) { disabledFastMobSpawningDimensions.add(disabledDimension); } PacketCount.allowCounting = false; } @Mod.ServerStarting public void serverStarting(FMLServerStartingEvent event) { Log.severe(VersionUtil.versionString() + " is installed on this server!" + "\nIf anything breaks, check if it is still broken without TickThreading" + "\nWe don't want to annoy mod devs with issue reports caused by TickThreading." + "\nSeriously, please don't." + "\nIf it's only broken with TickThreading, report it at http://github.com/nallar/TickThreading" + "\n\nAlso, you really should be making regular backups. (You should be doing that even when not using TT.)"); if (Log.debug) { Log.severe("TickThreading is running in debug mode."); } ServerCommandManager serverCommandManager = (ServerCommandManager) event.getServer().getCommandManager(); serverCommandManager.registerCommand(new TicksCommand()); serverCommandManager.registerCommand(new TPSCommand()); serverCommandManager.registerCommand(new ProfileCommand()); serverCommandManager.registerCommand(new DumpCommand()); MinecraftServer.setTargetTPS(targetTPS); Command.checkForPermissions(); String javaVersion = System.getProperty("java.runtime.version"); if (javaVersion.startsWith("1.6")) { Log.severe("It is recommended to use a Java 7 JRE. Current version: " + javaVersion); Log.severe("Java 7 has many performance improvements over 6, and some of TT's changes actually make performance worse when using java 6."); } else if (javaVersion.startsWith("1.8")) { Log.warning("You are using java version " + javaVersion + '.'); Log.warning("This is not recommended, as 1.8 causes the deadlock detector to be unable to attempt to fix deadlocks due to the removal of Thread.stop(), and I have not yet implemented a workaround."); } } @ForgeSubscribe ( priority = EventPriority.HIGHEST ) public synchronized void onWorldLoad(WorldEvent.Load event) { World world = event.world; if (world.isRemote) { Log.severe("World " + Log.name(world) + " seems to be a client world", new Throwable()); return; } if (DimensionManager.getWorld(world.getDimension()) != world) { Log.severe("World " + world.getName() + " was loaded with an incorrect dimension ID!", new Throwable()); return; } if (managers.containsKey(world)) { Log.severe("World " + world.getName() + "'s world load event was fired twice.", new Throwable()); return; } if (!worlds.add(world.provider.dimensionId)) { Log.severe("World " + world.getName() + " has a duplicate provider dimension ID.\n" + Log.dumpWorlds()); } world.loadEventFired = true; TickManager manager = new TickManager((WorldServer) world, getThreadCount(), waitForEntityTickCompletion); try { Field loadedTileEntityField = ReflectUtil.getFields(World.class, List.class)[loadedTileEntityFieldIndex]; new LoadedTileEntityList(world, loadedTileEntityField, manager); Field loadedEntityField = ReflectUtil.getFields(World.class, List.class)[loadedEntityFieldIndex]; new LoadedEntityList(world, loadedEntityField, manager); if (managers.put(world, manager) != null) { Log.severe("World load fired twice for world " + world.getName()); } } catch (Exception e) { Log.severe("Failed to initialise threading for world " + Log.name(world), e); } if (deadLockDetector == null) { deadLockDetector = new DeadLockDetector(); } } @ForgeSubscribe public synchronized void onWorldUnload(WorldEvent.Unload event) { if (MinecraftServer.getServer().isServerRunning() && !ContextAccess.$.runningUnder(DimensionManager.class)) { Log.severe("World unload event fired from unexpected location", new Throwable()); } World world = event.world; try { TickManager tickManager = managers.remove(world); if (tickManager == null) { Log.severe("World unload fired twice for world " + world.getName(), new Throwable()); return; } tickManager.unload(); Field loadedTileEntityField = ReflectUtil.getFields(World.class, List.class)[loadedTileEntityFieldIndex]; Object loadedTileEntityList = loadedTileEntityField.get(world); if (!(loadedTileEntityList instanceof EntityList)) { Log.severe("Looks like another mod broke TT's replacement tile entity list in world: " + Log.name(world)); } Field loadedEntityField = ReflectUtil.getFields(World.class, List.class)[loadedEntityFieldIndex]; Object loadedEntityList = loadedEntityField.get(world); if (!(loadedEntityList instanceof EntityList)) { Log.severe("Looks like another mod broke TT's replacement entity list in world: " + Log.name(world)); } } catch (Exception e) { Log.severe("Probable memory leak, failed to unload threading for world " + Log.name(world), e); } if (!worlds.remove(world.provider.dimensionId)) { Log.severe("When removing " + world.getName() + ", its provider dimension ID was not already in the world dimension ID set.\n" + Log.dumpWorlds()); } if (world instanceof WorldServer) { ((WorldServer) world).stopChunkTickThreads(); leakDetector.scheduleLeakCheck(world, world.getName(), cleanWorlds); } } @ForgeSubscribe public void onPlayerInteract(PlayerInteractEvent event) { if (event.action == PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK) { EntityPlayer entityPlayer = event.entityPlayer; ItemStack usedItem = entityPlayer.getCurrentEquippedItem(); if (usedItem != null) { Item usedItemType = usedItem.getItem(); if (usedItemType == Item.pocketSundial && (!requireOpForDumpCommand || entityPlayer.canCommandSenderUseCommand(4, "dump"))) { Command.sendChat(entityPlayer, DumpCommand.dump(new TableFormatter(entityPlayer), entityPlayer.worldObj, event.x, event.y, event.z, 35).toString()); event.setCanceled(true); } } } } @ForgeSubscribe public void onPlayerFall(LivingFallEvent event) { EntityLiving livingEntity = event.entityLiving; if (livingEntity.fallDistance > 2 && Log.debug && livingEntity instanceof EntityPlayerMP) { EntityPlayerMP entityPlayerMP = (EntityPlayerMP) livingEntity; Log.debug(entityPlayerMP.username + " fell " + entityPlayerMP.fallDistance + " blocks. Teleported counter: " + entityPlayerMP.playerNetServerHandler.teleported, new Throwable()); } } public TickManager getManager(World world) { return managers.get(world); } public List<TickManager> getManagers() { return new ArrayList<TickManager>(managers.values()); } public boolean shouldFastSpawn(World world) { return this.enableFastMobSpawning && !disabledFastMobSpawningDimensions.contains(world.getDimension()); } public int getThreadCount() { return tickThreads == 0 ? runtime.availableProcessors() + 1 : tickThreads; } public void waitForEntityTicks() { if (!waitForEntityTickCompletion) { long sT = 0; boolean profiling = Timings.enabled; if (profiling) { sT = System.nanoTime(); } for (TickManager manager : managers.values()) { manager.tickEnd(); } if (profiling) { Timings.record("server/EntityTickWait", System.nanoTime() - sT); } } } public boolean removeIfOverMaxItems(final EntityItem e, final Chunk chunk) { if (maxItemsPerChunk == 0) { return false; } ArrayList<EntityItem> entityItems = chunk.getEntitiesOfType(EntityItem.class); if (entityItems.size() > maxItemsPerChunk) { int remaining = 0; for (EntityItem entityItem : entityItems) { if (!entityItem.isDead) { remaining++; entityItem.combineList(entityItems); } } if (remaining > maxItemsPerChunk) { e.setDead(); } if (lastMaxItemWarnedTime < MinecraftServer.currentTick - 10) { lastMaxItemWarnedTime = MinecraftServer.currentTick; Log.warning("Entity items in chunk " + chunk + " exceeded limit of " + maxItemsPerChunk); } return e.isDead; } return false; } private class LoginWarningHandler implements IPlayerTracker { LoginWarningHandler() { } @Override public void onPlayerLogin(final EntityPlayer player) { if (player instanceof EntityPlayerMP) { NetServerHandler netServerHandler = ((EntityPlayerMP) player).playerNetServerHandler; // Warnings for severe issues go here. } } @Override public void onPlayerLogout(final EntityPlayer player) { } @Override public void onPlayerChangedDimension(final EntityPlayer player) { } @Override public void onPlayerRespawn(final EntityPlayer player) { } } private static class ProfilingScheduledTickHandler implements IScheduledTickHandler { private static final EnumSet<TickType> TICKS = EnumSet.of(TickType.SERVER); private final int profilingInterval; private final File profilingFile; private final boolean json; public ProfilingScheduledTickHandler(final int profilingInterval, final File profilingFile, final boolean json) { this.profilingInterval = profilingInterval; this.profilingFile = profilingFile; this.json = json; } @Override public int nextTickSpacing() { return profilingInterval * 60 * 20; } @Override public void tickStart(final EnumSet<TickType> type, final Object... tickData) { final EntityTickProfiler entityTickProfiler = EntityTickProfiler.ENTITY_TICK_PROFILER; entityTickProfiler.startProfiling(new Runnable() { @Override public void run() { try { TableFormatter tf = new TableFormatter(MinecraftServer.getServer()); tf.tableSeparator = "\n"; if (json) { entityTickProfiler.writeJSONData(profilingFile); } else { Files.write(entityTickProfiler.writeStringData(tf, 6).toString(), profilingFile, Charsets.UTF_8); } } catch (Throwable t) { Log.severe("Failed to save periodic profiling data to " + profilingFile, t); } } }, ProfileCommand.ProfilingState.GLOBAL, 10, Arrays.<World>asList(DimensionManager.getWorlds())); } @Override public void tickEnd(final EnumSet<TickType> type, final Object... tickData) { } @Override public EnumSet<TickType> ticks() { return TICKS; } @Override public String getLabel() { return "TickThreading scheduled profiling handler"; } } }
package pitt.search.semanticvectors.vectors; import java.io.IOException; import java.util.ArrayList; import java.util.Random; import java.util.logging.Logger; import org.apache.lucene.store.IndexInput; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.util.OpenBitSet; /** * Binary implementation of Vector. * * Uses an "elemental" representation which is a single bit string (Lucene OpenBitSet). * * Superposes on this a "semantic" representation which contains the weights with which different * vectors have been added (superposed) onto this one. Calling {@link #superpose} causes the * voting record to be updated, but for performance the votes are not tallied back into the * elemental bit set representation until {@link #normalize} or one of the writing functions * is called. * * @author cohen */ public class BinaryVector extends Vector { public static final Logger logger = Logger.getLogger(BinaryVector.class.getCanonicalName()); private static final int DEBUG_PRINT_LENGTH = 64; private final int dimension; /** * Elemental representation for binary vectors. */ private OpenBitSet bitSet; private boolean isSparse; /** * Representation of voting record for superposition. Each OpenBitSet object contains one bit * of the count for the vote in each dimension. The count for any given dimension is derived from * all of the bits in that dimension across the OpenBitSets in the voting record. * * The precision of the voting record (in number of decimal places) is defined upon initialization. * By default, if the first weight added is an integer, rounding occurs to the nearest integer. * Otherwise, rounding occurs to the second binary place. */ private ArrayList<OpenBitSet> votingRecord; int decimalPlaces = 0; /** Accumulated sum of the weights with which vectors have been added into the voting record */ int totalNumberOfVotes = 0; // TODO(widdows) Understand and comment this. int minimum = 0; // Used only for temporary internal storage. private OpenBitSet tempSet; public BinaryVector(int dimension) { // Check "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks if (dimension % 64 != 0) { throw new IllegalArgumentException("Dimension should be a multiple of 64: " + dimension + " will lead to trouble!"); } this.dimension = dimension; this.bitSet = new OpenBitSet(dimension); this.isSparse = true; } /** * Returns a new copy of this vector, in dense format. */ @SuppressWarnings("unchecked") public BinaryVector copy() { BinaryVector copy = new BinaryVector(dimension); copy.bitSet = (OpenBitSet) bitSet.clone(); if (!isSparse) copy.votingRecord = (ArrayList<OpenBitSet>) votingRecord.clone(); return copy; } public String toString() { StringBuilder debugString = new StringBuilder("BinaryVector."); if (isSparse) { debugString.append(" Elemental. First " + DEBUG_PRINT_LENGTH + " values are:\n"); for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(bitSet.getBit(x) + " "); debugString.append("\nCardinality " + bitSet.cardinality()+"\n"); } else { debugString.append(" Semantic. First " + DEBUG_PRINT_LENGTH + " values are:\n"); // output voting record for first DEBUG_PRINT_LENGTH dimension debugString.append("\nVOTING RECORD: \n"); for (int y =0; y < votingRecord.size(); y++) { for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(votingRecord.get(y).getBit(x) + " "); debugString.append("\n"); } // TODO - output count from first DEBUG_PRINT_LENGTH dimension debugString.append("\nNORMALIZED: "); this.normalize(); for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(bitSet.getBit(x) + " "); debugString.append("\n"); // Calculate actual values for first 20 dimension double[] actualvals = new double[DEBUG_PRINT_LENGTH]; debugString.append("COUNTS : "); for (int x =0; x < votingRecord.size(); x++) { for (int y = 0; y < DEBUG_PRINT_LENGTH; y++) { if (votingRecord.get(x).fastGet(y)) actualvals[y] += Math.pow(2, x); } } for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) { debugString.append((int) ((minimum + actualvals[x]) / Math.pow(10, decimalPlaces)) + " "); } debugString.append("\nCardinality " + bitSet.cardinality()+"\n"); debugString.append("Votes " + totalNumberOfVotes+"\n"); debugString.append("Minimum " + minimum + "\n"); } return debugString.toString(); } @Override public int getDimension() { return dimension; } public BinaryVector createZeroVector(int dimension) { // Check "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks if (dimension % 64 != 0) { logger.severe("Dimension should be a multiple of 64: " + dimension + " will lead to trouble!"); } return new BinaryVector(dimension); } @Override public boolean isZeroVector() { if (isSparse) { return bitSet.cardinality() == 0; } else { return (votingRecord == null) || (votingRecord.size() == 0); } } @Override /** * Generates a basic elemental vector with a given number of 1's and otherwise 0's. * For binary vectors, the numnber of 1's and 0's must be the same, half the dimension. * * @return representation of basic binary vector. */ public BinaryVector generateRandomVector(int dimension, int numEntries, Random random) { // Check "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks if (dimension % 64 != 0) { throw new IllegalArgumentException("Dimension should be a multiple of 64: " + dimension + " will lead to trouble!"); } // Check for balance between 1's and 0's if (numEntries != dimension / 2) { logger.severe("Attempting to create binary vector with unequal number of zeros and ones." + " Unlikely to produce meaningful results. Therefore, seedlength has been set to " + " dimension/2, as recommended for binary vectors"); numEntries = dimension / 2; } BinaryVector randomVector = new BinaryVector(dimension); randomVector.bitSet = new OpenBitSet(dimension); int testPlace = dimension - 1, entryCount = 0; // Iterate across dimension of bitSet, changing 0 to 1 if random(1) > 0.5 // until dimension/2 1's added. while (entryCount < numEntries) { testPlace = random.nextInt(dimension); if (!randomVector.bitSet.fastGet(testPlace)) { randomVector.bitSet.fastSet(testPlace); entryCount++; } } return randomVector; } @Override /** * Measures overlap of two vectors using 1 - normalized Hamming distance * * Causes this and other vector to be converted to dense representation. */ public double measureOverlap(Vector other) { IncompatibleVectorsException.checkVectorsCompatible(this, other); if (isZeroVector()) return 0; BinaryVector binaryOther = (BinaryVector) other; if (binaryOther.isZeroVector()) return 0; // Calculate hamming distance in place using cardinality and XOR, then return bitset to // original state. this.bitSet.xor(binaryOther.bitSet); double hammingDistance = this.bitSet.cardinality(); this.bitSet.xor(binaryOther.bitSet); return 1 - (hammingDistance / (double) dimension); } @Override /** * Adds the other vector to this one. If this vector was an elemental vector, the * "semantic vector" components (i.e. the voting record and temporary bitset) will be * initialized. * * Note that the precision of the voting record (in decimal places) is decided at this point: * if the initialization weight is an integer, rounding will occur to the nearest integer. * If not, rounding will occur to the second decimal place. * * This is an attempt to save space, as voting records can be prohibitively expansive * if not contained. */ public void superpose(Vector other, double weight, int[] permutation) { IncompatibleVectorsException.checkVectorsCompatible(this, other); BinaryVector binaryOther = (BinaryVector) other; if (isSparse) { if (Math.round(weight) != weight) { decimalPlaces = 2; } elementalToSemantic(); } if (permutation != null) { // Rather than permuting individual dimensions, we permute 64 bit groups at a time. // This should be considerably quicker, and dimension/64 should allow for sufficient // permutations if (permutation.length != dimension / 64) { throw new IllegalArgumentException("Binary vector of dimension " + dimension + " must have permutation of length " + dimension / 64 + " not " + permutation.length); } //TODO permute in place and reverse, to avoid creating a new BinaryVector here BinaryVector temp = binaryOther.copy(); temp.permute(permutation); superposeBitSet(temp.bitSet, weight); } else { superposeBitSet(binaryOther.bitSet, weight); } } /** * This method is the first of two required to facilitate superposition. The underlying representation * (i.e. the voting record) is an ArrayList of OpenBitSet, each with dimension "dimension", which can * be thought of as an expanding 2D array of bits. Each column keeps count (in binary) for the respective * dimension, and columns are incremented in parallel by sweeping a bitset across the rows. In any dimension * in which the BitSet to be added contains a "1", the effect will be that 1's are changed to 0's until a * new 1 is added (e.g. the column '110' would become '001' and so forth). * * The first method deals with floating point issues, and accelerates superposition by decomposing * the task into segments. * * @param incomingBitSet * @param weight */ protected void superposeBitSet(OpenBitSet incomingBitSet, double weight) { // If fractional weights are used, encode all weights as integers (1000 x double value). weight = (int) Math.round(weight * Math.pow(10, decimalPlaces)); if (weight == 0) return; // Keep track of number (or cumulative weight) of votes. totalNumberOfVotes += weight; // Decompose superposition task such that addition of some power of 2 (e.g. 64) is accomplished // by beginning the process at the relevant row (e.g. 7) instead of starting multiple (e.g. 64) // superposition processes at the first row. int logFloorOfWeight = (int) (Math.floor(Math.log(weight)/Math.log(2))); if (logFloorOfWeight < votingRecord.size() - 1) { while (logFloorOfWeight > 0) { superposeBitSetFromRowFloor(incomingBitSet, logFloorOfWeight); weight = weight - (int) Math.pow(2,logFloorOfWeight); logFloorOfWeight = (int) (Math.floor(Math.log(weight)/Math.log(2))); } } // Add remaining component of weight incrementally. for (int x = 0; x < weight; x++) superposeBitSetFromRowFloor(incomingBitSet, 0); } /** * Performs superposition from a particular row by sweeping a bitset across the voting record * such that for any column in which the incoming bitset contains a '1', 1's are changed * to 0's until a new 1 can be added, facilitating incrementation of the * binary number represented in this column. * * @param incomingBitSet the bitset to be added * @param rowfloor the index of the place in the voting record to start the sweep at */ protected void superposeBitSetFromRowFloor(OpenBitSet incomingBitSet, int rowfloor) { // Attempt to save space when minimum value across all columns > 0 // by decrementing across the board and raising the minimum where possible. int max = getMaximumSharedWeight(); if (max > 0) { decrement(max); } // Handle overflow: if any column that will be incremented // contains all 1's, add a new row to the voting record. tempSet.xor(tempSet); tempSet.xor(incomingBitSet); for (int x = rowfloor; x < votingRecord.size() && tempSet.cardinality() > 0; x++) { tempSet.and(votingRecord.get(x)); } if (tempSet.cardinality() > 0) { votingRecord.add(new OpenBitSet(dimension)); } // Sweep copy of bitset to be added across rows of voting record. // If a new '1' is added, this position in the copy is changed to zero // and will not affect future rows. // The xor step will transform 1's to 0's or vice versa for // dimension in which the temporary bitset contains a '1'. votingRecord.get(rowfloor).xor(incomingBitSet); tempSet.xor(tempSet); tempSet.xor(incomingBitSet); for (int x = rowfloor + 1; x < votingRecord.size(); x++) { tempSet.andNot(votingRecord.get(x-1)); //if 1 already added, eliminate dimension from tempSet votingRecord.get(x).xor(tempSet); votingRecord.get(x).trimTrailingZeros(); //attempt to save in sparsely populated rows } } /** * Reverses a string - simplifies the decoding of the binary vector for the 'exact' method * although it wouldn't be difficult to reverse the counter instead */ public static String reverse(String str) { if ((null == str) || (str.length() <= 1)) { return str; } return new StringBuffer(str).reverse().toString(); } /** * Sets {@link #tempSet} to be a bitset with a "1" in the position of every dimension * in the {@link #votingRecord} that exactly matches the target number. */ private void setTempSetToExactMatches(int target) { if (target == 0) { tempSet.set(0, dimension); tempSet.xor(votingRecord.get(0)); for (int x = 1; x < votingRecord.size(); x++) tempSet.andNot(votingRecord.get(x)); } String inbinary = reverse(Integer.toBinaryString(target)); tempSet.xor(tempSet); tempSet.xor(votingRecord.get(inbinary.indexOf("1"))); for (int q =0; q < votingRecord.size(); q++) { if (q < inbinary.length()) if (inbinary.charAt(q) == '1') tempSet.and(votingRecord.get(q)); else tempSet.andNot(votingRecord.get(q)); } } /** * This method is used determine which dimension will receive 1 and which 0 when the voting * process is concluded. It produces an OpenBitSet in which * "1" is assigned to all dimension with a count > 50% of the total number of votes (i.e. more 1's than 0's added) * "0" is assigned to all dimension with a count < 50% of the total number of votes (i.e. more 0's than 1's added) * "0" or "1" are assigned to all dimension with a count = 50% of the total number of votes (i.e. equal 1's and 0's added) * * @return an OpenBitSet representing the superposition of all vectors added up to this point */ protected OpenBitSet concludeVote() { if (votingRecord.size() == 0) return new OpenBitSet(dimension); else return concludeVote(totalNumberOfVotes); } protected OpenBitSet concludeVote(int target) { int target2 = (int) Math.ceil((double) target / (double) 2); target2 = target2 - minimum; // Unlikely other than in testing: minimum more than half the votes if (target2 < 0) { OpenBitSet ans = new OpenBitSet(dimension); ans.set(0, dimension); return ans; } boolean even = (target % 2 == 0); OpenBitSet result = concludeVote(target2, votingRecord.size() - 1); if (even) { setTempSetToExactMatches(target2); boolean switcher = true; // 50% chance of being true with split vote. for (int q = 0; q < dimension; q++) { if (tempSet.fastGet(q)) { switcher = !switcher; if (switcher) tempSet.fastClear(q); } } result.andNot(tempSet); } return result; } protected OpenBitSet concludeVote(int target, int row_ceiling) { /** logger.info("Entering conclude vote, target " + target + " row_ceiling " + row_ceiling + "voting record " + votingRecord.size() + " minimum "+ minimum + " index "+ Math.log(target)/Math.log(2) + " vector\n" + toString()); **/ if (target == 0) { OpenBitSet atLeastZero = new OpenBitSet(dimension); atLeastZero.set(0, dimension); return atLeastZero; } double rowfloor = Math.log(target)/Math.log(2); int row_floor = (int) Math.floor(rowfloor); //for 0 index int remainder = target - (int) Math.pow(2,row_floor); //System.out.println(target+"\t"+rowfloor+"\t"+row_floor+"\t"+remainder); if (row_ceiling == 0 && target == 1) { return votingRecord.get(0); } if (remainder == 0) { // Simple case - the number we're looking for is 2^n, so anything with a "1" in row n or above is true. OpenBitSet definitePositives = new OpenBitSet(dimension); for (int q = row_floor; q <= row_ceiling; q++) definitePositives.or(votingRecord.get(q)); return definitePositives; } else { // Simple part of complex case: first get anything with a "1" in a row above n (all true). OpenBitSet definitePositives = new OpenBitSet(dimension); for (int q = row_floor+1; q <= row_ceiling; q++) definitePositives.or(votingRecord.get(q)); // Complex part of complex case: get those that have a "1" in the row of n. OpenBitSet possiblePositives = (OpenBitSet) votingRecord.get(row_floor).clone(); OpenBitSet definitePositives2 = concludeVote(remainder, row_floor-1); possiblePositives.and(definitePositives2); definitePositives.or(possiblePositives); return definitePositives; } } /** * Decrement every dimension. Assumes at least one count in each dimension * i.e: no underflow check currently - will wreak havoc with zero counts */ public void decrement() { tempSet.set(0, dimension); for (int q = 0; q < votingRecord.size(); q++) { votingRecord.get(q).xor(tempSet); tempSet.and(votingRecord.get(q)); } } /** * Decrement every dimension by the number passed as a parameter. Again at least one count in each dimension * i.e: no underflow check currently - will wreak havoc with zero counts */ public void decrement(int weight) { if (weight == 0) return; minimum+= weight; int logfloor = (int) (Math.floor(Math.log(weight)/Math.log(2))); if (logfloor < votingRecord.size() - 1) { while (logfloor > 0) { selectedDecrement(logfloor); weight = weight - (int) Math.pow(2,logfloor); logfloor = (int) (Math.floor(Math.log(weight)/Math.log(2))); } } for (int x = 0; x < weight; x++) { decrement(); } } public void selectedDecrement(int floor) { tempSet.set(0, dimension); for (int q = floor; q < votingRecord.size(); q++) { votingRecord.get(q).xor(tempSet); tempSet.and(votingRecord.get(q)); } } /** * Returns the highest value shared by all dimensions. */ protected int getMaximumSharedWeight() { int thismaximum = 0; tempSet.xor(tempSet); // Reset tempset to zeros. for (int x = votingRecord.size() - 1; x >= 0; x tempSet.or(votingRecord.get(x)); if (tempSet.cardinality() == dimension) { thismaximum += (int) Math.pow(2, x); tempSet.xor(tempSet); } } return thismaximum; } @Override /** * Implements binding using permutations and XOR. */ public void bind(Vector other, int direction) { IncompatibleVectorsException.checkVectorsCompatible(this, other); BinaryVector binaryOther = (BinaryVector) other; if (direction > 0) { binaryOther.permute(PermutationUtils.getShiftPermutation(VectorType.BINARY, dimension, 1)); this.bitSet.xor(binaryOther.bitSet); binaryOther.permute(PermutationUtils.getShiftPermutation(VectorType.BINARY, dimension, -1)); } else { binaryOther.permute(PermutationUtils.getShiftPermutation(VectorType.BINARY, dimension, -1)); this.bitSet.xor(binaryOther.bitSet); binaryOther.permute(PermutationUtils.getShiftPermutation(VectorType.BINARY, dimension, 1)); } } @Override /** * Implements inverse of binding using permutations and XOR. */ public void release(Vector other, int direction) { bind (other, direction); } @Override /** * Implements binding using exclusive OR. */ public void bind(Vector other) { IncompatibleVectorsException.checkVectorsCompatible(this, other); BinaryVector binaryOther = (BinaryVector) other; this.bitSet.xor(binaryOther.bitSet); } @Override /** * Implements inverse binding using exclusive OR. */ public void release(Vector other) { bind(other); } @Override /** * Normalizes the vector, converting sparse to dense representations in the process. */ public void normalize() { if (!isSparse) this.bitSet = concludeVote(); } @Override /** * Writes vector out to object output stream. Converts to dense format if necessary. */ public void writeToLuceneStream(IndexOutput outputStream) { if (isSparse) { elementalToSemantic(); } long[] bitArray = bitSet.getBits(); for (int i = 0; i < bitArray.length; i++) { try { outputStream.writeLong(bitArray[i]); } catch (IOException e) { logger.severe("Couldn't write binary vector to lucene output stream."); e.printStackTrace(); } } } @Override /** * Reads a (dense) version of a vector from a Lucene input stream. */ public void readFromLuceneStream(IndexInput inputStream) { long bitArray[] = new long[(dimension / 64)]; for (int i = 0; i < dimension / 64; ++i) { try { bitArray[i] = inputStream.readLong(); } catch (IOException e) { logger.severe("Couldn't read binary vector from lucene output stream."); e.printStackTrace(); } } this.bitSet = new OpenBitSet(bitArray, bitArray.length); this.isSparse = true; } @Override /** * Writes vector to a string of the form 010 etc. (no delimiters). * * No terminating newline or delimiter. */ public String writeToString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < dimension; ++i) { builder.append(Integer.toString(bitSet.getBit(i))); } return builder.toString(); } /** * Writes vector to a string of the form 010 etc. (no delimiters). * * No terminating newline or delimiter. */ public String writeLongToString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < (bitSet.getBits().length); ++i) { builder.append(Long.toString(bitSet.getBits()[i])+"|"); } return builder.toString(); } @Override /** * Writes vector from a string of the form 01001 etc. */ public void readFromString(String input) { if (input.length() != dimension) { throw new IllegalArgumentException("Found " + (input.length()) + " possible coordinates: " + "expected " + dimension); } for (int i = 0; i < dimension; ++i) { if (input.charAt(i) == '1') bitSet.fastSet(i); } } /** * Automatically translate elemental vector (no storage capacity) into * semantic vector (storage capacity initialized, this will occupy RAM) */ protected void elementalToSemantic() { if (!isSparse) { logger.warning("Tried to transform an elemental vector which is not in fact elemental." + "This may be a programming error."); return; } votingRecord = new ArrayList<OpenBitSet>(); votingRecord.add((OpenBitSet) bitSet.clone()); tempSet = new OpenBitSet(dimension); isSparse = false; } /** * Permute the long[] array underlying the OpenBitSet binary representation */ public void permute(int[] permutation) { if (permutation.length != getDimension() / 64) { throw new IllegalArgumentException("Binary vector of dimension " + getDimension() + " must have permutation of length " + getDimension() / 64 + " not " + permutation.length); } //TODO permute in place without creating additional long[] (if proves problematic at scale) long[] coordinates = bitSet.getBits(); long[] newCoordinates = new long[coordinates.length]; for (int i = 0; i < coordinates.length; ++i) { int positionToAdd = i; positionToAdd = permutation[positionToAdd]; newCoordinates[i] = coordinates[positionToAdd]; } bitSet.setBits(newCoordinates); } // Available for testing and copying. protected BinaryVector(OpenBitSet inSet) { this.dimension = (int) inSet.size(); this.bitSet = inSet; } // Available for testing protected int bitLength() { return bitSet.getBits().length; } // Monitor growth of voting record. protected int numRows() { if (isSparse) return 0; return votingRecord.size(); } }
package com.astoev.cave.survey.activity.dialog; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.text.Html; import android.text.method.LinkMovementMethod; import android.text.util.Linkify; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import com.astoev.cave.survey.BuildConfig; import com.astoev.cave.survey.Constants; import com.astoev.cave.survey.R; import com.astoev.cave.survey.util.ConfigUtil; import java.text.SimpleDateFormat; import java.util.Date; /** * Fragment that shows about dialog * * @author Zhivko Mitrev */ public class AboutDialog extends DialogFragment { /** * @see DialogFragment#onCreateDialog(Bundle) */ @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Activity activity = getActivity(); Context context = getActivity().getApplicationContext(); AlertDialog.Builder builder = new AlertDialog.Builder(activity); TextView titleView = new TextView(context); titleView.setText(R.string.about_title); titleView.setGravity(Gravity.CENTER); titleView.setPadding(10, 10, 10, 10); titleView.setTextSize(22); titleView.setTextColor(Color.WHITE); builder.setCustomTitle(titleView); LayoutInflater inflater = getActivity().getLayoutInflater(); View view = inflater.inflate(R.layout.about, null); builder.setView(view); TextView url = (TextView) view.findViewById(R.id.aboutUrl); Linkify.addLinks(url, Linkify.WEB_URLS); StringBuilder versionText = new StringBuilder("v"); try { versionText.append(context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName); } catch (PackageManager.NameNotFoundException e) { Log.e(Constants.LOG_TAG_UI, "Failed get version for about dialog", e); } String buildDate = getBuildDate(); versionText.append(buildDate); if (BuildConfig.DEBUG) { versionText.append(" (Debug)"); } TextView version = (TextView) view.findViewById(R.id.aboutVersion); version.setText(versionText.toString()); StringBuilder userGuideText = new StringBuilder("<a href=\""); userGuideText.append(getString(R.string.about_help)); userGuideText.append("\">"); userGuideText.append(getString(R.string.about_user_guide)); userGuideText.append("</a>"); TextView userGuide = (TextView) view.findViewById(R.id.aboutUserGuide); userGuide.setText(Html.fromHtml(userGuideText.toString())); userGuide.setMovementMethod(LinkMovementMethod.getInstance()); return builder.create(); } private String getBuildDate() { try { Context c = ConfigUtil.getContext(); PackageInfo packageInfo = c.getPackageManager().getPackageInfo(c.getPackageName(), 0); String appBuildDate = SimpleDateFormat.getDateInstance().format(new Date(packageInfo.lastUpdateTime)); return " / " + appBuildDate; } catch (PackageManager.NameNotFoundException e) { Log.e(Constants.LOG_TAG_UI, "Failed to get build date", e); return ""; } } }
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class TextBuddy { private static final String MESSAGE_WELCOME = "Welcome to TextBuddy. %1$s is ready for use"; private static final String MESSAGE_COMMAND = "command: "; private static final String MESSAGE_INVALID_FORMAT = "invalid command format: %1$s"; private static final String MESSAGE_ADDED = "added to %1$s: \"%2$s\""; private static final String MESSAGE_DELETE = "deleted from %1$s: \"%2$s\""; private static final String MESSAGE_DELETE_FAIL = "Line %1$s does not exist in %2$s"; private static final String MESSAGE_DISPLAY = "%1$s. %2$s"; private static final String MESSAGE_CLEAR = "all content deleted from %1$s"; private static final String MESSAGE_EMPTY = "%1$s is empty"; private static final String MESSAGE_ERROR = "Error: %s\n"; private static final String MESSAGE_SORTED = "Contents in %1$s have been sorted"; private static final String MESSAGE_SORTED_FAIL = "%1$s has nothing to sort"; private static final String MESSAGE_SEARCH_FAIL = "\"%1$s\" cannot be found in %2$s"; // These are the possible command types enum CommandTypes { ADD_TEXT, DISPLAY_TEXT, DELETE_TEXT, CLEAR_TEXT, INVALID, EXIT, SORT, SEARCH } // This is the correct number of parameters for delete command private static final int PARAM_SIZE_FOR_DELETE_TEXT = 1; // This is the position where the parameters will appear in a command private static final int PARAM_POSITION_DELETE_VALUE = 0; // This is the indication of empty storage private static final int STORAGE_EMPTY_VALUE = 0; private static final String DEFAULT_FILE = "default.txt"; public static String fileName = DEFAULT_FILE; private static ArrayList<String> storages = new ArrayList<String>(); private static Scanner scanner = new Scanner(System.in); public static void main(String[] args) throws IOException { String msg = getFileName(args); showToUser(msg); while (true) { System.out.print(MESSAGE_COMMAND); String userCommand = scanner.nextLine(); String feedback = executeCommand(userCommand); showToUser(feedback); } } private static String getFileName(String[] input) { if (input.length != 0) { fileName = input[0]; File getFile = new File(fileName); if (getFile.exists()) { openingFile(); } else { try { getFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } } return String.format(MESSAGE_WELCOME, fileName); } private static void openingFile() { BufferedReader inputFile; try { inputFile = new BufferedReader(new FileReader(fileName)); readFromFile(inputFile); } catch (FileNotFoundException e) { e.printStackTrace(); } } private static void readFromFile(BufferedReader file) { String content; try { while ((content = file.readLine()) != null) { storages.add(content); } } catch (IOException e) { e.printStackTrace(); } } private static void showToUser(String text) { System.out.println(text); } public static String executeCommand(String userCommand) { if (userCommand.trim().equals("")) { return String.format(MESSAGE_INVALID_FORMAT, userCommand); } String commandTypeString = getFirstWord(userCommand); CommandTypes commandType = determineCommandType(commandTypeString); switch (commandType) { case ADD_TEXT: return addText(userCommand); case DELETE_TEXT: return deleteText(userCommand); case DISPLAY_TEXT: return displayText(); case CLEAR_TEXT: return clearText(); case INVALID: return String.format(MESSAGE_INVALID_FORMAT, userCommand); case EXIT: exitProgram(); case SORT: return sortText(); case SEARCH: return searchText(userCommand); default: throw new Error("Unrecognized command type"); } } /** * This operation determines which of the supported command types the user * wants to perform * * @param commandTypeString * is the first word of the user command */ private static CommandTypes determineCommandType(String commandTypeString) { if (commandTypeString == null) { throw new Error("command type string cannot be null"); } if (commandTypeString.equalsIgnoreCase("add")) { return CommandTypes.ADD_TEXT; } else if (commandTypeString.equalsIgnoreCase("delete")) { return CommandTypes.DELETE_TEXT; } else if (commandTypeString.equalsIgnoreCase("display")) { return CommandTypes.DISPLAY_TEXT; } else if (commandTypeString.equalsIgnoreCase("clear")) { return CommandTypes.CLEAR_TEXT; } else if (commandTypeString.equalsIgnoreCase("exit")) { return CommandTypes.EXIT; } else if (commandTypeString.equalsIgnoreCase("sort")) { return CommandTypes.SORT; } else if (commandTypeString.equalsIgnoreCase("search")) { return CommandTypes.SEARCH; } else { return CommandTypes.INVALID; } } private static String sortText() { if (storages.size() == 0) { return String.format(MESSAGE_SORTED_FAIL, fileName); } Collections.sort(storages, String.CASE_INSENSITIVE_ORDER); return String.format(MESSAGE_SORTED, fileName); } private static String searchText(String userCommand) { String searchValue = removeFirstWord(userCommand).trim(); if(storages.isEmpty()) { return String.format(MESSAGE_SEARCH_FAIL, searchValue, fileName); } String searchOutput = getSearchOutput(searchValue); if (searchOutput.equals("")) { return String.format(MESSAGE_SEARCH_FAIL, searchValue, fileName); } return searchOutput; } private static String getSearchOutput(String searchValue) { ArrayList<String> searchResult = getSearchResult(searchValue); String searchOutput = ""; for (int i = 0; i < searchResult.size(); i++) { String currentMsg = String.format(MESSAGE_DISPLAY, i + 1, searchResult.get(i)); searchOutput += currentMsg; if (i != searchResult.size() - 1) { searchOutput += "\n"; } } return searchOutput; } private static ArrayList<String> getSearchResult(String searchValue) { ArrayList<String> results = new ArrayList<String>(); for (int i = 0; i < storages.size(); i++) { String text = storages.get(i); if (text.toLowerCase().contains(searchValue.toLowerCase())) { results.add(text); } } return results; } private static String addText(String userCommand) { String textValue = removeFirstWord(userCommand); storages.add(textValue); return String.format(MESSAGE_ADDED, fileName, textValue); } /** * This operation finds the value to be deleted. * * @param userCommand * @return message in String */ private static String deleteText(String userCommand) { String[] parameters = splitParameters(removeFirstWord(userCommand)); if (parameters.length != PARAM_SIZE_FOR_DELETE_TEXT) { return String.format(MESSAGE_INVALID_FORMAT, userCommand); } String deleteValue = parameters[PARAM_POSITION_DELETE_VALUE]; if (!isPositiveNonZeroInt(deleteValue)) { return String.format(MESSAGE_INVALID_FORMAT, userCommand); } if (!isValidIndex(deleteValue)) { return String.format(MESSAGE_DELETE_FAIL, userCommand, fileName); } String deletedText = deleteTextAtPosition(deleteValue); return String.format(MESSAGE_DELETE, fileName, deletedText); } private static String deleteTextAtPosition(String deleteValue) { int deleteIntValue = Integer.parseInt(deleteValue) - 1; String deleteText = storages.get(deleteIntValue); storages.remove(deleteIntValue); return deleteText; } /** * This operation display the data that are saved in the Arraylist of the * program */ private static String displayText() { if (storages.size() == STORAGE_EMPTY_VALUE) { return String.format(MESSAGE_EMPTY, fileName); } String msgToDisplay = getStringText(); return msgToDisplay; } private static String getStringText() { String printingMsg = ""; for (int i = 0; i < storages.size(); i++) { String currentMsg = String.format(MESSAGE_DISPLAY, i + 1, storages.get(i)); printingMsg += currentMsg; if (i != storages.size() - 1) { printingMsg += "\n"; } } return printingMsg; } /** * This operation clear the whole data being saved in the Arraylist of the * program * @return cleared message */ private static String clearText() { storages.clear(); return String.format(MESSAGE_CLEAR, fileName); } /** * This operation overwrites the content of the file and exit the program */ private static void exitProgram() { try { PrintWriter out = new PrintWriter(fileName, "UTF-8"); for (int i = 0; i < storages.size(); i++) { out.println(storages.get(i)); } out.close(); System.exit(0); } catch (IOException e) { System.out.printf(MESSAGE_ERROR, e.getMessage()); } } private static String getFirstWord(String userCommand) { String commandTypeString = userCommand.trim().split("\\s+")[0]; return commandTypeString; } private static String removeFirstWord(String userCommand) { return userCommand.replace(getFirstWord(userCommand), "").trim(); } private static String[] splitParameters(String commandParametersString) { String[] parameters = commandParametersString.trim().split("\\s+"); return parameters; } private static boolean isPositiveNonZeroInt(String deletingValue) { try { int intValue = Integer.parseInt(deletingValue); // return turn if intValue is greater than 0 return (intValue > 0); } catch (NumberFormatException nfe) { return false; } } private static boolean isValidIndex(String deleteValue) { int intValue = Integer.parseInt(deleteValue); if (intValue >= storages.size()) { return false; } return true; } }
// Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.admin.server; import java.util.HashMap; import com.samskivert.io.PersistenceException; import com.samskivert.jdbc.ConnectionProvider; import com.samskivert.util.Invoker; import com.samskivert.util.StringUtil; import com.threerings.presents.dobj.DObject; import com.threerings.admin.Log; import com.threerings.admin.server.persist.ConfigRepository; /** * Implements the {@link ConfigRegistry} using a JDBC database as a persistent * store for the configuration information. <em>Note:</em> config objects * should only be created during server startup because they will result in * synchronous requests to load up the initial configuration data from the * database. This ensures that systems initialized after the config registry * can safely make use of configuration information. */ public class DatabaseConfigRegistry extends ConfigRegistry { /** * Creates a configuration registry and prepares it for operation. * * @param conprov will provide access to our JDBC database. * @param invoker this will be used to perform all database activity * (except first time initialization) so as to avoid blocking the * distributed object thread. */ public DatabaseConfigRegistry (ConnectionProvider conprov, Invoker invoker) throws PersistenceException { _repo = new ConfigRepository(conprov); _invoker = invoker; } // documentation inherited protected ObjectRecord createObjectRecord (String path, DObject object) { return new DatabaseObjectRecord(path, object); } protected class DatabaseObjectRecord extends ObjectRecord { public DatabaseObjectRecord (String path, DObject object) { super(object); _path = path; } public void init () { // load up our persistent data synchronously because we should be // in the middle of server startup when it's OK to do database // access on the main thread and we need to be completely // initialized when we return from this call so that subsequent // systems can predictably make use of the configuration // information that we load try { _data = _repo.loadConfig(_path); } catch (PersistenceException pe) { Log.warning("Failed to load object configuration " + "[path=" + _path + "]."); Log.logStackTrace(pe); _data = new HashMap(); } super.init(); } protected boolean getValue (String field, boolean defval) { String value = (String)_data.get(field); if (value != null) { return "true".equalsIgnoreCase(value); } return defval; } protected short getValue (String field, short defval) { String value = (String)_data.get(field); try { if (value != null) { return Short.parseShort(value); } } catch (Exception e) { // ignore bogus values and return the default } return defval; } protected int getValue (String field, int defval) { String value = (String)_data.get(field); try { if (value != null) { return Integer.parseInt(value); } } catch (Exception e) { // ignore bogus values and return the default } return defval; } protected long getValue (String field, long defval) { String value = (String)_data.get(field); try { if (value != null) { return Long.parseLong(value); } } catch (Exception e) { // ignore bogus values and return the default } return defval; } protected float getValue (String field, float defval) { String value = (String)_data.get(field); try { if (value != null) { return Float.parseFloat(value); } } catch (Exception e) { // ignore bogus values and return the default } return defval; } protected String getValue (String field, String defval) { String value = (String)_data.get(field); return (value == null) ? defval : value; } protected int[] getValue (String field, int[] defval) { String value = (String)_data.get(field); try { if (value != null) { int[] avalue = StringUtil.parseIntArray(value); if (avalue != null) { return avalue; } } } catch (Exception e) { // ignore bogus values and return the default } return defval; } protected float[] getValue (String field, float[] defval) { String value = (String)_data.get(field); try { if (value != null) { float[] avalue = StringUtil.parseFloatArray(value); if (avalue != null) { return avalue; } } } catch (Exception e) { // ignore bogus values and return the default } return defval; } protected long[] getValue (String field, long[] defval) { String value = (String)_data.get(field); try { if (value != null) { long[] avalue = StringUtil.parseLongArray(value); if (avalue != null) { return avalue; } } } catch (Exception e) { // ignore bogus values and return the default } return defval; } protected String[] getValue (String field, String[] defval) { String value = (String)_data.get(field); try { if (value != null) { return StringUtil.parseStringArray(value); } } catch (Exception e) { // ignore bogus values and return the default } return defval; } protected void setValue (String field, boolean value) { setAndFlush(field, String.valueOf(value)); } protected void setValue (String field, short value) { setAndFlush(field, String.valueOf(value)); } protected void setValue (String field, int value) { setAndFlush(field, String.valueOf(value)); } protected void setValue (String field, long value) { setAndFlush(field, String.valueOf(value)); } protected void setValue (String field, float value) { setAndFlush(field, String.valueOf(value)); } protected void setValue (String field, String value) { setAndFlush(field, value); } protected void setValue (String field, int[] value) { setAndFlush(field, StringUtil.toString(value, "", "")); } protected void setValue (String field, float[] value) { setAndFlush(field, StringUtil.toString(value, "", "")); } protected void setValue (String field, long[] value) { setAndFlush(field, StringUtil.toString(value, "", "")); } protected void setValue (String field, String[] value) { setAndFlush(field, StringUtil.joinEscaped(value)); } protected void setAndFlush (final String field, final String value) { _data.put(field, value); _invoker.postUnit(new Invoker.Unit() { public boolean invoke () { try { _repo.updateConfig(_path, field, value); } catch (PersistenceException pe) { Log.warning("Failed to update object configuration " + "[path=" + _path + ", field=" + field + ", value=" + value + "]."); Log.logStackTrace(pe); } return false; } }); } protected String _path; protected HashMap _data; } protected ConfigRepository _repo; protected Invoker _invoker; }
package es.logongas.fpempresa.modelo.comun.usuario; import es.logongas.fpempresa.modelo.centro.Centro; import es.logongas.fpempresa.modelo.empresa.Empresa; import es.logongas.fpempresa.modelo.titulado.Titulado; import es.logongas.ix3.core.BusinessException; import es.logongas.ix3.security.model.User; import es.logongas.ix3.core.annotations.Label; import es.logongas.ix3.security.authentication.Principal; import es.logongas.ix3.service.rules.ActionRule; import es.logongas.ix3.service.rules.ConstraintRule; import es.logongas.ix3.service.rules.RuleContext; import es.logongas.ix3.service.rules.RuleGroupPredefined; import es.logongas.ix3.web.json.annotations.ForbiddenExport; import es.logongas.ix3.web.json.annotations.ForbiddenImport; import javax.validation.constraints.AssertTrue; import javax.validation.constraints.NotNull; import org.hibernate.event.spi.PostLoadEvent; import org.hibernate.event.spi.PostLoadEventListener; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotBlank; /** * * @author Lorenzo */ public class Usuario extends User implements PostLoadEventListener, Principal { @Email @NotBlank @Label("Correo electrónico") private String email; @NotBlank private String nombre; @Label("Apellidos") @NotBlank private String apellidos; private byte[] foto; @Label("Contraseña") private String password; @NotNull @Label("Tipo de usuario") private TipoUsuario tipoUsuario; private Centro centro; private Titulado titulado; private Empresa empresa; @Label("Estado del usuario") private EstadoUsuario estadoUsuario; @ForbiddenImport private boolean validadoEmail; @ForbiddenImport @ForbiddenExport private String claveValidacionEmail; public Usuario() { this.tipoUsuario = TipoUsuario.TITULADO; } @Override public String toString() { return name; } @ConstraintRule(message = "No está habilitado el registro de usuarios",groups=RuleGroupPredefined.PreInsert.class) private boolean isProhibidoNuevoUsuario() { return true; } @AssertTrue(message = "Solo se permite registrar titulados") @Label("") private boolean isSoloPermitidoTitulados() { if (this.getTipoUsuario() == TipoUsuario.TITULADO) { return true; } else { return true; } } @AssertTrue(message = "El centro es requerido si el usuario está aceptado") @Label("") private boolean isCentroRequeridoSiUsuarioAceptado() { if ((this.getTipoUsuario() == TipoUsuario.CENTRO) && (this.getEstadoUsuario() == EstadoUsuario.ACEPTADO)) { if (this.centro == null) { return false; } else { return true; } } else { return true; } } @AssertTrue(message = "La empresa es requerida si el usuario está aceptado") @Label("") private boolean isEmpresaRequeridaSiUsuarioAceptado() { if ((this.getTipoUsuario() == TipoUsuario.EMPRESA) && (this.getEstadoUsuario() == EstadoUsuario.ACEPTADO)) { if (this.empresa == null) { return false; } else { return true; } } else { return true; } } @AssertTrue(message = "Un administrador siempre debe estar aceptado") @Label("") private boolean isAdministradorAceptado() { if (this.getTipoUsuario() == TipoUsuario.ADMINISTRADOR) { if (this.getEstadoUsuario() == EstadoUsuario.ACEPTADO) { return true; } else { return false; } } else { return true; } } @AssertTrue(message = "No es posible añadir usuarios desarrolladores") @Label("") private boolean isDesarrollador() { if (this.getTipoUsuario() == TipoUsuario.DESARROLLADOR) { return false; } else { return true; } } @Override public void onPostLoad(PostLoadEvent ple) { Usuario usuario = (Usuario) ple.getEntity(); usuario.setPassword(null); } @ConstraintRule(message="No es posible modificar el tipo del usuario de '${originalEntity?.tipoUsuario?.toString()}' a '${entity?.tipoUsuario?.toString()}'",groups=RuleGroupPredefined.PreUpdate.class) private boolean isModificadoTipoUsuario(RuleContext<Usuario> ruleContext) { if (ruleContext.getOriginalEntity().getTipoUsuario() != ruleContext.getEntity().getTipoUsuario()) { return false; } return true; } @ConstraintRule(message="Error en el sistema de mensajes",groups=RuleGroupPredefined.PreUpdate.class) private boolean isModificadosValoresUsuario(RuleContext<Usuario> ruleContext) throws BusinessException { Usuario usuario=ruleContext.getEntity(); Usuario usuarioOriginal=ruleContext.getOriginalEntity(); Usuario principal=(Usuario)ruleContext.getPrincipal(); //REGLA SEGURIDAD:Comprobar si puede modificar el estado de un usuario if (usuarioOriginal.getEstadoUsuario() != usuario.getEstadoUsuario()) { if (principal.getEstadoUsuario() != EstadoUsuario.ACEPTADO) { throw new BusinessException("No es posible modificar el estado del usuario ya que TU no estás aceptado"); } switch (principal.getTipoUsuario()) { case ADMINISTRADOR: //No es necesario hace nada pq el administrador siempre puede modificarlo break; case CENTRO: //Solo puede si no es el mismo if (usuario.getIdIdentity() == principal.getIdIdentity()) { throw new BusinessException("Tu mismo no te puedes modificar el estado"); } if (usuario.getTipoUsuario() != TipoUsuario.CENTRO) { throw new BusinessException("No puedes modificar el estado de usuarios que no sean de tipo CENTRO"); } if (usuario.getCentro().getIdCentro() != principal.getCentro().getIdCentro()) { throw new BusinessException("No puedes modificar el estado de usuarios que sean de centros distintos al tuyo"); } break; case EMPRESA: //Solo puede si no es el mismo if (usuario.getIdIdentity() == principal.getIdIdentity()) { throw new BusinessException("Tu mismo no te puedes modificar el estado"); } if (usuario.getTipoUsuario() != TipoUsuario.EMPRESA) { throw new BusinessException("No puedes modificar el estado de usuarios que no sean de tipo EMPRESA"); } if (usuario.getEmpresa().getIdEmpresa() != principal.getEmpresa().getIdEmpresa()) { throw new BusinessException("No puedes modificar el estado de usuarios que sean de empresas distintas a la tuya"); } break; case TITULADO: throw new BusinessException("No es posible modificar el estado de un titulado , ya que siempre es ACEPTADO"); default: throw new BusinessException("No es posible modificar el estado del usuario"); } } return true; } @ActionRule(groups=RuleGroupPredefined.PreInsert.class) private void estadoInicialDelUsuario(RuleContext<Usuario> ruleContext) { Usuario usuario=ruleContext.getEntity(); Usuario usuarioOriginal=ruleContext.getOriginalEntity(); Usuario principal=(Usuario)ruleContext.getPrincipal(); if ((principal!=null) && (principal.getTipoUsuario() == TipoUsuario.ADMINISTRADOR)) { if ((usuario.getTipoUsuario() != TipoUsuario.CENTRO) && (usuario.getTipoUsuario() != TipoUsuario.EMPRESA)) { usuario.setEstadoUsuario(EstadoUsuario.ACEPTADO); } } else { if (usuario.getTipoUsuario() == TipoUsuario.TITULADO) { usuario.setEstadoUsuario(EstadoUsuario.ACEPTADO); } else { usuario.setEstadoUsuario(EstadoUsuario.PENDIENTE_ACEPTACION); } } } @ActionRule(groups=RuleGroupPredefined.PreUpdate.class) private void pasarAPendienteAlCambiarDeCentro(RuleContext<Usuario> ruleContext) { Usuario usuario=ruleContext.getEntity(); Usuario usuarioOriginal=ruleContext.getOriginalEntity(); Usuario principal=(Usuario)ruleContext.getPrincipal(); if (principal.getTipoUsuario() != TipoUsuario.ADMINISTRADOR) { if (usuario.getTipoUsuario() == TipoUsuario.CENTRO) { if (((usuarioOriginal.getCentro() == null) && (usuario.getCentro() != null)) || ((usuarioOriginal.getCentro() != null) && (usuario.getCentro() == null)) || (usuarioOriginal.getCentro().getIdCentro() != usuario.getCentro().getIdCentro())) { usuario.setEstadoUsuario(EstadoUsuario.PENDIENTE_ACEPTACION); } } } } @ActionRule(groups=RuleGroupPredefined.PreUpdate.class) private void pasarAPendienteAlCambiarDeEmpresa(RuleContext<Usuario> ruleContext) { Usuario usuario=ruleContext.getEntity(); Usuario usuarioOriginal=ruleContext.getOriginalEntity(); Usuario principal=(Usuario)ruleContext.getPrincipal(); if (principal.getTipoUsuario() != TipoUsuario.ADMINISTRADOR) { if (usuario.getTipoUsuario() == TipoUsuario.EMPRESA) { if (((usuarioOriginal.getEmpresa() == null) && (usuario.getEmpresa() != null)) || ((usuarioOriginal.getEmpresa() != null) && (usuario.getEmpresa() == null)) || (usuarioOriginal.getEmpresa().getIdEmpresa() != usuario.getEmpresa().getIdEmpresa())) { usuario.setEstadoUsuario(EstadoUsuario.PENDIENTE_ACEPTACION); } } } } /** * @return the titulado */ public Titulado getTitulado() { return titulado; } /** * @param titulado the titulado to set */ public void setTitulado(Titulado titulado) { this.titulado = titulado; } /** * @return the eMail */ public String getEmail() { return email; } /** * @param email the eMail to set */ public void setEmail(String email) { this.email = email; this.login = email; } /** * @return the nombre */ public String getNombre() { return nombre; } /** * @param nombre the nombre to set */ public void setNombre(String nombre) { this.nombre = nombre; this.name = nombre; } /** * @return the apellidos */ public String getApellidos() { return apellidos; } /** * @param apellidos the apellidos to set */ public void setApellidos(String apellidos) { this.apellidos = apellidos; } /** * @return the foto */ public byte[] getFoto() { return foto; } /** * @param foto the foto to set */ public void setFoto(byte[] foto) { this.foto = foto; } /** * @return the password */ public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } /** * @return the tipoUsuario */ public TipoUsuario getTipoUsuario() { return tipoUsuario; } /** * @param tipoUsuario the tipoUsuario to set */ public void setTipoUsuario(TipoUsuario tipoUsuario) { this.tipoUsuario = tipoUsuario; } /** * @return the centro */ public Centro getCentro() { return centro; } /** * @param centro the centro to set */ public void setCentro(Centro centro) { this.centro = centro; } /** * @return the empresa */ public Empresa getEmpresa() { return empresa; } /** * @param empresa the empresa to set */ public void setEmpresa(Empresa empresa) { this.empresa = empresa; } /** * @return the estadoUsuario */ public EstadoUsuario getEstadoUsuario() { return estadoUsuario; } /** * @param estadoUsuario the estadoUsuario to set */ public void setEstadoUsuario(EstadoUsuario estadoUsuario) { this.estadoUsuario = estadoUsuario; } /** * @return the validadoEMail */ public boolean isValidadoEmail() { return validadoEmail; } /** * @param validadoEmail the validadoEmail to set */ public void setValidadoEmail(boolean validadoEmail) { this.validadoEmail = validadoEmail; } /** * @return the claveValidacionEmail */ public String getClaveValidacionEmail() { return claveValidacionEmail; } /** * @param claveValidacionEmail the claveValidacionEmail to set */ public void setClaveValidacionEmail(String claveValidacionEmail) { this.claveValidacionEmail = claveValidacionEmail; } }
package es.logongas.fpempresa.modelo.comun.usuario; import es.logongas.fpempresa.modelo.centro.Centro; import es.logongas.fpempresa.modelo.empresa.Empresa; import es.logongas.fpempresa.modelo.titulado.Titulado; import es.logongas.ix3.core.BusinessException; import es.logongas.ix3.security.model.User; import es.logongas.ix3.core.annotations.Label; import es.logongas.ix3.security.authentication.Principal; import es.logongas.ix3.service.rules.ActionRule; import es.logongas.ix3.service.rules.ConstraintRule; import es.logongas.ix3.service.rules.RuleContext; import es.logongas.ix3.service.rules.RuleGroupPredefined; import java.util.Date; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotBlank; /** * * @author Lorenzo */ public class Usuario extends User implements Principal { @Email @NotBlank @Label("Correo electrónico") private String email; @NotBlank private String nombre; @Label("Apellidos") @NotBlank private String apellidos; private byte[] foto; @Label("Contraseña") private String password; @NotNull @Label("Tipo de usuario") private TipoUsuario tipoUsuario; private Centro centro; private Titulado titulado; private Empresa empresa; @Label("Estado del usuario") private EstadoUsuario estadoUsuario; private boolean validadoEmail; private String claveValidacionEmail; private Date fecha; public Usuario() { this.tipoUsuario = TipoUsuario.TITULADO; } @Override public String toString() { return name; } @ActionRule(groups = RuleGroupPredefined.PreInsert.class) private void estableceFechaCreacion() { this.fecha=new Date(); } @ConstraintRule(disabled = true,message = "No está habilitado el registro de usuarios",groups=RuleGroupPredefined.PreInsert.class,priority = -20) private boolean isProhibidoNuevoUsuario() { return true; } @ConstraintRule(message = "El centro es requerido si el usuario está aceptado") private boolean isCentroRequeridoSiUsuarioAceptado() { if ((this.getTipoUsuario() == TipoUsuario.CENTRO) && (this.getEstadoUsuario() == EstadoUsuario.ACEPTADO)) { if (this.centro == null) { return false; } else { return true; } } else { return true; } } @ConstraintRule(message = "La empresa es requerida si el usuario está aceptado") private boolean isEmpresaRequeridaSiUsuarioAceptado() { if ((this.getTipoUsuario() == TipoUsuario.EMPRESA) && (this.getEstadoUsuario() == EstadoUsuario.ACEPTADO)) { if (this.empresa == null) { return false; } else { return true; } } else { return true; } } @ConstraintRule(message = "Un administrador siempre debe estar aceptado") private boolean isAdministradorAceptado() { if (this.getTipoUsuario() == TipoUsuario.ADMINISTRADOR) { if (this.getEstadoUsuario() == EstadoUsuario.ACEPTADO) { return true; } else { return false; } } else { return true; } } @ConstraintRule(message = "No es posible añadir usuarios desarrolladores") private boolean isDesarrollador() { if (this.getTipoUsuario() == TipoUsuario.DESARROLLADOR) { return false; } else { return true; } } @ConstraintRule(message="No es posible modificar el tipo del usuario de '${originalEntity?.tipoUsuario?.toString()}' a '${entity?.tipoUsuario?.toString()}'",groups=RuleGroupPredefined.PreUpdate.class) private boolean isModificadoTipoUsuario(RuleContext<Usuario> ruleContext) { if (ruleContext.getOriginalEntity().getTipoUsuario() != ruleContext.getEntity().getTipoUsuario()) { return false; } return true; } @ConstraintRule(disabled = true,message="Error en el sistema de mensajes",groups=RuleGroupPredefined.PreUpdate.class) private boolean isModificadosValoresUsuario(RuleContext<Usuario> ruleContext) throws BusinessException { Usuario usuario=ruleContext.getEntity(); Usuario usuarioOriginal=ruleContext.getOriginalEntity(); Usuario principal=(Usuario)ruleContext.getPrincipal(); //REGLA SEGURIDAD:Comprobar si puede modificar el estado de un usuario if (usuarioOriginal.getEstadoUsuario() != usuario.getEstadoUsuario()) { if (principal.getEstadoUsuario() != EstadoUsuario.ACEPTADO) { throw new BusinessException("No es posible modificar el estado del usuario ya que TU no estás aceptado"); } switch (principal.getTipoUsuario()) { case ADMINISTRADOR: //No es necesario hace nada pq el administrador siempre puede modificarlo break; case CENTRO: if (usuario.getTipoUsuario() != TipoUsuario.CENTRO) { throw new BusinessException("No puedes modificar el estado de usuarios que no sean de tipo CENTRO"); } if (usuario.getCentro().getIdCentro() != principal.getCentro().getIdCentro()) { throw new BusinessException("No puedes modificar el estado de usuarios que sean de centros distintos al tuyo"); } break; case EMPRESA: if (usuario.getTipoUsuario() != TipoUsuario.EMPRESA) { throw new BusinessException("No puedes modificar el estado de usuarios que no sean de tipo EMPRESA"); } if (usuario.getEmpresa().getIdEmpresa() != principal.getEmpresa().getIdEmpresa()) { throw new BusinessException("No puedes modificar el estado de usuarios que sean de empresas distintas a la tuya"); } break; case TITULADO: throw new BusinessException("No es posible modificar el estado de un titulado , ya que siempre es ACEPTADO"); default: throw new BusinessException("No es posible modificar el estado del usuario"); } } return true; } @ActionRule(groups = RuleGroupPredefined.PostRead.class) private void quitarHashPassword() { this.setPassword(null); } @ActionRule(groups=RuleGroupPredefined.PreInsert.class) private void estadoInicialDelUsuario(RuleContext<Usuario> ruleContext) { Usuario usuario=ruleContext.getEntity(); Usuario usuarioOriginal=ruleContext.getOriginalEntity(); Usuario principal=(Usuario)ruleContext.getPrincipal(); if ((principal!=null) && (principal.getTipoUsuario() == TipoUsuario.ADMINISTRADOR)) { if ((usuario.getTipoUsuario() != TipoUsuario.CENTRO) && (usuario.getTipoUsuario() != TipoUsuario.EMPRESA)) { usuario.setEstadoUsuario(EstadoUsuario.ACEPTADO); } } else { if (usuario.getTipoUsuario() == TipoUsuario.TITULADO) { usuario.setEstadoUsuario(EstadoUsuario.ACEPTADO); } else { usuario.setEstadoUsuario(EstadoUsuario.PENDIENTE_ACEPTACION); } } } @ActionRule(groups=RuleGroupPredefined.PreUpdate.class) private void pasarAPendienteAlCambiarDeCentro(RuleContext<Usuario> ruleContext) { Usuario usuario=ruleContext.getEntity(); Usuario usuarioOriginal=ruleContext.getOriginalEntity(); Usuario principal=(Usuario)ruleContext.getPrincipal(); if (principal.getTipoUsuario() != TipoUsuario.ADMINISTRADOR) { if (usuario.getTipoUsuario() == TipoUsuario.CENTRO) { if (((usuarioOriginal.getCentro() == null) && (usuario.getCentro() != null)) || ((usuarioOriginal.getCentro() != null) && (usuario.getCentro() == null)) || (usuarioOriginal.getCentro().getIdCentro() != usuario.getCentro().getIdCentro())) { usuario.setEstadoUsuario(EstadoUsuario.PENDIENTE_ACEPTACION); } } } } /** * @return the titulado */ public Titulado getTitulado() { return titulado; } /** * @param titulado the titulado to set */ public void setTitulado(Titulado titulado) { this.titulado = titulado; } /** * @return the eMail */ public String getEmail() { return email; } /** * @param email the eMail to set */ public void setEmail(String email) { this.email = email; this.login = email; } /** * @return the nombre */ public String getNombre() { return nombre; } /** * @param nombre the nombre to set */ public void setNombre(String nombre) { this.nombre = nombre; this.name = nombre; } /** * @return the apellidos */ public String getApellidos() { return apellidos; } /** * @param apellidos the apellidos to set */ public void setApellidos(String apellidos) { this.apellidos = apellidos; } /** * @return the foto */ public byte[] getFoto() { return foto; } /** * @param foto the foto to set */ public void setFoto(byte[] foto) { this.foto = foto; } /** * @return the password */ public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } /** * @return the tipoUsuario */ public TipoUsuario getTipoUsuario() { return tipoUsuario; } /** * @param tipoUsuario the tipoUsuario to set */ public void setTipoUsuario(TipoUsuario tipoUsuario) { this.tipoUsuario = tipoUsuario; } /** * @return the centro */ public Centro getCentro() { return centro; } /** * @param centro the centro to set */ public void setCentro(Centro centro) { this.centro = centro; } /** * @return the empresa */ public Empresa getEmpresa() { return empresa; } /** * @param empresa the empresa to set */ public void setEmpresa(Empresa empresa) { this.empresa = empresa; } /** * @return the estadoUsuario */ public EstadoUsuario getEstadoUsuario() { return estadoUsuario; } /** * @param estadoUsuario the estadoUsuario to set */ public void setEstadoUsuario(EstadoUsuario estadoUsuario) { this.estadoUsuario = estadoUsuario; } /** * @return the validadoEMail */ public boolean isValidadoEmail() { return validadoEmail; } /** * @param validadoEmail the validadoEmail to set */ public void setValidadoEmail(boolean validadoEmail) { this.validadoEmail = validadoEmail; } /** * @return the claveValidacionEmail */ public String getClaveValidacionEmail() { return claveValidacionEmail; } /** * @param claveValidacionEmail the claveValidacionEmail to set */ public void setClaveValidacionEmail(String claveValidacionEmail) { this.claveValidacionEmail = claveValidacionEmail; } /** * @return the fecha */ public Date getFecha() { return fecha; } /** * @param fecha the fecha to set */ public void setFecha(Date fecha) { this.fecha = fecha; } }
package imagej.legacy; import ij.IJ; import ij.Prefs; import ij.gui.Arrow; import ij.gui.Line; import ij.gui.ProfilePlot; import ij.gui.Roi; import ij.gui.TextRoi; import ij.gui.Toolbar; import ij.io.FileSaver; import ij.plugin.RectToolOptions; import ij.plugin.WandToolOptions; import ij.plugin.filter.Analyzer; import ij.process.ColorProcessor; import ij.process.FloatBlitter; import ij.process.ImageConverter; import imagej.core.options.OptionsAppearance; import imagej.core.options.OptionsArrowTool; import imagej.core.options.OptionsCompiler; import imagej.core.options.OptionsConversions; import imagej.core.options.OptionsDicom; import imagej.core.options.OptionsFont; import imagej.core.options.OptionsInputOutput; import imagej.core.options.OptionsLineWidth; import imagej.core.options.OptionsMemoryAndThreads; import imagej.core.options.OptionsMisc; import imagej.core.options.OptionsPointTool; import imagej.core.options.OptionsProfilePlot; import imagej.core.options.OptionsProxy; import imagej.core.options.OptionsRoundedRectangleTool; import imagej.core.options.OptionsWandTool; import imagej.data.options.OptionsChannels; import imagej.data.options.OptionsOverlay; import imagej.options.OptionsService; import imagej.util.ClassUtils; import imagej.util.ColorRGB; import imagej.util.awt.AWTColors; import java.awt.Color; import java.awt.Font; import java.lang.reflect.Field; /** * The options synchronizer bidirectionally synchronizes IJ2 options with IJ1 * settings and preferences. * * @author Barry DeZonia */ public class OptionsSynchronizer { private final OptionsService optionsService; public OptionsSynchronizer(final OptionsService optionsService) { this.optionsService = optionsService; } /** * Updates IJ1 settings and preferences to reflect values set in IJ2 dialogs. */ public void updateIJ1SettingsFromIJ2() { appearanceOptions(); arrowOptions(); colorOptions(); compilerOptions(); conversionsOptions(); dicomOptions(); fontOptions(); ioOptions(); lineWidthOptions(); memoryAndThreadsOptions(); miscOptions(); overlayOptions(); pointOptions(); profilePlotOptions(); proxyOptions(); roundRectOptions(); wandToolOptions(); } /** * Updates IJ2 options dialog settings to reflect values set by IJ1 plugins. */ public void updateIJ2SettingsFromIJ1() { setOptionsFromStatics(); } // -- helpers -- private void appearanceOptions() { final OptionsAppearance optionsAppearance = optionsService.getOptions(OptionsAppearance.class); Prefs.antialiasedText = false; Prefs.antialiasedTools = optionsAppearance.isAntialiasedToolIcons(); Prefs.blackCanvas = optionsAppearance.isBlackCanvas(); Prefs.open100Percent = optionsAppearance.isFullZoomImages(); Prefs.interpolateScaledImages = optionsAppearance.isInterpZoomedImages(); Prefs.noBorder = optionsAppearance.isNoImageBorder(); Prefs.useInvertingLut = optionsAppearance.isUseInvertingLUT(); Roi.setColor(AWTColors.getColor(optionsAppearance.getSelectionColor())); // TODO // this one needs to have code applied to IJ2. Nothing to set for IJ1. // Prefs.get(SettingsKeys.OPTIONS_APPEARANCE_MENU_FONT_SIZE); } private void arrowOptions() { final OptionsArrowTool optionsArrowTool = optionsService.getOptions(OptionsArrowTool.class); // TODO - arrow color support: when the arrow color is edited in the IJ1 // arrow tool options dialog the foreground color is changed to match. // Might need to set IJ1's Toolbar foreground color to our arrow color. But // this likely has unintended side effects if its set during every options // synchronization. Think about what is best. Ignore for now. // String color = optionsArrowTool.getArrowColor(); final boolean doubleHeaded = optionsArrowTool.isArrowDoubleHeaded(); final boolean outline = optionsArrowTool.isArrowOutline(); final int size = optionsArrowTool.getArrowSize(); String style = optionsArrowTool.getArrowStyle(); final int width = optionsArrowTool.getArrowWidth(); if (style == null) style = "Filled"; int styleIndex = 0; if (style.equals("Filled")) styleIndex = 0; else if (style.equals("Notched")) styleIndex = 1; else if (style.equals("Open")) styleIndex = 2; else if (style.equals("Headless")) styleIndex = 3; Prefs.set(Arrow.STYLE_KEY, styleIndex); Prefs.set(Arrow.WIDTH_KEY, width); Prefs.set(Arrow.SIZE_KEY, size); Prefs.set(Arrow.OUTLINE_KEY, outline); Prefs.set(Arrow.DOUBLE_HEADED_KEY, doubleHeaded); Arrow.setDefaultStyle(styleIndex); Arrow.setDefaultWidth(width); Arrow.setDefaultHeadSize(size); Arrow.setDefaultOutline(outline); Arrow.setDefaultDoubleHeaded(doubleHeaded); } private void colorOptions() { OptionsChannels options = optionsService.getOptions(OptionsChannels.class); final ColorRGB lastFgColor = options.getLastFgColor(); final ColorRGB lastBgColor = options.getLastBgColor(); colorOptions(lastFgColor, lastBgColor); } public void colorOptions(ColorRGB fgColor, ColorRGB bgColor) { Toolbar.setForegroundColor(AWTColors.getColor(fgColor)); Toolbar.setBackgroundColor(AWTColors.getColor(bgColor)); OptionsChannels options = optionsService.getOptions(OptionsChannels.class); options.setLastFgColor(fgColor, false); options.setLastBgColor(bgColor, false); //options.save(); BDZ - shouldn't be necessary - see OptionsChannels impl } private void compilerOptions() { final OptionsCompiler optionsCompiler = optionsService.getOptions(OptionsCompiler.class); String version = optionsCompiler.getTargetJavaVersion(); if (version == null) version = "1.5"; if (version.equals("1.4")) Prefs.set("javac.target", 0); else if (version.equals("1.5")) Prefs.set("javac.target", 1); else if (version.equals("1.6")) Prefs.set("javac.target", 2); else if (version.equals("1.7")) Prefs.set("javac.target", 3); setIJ1CompilerTarget(optionsCompiler.getTargetJavaVersion()); setIJ1CompilerDebugFlag(optionsCompiler.isGenerateDebugInfo()); } private void conversionsOptions() { final OptionsConversions optionsConversions = optionsService.getOptions(OptionsConversions.class); final double third = 1d / 3d; final double[] weights = ColorProcessor.getWeightingFactors(); final boolean weighted = !(weights[0] == third && weights[1] == third && weights[2] == third); ImageConverter.setDoScaling(optionsConversions.isScaleWhenConverting()); Prefs.weightedColor = optionsConversions.isWeightedRgbConversions(); if (!Prefs.weightedColor) { ColorProcessor.setWeightingFactors(third, third, third); } else if (Prefs.weightedColor && !weighted) { ColorProcessor.setWeightingFactors(0.299, 0.587, 0.114); } } private void dicomOptions() { final OptionsDicom optionsDicom = optionsService.getOptions(OptionsDicom.class); Prefs.openDicomsAsFloat = optionsDicom.isOpenAs32bitFloat(); Prefs.flipXZ = optionsDicom.isRotateXZ(); Prefs.rotateYZ = optionsDicom.isRotateYZ(); } private void fontOptions() { final OptionsFont optionsFont = optionsService.getOptions(OptionsFont.class); final String fontName = optionsFont.getFont(); final int fontSize = optionsFont.getFontSize(); String styleName = optionsFont.getFontStyle(); final boolean smooth = optionsFont.isFontSmooth(); if (styleName == null) styleName = ""; int fontStyle = Font.PLAIN; if (styleName.equals("Bold")) fontStyle = Font.BOLD; else if (styleName.equals("Italic")) fontStyle = Font.ITALIC; else if (styleName.equals("Bold+Italic")) fontStyle = Font.BOLD + Font.ITALIC; TextRoi.setFont(fontName, fontSize, fontStyle, smooth); } private void ioOptions() { final OptionsInputOutput optionsInputOutput = optionsService.getOptions(OptionsInputOutput.class); Prefs.copyColumnHeaders = optionsInputOutput.isCopyColumnHeaders(); Prefs.noRowNumbers = !optionsInputOutput.isCopyRowNumbers(); String extension = optionsInputOutput.getTableFileExtension(); if (extension == null) extension = ".txt"; Prefs.set("options.ext", extension); FileSaver.setJpegQuality(optionsInputOutput.getJpegQuality()); Prefs.dontSaveHeaders = !optionsInputOutput.isSaveColumnHeaders(); Prefs.intelByteOrder = optionsInputOutput.isSaveOrderIntel(); Prefs.dontSaveRowNumbers = !optionsInputOutput.isSaveRowNumbers(); Prefs.setTransparentIndex(optionsInputOutput.getTransparentIndex()); Prefs.useJFileChooser = optionsInputOutput.isUseJFileChooser(); } private void lineWidthOptions() { final OptionsLineWidth optionsLineWidth = optionsService.getOptions(OptionsLineWidth.class); Line.setWidth(optionsLineWidth.getLineWidth()); } private void memoryAndThreadsOptions() { final OptionsMemoryAndThreads optionsMemoryAndThreads = optionsService.getOptions(OptionsMemoryAndThreads.class); Prefs.keepUndoBuffers = optionsMemoryAndThreads.isMultipleBuffers(); Prefs.noClickToGC = !optionsMemoryAndThreads.isRunGcOnClick(); Prefs.setThreads(optionsMemoryAndThreads.getStackThreads()); // TODO // nothing to set in this next case. Need IJ2 to fire some code as // appropriate // Prefs.get(SettingsKeys.OPTIONS_MEMORYTHREADS_MAX_MEMORY); } private void miscOptions() { final OptionsMisc optionsMisc = optionsService.getOptions(OptionsMisc.class); String divValue = optionsMisc.getDivByZeroVal(); IJ.debugMode = optionsMisc.isDebugMode(); IJ.hideProcessStackDialog = optionsMisc.isHideProcessStackDialog(); Prefs.moveToMisc = optionsMisc.isMoveIsolatedPlugins(); Prefs.usePointerCursor = optionsMisc.isUsePtrCursor(); Prefs.requireControlKey = optionsMisc.isRequireCommandKey(); Prefs.runSocketListener = optionsMisc.isRunSingleInstanceListener(); if (divValue == null) divValue = "infinity"; if (divValue.equalsIgnoreCase("infinity") || divValue.equalsIgnoreCase("infinite")) FloatBlitter.divideByZeroValue = Float.POSITIVE_INFINITY; else if (divValue.equalsIgnoreCase("NaN")) FloatBlitter.divideByZeroValue = Float.NaN; else if (divValue.equalsIgnoreCase("max")) FloatBlitter.divideByZeroValue = Float.MAX_VALUE; else { Float f; try { f = new Float(divValue); } catch (final NumberFormatException e) { f = null; } if (f != null) FloatBlitter.divideByZeroValue = f.floatValue(); } } private void overlayOptions() { final OptionsOverlay options = optionsService.getOptions(OptionsOverlay.class); final Roi defaultRoi = getIJ1DefaultRoi(); // NB - setStrokeWidth() must be called before setFillColor() or fill info // gets lost going to IJ1 when stroke width > 1. defaultRoi.setStrokeWidth(options.getLineWidth()); Color color = AWTColors.getColor(options.getLineColor()); defaultRoi.setStrokeColor(color); if (options.getAlpha() == 0) { defaultRoi.setFillColor(null); } else { color = AWTColors.getColor(options.getFillColor(), options.getAlpha()); defaultRoi.setFillColor(color); } } private void pointOptions() { final OptionsPointTool optionsPointTool = optionsService.getOptions(OptionsPointTool.class); Prefs.pointAddToManager = optionsPointTool.isAddToRoiMgr(); Prefs.pointAutoMeasure = optionsPointTool.isAutoMeasure(); Prefs.pointAutoNextSlice = optionsPointTool.isAutoNextSlice(); Prefs.noPointLabels = !optionsPointTool.isLabelPoints(); Analyzer.markWidth = optionsPointTool.getMarkWidth(); // removing: set elsewhere - can get out of sync // Roi.setColor(getColor(optionsPointTool.getSelectionColor(), // Color.yellow)); } private void profilePlotOptions() { final OptionsProfilePlot optionsProfilePlot = optionsService.getOptions(OptionsProfilePlot.class); ij.gui.PlotWindow.autoClose = optionsProfilePlot.isAutoClose(); ij.gui.PlotWindow.saveXValues = !optionsProfilePlot.isNoSaveXValues(); ij.gui.PlotWindow.noGridLines = !optionsProfilePlot.isDrawGridLines(); boolean fixedScale = optionsProfilePlot.isYFixedScale(); ij.gui.PlotWindow.plotHeight = optionsProfilePlot.getHeight(); ij.gui.PlotWindow.interpolate = optionsProfilePlot.isInterpLineProf(); ij.gui.PlotWindow.listValues = optionsProfilePlot.isListValues(); double yMax = optionsProfilePlot.getMaxY(); double yMin = optionsProfilePlot.getMinY(); Prefs.verticalProfile = optionsProfilePlot.isVertProfile(); ij.gui.PlotWindow.plotWidth = optionsProfilePlot.getWidth(); if (!fixedScale && (yMin != 0.0 || yMax != 0.0)) fixedScale = true; if (!fixedScale) { yMin = 0.0; yMax = 0.0; } else if (yMin > yMax) { final double tmp = yMin; yMin = yMax; yMax = tmp; } ProfilePlot.setMinAndMax(yMin, yMax); } private void proxyOptions() { final OptionsProxy optionsProxy = optionsService.getOptions(OptionsProxy.class); final String server = optionsProxy.getProxyServer(); if (server != null) { Prefs.set("proxy.server", server); Prefs.set("proxy.port", optionsProxy.getPort()); } ij.Prefs.useSystemProxies = optionsProxy.isUseSystemProxy(); } private void roundRectOptions() { final OptionsRoundedRectangleTool optionsRoundedRectangleTool = optionsService.getOptions(OptionsRoundedRectangleTool.class); final int crnDiam = optionsRoundedRectangleTool.getCornerDiameter(); Toolbar.setRoundRectArcSize(crnDiam); final double width = optionsRoundedRectangleTool.getStrokeWidth(); setIJ1DefaultStrokeWidth(width); // TODO // IJ1 RectToolOptions does not manipulate Prefs much. It fires // code to change behavior when dialog entries changed. No programmatic // way to make our settings affect IJ1. Need pure IJ2 support elsewhere. // Prefs.get(SettingsKeys.OPTIONS_ROUND_RECT_FILL_COLOR, none); ?how to // handle "none"? // Prefs.get(SettingsKeys.OPTIONS_ROUND_RECT_STROKE_COLOR, Color.black); // NB BDZ thinks these prefs are unimportant. We use Overlay "Properties" // dialog in IJ2 to change these. } private void wandToolOptions() { final OptionsWandTool optionsWand = optionsService.getOptions(OptionsWandTool.class); final String mode = optionsWand.getMode(); final double tol = optionsWand.getTolerance(); setIJ1WandMode(mode); setIJ1WandTolerance(tol); } private void setOptionsFromStatics() { final OptionsAppearance optionsAppearance = optionsService.getOptions(OptionsAppearance.class); optionsAppearance.setAntialiasedToolIcons(Prefs.antialiasedTools); optionsAppearance.setBlackCanvas(Prefs.blackCanvas); optionsAppearance.setFullZoomImages(Prefs.open100Percent); optionsAppearance.setInterpZoomedImages(Prefs.interpolateScaledImages); optionsAppearance.setNoImageBorder(Prefs.noBorder); optionsAppearance.setUseInvertingLUT(Prefs.useInvertingLut); optionsAppearance.setSelectionColor(AWTColors.getColorRGB(Roi.getColor())); optionsAppearance.save(); final OptionsArrowTool optionsArrowTool = optionsService.getOptions(OptionsArrowTool.class); final boolean arrowTwoHeads = Arrow.getDefaultDoubleHeaded(); optionsArrowTool.setArrowDoubleHeaded(arrowTwoHeads); final boolean arrowOutline = Arrow.getDefaultOutline(); optionsArrowTool.setArrowOutline(arrowOutline); final int arrowSize = (int) Arrow.getDefaultHeadSize(); optionsArrowTool.setArrowSize(arrowSize); final int arrowStyle = Arrow.getDefaultStyle(); String arrowStyleName; if (arrowStyle == 1) arrowStyleName = "Notched"; else if (arrowStyle == 2) arrowStyleName = "Open"; else if (arrowStyle == 3) arrowStyleName = "Headless"; else arrowStyleName = "Filled"; optionsArrowTool.setArrowStyle(arrowStyleName); final int arrowWidth = (int) Arrow.getDefaultWidth(); optionsArrowTool.setArrowWidth(arrowWidth); optionsArrowTool.save(); /* retired final OptionsChannels optionsColors = optionsService.getOptions(OptionsChannels.class); optionsColors.setFgColor( AWTColors.getColorRGB(Toolbar.getForegroundColor())); optionsColors.setBgColor( AWTColors.getColorRGB(Toolbar.getBackgroundColor())); optionsColors.save(); */ final OptionsCompiler optionsCompiler = optionsService.getOptions(OptionsCompiler.class); final Field field = getCompilerField("target"); final boolean debug = getIJ1CompilerDebugFlag(); final String target = getIJ1CompilerTarget(); if (field != null) { optionsCompiler.setTargetJavaVersion(target); optionsCompiler.setGenerateDebugInfo(debug); optionsCompiler.save(); } final OptionsConversions optionsConversions = optionsService.getOptions(OptionsConversions.class); optionsConversions.setScaleWhenConverting(ImageConverter.getDoScaling()); optionsConversions.setWeightedRgbConversions(Prefs.weightedColor); optionsConversions.save(); final OptionsDicom optionsDicom = optionsService.getOptions(OptionsDicom.class); optionsDicom.setOpenAs32bitFloat(Prefs.openDicomsAsFloat); optionsDicom.setRotateXZ(Prefs.flipXZ); optionsDicom.setRotateYZ(Prefs.rotateYZ); optionsDicom.save(); final OptionsFont optionsFont = optionsService.getOptions(OptionsFont.class); optionsFont.setFont(TextRoi.getFont()); optionsFont.setFontSize(TextRoi.getSize()); String fontStyleString; final int tmp = TextRoi.getStyle(); if (tmp == Font.BOLD + Font.ITALIC) fontStyleString = "Bold+Italic"; else if (tmp == Font.BOLD) fontStyleString = "Bold"; else if (tmp == Font.ITALIC) fontStyleString = "Italic"; else fontStyleString = ""; optionsFont.setFontStyle(fontStyleString); optionsFont.save(); final OptionsInputOutput optionsInputOutput = optionsService.getOptions(OptionsInputOutput.class); optionsInputOutput.setCopyColumnHeaders(Prefs.copyColumnHeaders); optionsInputOutput.setCopyRowNumbers(!Prefs.noRowNumbers); optionsInputOutput.setJpegQuality(FileSaver.getJpegQuality()); optionsInputOutput.setSaveColumnHeaders(!Prefs.dontSaveHeaders); optionsInputOutput.setSaveOrderIntel(Prefs.intelByteOrder); optionsInputOutput.setSaveRowNumbers(!Prefs.dontSaveRowNumbers); optionsInputOutput.setTransparentIndex(Prefs.getTransparentIndex()); optionsInputOutput.setUseJFileChooser(Prefs.useJFileChooser); optionsInputOutput.save(); final OptionsLineWidth optionsLineWidth = optionsService.getOptions(OptionsLineWidth.class); optionsLineWidth.setLineWidth(Line.getWidth()); optionsLineWidth.save(); final OptionsMemoryAndThreads optionsMemoryAndThreads = optionsService.getOptions(OptionsMemoryAndThreads.class); optionsMemoryAndThreads.setMultipleBuffers(Prefs.keepUndoBuffers); optionsMemoryAndThreads.setRunGcOnClick(!Prefs.noClickToGC); optionsMemoryAndThreads.setStackThreads(Prefs.getThreads()); optionsMemoryAndThreads.save(); final OptionsMisc optionsMisc = optionsService.getOptions(OptionsMisc.class); final String dbzString = new Float(FloatBlitter.divideByZeroValue).toString(); optionsMisc.setDivByZeroVal(dbzString); optionsMisc.setDebugMode(IJ.debugMode); optionsMisc.setHideProcessStackDialog(IJ.hideProcessStackDialog); optionsMisc.setMoveIsolatedPlugins(Prefs.moveToMisc); optionsMisc.setUsePtrCursor(Prefs.usePointerCursor); optionsMisc.setRequireCommandKey(Prefs.requireControlKey); optionsMisc.setRunSingleInstanceListener(Prefs.runSocketListener); optionsMisc.save(); final OptionsOverlay optionsOverlay = optionsService.getOptions(OptionsOverlay.class); final Roi defaultRoi = getIJ1DefaultRoi(); Color c = defaultRoi.getFillColor(); if (c == null) optionsOverlay.setAlpha(0); else { optionsOverlay.setAlpha(c.getAlpha()); final ColorRGB crgb = AWTColors.getColorRGB(c); optionsOverlay.setFillColor(crgb); } c = defaultRoi.getStrokeColor(); if (c == null) c = Roi.getColor(); if (c != null) optionsOverlay.setLineColor(AWTColors.getColorRGB(c)); optionsOverlay.setLineWidth(defaultRoi.getStrokeWidth()); optionsOverlay.save(); final OptionsPointTool optionsPointTool = optionsService.getOptions(OptionsPointTool.class); optionsPointTool.setAddToRoiMgr(Prefs.pointAddToManager); optionsPointTool.setAutoMeasure(Prefs.pointAutoMeasure); optionsPointTool.setAutoNextSlice(Prefs.pointAutoNextSlice); optionsPointTool.setLabelPoints(!Prefs.noPointLabels); optionsPointTool.setMarkWidth(Analyzer.markWidth); optionsPointTool.save(); final OptionsProfilePlot optionsProfilePlot = optionsService.getOptions(OptionsProfilePlot.class); optionsProfilePlot.setAutoClose(ij.gui.PlotWindow.autoClose); optionsProfilePlot.setNoSaveXValues(!ij.gui.PlotWindow.saveXValues); optionsProfilePlot.setDrawGridLines(!ij.gui.PlotWindow.noGridLines); optionsProfilePlot.setHeight(ij.gui.PlotWindow.plotHeight); optionsProfilePlot.setInterpLineProf(ij.gui.PlotWindow.interpolate); optionsProfilePlot.setListValues(ij.gui.PlotWindow.listValues); final double yMin = ProfilePlot.getFixedMin(); final double yMax = ProfilePlot.getFixedMax(); optionsProfilePlot.setMaxY(yMax); optionsProfilePlot.setMinY(yMin); optionsProfilePlot.setVertProfile(Prefs.verticalProfile); optionsProfilePlot.setWidth(ij.gui.PlotWindow.plotWidth); optionsProfilePlot.save(); final OptionsProxy optionsProxy = optionsService.getOptions(OptionsProxy.class); optionsProxy.setUseSystemProxy(ij.Prefs.useSystemProxies); optionsProxy.save(); final OptionsRoundedRectangleTool optionsRoundedRectangleTool = optionsService.getOptions(OptionsRoundedRectangleTool.class); final int crnDiam = Toolbar.getRoundRectArcSize(); final double width = getIJ1DefaultStrokeWidth(); optionsRoundedRectangleTool.setCornerDiameter(crnDiam); optionsRoundedRectangleTool.setStrokeWidth((int) width); optionsRoundedRectangleTool.save(); final OptionsWandTool optionsWandTool = optionsService.getOptions(OptionsWandTool.class); final String mode = getIJ1WandMode(); final double tol = getIJ1WandTolerance(); optionsWandTool.setMode(mode); optionsWandTool.setTolerance(tol); optionsWandTool.save(); } private Roi getIJ1DefaultRoi() { final Field field = ClassUtils.getField("ij.plugin.OverlayCommands", "defaultRoi"); final Object obj = ClassUtils.getValue(field, null); return (Roi) obj; } private void setIJ1CompilerDebugFlag(final boolean b) { final Field field = getCompilerField("generateDebuggingInfo"); if (field == null) return; ClassUtils.setValue(field, null, b); } private boolean getIJ1CompilerDebugFlag() { final Field field = getCompilerField("generateDebuggingInfo"); if (field == null) return false; return (Boolean) ClassUtils.getValue(field, null); } private void setIJ1CompilerTarget(final String target) { final Field field = getCompilerField("target"); if (field == null) return; int t = 1; if (target.equals("1.4")) t = 0; else if (target.equals("1.5")) t = 1; else if (target.equals("1.6")) t = 2; else if (target.equals("1.7")) t = 3; ClassUtils.setValue(field, null, t); } private String getIJ1CompilerTarget() { final Field field = getCompilerField("target"); if (field == null) return "1.5"; final int t = (Integer) ClassUtils.getValue(field, null); if (t == 0) return "1.4"; if (t == 1) return "1.5"; if (t == 2) return "1.6"; if (t == 3) return "1.7"; return "1.5"; } private void setIJ1DefaultStrokeWidth(final double width) { final Field field = ClassUtils.getField(RectToolOptions.class, "defaultStrokeWidth"); ClassUtils.setValue(field, null, width); } private double getIJ1DefaultStrokeWidth() { final Field field = ClassUtils.getField(RectToolOptions.class, "defaultStrokeWidth"); return (Double) ClassUtils.getValue(field, null); } private void setIJ1WandMode(final String mode) { final Field field = ClassUtils.getField(WandToolOptions.class, "mode"); ClassUtils.setValue(field, null, mode); } private String getIJ1WandMode() { final Field field = ClassUtils.getField(WandToolOptions.class, "mode"); return (String) ClassUtils.getValue(field, null); } private void setIJ1WandTolerance(final double tol) { final Field field = ClassUtils.getField(WandToolOptions.class, "tolerance"); ClassUtils.setValue(field, null, tol); } private double getIJ1WandTolerance() { final Field field = ClassUtils.getField(WandToolOptions.class, "tolerance"); return (Double) ClassUtils.getValue(field, null); } /** * IJ1 directly refers to compiler that may not be loaded (since it may not be * on class path). Thus have a safe accessor that does not cause runtime * exceptions when user misconfigures their java tools. Instead we should * avoid issues here and we should safely report the issue to the user if they * try to run the Compile/Run plugin. */ private Field getCompilerField(String fieldName) { try { return ClassUtils.getField(ij.plugin.Compiler.class, fieldName); } catch (Throwable t) { return null; } } }
// OptionsSynchronizer.java package imagej.legacy; import ij.IJ; import ij.gui.Arrow; import ij.gui.Line; import ij.gui.ProfilePlot; import ij.gui.Roi; import ij.gui.TextRoi; import ij.gui.Toolbar; import ij.io.FileSaver; import ij.plugin.Colors; import ij.plugin.filter.Analyzer; import ij.process.ColorProcessor; import ij.process.FloatBlitter; import ij.process.ImageConverter; import imagej.ImageJ; import imagej.ext.options.OptionsPlugin; import imagej.ext.options.OptionsService; import imagej.util.Prefs; import imagej.util.SettingsKeys; import java.awt.Color; import java.awt.Font; import java.util.List; /** * The {@link OptionsSynchronizer} sets IJ1 settings and preferences to reflect * values set within IJ2 Options dialogs. * * @author Barry DeZonia * */ public class OptionsSynchronizer { public OptionsSynchronizer() { // make sure OptionsPlugin fields are initialized List<OptionsPlugin> optionsPlugins = ImageJ.get(OptionsService.class).getOptions(); for (OptionsPlugin plugin : optionsPlugins) plugin.load(); } /** * Updates IJ1 settings and preferences to reflect values set in IJ2 dialogs. */ public void update() { appearenceOptions(); arrowOptions(); colorOptions(); compilerOptions(); conversionsOptions(); dicomOptions(); fontOptions(); ioOptions(); lineWidthOptions(); memoryAndThreadsOptions(); miscOptions(); pointOptions(); profilePlotOptions(); proxyOptions(); roundRectOptions(); wandToolOptions(); } // -- helpers -- private String getString(String key, String defaultValue) { return Prefs.get(key, defaultValue); } private boolean getBoolean(String key, boolean defaultValue) { String defaultString = (defaultValue ? "true" : "false"); String value = Prefs.get(key, defaultString); if ((value == null) || (value == "")) value = defaultString; return value.equalsIgnoreCase("true"); } private int getInteger(String key, int defaultValue) { String defaultString = "" + defaultValue; String value = Prefs.get(key, defaultString); if (value.equals("")) value = defaultString; return Integer.parseInt(value); } private double getDouble(String key, double defaultValue) { String defaultString = "" + defaultValue; String value = Prefs.get(key, defaultString); if (value.equals("")) value = defaultString; return Double.parseDouble(value); } private Color getColor(String key, Color defaultValue) { String defaultString = defaultValue.toString(); String value = Prefs.get(key, defaultString); if (value.equals("")) value = defaultString; return Colors.getColor(value, defaultValue); } private void appearenceOptions() { ij.Prefs.antialiasedTools = getBoolean(SettingsKeys.OPTIONS_APPEARANCE_ANTIALIASED_TOOL_ICONS, true); ij.Prefs.blackCanvas = getBoolean(SettingsKeys.OPTIONS_APPEARANCE_BLACK_CANVAS, false); ij.Prefs.open100Percent = getBoolean(SettingsKeys.OPTIONS_APPEARANCE_FULL_ZOOMED_IMAGES, false); ij.Prefs.interpolateScaledImages = getBoolean(SettingsKeys.OPTIONS_APPEARANCE_INTERPOLATE_ZOOMED_IMAGES, false); // TODO // this one needs to have code applied to IJ2. Nothing to set for IJ1. //Prefs.get(SettingsKeys.OPTIONS_APPEARANCE_MENU_FONT_SIZE); ij.Prefs.noBorder = getBoolean(SettingsKeys.OPTIONS_APPEARANCE_NO_IMAGE_BORDER, false); ij.Prefs.useInvertingLut = getBoolean(SettingsKeys.OPTIONS_APPEARANCE_USE_INVERTING_LUT, false); } private void arrowOptions() { // TODO - for this next setting there is nothing to synchronize. Changing // this setting runs some code in IJ1's UI. Might need some code on the IJ2 // side that mirrors the behavior. //String color = getString(SettingsKeys.OPTIONS_ARROW_COLOR); boolean doubleHeaded = getBoolean(SettingsKeys.OPTIONS_ARROW_DOUBLEHEADED, false); boolean outline = getBoolean(SettingsKeys.OPTIONS_ARROW_OUTLINE, false); int size = getInteger(SettingsKeys.OPTIONS_ARROW_SIZE, 10); String style = getString(SettingsKeys.OPTIONS_ARROW_STYLE, "Filled"); int width = getInteger(SettingsKeys.OPTIONS_ARROW_WIDTH, 2); if (style == null) style = "Filled"; int styleIndex = 0; if (style.equals("Filled")) styleIndex = 0; else if (style.equals("Notched")) styleIndex = 1; else if (style.equals("Open")) styleIndex = 2; else if (style.equals("Headless")) styleIndex = 3; ij.Prefs.set(Arrow.STYLE_KEY, style); ij.Prefs.set(Arrow.WIDTH_KEY, width); ij.Prefs.set(Arrow.SIZE_KEY, size); ij.Prefs.set(Arrow.OUTLINE_KEY, outline); ij.Prefs.set(Arrow.DOUBLE_HEADED_KEY, doubleHeaded); Arrow.setDefaultStyle(styleIndex); Arrow.setDefaultWidth(width); Arrow.setDefaultHeadSize(size); Arrow.setDefaultOutline(outline); Arrow.setDefaultDoubleHeaded(doubleHeaded); } private void colorOptions() { Toolbar.setForegroundColor(getColor(SettingsKeys.OPTIONS_COLORS_FOREGROUND, Color.black)); Toolbar.setBackgroundColor(getColor(SettingsKeys.OPTIONS_COLORS_BACKGROUND, Color.white)); Roi.setColor(getColor(SettingsKeys.OPTIONS_COLORS_SELECTION, Color.yellow)); } private void compilerOptions() { // TODO // this next key has no way to be set programmatically in IJ1 // Prefs.get(SettingsKeys.OPTIONS_COMPILER_DEBUG_INFO, false); String version = getString(SettingsKeys.OPTIONS_COMPILER_VERSION, "1.5"); if (version == null) version = "1.5"; if (version.equals("1.4")) ij.Prefs.set("javac.target", 0); else if (version.equals("1.5")) ij.Prefs.set("javac.target", 1); else if (version.equals("1.6")) ij.Prefs.set("javac.target", 2); else if (version.equals("1.7")) ij.Prefs.set("javac.target", 3); } private void conversionsOptions() { double[] weights = ColorProcessor.getWeightingFactors(); boolean weighted = !(weights[0]==1d/3d && weights[1]==1d/3d && weights[2]==1d/3d); ImageConverter.setDoScaling(getBoolean(SettingsKeys.OPTIONS_CONVERSIONS_SCALE, true)); ij.Prefs.weightedColor = getBoolean(SettingsKeys.OPTIONS_CONVERSIONS_WEIGHTED, false); if (!ij.Prefs.weightedColor) ColorProcessor.setWeightingFactors(1d/3d, 1d/3d, 1d/3d); else if (ij.Prefs.weightedColor && !weighted) ColorProcessor.setWeightingFactors(0.299, 0.587, 0.114); } private void dicomOptions() { ij.Prefs.openDicomsAsFloat = getBoolean(SettingsKeys.OPTIONS_DICOM_OPEN_FLOAT32, false); ij.Prefs.flipXZ = getBoolean(SettingsKeys.OPTIONS_DICOM_ROTATE_XZ, false); ij.Prefs.rotateYZ = getBoolean(SettingsKeys.OPTIONS_DICOM_ROTATE_YZ, false); } private void fontOptions() { String fontName = getString(SettingsKeys.OPTIONS_FONT_NAME, "SansSerif"); // TODO - bad default name? int fontSize = getInteger(SettingsKeys.OPTIONS_FONT_SIZE, 18); String styleName = getString(SettingsKeys.OPTIONS_FONT_STYLE, ""); boolean smooth = getBoolean(SettingsKeys.OPTIONS_FONT_SMOOTHING, true); if (styleName == null) styleName = ""; int fontStyle = Font.PLAIN; if (styleName.equals("Bold")) fontStyle = Font.BOLD; else if (styleName.equals("Italic")) fontStyle = Font.ITALIC; else if (styleName.equals("Bold+Italic")) fontStyle = Font.BOLD+Font.ITALIC; TextRoi.setFont(fontName, fontSize, fontStyle, smooth); } private void ioOptions() { ij.Prefs.copyColumnHeaders = getBoolean(SettingsKeys.OPTIONS_IO_COPY_COLUMNS, false); ij.Prefs.noRowNumbers = !getBoolean(SettingsKeys.OPTIONS_IO_COPY_ROWS, true); String extension = getString(SettingsKeys.OPTIONS_IO_FILE_EXT, ".txt"); if (extension == null) extension = ".TXT"; ij.Prefs.set("options.ext", extension); FileSaver.setJpegQuality(getInteger(SettingsKeys.OPTIONS_IO_JPEG_QUALITY, 85)); ij.Prefs.dontSaveHeaders = !getBoolean(SettingsKeys.OPTIONS_IO_SAVE_COLUMNS, true); ij.Prefs.intelByteOrder = getBoolean(SettingsKeys.OPTIONS_IO_SAVE_INTEL, false); ij.Prefs.dontSaveRowNumbers = !getBoolean(SettingsKeys.OPTIONS_IO_SAVE_ROWS, true); ij.Prefs.setTransparentIndex(getInteger(SettingsKeys.OPTIONS_IO_TRANSPARENT_INDEX, -1)); ij.Prefs.useJFileChooser = getBoolean(SettingsKeys.OPTIONS_IO_USE_JFILECHOOSER, false); } private void lineWidthOptions() { Line.setWidth(getInteger(SettingsKeys.OPTIONS_LINEWIDTH_WIDTH, 1)); } private void memoryAndThreadsOptions() { // TODO // nothing to set in this next case. Need IJ2 to fire some code as appropriate //Prefs.get(SettingsKeys.OPTIONS_MEMORYTHREADS_MAX_MEMORY); ij.Prefs.keepUndoBuffers = getBoolean(SettingsKeys.OPTIONS_MEMORYTHREADS_MULTIPLE_UNDO_BUFFERS, false); ij.Prefs.noClickToGC = !getBoolean(SettingsKeys.OPTIONS_MEMORYTHREADS_RUN_GC, false); ij.Prefs.setThreads(getInteger(SettingsKeys.OPTIONS_MEMORYTHREADS_STACK_THREADS, 2)); } private void miscOptions() { String divValue = getString(SettingsKeys.OPTIONS_MISC_DBZ_VALUE,"infinity"); IJ.debugMode = getBoolean(SettingsKeys.OPTIONS_MISC_DEBUG_MODE, false); IJ.hideProcessStackDialog = getBoolean(SettingsKeys.OPTIONS_MISC_HIDE_STACK_MSG, false); ij.Prefs.moveToMisc = getBoolean(SettingsKeys.OPTIONS_MISC_MOVE_PLUGINS, false); ij.Prefs.usePointerCursor = getBoolean(SettingsKeys.OPTIONS_MISC_POINTER_CURSOR, false); ij.Prefs.requireControlKey = getBoolean(SettingsKeys.OPTIONS_MISC_REQUIRE_COMMAND, false); ij.Prefs.runSocketListener = getBoolean(SettingsKeys.OPTIONS_MISC_SINGLE_INSTANCE, false); if (divValue == null) divValue = "infinity"; if (divValue.equalsIgnoreCase("infinity") || divValue.equalsIgnoreCase("infinite")) FloatBlitter.divideByZeroValue = Float.POSITIVE_INFINITY; else if (divValue.equalsIgnoreCase("NaN")) FloatBlitter.divideByZeroValue = Float.NaN; else if (divValue.equalsIgnoreCase("max")) FloatBlitter.divideByZeroValue = Float.MAX_VALUE; else { Float f; try {f = new Float(divValue);} catch (NumberFormatException e) {f = null;} if (f!=null) FloatBlitter.divideByZeroValue = f.floatValue(); } } private void pointOptions() { ij.Prefs.pointAddToManager = getBoolean(SettingsKeys.OPTIONS_POINT_ADD_ROI, false); ij.Prefs.pointAutoMeasure = getBoolean(SettingsKeys.OPTIONS_POINT_AUTO_MEASURE, false); ij.Prefs.pointAutoNextSlice = getBoolean(SettingsKeys.OPTIONS_POINT_AUTOSLICE, false); ij.Prefs.noPointLabels = !getBoolean(SettingsKeys.OPTIONS_POINT_LABEL_POINTS, true); Analyzer.markWidth = getInteger(SettingsKeys.OPTIONS_POINT_MARK_WIDTH, 0); Roi.setColor(getColor(SettingsKeys.OPTIONS_POINT_SELECTION_COLOR, Color.yellow)); } private void profilePlotOptions() { ij.gui.PlotWindow.autoClose = getBoolean(SettingsKeys.OPTIONS_PROFILEPLOT_AUTOCLOSE, false); ij.gui.PlotWindow.saveXValues = !getBoolean(SettingsKeys.OPTIONS_PROFILEPLOT_DISCARD_X, false); ij.gui.PlotWindow.noGridLines = !getBoolean(SettingsKeys.OPTIONS_PROFILEPLOT_DRAW_GRID, true); boolean fixedScale = getBoolean(SettingsKeys.OPTIONS_PROFILEPLOT_FIXED_YSCALE, false); ij.gui.PlotWindow.plotHeight = getInteger(SettingsKeys.OPTIONS_PROFILEPLOT_HEIGHT, 200); ij.gui.PlotWindow.interpolate = getBoolean(SettingsKeys.OPTIONS_PROFILEPLOT_INTERPOLATE, true); ij.gui.PlotWindow.listValues = getBoolean(SettingsKeys.OPTIONS_PROFILEPLOT_LIST_VALUES, false); double yMax = getDouble(SettingsKeys.OPTIONS_PROFILEPLOT_MAX_Y, 0); double yMin = getDouble(SettingsKeys.OPTIONS_PROFILEPLOT_MIN_Y, 0); ij.Prefs.verticalProfile = getBoolean(SettingsKeys.OPTIONS_PROFILEPLOT_VERTICAL, false); ij.gui.PlotWindow.plotWidth = getInteger(SettingsKeys.OPTIONS_PROFILEPLOT_WIDTH, 450); if (!fixedScale && (yMin!=0.0 || yMax!=0.0)) fixedScale = true; if (!fixedScale) { yMin = 0.0; yMax = 0.0; } else if (yMin>yMax) { double tmp = yMin; yMin = yMax; yMax = tmp; } ProfilePlot.setMinAndMax(yMin, yMax); } private void proxyOptions() { // TODO // This next setting affects IJ1 dialog. Nothing programmatic can be set. // Need pure IJ2 plugins when this setting is utilized. //Prefs.get(SettingsKeys.OPTIONS_PROXY_AUTHENTICATE); String server = getString(SettingsKeys.OPTIONS_PROXY_SERVER, null); if (server != null) { ij.Prefs.set("proxy.server", server); ij.Prefs.set("proxy.port", getInteger(SettingsKeys.OPTIONS_PROXY_PORT, 8080)); } } private void roundRectOptions() { int crnDiam = getInteger(SettingsKeys.OPTIONS_ROUND_RECT_CORNER_DIAMETER, 20); Toolbar.setRoundRectArcSize(crnDiam); // TODO // IJ1 RectToolOptions does not manipulate Prefs much. It fires // code to change behavior when dialog entries changed. No programmatic // way to make our settings affect IJ1. Need pure IJ2 support elsewhere. //Prefs.get(SettingsKeys.OPTIONS_ROUND_RECT_FILL_COLOR, none); ?how to handle "none"? //Prefs.get(SettingsKeys.OPTIONS_ROUND_RECT_STROKE_COLOR, Color.black); //Prefs.get(SettingsKeys.OPTIONS_ROUND_RECT_STROKE_WIDTH, 2); } private void wandToolOptions() { // TODO // IJ1 WandToolOptions does not mess with preferences in any way. There // is no way in IJ1 to set values without running dialog. Programmatic // approach is out. Can't synchronize unless Wayne adds code. May not be // needed because Wand is not ever active in IJ2. Right? //Prefs.get(SettingsKeys.OPTIONS_WAND_MODE, "Legacy"); //Prefs.get(SettingsKeys.OPTIONS_WAND_TOLERANCE, 0.0); } }
package com.mindfulst.dneves.pomotivity; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.media.AudioManager; import android.media.SoundPool; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.CompoundButton; import android.widget.Spinner; import android.widget.TextView; import android.widget.ToggleButton; import android.widget.ViewSwitcher; import org.joda.time.Period; import org.joda.time.format.PeriodFormatter; import org.joda.time.format.PeriodFormatterBuilder; /** * Some description. */ public class MainActivity extends Activity { private static final String DEBUG_TAG = "pomoui"; private ViewSwitcher mSwitcher = null; private SoundPool mPlayer = null; private static int mTickSoundId = 0; private static int mTickStreamId = 0; private static int mAlarmSoundId = 0; private PeriodFormatter mFormatter = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mSwitcher = (ViewSwitcher) findViewById(R.id.view_switcher); PomodoroApi api = PomodoroApi.getInstance(); api.load(this, getPreferences(Context.MODE_PRIVATE)); // We need 2 channels, 1 for the tick the other for the end alarm if (mPlayer == null) { mPlayer = new SoundPool(2, AudioManager.STREAM_MUSIC, 0); mTickSoundId = mPlayer.load(this, R.raw.tick_sound, 1); mAlarmSoundId = mPlayer.load(this, R.raw.alarm_sound, 1); } ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item) { @Override public View getView(int position, View convertView, ViewGroup parent) { View v = super.getView(position, convertView, parent); if (position == getCount()) { ((TextView) v.findViewById(android.R.id.text1)).setText(""); ((TextView) v.findViewById(android.R.id.text1)).setHint(getResources().getString(R.string.project_hint)); } return v; } @Override public int getCount() { return super.getCount() - 1; } }; adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); adapter.add(getResources().getString(R.string.project_add)); // Always keep this last ;) adapter.add(getResources().getString(R.string.project_hint)); Spinner projectChooser = (Spinner) findViewById(R.id.current_project); projectChooser.setAdapter(adapter); projectChooser.setSelection(adapter.getCount()); projectChooser.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Log.d(DEBUG_TAG, String .format("count: %d; text: %s; pos: %d; id: %d", parent.getCount(), ((TextView) view).getText(), position, id)); // TODO: Clean this code! if (position == parent.getCount()) { // This is the hint return; } else if (position == parent.getCount() - 1) { // + Project Log.d(DEBUG_TAG, "Adding project"); } else { // User Project Log.d(DEBUG_TAG, String.format("Settting to user project %s", ((TextView) view).getText())); } } @Override public void onNothingSelected(AdapterView<?> parent) { Log.d(DEBUG_TAG, String.format("count: %d", parent.getCount())); } }); findViewById(R.id.start_button).setOnClickListener(mStartButtonListener); findViewById(R.id.stop_button).setOnClickListener(mStopButtonListener); findViewById(R.id.pause_button).setOnClickListener(mPauseButtonListener); findViewById(R.id.resume_button).setOnClickListener(mResumeButtonListener); ToggleButton autoStartToggle = (ToggleButton) findViewById(R.id.auto_start_toggle); autoStartToggle.setChecked(api.getAutoStart()); autoStartToggle.setOnCheckedChangeListener(mAutoStartToggleListener); mFormatter = new PeriodFormatterBuilder().printZeroAlways().minimumPrintedDigits(2).appendMinutes().appendSeparator(":") .printZeroAlways().minimumPrintedDigits(2).appendSeconds().toFormatter(); Period period = new Period(PomodoroApi.POMODORO_DURATION * 1000); ((TextView) findViewById(R.id.current_time)).setText(mFormatter.print(period)); api.setPomodoroListener(new PomodoroApi.PomodoroEventListener() { @Override public void pomodoroStarted(final PomodoroApi.PomodoroEvent event) { runOnUiThread(new Runnable() { @Override public void run() { mTickStreamId = mPlayer.play(mTickSoundId, 1.0f, 1.0f, 1, -1, 1.0f); if (mTickStreamId == 0) { Log.e(DEBUG_TAG, "Oops, failed to play the tick sound"); } AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); audioManager.setStreamMute(AudioManager.STREAM_NOTIFICATION, true); audioManager.setStreamMute(AudioManager.STREAM_RING, true); resetButtonsVisibility(false, event.autoStart); } }); } @Override public void pomodoroTicked(final PomodoroApi.PomodoroEvent event) { runOnUiThread(new Runnable() { @Override public void run() { Period period = new Period(event.currentTime * 1000); ((TextView) findViewById(R.id.current_time)).setText(mFormatter.print(period)); } }); } @Override public void pomodoroEnded(final PomodoroApi.PomodoroEvent event) { runOnUiThread(new Runnable() { @Override public void run() { mPlayer.play(mAlarmSoundId, 1.0f, 1.0f, 2, 0, 1.0f); AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); audioManager.setStreamMute(AudioManager.STREAM_NOTIFICATION, false); audioManager.setStreamMute(AudioManager.STREAM_RING, false); } }); } @Override public void breakStarted(final PomodoroApi.PomodoroEvent event) { runOnUiThread(new Runnable() { @Override public void run() { mSwitcher.showNext(); Period period = new Period(event.currentTime * 1000); ((TextView) findViewById(R.id.current_time)).setText(mFormatter.print(period)); } }); } @Override public void pomodoroFinished(final PomodoroApi.PomodoroEvent event) { runOnUiThread(new Runnable() { @Override public void run() { resetButtonsVisibility(true, event.autoStart); if (event.currentTime > 0) { AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); audioManager.setStreamMute(AudioManager.STREAM_NOTIFICATION, false); audioManager.setStreamMute(AudioManager.STREAM_RING, false); } else { mPlayer.play(mAlarmSoundId, 1.0f, 1.0f, 2, 0, 1.0f); } if (mTickStreamId != 0) { mPlayer.stop(mTickStreamId); } if (event.currentState != PomodoroApi.PomodoroState.POMODORO) { mSwitcher.showPrevious(); } Period period = new Period(PomodoroApi.POMODORO_DURATION * 1000); ((TextView) findViewById(R.id.current_time)).setText(mFormatter.print(period)); } }); } @Override public void paused(PomodoroApi.PomodoroEvent event) { runOnUiThread(new Runnable() { @Override public void run() { if (mTickStreamId != 0) { mPlayer.pause(mTickStreamId); } setButtonsVisibility(true); } }); } @Override public void resumed(PomodoroApi.PomodoroEvent event) { runOnUiThread(new Runnable() { @Override public void run() { if (mTickStreamId != 0) { mPlayer.resume(mTickStreamId); } setButtonsVisibility(false); } }); } }); } private void resetButtonsVisibility(boolean isFinishing, boolean isAutoStart) { if (isFinishing && !isAutoStart) { findViewById(R.id.start_button).setVisibility(View.VISIBLE); findViewById(R.id.pause_button).setVisibility(View.GONE); } else { // Starting findViewById(R.id.start_button).setVisibility(View.GONE); findViewById(R.id.pause_button).setVisibility(View.VISIBLE); } findViewById(R.id.stop_button).setVisibility(View.GONE); findViewById(R.id.resume_button).setVisibility(View.GONE); } private void setButtonsVisibility(boolean isPaused) { findViewById(R.id.start_button).setVisibility(View.GONE); if (isPaused) { findViewById(R.id.pause_button).setVisibility(View.GONE); findViewById(R.id.resume_button).setVisibility(View.VISIBLE); findViewById(R.id.stop_button).setVisibility(View.VISIBLE); } else { findViewById(R.id.pause_button).setVisibility(View.VISIBLE); findViewById(R.id.resume_button).setVisibility(View.GONE); findViewById(R.id.stop_button).setVisibility(View.GONE); } } @Override protected void onPause() { super.onPause(); SharedPreferences preferences = getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); PomodoroApi.getInstance().save(this, editor); editor.apply(); } View.OnClickListener mStartButtonListener = new View.OnClickListener() { @Override public void onClick(View view) { try { PomodoroApi.getInstance().start(); } catch (PomodoroApi.AlreadyRunningException e) { e.printStackTrace(); } } }; View.OnClickListener mStopButtonListener = new View.OnClickListener() { @Override public void onClick(View view) { PomodoroApi.getInstance().stop(); } }; View.OnClickListener mPauseButtonListener = new View.OnClickListener() { @Override public void onClick(View view) { PomodoroApi.getInstance().pause(); } }; View.OnClickListener mResumeButtonListener = new View.OnClickListener() { @Override public void onClick(View view) { PomodoroApi.getInstance().resume(); } }; CompoundButton.OnCheckedChangeListener mAutoStartToggleListener = new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { PomodoroApi.getInstance().setAutoStart(isChecked); } }; }
package org.apache.commons.lang.exception; import java.io.PrintStream; import java.io.PrintWriter; import java.io.Serializable; import java.io.StringWriter; import java.util.*; /** * <code>NestableDelegate</code> is a shared implementation of the nestable * exception functionality. * <p> * The code is shared between * {@link org.apache.commons.lang.exception.NestableError NestableError}, * {@link org.apache.commons.lang.exception.NestableException NestableException} and * {@link org.apache.commons.lang.exception.NestableRuntimeException NestableRuntimeException}. * * @author <a href="mailto:Rafal.Krzewski@e-point.pl">Rafal Krzewski</a> * @author <a href="mailto:dlr@collab.net">Daniel Rall</a> * @author <a href="mailto:knielsen@apache.org">Kasper Nielsen</a> * @author <a href="mailto:steven@caswell.name">Steven Caswell</a> * @author Sean C. Sullivan * @author Stephen Colebourne * @since 1.0 * @version $Id: NestableDelegate.java,v 1.14 2003/06/10 06:16:54 scolebourne Exp $ */ public class NestableDelegate implements Serializable { /** * Constructor error message. */ private transient static final String MUST_BE_THROWABLE = "The Nestable implementation passed to the NestableDelegate(Nestable) " + "constructor must extend java.lang.Throwable"; /** * Holds the reference to the exception or error that we're * wrapping (which must be a {@link * org.apache.commons.lang.exception.Nestable} implementation). */ private Throwable nestable = null; /** * Whether to print the stack trace top-down. */ public static boolean topDown = true; /** * Whether to trim the repeated stack trace. */ public static boolean trimStackFrames = true; /** * Constructs a new <code>NestableDelegate</code> instance to manage the * specified <code>Nestable</code>. * * @param nestable the Nestable implementation (<i>must</i> extend * {@link java.lang.Throwable}) */ public NestableDelegate(Nestable nestable) { if (nestable instanceof Throwable) { this.nestable = (Throwable) nestable; } else { throw new IllegalArgumentException(MUST_BE_THROWABLE); } } /** * Returns the error message of the <code>Throwable</code> in the chain * of <code>Throwable</code>s at the specified index, numbererd from 0. * * @param index the index of the <code>Throwable</code> in the chain of * <code>Throwable</code>s * @return the error message, or null if the <code>Throwable</code> at the * specified index in the chain does not contain a message * @throws IndexOutOfBoundsException if the <code>index</code> argument is * negative or not less than the count of <code>Throwable</code>s in the * chain */ public String getMessage(int index) { Throwable t = this.getThrowable(index); if (Nestable.class.isInstance(t)) { return ((Nestable) t).getMessage(0); } else { return t.getMessage(); } } /** * Returns the full message contained by the <code>Nestable</code> * and any nested <code>Throwable</code>s. * * @param baseMsg the base message to use when creating the full * message. Should be generally be called via * <code>nestableHelper.getMessage(super.getMessage())</code>, * where <code>super</code> is an instance of {@link * java.lang.Throwable}. * @return The concatenated message for this and all nested * <code>Throwable</code>s */ public String getMessage(String baseMsg) { StringBuffer msg = new StringBuffer(); if (baseMsg != null) { msg.append(baseMsg); } Throwable nestedCause = ExceptionUtils.getCause(this.nestable); if (nestedCause != null) { String causeMsg = nestedCause.getMessage(); if (causeMsg != null) { if (baseMsg != null) { msg.append(": "); } msg.append(causeMsg); } } return (msg.length() > 0 ? msg.toString() : null); } /** * Returns the error message of this and any nested <code>Throwable</code>s * in an array of Strings, one element for each message. Any * <code>Throwable</code> not containing a message is represented in the * array by a null. This has the effect of cause the length of the returned * array to be equal to the result of the {@link #getThrowableCount()} * operation. * * @return the error messages */ public String[] getMessages() { Throwable[] throwables = this.getThrowables(); String[] msgs = new String[throwables.length]; for (int i = 0; i < throwables.length; i++) { msgs[i] = (Nestable.class.isInstance(throwables[i]) ? ((Nestable) throwables[i]).getMessage(0) : throwables[i].getMessage()); } return msgs; } /** * Returns the <code>Throwable</code> in the chain of * <code>Throwable</code>s at the specified index, numbererd from 0. * * @param index the index, numbered from 0, of the <code>Throwable</code> in * the chain of <code>Throwable</code>s * @return the <code>Throwable</code> * @throws IndexOutOfBoundsException if the <code>index</code> argument is * negative or not less than the count of <code>Throwable</code>s in the * chain */ public Throwable getThrowable(int index) { if (index == 0) { return this.nestable; } Throwable[] throwables = this.getThrowables(); return throwables[index]; } /** * Returns the number of <code>Throwable</code>s contained in the * <code>Nestable</code> contained by this delegate. * * @return the throwable count */ public int getThrowableCount() { return ExceptionUtils.getThrowableCount(this.nestable); } /** * Returns this delegate's <code>Nestable</code> and any nested * <code>Throwable</code>s in an array of <code>Throwable</code>s, one * element for each <code>Throwable</code>. * * @return the <code>Throwable</code>s */ public Throwable[] getThrowables() { return ExceptionUtils.getThrowables(this.nestable); } /** * Returns the index, numbered from 0, of the first <code>Throwable</code> * that matches the specified type in the chain of <code>Throwable</code>s * held in this delegate's <code>Nestable</code> with an index greater than * or equal to the specified index, or -1 if the type is not found. * * @param type <code>Class</code> to be found * @param fromIndex the index, numbered from 0, of the starting position in * the chain to be searched * @return index of the first occurrence of the type in the chain, or -1 if * the type is not found * @throws IndexOutOfBoundsException if the <code>fromIndex</code> argument * is negative or not less than the count of <code>Throwable</code>s in the * chain */ public int indexOfThrowable(Class type, int fromIndex) { return ExceptionUtils.indexOfThrowable(this.nestable, type, fromIndex); } /** * Prints the stack trace of this exception the the standar error * stream. */ public void printStackTrace() { printStackTrace(System.err); } /** * Prints the stack trace of this exception to the specified * stream. * * @param out <code>PrintStream</code> to use for output. * @see #printStackTrace(PrintWriter) */ public void printStackTrace(PrintStream out) { synchronized (out) { PrintWriter pw = new PrintWriter(out, false); printStackTrace(pw); // Flush the PrintWriter before it's GC'ed. pw.flush(); } } /** * Prints the stack trace of this exception to the specified * writer. If the Throwable class has a <code>getCause</code> * method (i.e. running on jre1.4 or higher), this method just * uses Throwable's printStackTrace() method. Otherwise, generates * the stack-trace, by taking into account the 'topDown' and * 'trimStackFrames' parameters. The topDown and trimStackFrames * are set to 'true' by default (produces jre1.4-like stack trace). * * @param out <code>PrintWriter</code> to use for output. */ public void printStackTrace(PrintWriter out) { Throwable throwable = this.nestable; // if running on jre1.4 or higher, use default printStackTrace if (ExceptionUtils.isThrowableNested()) { if (throwable instanceof Nestable) { ((Nestable)throwable).printPartialStackTrace(out); } else { throwable.printStackTrace(out); } return; } // generating the nested stack trace List stacks = new ArrayList(); while (throwable != null) { String[] st = getStackFrames(throwable); stacks.add(st); throwable = ExceptionUtils.getCause(throwable); } // If NOT topDown, reverse the stack String separatorLine = "Caused by: "; if (!topDown) { separatorLine = "Rethrown as: "; Collections.reverse(stacks); } // Remove the repeated lines in the stack if (trimStackFrames) trimStackFrames(stacks); synchronized (out) { for (Iterator iter=stacks.iterator(); iter.hasNext();) { String[] st = (String[]) iter.next(); for (int i=0, len=st.length; i < len; i++) { out.println(st[i]); } if (iter.hasNext()) out.print(separatorLine); } } } /** * Captures the stack trace associated with the specified * <code>Throwable</code> object, decomposing it into a list of * stack frames. * * @param t The <code>Throwable</code>. * @return An array of strings describing each stack frame. */ protected String[] getStackFrames(Throwable t) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); // Avoid infinite loop between decompose() and printStackTrace(). if (t instanceof Nestable) { ((Nestable) t).printPartialStackTrace(pw); } else { t.printStackTrace(pw); } return ExceptionUtils.getStackFrames(sw.getBuffer().toString()); } /** * Trims the stack frames. The first set is left untouched. The rest * of the frames are truncated from the bottom by comparing with * one just on top. * * @param stacks The list containing String[] elements */ protected void trimStackFrames(List stacks) { for (int size=stacks.size(), i=size-1; i > 0; i String[] curr = (String[]) stacks.get(i); String[] next = (String[]) stacks.get(i-1); List currList = new ArrayList(Arrays.asList(curr)); List nextList = new ArrayList(Arrays.asList(next)); ExceptionUtils.removeCommonFrames(currList, nextList); int trimmed = curr.length - currList.size(); if (trimmed > 0) { currList.add("\t... "+trimmed+" more"); stacks.set( i, (String[])currList.toArray(new String[currList.size()]) ); } } } }
package org.jivesoftware.openfire.nio; import org.apache.mina.common.ByteBuffer; import org.jivesoftware.util.JiveGlobals; import org.jivesoftware.util.Log; import org.jivesoftware.util.PropertyEventDispatcher; import org.jivesoftware.util.PropertyEventListener; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * This is a Light-Weight XML Parser. * It read data from a channel and collect data until data are available in * the channel. * When a message is complete you can retrieve messages invoking the method * getMsgs() and you can invoke the method areThereMsgs() to know if at least * an message is presents. * * @author Daniele Piras * @author Gaston Dombiak */ class XMLLightweightParser { private static final String MAX_PROPERTY_NAME = "xmpp.parser.buffer.size"; private static int maxBufferSize; // Chars that rappresent CDATA section start protected static char[] CDATA_START = {'<', '!', '[', 'C', 'D', 'A', 'T', 'A', '['}; // Chars that rappresent CDATA section end protected static char[] CDATA_END = {']', ']', '>'}; // Buffer with all data retrieved protected StringBuilder buffer = new StringBuilder(); // Initial status protected static final int INIT = 0; // Status used when the first tag name is retrieved protected static final int HEAD = 2; // Status used when robot is inside the xml and it looking for the tag conclusion protected static final int INSIDE = 3; // Status used when a '<' is found and try to find the conclusion tag. protected static final int PRETAIL = 4; // Status used when the ending tag is equal to the head tag protected static final int TAIL = 5; // Status used when robot is inside the main tag and found an '/' to check '/>'. protected static final int VERIFY_CLOSE_TAG = 6; // Status used when you are inside a parameter protected static final int INSIDE_PARAM_VALUE = 7; // Status used when you are inside a cdata section protected static final int INSIDE_CDATA = 8; // Status used when you are outside a tag/reading text protected static final int OUTSIDE = 9; final String[] sstatus = {"INIT", "", "HEAD", "INSIDE", "PRETAIL", "TAIL", "VERIFY", "INSIDE_PARAM", "INSIDE_CDATA", "OUTSIDE"}; // Current robot status protected int status = XMLLightweightParser.INIT; // Index to looking for a CDATA section start or end. protected int cdataOffset = 0; // Number of chars that machs with the head tag. If the tailCount is equal to // the head length so a close tag is found. protected int tailCount = 0; // Indicate the starting point in the buffer for the next message. protected int startLastMsg = 0; // Flag used to discover tag in the form <tag />. protected boolean insideRootTag = false; // Object conteining the head tag protected StringBuilder head = new StringBuilder(5); // List with all finished messages found. protected List<String> msgs = new ArrayList<String>(); private int depth = 0; protected boolean insideChildrenTag = false; Charset encoder; static { // Set default max buffer size to 1MB. If limit is reached then close connection maxBufferSize = JiveGlobals.getIntProperty(MAX_PROPERTY_NAME, 1048576); // Listen for changes to this property PropertyEventDispatcher.addListener(new PropertyListener()); } public XMLLightweightParser(String charset) { encoder = Charset.forName(charset); } /* * true if the parser has found some complete xml message. */ public boolean areThereMsgs() { return (msgs.size() > 0); } /* * @return an array with all messages found */ public String[] getMsgs() { String[] res = new String[msgs.size()]; for (int i = 0; i < res.length; i++) { res[i] = msgs.get(i); } msgs.clear(); invalidateBuffer(); return res; } /* * Method use to re-initialize the buffer */ protected void invalidateBuffer() { if (buffer.length() > 0) { String str = buffer.substring(startLastMsg); buffer.delete(0, buffer.length()); buffer.append(str); buffer.trimToSize(); } startLastMsg = 0; } /* * Method that add a message to the list and reinit parser. */ protected void foundMsg(String msg) { // Add message to the complete message list if (msg != null) { msgs.add(msg); } // Move the position into the buffer status = XMLLightweightParser.INIT; tailCount = 0; cdataOffset = 0; head.setLength(0); insideRootTag = false; insideChildrenTag = false; depth = 0; } /* * Main reading method */ public void read(ByteBuffer byteBuffer) throws Exception { invalidateBuffer(); // Check that the buffer is not bigger than 1 Megabyte. For security reasons // we will abort parsing when 1 Mega of queued chars was found. if (buffer.length() > maxBufferSize) { throw new Exception("Stopped parsing never ending stanza"); } CharBuffer charBuffer = encoder.decode(byteBuffer.buf()); char[] buf = charBuffer.array(); int readByte = charBuffer.remaining(); // Verify if the last received byte is an incomplete double byte character char lastChar = buf[readByte-1]; if (lastChar >= 0xfff0) { if (Log.isDebugEnabled()) { Log.debug("Waiting to get complete char: " + String.valueOf(buf)); } // Rewind the position one place so the last byte stays in the buffer // The missing byte should arrive in the next iteration. Once we have both // of bytes we will have the correct character byteBuffer.position(byteBuffer.position()-1); // Decrease the number of bytes read by one readByte // Just return if nothing was read if (readByte == 0) { return; } } buffer.append(buf, 0, readByte); // Do nothing if the buffer only contains white spaces if (buffer.charAt(0) <= ' ' && buffer.charAt(buffer.length()-1) <= ' ') { if ("".equals(buffer.toString().trim())) { // Empty the buffer so there is no memory leak buffer.delete(0, buffer.length()); return; } } // Robot. char ch; for (int i = 0; i < readByte; i++) { ch = buf[i]; if (status == XMLLightweightParser.TAIL) { // Looking for the close tag if (depth < 1 && ch == head.charAt(tailCount)) { tailCount++; if (tailCount == head.length()) { // Close stanza found! // Calculate the correct start,end position of the message into the buffer int end = buffer.length() - readByte + (i + 1); String msg = buffer.substring(startLastMsg, end); // Add message to the list foundMsg(msg); startLastMsg = end; } } else { tailCount = 0; status = XMLLightweightParser.INSIDE; } } else if (status == XMLLightweightParser.PRETAIL) { if (ch == XMLLightweightParser.CDATA_START[cdataOffset]) { cdataOffset++; if (cdataOffset == XMLLightweightParser.CDATA_START.length) { status = XMLLightweightParser.INSIDE_CDATA; cdataOffset = 0; continue; } } else { cdataOffset = 0; status = XMLLightweightParser.INSIDE; } if (ch == '/') { status = XMLLightweightParser.TAIL; depth } else if (ch == '!') { // This is a <! (comment) so ignore it status = XMLLightweightParser.INSIDE; } else { depth++; } } else if (status == XMLLightweightParser.VERIFY_CLOSE_TAG) { if (ch == '>') { depth status = XMLLightweightParser.OUTSIDE; if (depth < 1) { // Found a tag in the form <tag /> int end = buffer.length() - readByte + (i + 1); String msg = buffer.substring(startLastMsg, end); // Add message to the list foundMsg(msg); startLastMsg = end; } } else if (ch == '<') { status = XMLLightweightParser.PRETAIL; insideChildrenTag = true; } else { status = XMLLightweightParser.INSIDE; } } else if (status == XMLLightweightParser.INSIDE_PARAM_VALUE) { if (ch == '"') { status = XMLLightweightParser.INSIDE; } } else if (status == XMLLightweightParser.INSIDE_CDATA) { if (ch == XMLLightweightParser.CDATA_END[cdataOffset]) { cdataOffset++; if (cdataOffset == XMLLightweightParser.CDATA_END.length) { status = XMLLightweightParser.OUTSIDE; cdataOffset = 0; } } else { cdataOffset = 0; } } else if (status == XMLLightweightParser.INSIDE) { if (ch == XMLLightweightParser.CDATA_START[cdataOffset]) { cdataOffset++; if (cdataOffset == XMLLightweightParser.CDATA_START.length) { status = XMLLightweightParser.INSIDE_CDATA; cdataOffset = 0; continue; } } else { cdataOffset = 0; status = XMLLightweightParser.INSIDE; } if (ch == '"') { status = XMLLightweightParser.INSIDE_PARAM_VALUE; } else if (ch == '>') { status = XMLLightweightParser.OUTSIDE; if (insideRootTag && ("stream:stream>".equals(head.toString()) || ("?xml>".equals(head.toString())) || ("flash:stream>".equals(head.toString())))) { // Found closing stream:stream int end = buffer.length() - readByte + (i + 1); // Skip LF, CR and other "weird" characters that could appear while (startLastMsg < end && '<' != buffer.charAt(startLastMsg)) { startLastMsg++; } String msg = buffer.substring(startLastMsg, end); foundMsg(msg); startLastMsg = end; } insideRootTag = false; } else if (ch == '/') { status = XMLLightweightParser.VERIFY_CLOSE_TAG; } } else if (status == XMLLightweightParser.HEAD) { if (ch == ' ' || ch == '>') { // Append > to head to allow searching </tag> head.append(">"); if(ch == '>') status = XMLLightweightParser.OUTSIDE; else status = XMLLightweightParser.INSIDE; insideRootTag = true; insideChildrenTag = false; continue; } else if (ch == '/' && head.length() > 0) { status = XMLLightweightParser.VERIFY_CLOSE_TAG; depth } head.append(ch); } else if (status == XMLLightweightParser.INIT) { if (ch == '<') { status = XMLLightweightParser.HEAD; depth = 1; } else { startLastMsg++; } } else if (status == XMLLightweightParser.OUTSIDE) { if (ch == '<') { status = XMLLightweightParser.PRETAIL; cdataOffset = 1; insideChildrenTag = true; } } } if (head.length() > 0 && ("/stream:stream>".equals(head.toString()) || ("/flash:stream>".equals(head.toString())))) { // Found closing stream:stream foundMsg("</stream:stream>"); } } private static class PropertyListener implements PropertyEventListener { public void propertySet(String property, Map<String, Object> params) { if (MAX_PROPERTY_NAME.equals(property)) { String value = (String) params.get("value"); if (value != null) { maxBufferSize = Integer.parseInt(value); } } } public void propertyDeleted(String property, Map<String, Object> params) { if (MAX_PROPERTY_NAME.equals(property)) { // Use default value when none was specified maxBufferSize = 1048576; } } public void xmlPropertySet(String property, Map<String, Object> params) { // Do nothing } public void xmlPropertyDeleted(String property, Map<String, Object> params) { // Do nothing } } }
package org.mskcc.cbio.cgds.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; import java.util.regex.*; import org.apache.commons.lang.StringUtils; import org.mskcc.cbio.cgds.model.Case; import org.mskcc.cbio.cgds.model.CosmicMutationFrequency; import org.mskcc.cbio.cgds.model.ExtendedMutation; /** * Data access object for mutation_event and case_mutation_event tables */ public final class DaoMutationEvent { /** * Private Constructor (Singleton pattern). */ private DaoMutationEvent() { } public static int addMutation(ExtendedMutation mutation) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutationEvent.class); long eventId = addMutationEvent(mutation, con); if (eventExists(eventId, mutation.getCaseId(), mutation.getGeneticProfileId(), con)) { return 0; } pstmt = con.prepareStatement ("INSERT INTO case_mutation_event (`MUTATION_EVENT_ID`, `CASE_ID`, `GENETIC_PROFILE_ID`, " + "`VALIDATION_STATUS`, `TUMOR_ALT_COUNT`, `TUMOR_REF_COUNT`, `NORMAL_ALT_COUNT`, `NORMAL_REF_COUNT`) VALUES(?,?,?,?,?,?,?,?)"); pstmt.setLong(1, eventId); pstmt.setString(2, mutation.getCaseId()); pstmt.setInt(3, mutation.getGeneticProfileId()); pstmt.setString(4, mutation.getValidationStatus()); pstmt.setInt(5, mutation.getTumorAltCount()); pstmt.setInt(6, mutation.getTumorRefCount()); pstmt.setInt(7, mutation.getNormalAltCount()); pstmt.setInt(8, mutation.getNormalRefCount()); return pstmt.executeUpdate(); } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutationEvent.class, con, pstmt, rs); } } private static long addMutationEvent(ExtendedMutation mutation, Connection con) throws DaoException { PreparedStatement pstmt = null; ResultSet rs = null; try { long eventId = getMutationEventId(mutation, con); if (eventId==-1) { // no existing, create new pstmt = con.prepareStatement ("INSERT INTO mutation_event (`ENTREZ_GENE_ID`, `AMINO_ACID_CHANGE`, " + "`MUTATION_STATUS`, `MUTATION_TYPE`,`CHR`,`START_POSITION`," + "`END_POSITION`, `FUNCTIONAL_IMPACT_SCORE`, `LINK_XVAR`, `LINK_PDB`," + "`LINK_MSA`, `KEYWORD`) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)"); pstmt.setLong(1, mutation.getEntrezGeneId()); pstmt.setString(2, mutation.getProteinChange()); pstmt.setString(3, mutation.getMutationStatus()); pstmt.setString(4, mutation.getMutationType()); pstmt.setString(5, mutation.getChr()); pstmt.setLong(6, mutation.getStartPosition()); pstmt.setLong(7, mutation.getEndPosition()); pstmt.setString(8, mutation.getFunctionalImpactScore()); pstmt.setString(9, mutation.getLinkXVar()); pstmt.setString(10, mutation.getLinkPdb()); pstmt.setString(11, mutation.getLinkMsa()); pstmt.setString(12, extractMutationKeyword(mutation)); pstmt.executeUpdate(); eventId = getMutationEventId(mutation, con); // add cosmic for (CosmicMutationFrequency cosmic : parseCosmic(mutation)) { importCosmic(eventId, cosmic, con); } } return eventId; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(pstmt, rs); } } private static long getMutationEventId(ExtendedMutation mutation, Connection con) throws DaoException { PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = con.prepareStatement ("SELECT `MUTATION_EVENT_ID` FROM mutation_event WHERE `ENTREZ_GENE_ID`=? " + "AND `AMINO_ACID_CHANGE`=? AND `MUTATION_STATUS`=?"); pstmt.setLong(1, mutation.getEntrezGeneId()); pstmt.setString(2, mutation.getProteinChange()); pstmt.setString(3, mutation.getMutationStatus()); rs = pstmt.executeQuery(); if (rs.next()) { return rs.getLong(1); } else { return -1; } } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(pstmt, rs); } } private static String extractMutationKeyword(ExtendedMutation mutation) { String type = mutation.getMutationType(); if (type.equals("Nonsense_Mutation") || type.equals("Splice_Site") || type.startsWith("Frame_Shift_") || type.equals("Nonstop_Mutation")) { return mutation.getGeneSymbol() + " truncating"; } if (type.equals("Missense_Mutation")) { String aa = mutation.getProteinChange(); if (aa.startsWith("M1")&&!aa.equals("M1M")) { // how about indels on the first position? // non-start return mutation.getGeneSymbol() + " truncating"; } Pattern p = Pattern.compile("([A-Z][0-9]+)"); Matcher m = p.matcher(aa); if (m.find()) { return mutation.getGeneSymbol() + " " + m.group(1) + " missense"; } } if (type.equals("In_Frame_Ins")) { String aa = mutation.getProteinChange(); if (aa.contains("*")) { // insert * return mutation.getGeneSymbol() + " truncating"; } Pattern p = Pattern.compile("([0-9]+)"); Matcher m = p.matcher(aa); if (m.find()) { return mutation.getGeneSymbol() + " " + m.group(1) + " ins"; } } if (type.equals("In_Frame_Del")) { String aa = mutation.getProteinChange(); // only the first deleted residue was considered Pattern p = Pattern.compile("([0-9]+)"); Matcher m = p.matcher(aa); if (m.find()) { return mutation.getGeneSymbol() + " " + m.group(1) + " del"; } } if (type.equals("Silent")) { String aa = mutation.getProteinChange(); Pattern p = Pattern.compile("([0-9]+)"); Matcher m = p.matcher(aa); if (m.find()) { return mutation.getGeneSymbol() + " " + m.group(1) + "silent"; } } // RNA or Translation_Start_Site return "Chm"+mutation.getChr()+","+mutation.getStartPosition(); } private static boolean eventExists(long eventId, String caseId, int mutProfileId, Connection con) throws DaoException { PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = con.prepareStatement ("SELECT count(*) FROM case_mutation_event WHERE `MUTATION_EVENT_ID`=? AND `CASE_ID`=? AND `GENETIC_PROFILE_ID`=?"); pstmt.setLong(1, eventId); pstmt.setString(2, caseId); pstmt.setInt(3, mutProfileId); rs = pstmt.executeQuery(); if (rs.next()) { return rs.getInt(1)>0; } return false; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(pstmt, rs); } } public static List<ExtendedMutation> getMutationEvents(String caseId, int profileId) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutationEvent.class); pstmt = con.prepareStatement ("SELECT case_mutation_event.MUTATION_EVENT_ID, CASE_ID, GENETIC_PROFILE_ID," + " VALIDATION_STATUS, TUMOR_ALT_COUNT, TUMOR_REF_COUNT, NORMAL_ALT_COUNT, NORMAL_REF_COUNT," + " ENTREZ_GENE_ID, MUTATION_STATUS, AMINO_ACID_CHANGE, MUTATION_TYPE," + " CHR, START_POSITION, END_POSITION, FUNCTIONAL_IMPACT_SCORE, LINK_XVAR, LINK_PDB," + " LINK_MSA, KEYWORD" + " FROM case_mutation_event, mutation_event" + " WHERE `CASE_ID`=? AND `GENETIC_PROFILE_ID`=? AND" + " case_mutation_event.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID"); pstmt.setString(1, caseId); pstmt.setInt(2, profileId); rs = pstmt.executeQuery(); return extractMutations(rs); } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutationEvent.class, con, pstmt, rs); } } private static List<ExtendedMutation> extractMutations(ResultSet rs) throws SQLException, DaoException { List<ExtendedMutation> events = new ArrayList<ExtendedMutation>(); while (rs.next()) { ExtendedMutation event = new ExtendedMutation( DaoGeneOptimized.getInstance().getGene(rs.getLong("ENTREZ_GENE_ID")), rs.getString("VALIDATION_STATUS"), rs.getString("MUTATION_STATUS"), rs.getString("MUTATION_TYPE")); event.setCaseId(rs.getString("CASE_ID")); event.setGeneticProfileId(rs.getInt("GENETIC_PROFILE_ID")); event.setProteinChange(rs.getString("AMINO_ACID_CHANGE")); event.setChr(rs.getString("CHR")); event.setStartPosition(rs.getLong("START_POSITION")); event.setEndPosition(rs.getLong("END_POSITION")); event.setMutationEventId(rs.getLong("MUTATION_EVENT_ID")); event.setFunctionalImpactScore(rs.getString("FUNCTIONAL_IMPACT_SCORE")); event.setLinkXVar(rs.getString("LINK_XVAR")); event.setLinkPdb(rs.getString("LINK_PDB")); event.setLinkMsa(rs.getString("LINK_MSA")); event.setKeyword(rs.getString("KEYWORD")); event.setTumorAltCount(rs.getInt("TUMOR_ALT_COUNT")); event.setTumorRefCount(rs.getInt("TUMOR_REF_COUNT")); event.setNormalAltCount(rs.getInt("NORMAL_ALT_COUNT")); event.setNormalRefCount(rs.getInt("NORMAL_REF_COUNT")); events.add(event); } return events; } /** * return the number of mutations for each case * @param caseIds if null, return all case available * @param profileId * @return Map &lt; case id, mutation count &gt; * @throws DaoException */ public static Map<String, Integer> countMutationEvents( int profileId, Collection<String> caseIds) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutationEvent.class); String sql; if (caseIds==null) { sql = "SELECT `CASE_ID`, count(*) FROM case_mutation_event" + " WHERE `GENETIC_PROFILE_ID`=" + profileId + " GROUP BY `CASE_ID`"; } else { sql = "SELECT `CASE_ID`, count(*) FROM case_mutation_event" + " WHERE `GENETIC_PROFILE_ID`=" + profileId + " AND `CASE_ID` IN ('" + StringUtils.join(caseIds,"','") + "') GROUP BY `CASE_ID`"; } pstmt = con.prepareStatement(sql); Map<String, Integer> map = new HashMap<String, Integer>(); rs = pstmt.executeQuery(); while (rs.next()) { map.put(rs.getString(1), rs.getInt(2)); } return map; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutationEvent.class, con, pstmt, rs); } } /** * return the number of all mutations for a profile * @param caseIds if null, return all case available * @param profileId * @return Map &lt; case id, mutation count &gt; * @throws DaoException */ public static int countMutationEvents(int profileId) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutationEvent.class); String sql = "SELECT count(*) FROM case_mutation_event" + " WHERE `GENETIC_PROFILE_ID`=" + profileId; pstmt = con.prepareStatement(sql); rs = pstmt.executeQuery(); if (rs.next()) { return rs.getInt(1); } return 0; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutationEvent.class, con, pstmt, rs); } } /** * get events for each case * @return Map &lt; case id, list of event ids &gt; * @throws DaoException */ public static Map<String, Set<Long>> getCasesWithMutations(Collection<Long> eventIds) throws DaoException { return getCasesWithMutations(StringUtils.join(eventIds, ",")); } /** * get events for each case * @param concatEventIds event ids concatenated by comma (,) * @return Map &lt; case id, list of event ids &gt; * @throws DaoException */ public static Map<String, Set<Long>> getCasesWithMutations(String concatEventIds) throws DaoException { if (concatEventIds.isEmpty()) { return Collections.emptyMap(); } Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutationEvent.class); String sql = "SELECT `CASE_ID`, `MUTATION_EVENT_ID` FROM case_mutation_event" + " WHERE `MUTATION_EVENT_ID` IN (" + concatEventIds + ")"; pstmt = con.prepareStatement(sql); Map<String, Set<Long>> map = new HashMap<String, Set<Long>> (); rs = pstmt.executeQuery(); while (rs.next()) { String caseId = rs.getString("CASE_ID"); long eventId = rs.getLong("MUTATION_EVENT_ID"); Set<Long> events = map.get(caseId); if (events == null) { events = new HashSet<Long>(); map.put(caseId, events); } events.add(eventId); } return map; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutationEvent.class, con, pstmt, rs); } } /** * @return Map &lt; case id, list of event ids &gt; * @throws DaoException */ public static Map<Case, Set<Long>> getSimilarCasesWithMutationsByKeywords( Collection<Long> eventIds) throws DaoException { return getSimilarCasesWithMutationsByKeywords(StringUtils.join(eventIds, ",")); } /** * @param concatEventIds event ids concatenated by comma (,) * @return Map &lt; case id, list of event ids &gt; * @throws DaoException */ public static Map<Case, Set<Long>> getSimilarCasesWithMutationsByKeywords( String concatEventIds) throws DaoException { if (concatEventIds.isEmpty()) { return Collections.emptyMap(); } Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutationEvent.class); String sql = "SELECT `CASE_ID`, `GENETIC_PROFILE_ID`, me1.`MUTATION_EVENT_ID`" + " FROM case_mutation_event cme, mutation_event me1, mutation_event me2" + " WHERE me1.`MUTATION_EVENT_ID` IN ("+ concatEventIds + ")" + " AND me1.`KEYWORD`=me2.`KEYWORD`" + " AND cme.`MUTATION_EVENT_ID`=me2.`MUTATION_EVENT_ID`"; pstmt = con.prepareStatement(sql); Map<Case, Set<Long>> map = new HashMap<Case, Set<Long>> (); rs = pstmt.executeQuery(); while (rs.next()) { String caseId = rs.getString("CASE_ID"); int cancerStudyId = DaoGeneticProfile.getGeneticProfileById( rs.getInt("GENETIC_PROFILE_ID")).getCancerStudyId(); Case _case = new Case(caseId, cancerStudyId); long eventId = rs.getLong("MUTATION_EVENT_ID"); Set<Long> events = map.get(_case); if (events == null) { events = new HashSet<Long>(); map.put(_case, events); } events.add(eventId); } return map; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutationEvent.class, con, pstmt, rs); } } /** * @param concatEventIds event ids concatenated by comma (,) * @return Map &lt; case id, list of event ids &gt; * @throws DaoException */ public static Map<Case, Set<Long>> getSimilarCasesWithMutatedGenes( Collection<Long> entrezGeneIds) throws DaoException { if (entrezGeneIds.isEmpty()) { return Collections.emptyMap(); } Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutationEvent.class); String sql = "SELECT `CASE_ID`, `GENETIC_PROFILE_ID`, me.`ENTREZ_GENE_ID`" + " FROM case_mutation_event cme, mutation_event me" + " WHERE me.`ENTREZ_GENE_ID` IN ("+ StringUtils.join(entrezGeneIds,",") + ")" + " AND cme.`MUTATION_EVENT_ID`=me.`MUTATION_EVENT_ID`"; pstmt = con.prepareStatement(sql); Map<Case, Set<Long>> map = new HashMap<Case, Set<Long>> (); rs = pstmt.executeQuery(); while (rs.next()) { String caseId = rs.getString("CASE_ID"); int cancerStudyId = DaoGeneticProfile.getGeneticProfileById( rs.getInt("GENETIC_PROFILE_ID")).getCancerStudyId(); Case _case = new Case(caseId, cancerStudyId); long entrez = rs.getLong("ENTREZ_GENE_ID"); Set<Long> genes = map.get(_case); if (genes == null) { genes = new HashSet<Long>(); map.put(_case, genes); } genes.add(entrez); } return map; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutationEvent.class, con, pstmt, rs); } } public static Map<Long, Integer> countSamplesWithMutationEvents(Collection<Long> eventIds, int profileId) throws DaoException { return countSamplesWithMutationEvents(StringUtils.join(eventIds, ","), profileId); } /** * return the number of samples for each mutation event * @param concatEventIds * @param profileId * @return Map &lt; event id, sampleCount &gt; * @throws DaoException */ public static Map<Long, Integer> countSamplesWithMutationEvents(String concatEventIds, int profileId) throws DaoException { if (concatEventIds.isEmpty()) { return Collections.emptyMap(); } Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutationEvent.class); String sql = "SELECT `MUTATION_EVENT_ID`, count(*) FROM case_mutation_event" + " WHERE `GENETIC_PROFILE_ID`=" + profileId + " AND `MUTATION_EVENT_ID` IN (" + concatEventIds + ") GROUP BY `MUTATION_EVENT_ID`"; pstmt = con.prepareStatement(sql); Map<Long, Integer> map = new HashMap<Long, Integer>(); rs = pstmt.executeQuery(); while (rs.next()) { map.put(rs.getLong(1), rs.getInt(2)); } return map; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutationEvent.class, con, pstmt, rs); } } public static Map<Long, Integer> countSamplesWithMutatedGenes(Collection<Long> entrezGeneIds, int profileId) throws DaoException { return countSamplesWithMutatedGenes(StringUtils.join(entrezGeneIds, ","), profileId); } /** * return the number of samples for each mutated genes * @param concatEntrezGeneIds * @param profileId * @return Map &lt; entrez, sampleCount &gt; * @throws DaoException */ public static Map<Long, Integer> countSamplesWithMutatedGenes(String concatEntrezGeneIds, int profileId) throws DaoException { if (concatEntrezGeneIds.isEmpty()) { return Collections.emptyMap(); } Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutationEvent.class); String sql = "SELECT ENTREZ_GENE_ID, count(DISTINCT CASE_ID)" + " FROM case_mutation_event, mutation_event" + " WHERE GENETIC_PROFILE_ID=" + profileId + " AND case_mutation_event.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID" + " AND ENTREZ_GENE_ID IN (" + concatEntrezGeneIds + ") GROUP BY `ENTREZ_GENE_ID`"; pstmt = con.prepareStatement(sql); Map<Long, Integer> map = new HashMap<Long, Integer>(); rs = pstmt.executeQuery(); while (rs.next()) { map.put(rs.getLong(1), rs.getInt(2)); } return map; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutationEvent.class, con, pstmt, rs); } } public static Map<String, Integer> countSamplesWithKeywords(Collection<String> keywords, int profileId) throws DaoException { if (keywords.isEmpty()) { return Collections.emptyMap(); } Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutationEvent.class); String sql = "SELECT KEYWORD, count(DISTINCT CASE_ID)" + " FROM case_mutation_event, mutation_event" + " WHERE GENETIC_PROFILE_ID=" + profileId + " AND case_mutation_event.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID" + " AND KEYWORD IN ('" + StringUtils.join(keywords,"','") + "') GROUP BY `KEYWORD`"; pstmt = con.prepareStatement(sql); Map<String, Integer> map = new HashMap<String, Integer>(); rs = pstmt.executeQuery(); while (rs.next()) { map.put(rs.getString(1), rs.getInt(2)); } return map; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutationEvent.class, con, pstmt, rs); } } public static Set<Long> getMutatedGenesForACase(String caseId, int profileId) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutationEvent.class); String sql = "SELECT DISTINCT ENTREZ_GENE_ID" + " FROM mutation_event, case_mutation_event," + " WHERE case_mutation_event.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID" + " AND CASE_ID='" + caseId + "'"; pstmt = con.prepareStatement(sql); Set<Long> set = new HashSet<Long>(); rs = pstmt.executeQuery(); while (rs.next()) { set.add(rs.getLong(1)); } return set; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutationEvent.class, con, pstmt, rs); } } public static Set<Long> getGenesOfMutations( Collection<Long> eventIds, int profileId) throws DaoException { return getGenesOfMutations(StringUtils.join(eventIds, ","), profileId); } /** * return entrez gene ids of the mutations specified by their mutaiton event ids. * @param concatEventIds * @param profileId * @return * @throws DaoException */ public static Set<Long> getGenesOfMutations(String concatEventIds, int profileId) throws DaoException { if (concatEventIds.isEmpty()) { return Collections.emptySet(); } Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutationEvent.class); String sql = "SELECT DISTINCT ENTREZ_GENE_ID FROM mutation_event " + "WHERE MUTATION_EVENT_ID in (" + concatEventIds + ")"; pstmt = con.prepareStatement(sql); Set<Long> set = new HashSet<Long>(); rs = pstmt.executeQuery(); while (rs.next()) { set.add(rs.getLong(1)); } return set; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutationEvent.class, con, pstmt, rs); } } /** * return keywords of the mutations specified by their mutaiton event ids. * @param concatEventIds * @param profileId * @return * @throws DaoException */ public static Set<String> getKeywordsOfMutations(String concatEventIds, int profileId) throws DaoException { if (concatEventIds.isEmpty()) { return Collections.emptySet(); } Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutationEvent.class); String sql = "SELECT DISTINCT KEYWORD FROM mutation_event " + "WHERE MUTATION_EVENT_ID in (" + concatEventIds + ")"; pstmt = con.prepareStatement(sql); Set<String> set = new HashSet<String>(); rs = pstmt.executeQuery(); while (rs.next()) { set.add(rs.getString(1)); } return set; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutationEvent.class, con, pstmt, rs); } } static String filterCosmic(ExtendedMutation mutation) { List<CosmicMutationFrequency> cmfs = parseCosmic(mutation); StringBuilder sb = new StringBuilder(); for (CosmicMutationFrequency cmf : cmfs) { sb.append(cmf.getAminoAcidChange()).append("(") .append(cmf.getFrequency()).append(")|"); } if (sb.length()>0) { sb.deleteCharAt(sb.length()-1); } return sb.toString(); } private static List<CosmicMutationFrequency> parseCosmic(ExtendedMutation mutation) { String strCosmic = mutation.getOncotatorCosmicOverlapping(); if (strCosmic==null || strCosmic.isEmpty()) { return Collections.emptyList(); } String[] parts = strCosmic.split("\\|"); List<CosmicMutationFrequency> list = new ArrayList<CosmicMutationFrequency>(parts.length); Pattern p = Pattern.compile("(p\\..+)\\(([0-9]+)\\)"); for (String part : parts) { Matcher m = p.matcher(part); if (m.matches()) { String aa = m.group(1); if (matchCosmic(mutation, aa)) { int count = Integer.parseInt(m.group(2)); list.add(new CosmicMutationFrequency(mutation.getEntrezGeneId(), aa, count)); } } // else if (!part.equals("NA")) { // System.err.println("wrong cosmic string: "+part); } return list; } private static boolean matchCosmic(ExtendedMutation mutation, String cosmicAAChange) { if (cosmicAAChange.endsWith("p.?")||cosmicAAChange.endsWith("p.0?")) { return false; } String type = mutation.getMutationType(); if (cosmicAAChange.matches( "(p\\.[A-Z]?[0-9]+_[A-Z]?[0-9]+((>)|(ins))[A-Z]+)|(p\\.[A-Z][0-9]+>[A-Z][A-Z]+)|(p\\.[A-Z]?[0-9]+.+del[A-Z]*)")) { // in frame del or ins return type.toLowerCase().startsWith("in_frame_"); } if (cosmicAAChange.matches("p\\.[A-Z][0-9]+>?[A-Z]")) { return type.toLowerCase().startsWith("missense"); } return type.toLowerCase().startsWith("nonsense") || type.toLowerCase().startsWith("splice_site") || type.toLowerCase().startsWith("frame_shift_") || type.toLowerCase().startsWith("nonstop"); // TODO: how about Translation_Start_Site } private static int importCosmic(long eventId, CosmicMutationFrequency cosmic, Connection con) throws DaoException { PreparedStatement pstmt = null; ResultSet rs = null; try { int n = importCosmic(cosmic, con); CosmicMutationFrequency cmf = getCosmicMutationFrequency(cosmic.getEntrezGeneId(), cosmic.getAminoAcidChange(), con); pstmt = con.prepareStatement("INSERT INTO mutation_event_cosmic_mapping" + " (`MUTATION_EVENT_ID`,`COSMIC_MUTATION_ID`) VALUES(?,?)"); pstmt.setLong(1, eventId); pstmt.setInt(2, cmf.getId()); n += pstmt.executeUpdate(); return n; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(pstmt, rs); } } private static int importCosmic(CosmicMutationFrequency cosmic, Connection con) throws DaoException { PreparedStatement pstmt = null; ResultSet rs = null; try { if (null != getCosmicMutationFrequency( cosmic.getEntrezGeneId(), cosmic.getAminoAcidChange(),con)) { return 0; } pstmt = con.prepareStatement("INSERT INTO cosmic_mutation (`ENTREZ_GENE_ID`," + "`AMINO_ACID_CHANGE`,`COUNT`) VALUES(?,?,?)"); pstmt.setLong(1, cosmic.getEntrezGeneId()); pstmt.setString(2, cosmic.getAminoAcidChange()); pstmt.setInt(3, cosmic.getFrequency()); return pstmt.executeUpdate(); } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(pstmt, rs); } } public static CosmicMutationFrequency getCosmicMutationFrequency(long entrez, String aaChange) throws DaoException { Connection con = null; try { con = JdbcUtil.getDbConnection(DaoMutationEvent.class); return getCosmicMutationFrequency(entrez, aaChange, con); } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeConnection(DaoMutationEvent.class, con); } } private static CosmicMutationFrequency getCosmicMutationFrequency(long entrez, String aaChange, Connection con) throws DaoException { if (con == null) { throw new NullPointerException("Null SQL connection"); } PreparedStatement pstmt = null; ResultSet rs = null; try { String sql = "SELECT * FROM cosmic_mutation " + "WHERE `ENTREZ_GENE_ID`=? AND `AMINO_ACID_CHANGE`=?"; pstmt = con.prepareStatement(sql); pstmt.setLong(1, entrez); pstmt.setString(2, aaChange); rs = pstmt.executeQuery(); if (rs.next()) { return new CosmicMutationFrequency(rs.getInt("COSMIC_MUTATION_ID"), entrez, aaChange, rs.getInt("COUNT")); } return null; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(pstmt, rs); } } public static Map<Long, List<CosmicMutationFrequency>> getCosmicMutationFrequency( Collection<Long> mutationEventIds) throws DaoException { return getCosmicMutationFrequency(StringUtils.join(mutationEventIds,",")); } /** * get cosmic data for a mutation event * @param strMutationEventIds * @return Map &lt; mutation event id &gt; , list of cosmic &gt; &gt; * @throws DaoException */ public static Map<Long, List<CosmicMutationFrequency>> getCosmicMutationFrequency( String strMutationEventIds) throws DaoException { if (strMutationEventIds==null || strMutationEventIds.isEmpty()) { return Collections.emptyMap(); } Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutationEvent.class); String sql = "SELECT MUTATION_EVENT_ID, cosmic_mutation.COSMIC_MUTATION_ID," + " `ENTREZ_GENE_ID`, `AMINO_ACID_CHANGE`, `COUNT`" + " FROM cosmic_mutation, mutation_event_cosmic_mapping" + " WHERE `MUTATION_EVENT_ID` IN ("+ strMutationEventIds +")" + " AND cosmic_mutation.COSMIC_MUTATION_ID=mutation_event_cosmic_mapping.COSMIC_MUTATION_ID"; pstmt = con.prepareStatement(sql); rs = pstmt.executeQuery(); Map<Long,List<CosmicMutationFrequency>> map = new HashMap<Long,List<CosmicMutationFrequency>>(); while (rs.next()) { long eventId = rs.getLong(1); List<CosmicMutationFrequency> list = map.get(eventId); if (list==null) { list = new ArrayList<CosmicMutationFrequency>(); map.put(eventId, list); } list.add(new CosmicMutationFrequency(rs.getInt(2),rs.getLong(3),rs.getString(4),rs.getInt(5))); } return map; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutationEvent.class, con, pstmt, rs); } } }
package com.haulmont.cuba.core.sys; import com.haulmont.cuba.core.app.ClusterListener; import com.haulmont.cuba.core.app.ClusterManagerAPI; import com.haulmont.cuba.core.app.ServerConfig; import com.haulmont.cuba.core.global.ConfigProvider; import com.haulmont.cuba.core.global.GlobalConfig; import com.haulmont.cuba.core.global.ScriptingProvider; import com.haulmont.cuba.core.sys.javacl.JavaClassLoader; import groovy.util.GroovyScriptEngine; import groovy.lang.GroovyClassLoader; import groovy.lang.Binding; import groovy.lang.GroovyShell; import groovy.lang.Script; import java.io.*; import java.util.*; import org.codehaus.groovy.control.CompilerConfiguration; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.Log; import org.apache.commons.pool.impl.GenericKeyedObjectPool; import org.apache.commons.pool.BaseKeyedPoolableObjectFactory; public class ScriptingProviderImpl extends ScriptingProvider { private Log log = LogFactory.getLog(ScriptingProviderImpl.class); private String groovyClassPath = ""; private Map<Layer, Set<String>> imports = new HashMap<Layer, Set<String>>(); private volatile GroovyScriptEngine gse; private GroovyClassLoader gcl; private Map<Layer, GenericKeyedObjectPool> pools = new HashMap<Layer, GenericKeyedObjectPool>(); private ClusterManagerAPI clusterManager; public ScriptingProviderImpl(ConfigProvider configProvider, ClusterManagerAPI clusterManager) { this.clusterManager = clusterManager; this.clusterManager.addListener(ScriptingSettings.class, new ScriptingSettingsDistributor()); GlobalConfig config = configProvider.doGetConfig(GlobalConfig.class); doAddGroovyClassPath(config.getConfDir()); } // public void setClusterManager(ClusterManagerAPI clusterManager) { // this.clusterManager = clusterManager; // this.clusterManager.addListener(ScriptingSettings.class, new ScriptingSettingsDistributor()); public void doAddGroovyClassPath(String path) { internalAddGroovyClassPath(path, true); } private void internalAddGroovyClassPath(String path, boolean distribute) { if (!groovyClassPath.contains(File.pathSeparator + path)) { groovyClassPath = groovyClassPath + File.pathSeparator + path; if (distribute) clusterManager.send(new ScriptingSettings(null, null, path)); } } public synchronized void doAddGroovyEvaluatorImport(Layer layer, String className) { internalAddGroovyEvaluatorImport(layer, className, true); } private void internalAddGroovyEvaluatorImport(Layer layer, String className, boolean distribute) { Set<String> list = imports.get(layer); if (list == null) { list = new HashSet<String>(); imports.put(layer, list); } if (!list.contains(className)) { list.add(className); if (distribute) clusterManager.send(new ScriptingSettings(layer, className, null)); } } public GroovyScriptEngine doGetGroovyScriptEngine() { if (gse == null) { synchronized (this) { if (gse == null) { final String[] rootPath = new String[]{ // src-conf directory: ConfigProvider.getConfig(ServerConfig.class).getServerConfDir(), // db scripts directory: ConfigProvider.getConfig(ServerConfig.class).getServerDbDir() }; try { gse = new GroovyScriptEngine(rootPath); } catch (IOException e) { throw new RuntimeException(e); } } } } return gse; } public GroovyClassLoader doGetGroovyClassLoader() { if (gcl == null) { synchronized (this) { if (gcl == null) { CompilerConfiguration cc = new CompilerConfiguration(); cc.setClasspath(groovyClassPath); cc.setRecompileGroovySource(true); gcl = new GroovyClassLoader(JavaClassLoader.getInstance(), cc); } } } return gcl; } public <T> T doEvaluateGroovy(Layer layer, String text, Binding binding) { Script script = null; try { script = (Script) getPool(layer).borrowObject(text); script.setBinding(binding); return (T) script.run(); } catch (Exception e) { try { getPool(layer).invalidateObject(text, script); } catch (Exception e1) { log.warn("Error invalidating object in the pool", e1); } if (e instanceof RuntimeException) throw ((RuntimeException) e); else throw new RuntimeException(e); } finally { if (script != null) try { script.setBinding(null); // free memory getPool(layer).returnObject(text, script); } catch (Exception e) { log.warn("Error returning object into the pool", e); } } } private synchronized GenericKeyedObjectPool getPool(final Layer layer) { GenericKeyedObjectPool pool = pools.get(layer); if (pool == null) { GenericKeyedObjectPool.Config poolConfig = new GenericKeyedObjectPool.Config(); poolConfig.maxActive = -1; pool = new GenericKeyedObjectPool( new BaseKeyedPoolableObjectFactory() { public Object makeObject(Object key) throws Exception { if (!(key instanceof String)) throw new IllegalArgumentException(); String text = ((String) key); StringBuilder sb = new StringBuilder(); Set<String> strings = imports.get(layer); if (strings != null) { for (String importItem : strings) { sb.append("import ").append(importItem).append("\n"); } } sb.append(text); GroovyShell shell = new GroovyShell(); Script script = shell.parse(sb.toString()); return script; } }, poolConfig ); pools.put(layer, pool); } return pool; } private static class ScriptingSettings implements Serializable { private Layer importLayer; private String importClassName; private String classPath; private static final long serialVersionUID = -2146330970539251455L; private ScriptingSettings(Layer importLayer, String importClassName, String classPath) { this.classPath = classPath; this.importClassName = importClassName; this.importLayer = importLayer; } } private class ScriptingSettingsDistributor implements ClusterListener<ScriptingSettings> { public void receive(ScriptingSettings message) { if (message.importLayer != null && message.importClassName != null) internalAddGroovyEvaluatorImport(message.importLayer, message.importClassName, false); if (message.classPath != null) internalAddGroovyClassPath(message.classPath, false); } public byte[] getState() { List<ScriptingSettings> list = new ArrayList<ScriptingSettings>(); String[] strings = groovyClassPath.split(File.pathSeparator); for (String path : strings) { list.add(new ScriptingSettings(null, null, path)); } for (Map.Entry<Layer, Set<String>> entry : imports.entrySet()) { for (String className : entry.getValue()) { list.add(new ScriptingSettings(entry.getKey(), className, null)); } } ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(list); } catch (IOException e) { log.error("Error serializing ScriptingSettings", e); return new byte[0]; } return bos.toByteArray(); } public void setState(byte[] state) { if (state == null || state.length == 0) return; List<ScriptingSettings> list; ByteArrayInputStream bis = new ByteArrayInputStream(state); try { ObjectInputStream ois = new ObjectInputStream(bis); list = (List<ScriptingSettings>) ois.readObject(); } catch (Exception e) { log.error("Error deserializing ScriptingSettings", e); return; } for (ScriptingSettings ss : list) { receive(ss); } } } }
package org.mskcc.cbio.oncokb.util; import com.google.common.collect.Sets; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.map.HashedMap; import org.apache.commons.lang3.StringUtils; import org.mskcc.cbio.oncokb.bo.AlterationBo; import org.mskcc.cbio.oncokb.bo.ArticleBo; import org.mskcc.cbio.oncokb.bo.EvidenceBo; import org.mskcc.cbio.oncokb.model.*; import org.mskcc.cbio.oncokb.model.oncotree.TumorType; import javax.xml.parsers.ParserConfigurationException; import java.util.*; public class EvidenceUtils { private static EvidenceBo evidenceBo = ApplicationContextSingleton.getEvidenceBo(); /** * Remove evidences if its alteration in the alteration list * * @param evidences * @param alterations * @return */ public static List<Evidence> removeByAlterations(List<Evidence> evidences, Collection<Alteration> alterations) { if (alterations != null) { Iterator<Evidence> i = evidences.iterator(); while (i.hasNext()) { Boolean contain = false; Evidence evidence = i.next(); for (Alteration alteration : alterations) { if (alteration != null) { for (Alteration eviAlt : evidence.getAlterations()) { if (eviAlt != null && alteration.equals(eviAlt)) { contain = true; break; } } if (contain) { i.remove(); break; } } } } } return evidences; } public static Set<Evidence> getRelevantEvidences( Query query, String source, String geneStatus, Alteration matchedAlt, Set<EvidenceType> evidenceTypes, Set<LevelOfEvidence> levelOfEvidences) { if (query == null) { return new HashSet<>(); } Gene gene = GeneUtils.getGene(query.getEntrezGeneId(), query.getHugoSymbol()); if (gene != null) { String variantId = query.getQueryId() + (source != null ? ("&" + source) : "") + "&" + evidenceTypes.toString() + (levelOfEvidences == null ? "" : ("&" + levelOfEvidences.toString())); if (matchedAlt == null) { matchedAlt = AlterationUtils.getAlteration(gene.getHugoSymbol(), query.getAlteration(), AlterationType.getByName(query.getAlterationType()), query.getConsequence(), query.getProteinStart(), query.getProteinEnd()); AlterationUtils.annotateAlteration(matchedAlt, matchedAlt.getAlteration()); } List<Alteration> relevantAlterations = AlterationUtils.getRelevantAlterations(matchedAlt); List<Alteration> alleles = AlterationUtils.getAlleleAlterations(matchedAlt); Set<Evidence> relevantEvidences; List<TumorType> relevantTumorTypes = new ArrayList<>(); if (query.getTumorType() != null) { relevantTumorTypes = TumorTypeUtils.getMappedOncoTreeTypesBySource(query.getTumorType(), source); } EvidenceQueryRes evidenceQueryRes = new EvidenceQueryRes(); evidenceQueryRes.setGene(gene); evidenceQueryRes.setQuery(query); evidenceQueryRes.setAlterations(relevantAlterations); evidenceQueryRes.setOncoTreeTypes(relevantTumorTypes); evidenceQueryRes.setLevelOfEvidences(levelOfEvidences == null ? null : new ArrayList<>(levelOfEvidences)); List<EvidenceQueryRes> evidenceQueryResList = new ArrayList<>(); evidenceQueryResList.add(evidenceQueryRes); relevantEvidences = getEvidence(evidenceQueryResList, evidenceTypes, geneStatus, levelOfEvidences); Set<Evidence> evidencesToRemove = new HashSet<>(); Set<Alteration> excludeAlternativeAlleles = new HashSet<>(); for (Evidence tempEvidence : relevantEvidences) { if (LevelUtils.isResistanceLevel(tempEvidence.getLevelOfEvidence())) { excludeAlternativeAlleles.addAll(Sets.intersection(tempEvidence.getAlterations(), new HashSet<>(alleles))); } } for (Evidence tempEvidence : relevantEvidences) { if (!Collections.disjoint(excludeAlternativeAlleles, tempEvidence.getAlterations())) { evidencesToRemove.add(tempEvidence); } } relevantEvidences.removeAll(evidencesToRemove); return filterEvidence(relevantEvidences, evidenceQueryRes); } else { return new HashSet<>(); } } public static Set<Evidence> getEvidenceByEvidenceTypesAndLevels(Set<EvidenceType> types, Set<LevelOfEvidence> levels) { List<Evidence> evidences = new ArrayList<>(); for (Evidence evidence : CacheUtils.getAllEvidences()) { if (types != null && types.size() > 0 && !types.contains(evidence.getEvidenceType())) { continue; } if (levels != null && levels.size() > 0 && !levels.contains(evidence.getLevelOfEvidence())) { continue; } evidences.add(evidence); } return new HashSet<>(evidences); } private static List<Evidence> getEvidence(List<Alteration> alterations) { if (alterations == null || alterations.size() == 0) { return new ArrayList<>(); } if (CacheUtils.isEnabled()) { return getAlterationEvidences(alterations); } else { return evidenceBo.findEvidencesByAlteration(alterations); } } public static List<Evidence> getEvidence(List<Alteration> alterations, Set<EvidenceType> evidenceTypes, Set<LevelOfEvidence> levelOfEvidences) { if (alterations == null) { alterations = new ArrayList<>(); } if (evidenceTypes == null) { evidenceTypes = new HashSet<>(); } if (levelOfEvidences == null) { levelOfEvidences = new HashSet<>(); } if (alterations.size() == 0) { return new ArrayList<>(); } if (evidenceTypes.size() == 0 && levelOfEvidences.size() == 0) { return getEvidence(alterations); } if (CacheUtils.isEnabled()) { List<Evidence> alterationEvidences = getAlterationEvidences(alterations); List<Evidence> result = new ArrayList<>(); for (Evidence evidence : alterationEvidences) { if (evidenceTypes.size() > 0 && !evidenceTypes.contains(evidence.getEvidenceType())) { continue; } if (levelOfEvidences.size() > 0 && !levelOfEvidences.contains(evidence.getLevelOfEvidence())) { continue; } result.add(evidence); } return result; } else { if (levelOfEvidences.size() == 0) { return evidenceBo.findEvidencesByAlteration(alterations, evidenceTypes); } else { return evidenceBo.findEvidencesByAlterationWithLevels(alterations, evidenceTypes, levelOfEvidences); } } } public static List<Evidence> getEvidence(List<Alteration> alterations, Set<EvidenceType> evidenceTypes, Set<TumorType> tumorTypes, Set<LevelOfEvidence> levelOfEvidences) { if (alterations == null || alterations.size() == 0) { return new ArrayList<>(); } if (evidenceTypes == null || evidenceTypes.size() == 0) { return getEvidence(alterations); } if (tumorTypes == null || tumorTypes.size() == 0) { return getEvidence(alterations, evidenceTypes, levelOfEvidences); } if (levelOfEvidences == null || levelOfEvidences.size() == 0) { return evidenceBo.findEvidencesByAlteration(alterations, evidenceTypes, tumorTypes); } else { return evidenceBo.findEvidencesByAlteration(alterations, evidenceTypes, tumorTypes, levelOfEvidences); } } private static Set<Evidence> getEvidence(List<EvidenceQueryRes> queries, Set<EvidenceType> evidenceTypes, String geneStatus, Set<LevelOfEvidence> levelOfEvidences) { Set<Evidence> evidences = new HashSet<>(); Map<Integer, Gene> genes = new HashMap<>(); //Get gene evidences Map<Integer, Alteration> alterations = new HashMap<>(); Set<TumorType> tumorTypes = new HashSet<>(); for (EvidenceQueryRes query : queries) { if (query.getGene() != null) { int entrezGeneId = query.getGene().getEntrezGeneId(); if (!genes.containsKey(entrezGeneId)) { genes.put(entrezGeneId, query.getGene()); } Set<Alteration> allAlts = new HashSet<>(); if (query.getAlterations() != null) { allAlts.addAll(query.getAlterations()); } if (query.getAlleles() != null) { allAlts.addAll(query.getAlleles()); } for (Alteration alt : allAlts) { int altId = alt.getId(); if (!alterations.containsKey(altId)) { alterations.put(altId, alt); } } if (query.getOncoTreeTypes() != null) { for (TumorType tumorType : query.getOncoTreeTypes()) { if (!tumorTypes.contains(tumorType)) { tumorTypes.add(tumorType); } } } } } // Get all gene related evidences Map<Gene, Set<Evidence>> mappedEvidences = EvidenceUtils.getEvidenceByGenesAndEvidenceTypes(new HashSet<>(genes.values()), Sets.intersection(EvidenceTypeUtils.getGeneEvidenceTypes(), evidenceTypes)); for (Map.Entry<Gene, Set<Evidence>> cursor : mappedEvidences.entrySet()) { evidences.addAll(cursor.getValue()); } List<Alteration> uniqueAlterations = new ArrayList<>(alterations.values()); // Get all mutation related evidences Set<EvidenceType> common = Sets.intersection(EvidenceTypeUtils.getMutationEvidenceTypes(), evidenceTypes); if (common.size() > 0) { evidences.addAll(getEvidence(uniqueAlterations, common, null)); } // For sensitive evidences, get all ignore tumor types. They will be propagated to other tumor types // in assignEvidence function common = Sets.intersection(EvidenceTypeUtils.getSensitiveTreatmentEvidenceTypes(), evidenceTypes); if (common.size() > 0) { evidences.addAll(getEvidence(uniqueAlterations, common, levelOfEvidences)); } // Get other tumor type related evidences Set<EvidenceType> restTTevidenceTypes = EvidenceTypeUtils.getTumorTypeEvidenceTypes(); restTTevidenceTypes.removeAll(EvidenceTypeUtils.getSensitiveTreatmentEvidenceTypes()); common = Sets.intersection(restTTevidenceTypes, evidenceTypes); if (common.size() > 0) { evidences.addAll(getEvidence(uniqueAlterations, common, tumorTypes, levelOfEvidences)); } return evidences; } public static List<Evidence> getAlterationEvidences(List<Alteration> alterations) { List<Evidence> evidences = new ArrayList<>(); if (CacheUtils.isEnabled()) { Set<Evidence> geneEvidences = getAllEvidencesByAlterationsGenes(alterations); for (Evidence evidence : geneEvidences) { if (!Collections.disjoint(evidence.getAlterations(), alterations)) { evidences.add(evidence); } } } else { evidences = evidenceBo.findEvidencesByAlteration(alterations); } return evidences; } public static Map<Gene, Set<Evidence>> getEvidenceByGenes(Set<Gene> genes) { Map<Gene, Set<Evidence>> evidences = new HashMap<>(); if (CacheUtils.isEnabled()) { for (Gene gene : genes) { if (gene != null) { evidences.put(gene, CacheUtils.getEvidences(gene)); } } } else { evidences = EvidenceUtils.separateEvidencesByGene(genes, new HashSet<Evidence>(ApplicationContextSingleton.getEvidenceBo().findAll())); } return evidences; } public static Map<Gene, Set<Evidence>> getEvidenceByGenesAndEvidenceTypes(Set<Gene> genes, Set<EvidenceType> evidenceTypes) { Map<Gene, Set<Evidence>> result = new HashMap<>(); if (evidenceTypes == null || evidenceTypes.isEmpty()) return result; if (CacheUtils.isEnabled()) { for (Gene gene : genes) { if (gene != null) { Set<Evidence> evidences = CacheUtils.getEvidences(gene); Set<Evidence> filtered = new HashSet<>(); for (Evidence evidence : evidences) { if (evidenceTypes.contains(evidence.getEvidenceType())) { filtered.add(evidence); } } result.put(gene, filtered); } } } else { result = EvidenceUtils.separateEvidencesByGene(genes, new HashSet<Evidence>(ApplicationContextSingleton.getEvidenceBo().findAll())); for (Gene gene : genes) { Set<Evidence> evidences = result.get(gene); for (Evidence evidence : evidences) { if (!evidenceTypes.contains(evidence.getEvidenceType())) { evidences.remove(evidence); } } } } return result; } public static Set<Evidence> getEvidenceByGeneAndEvidenceTypes(Gene gene, Set<EvidenceType> evidenceTypes) { Set<Evidence> result = new HashSet<>(); if (gene != null) { if (CacheUtils.isEnabled()) { Set<Evidence> evidences = CacheUtils.getEvidences(gene); for (Evidence evidence : evidences) { if (evidenceTypes.contains(evidence.getEvidenceType())) { result.add(evidence); } } } else { List<Evidence> evidences = evidenceBo.findEvidencesByGene(Collections.singleton(gene), evidenceTypes); if (evidences != null) { result = new HashSet<>(evidences); } } } return result; } public static Set<Evidence> convertEvidenceLevel(List<Evidence> evidences, Set<TumorType> tumorTypes) { Set<Evidence> tmpEvidences = new HashSet<>(); for (Evidence evidence : evidences) { Evidence tmpEvidence = new Evidence(evidence, evidence.getId()); Boolean flag = true; if (Collections.disjoint(Collections.singleton(tmpEvidence.getOncoTreeType()), tumorTypes)) { if (tmpEvidence.getLevelOfEvidence() != null) { if (tmpEvidence.getPropagation() != null) { LevelOfEvidence propagationLevel = LevelOfEvidence.getByName(tmpEvidence.getPropagation()); if (propagationLevel != null) { tmpEvidence.setLevelOfEvidence(propagationLevel); } else { flag = false; } } // Don't include any resistance evidence if tumor type is not matched. if (LevelUtils.getResistanceLevels().contains(tmpEvidence.getLevelOfEvidence())) { flag = false; } } } if (flag) { tmpEvidences.add(tmpEvidence); } } return tmpEvidences; } private static Set<Evidence> filterEvidence(Set<Evidence> evidences, EvidenceQueryRes evidenceQuery) { Set<Evidence> filtered = new HashSet<>(); if (evidenceQuery.getGene() != null) { for (Evidence evidence : evidences) { if (evidence.getGene().equals(evidenceQuery.getGene())) { //Add all gene specific evidences if (evidence.getAlterations().isEmpty()) { filtered.add(evidence); } else { boolean hasjointed = !Collections.disjoint(evidence.getAlterations(), evidenceQuery.getAlterations()); if (!hasjointed) { hasjointed = !Collections.disjoint(evidence.getAlterations(), evidenceQuery.getAlleles()); } if (hasjointed) { if (evidence.getOncoTreeType() == null) { if (evidence.getEvidenceType().equals(EvidenceType.ONCOGENIC)) { if (evidence.getDescription() == null) { List<Alteration> alterations = new ArrayList<>(); alterations.addAll(evidence.getAlterations()); // tempEvidence.setDescription(SummaryUtils.variantSummary(Collections.singleton(tempEvidence.getGene()), alterations, evidenceQuery.getQueryAlteration(), Collections.singleton(tempEvidence.getTumorType()), evidenceQuery.getQueryTumorType())); } } filtered.add(evidence); } else { List<TumorType> tumorType = new ArrayList<>(); if (evidence.getOncoTreeType() != null) { tumorType.add(evidence.getOncoTreeType()); } hasjointed = !Collections.disjoint(evidenceQuery.getOncoTreeTypes(), tumorType); if (hasjointed || com.mysql.jdbc.StringUtils.isNullOrEmpty(evidenceQuery.getQuery().getTumorType())) { filtered.add(evidence); } else { if (evidence.getLevelOfEvidence() != null && evidence.getPropagation() != null) { LevelOfEvidence propagationLevel = LevelOfEvidence.getByName(evidence.getPropagation()); if (propagationLevel != null) { if (evidenceQuery.getLevelOfEvidences() == null || evidenceQuery.getLevelOfEvidences().size() == 0 || evidenceQuery.getLevelOfEvidences().contains(propagationLevel)) { Evidence tempEvidence = new Evidence(evidence, evidence.getId()); tempEvidence.setLevelOfEvidence(propagationLevel); filtered.add(tempEvidence); } } } } } } } } } } return filtered; } public static List<Evidence> filterAlteration(List<Evidence> evidences, List<Alteration> alterations) { for (Evidence evidence : evidences) { Set<Alteration> filterEvidences = new HashSet<>(); for (Alteration alt : evidence.getAlterations()) { if (alterations.contains(alt)) { filterEvidences.add(alt); } } evidence.getAlterations().clear(); evidence.setAlterations(filterEvidences); } return evidences; } public static Map<Gene, Set<Evidence>> separateEvidencesByGene(Set<Gene> genes, Set<Evidence> evidences) { Map<Gene, Set<Evidence>> result = new HashMap<>(); for (Gene gene : genes) { result.put(gene, new HashSet<Evidence>()); } for (Evidence evidence : evidences) { if (result.containsKey(evidence.getGene())) { result.get(evidence.getGene()).add(evidence); } } return result; } public static MutationEffect getMutationEffectFromEvidence(Set<Evidence> evidences) { Set<MutationEffect> result = new HashSet<>(); for (Evidence evidence : evidences) { if (evidence.getKnownEffect() != null) { result.add(MutationEffect.getByName(evidence.getKnownEffect())); } } if (result.size() > 1) { return MainUtils.findHighestMutationEffect(result); } else if (result.size() == 1) { return result.iterator().next(); } else { return null; } } public static Oncogenicity getOncogenicityFromEvidence(Set<Evidence> evidences) { Set<Oncogenicity> result = new HashSet<>(); for (Evidence evidence : evidences) { if (evidence.getKnownEffect() != null) { result.add(Oncogenicity.getByEvidence(evidence)); } } if (result.size() > 1) { return MainUtils.findHighestOncogenicity(result); } else if (result.size() == 1) { return result.iterator().next(); } else { return null; } } public static Set<String> getPmids(Set<Evidence> evidences) { Set<String> result = new HashSet<>(); for (Evidence evidence : evidences) { for (Article article : evidence.getArticles()) { if (article.getPmid() != null) { result.add(article.getPmid()); } } } return result; } public static Set<ArticleAbstract> getAbstracts(Set<Evidence> evidences) { Set<ArticleAbstract> result = new HashSet<>(); for (Evidence evidence : evidences) { for (Article article : evidence.getArticles()) { if (article.getAbstractContent() != null) { ArticleAbstract articleAbstract = new ArticleAbstract(); articleAbstract.setAbstractContent(article.getAbstractContent()); articleAbstract.setLink(article.getLink()); result.add(articleAbstract); } } } return result; } public static Set<String> getDrugs(Set<Evidence> evidences) { Set<String> result = new HashSet<>(); for (Evidence evidence : evidences) { for (Treatment treatment : evidence.getTreatments()) { Set<String> drugsInTreatment = new HashSet<>(); for (Drug drug : treatment.getDrugs()) { if (drug.getDrugName() != null) { drugsInTreatment.add(drug.getDrugName()); } } result.add(StringUtils.join(drugsInTreatment, " + ")); } } return result; } public static Map<Gene, Set<Evidence>> getAllGeneBasedEvidences() { Set<Gene> genes = GeneUtils.getAllGenes(); Map<Gene, Set<Evidence>> evidences = EvidenceUtils.getEvidenceByGenes(genes); return evidences; } public static Set<Evidence> getEvidenceBasedOnHighestOncogenicity(Set<Evidence> evidences) { Set<Evidence> filtered = new HashSet<>(); Map<Oncogenicity, Set<Evidence>> map = new HashMap<>(); if (evidences == null || evidences.size() == 0) return filtered; for (Evidence evidence : evidences) { if (evidence.getEvidenceType() != null && evidence.getEvidenceType().equals(EvidenceType.ONCOGENIC)) { Oncogenicity oncogenicity = Oncogenicity.getByEvidence(evidence); if (oncogenicity != null) { if (!map.containsKey(oncogenicity)) map.put(oncogenicity, new HashSet<Evidence>()); map.get(oncogenicity).add(evidence); } } } Oncogenicity highestOncogenicity = MainUtils.findHighestOncogenicByEvidences(evidences); if (map.get(highestOncogenicity) != null) filtered = map.get(highestOncogenicity); return filtered; } public static Set<Evidence> getOnlyHighestLevelEvidences(Set<Evidence> evidences, Alteration exactMatch) { Map<LevelOfEvidence, Set<Evidence>> levels = separateEvidencesByLevel(evidences); Set<LevelOfEvidence> keys = levels.keySet(); LevelOfEvidence highestLevel = LevelUtils.getHighestLevel(keys); LevelOfEvidence highestSensitiveLevel = LevelUtils.getHighestSensitiveLevel(keys); // When resistance level is not null, we need to consider whether the sensitive/resistance level is alteration specific // if so the resistance level is broader if (highestLevel != highestSensitiveLevel && highestSensitiveLevel != null) { LevelOfEvidence highestResistanceLevel = LevelUtils.getHighestResistanceLevel(keys); Set<Alteration> sensitiveAlterations = AlterationUtils.getEvidencesAlterations(levels.get(highestSensitiveLevel)); Set<Alteration> resistanceAlterations = AlterationUtils.getEvidencesAlterations(levels.get(highestResistanceLevel)); Set<Alteration> resistanceRelevantAlts = new HashSet<>(); for (Alteration alteration : resistanceAlterations) { List<Alteration> relevantAlterations = AlterationUtils.getRelevantAlterations(alteration); // we need to remove the ranges that overlap but not fully cover the alteration Iterator<Alteration> i = relevantAlterations.iterator(); while (i.hasNext()) { Alteration relAlt = i.next(); if (relAlt.getConsequence().equals(alteration.getConsequence())) { if (relAlt.getProteinStart() > alteration.getProteinStart() || relAlt.getProteinEnd() < alteration.getProteinEnd()) { i.remove(); } } } resistanceRelevantAlts.addAll(relevantAlterations); } if (exactMatch != null && Collections.disjoint(resistanceRelevantAlts, sensitiveAlterations) && sensitiveAlterations.contains(exactMatch)) { highestLevel = highestSensitiveLevel; } } if (highestLevel != null) { return levels.get(highestLevel); } else { return new HashSet<>(); } } public static Set<Evidence> getOnlySignificantLevelsEvidences(Set<Evidence> evidences) { Map<LevelOfEvidence, Set<Evidence>> levels = separateEvidencesByLevel(evidences); Set<LevelOfEvidence> keys = levels.keySet(); LevelOfEvidence highestLevel = LevelUtils.getHighestLevel(keys); Set<Evidence> result = new HashSet<>(); if (highestLevel != null) { if (highestLevel.equals(LevelOfEvidence.LEVEL_2B) && levels.containsKey(LevelOfEvidence.LEVEL_3A)) { result.addAll(levels.get(LevelOfEvidence.LEVEL_3A)); } result.addAll(levels.get(highestLevel)); } return result; } public static Map<LevelOfEvidence, Set<Evidence>> separateEvidencesByLevel(Set<Evidence> evidences) { Map<LevelOfEvidence, Set<Evidence>> levels = new HashMap<>(); for (Evidence evidence : evidences) { if (evidence.getLevelOfEvidence() != null) { if (!levels.containsKey(evidence.getLevelOfEvidence())) { levels.put(evidence.getLevelOfEvidence(), new HashSet<Evidence>()); } levels.get(evidence.getLevelOfEvidence()).add(evidence); } } return levels; } private static Map<String, Object> getBiggerItem(List<String> query, Set<List<String>> keys) { Map<String, Object> map = new HashMap<>(); map.put("exist", false); map.put("origin", false); map.put("result", query); for (List<String> key : keys) { // Check whether key has all elements in query; if (key.containsAll(query)) { map.put("exist", true); map.put("result", key); return map; } // Check whether query has all elements in key; if (query.containsAll(key)) { map.put("exist", true); map.put("origin", true); map.put("result", key); return map; } } return map; } public static Set<Evidence> keepHighestLevelForSameTreatments(Set<Evidence> evidences, Alteration exactMatch) { Map<List<String>, Set<Evidence>> maps = new HashedMap(); Set<Evidence> filtered = new HashSet<>(); for (Evidence evidence : evidences) { if (evidence.getTreatments() != null && evidence.getTreatments().size() > 0) { List<String> treatments = TreatmentUtils.getTreatments(new HashSet<>(evidence.getTreatments())); Map<String, Object> map = getBiggerItem(treatments, maps.keySet()); if ((boolean) map.get("exist")) { if ((boolean) map.get("origin")) { maps.get(map.get("result")).add(evidence); } else { maps.put(treatments, maps.get(map.get("result"))); maps.get(treatments).add(evidence); } } else { maps.put(treatments, new HashSet<Evidence>()); maps.get(treatments).add(evidence); } } else { // Keep all un-treatment evidences filtered.add(evidence); } } for (Map.Entry<List<String>, Set<Evidence>> entry : maps.entrySet()) { Set<Evidence> highestEvis = EvidenceUtils.getOnlyHighestLevelEvidences(entry.getValue(), exactMatch); // If highestEvis has more than 1 items, find highest original level if the level is 2B, 3B if (highestEvis.size() > 1) { Set<LevelOfEvidence> checkLevels = new HashSet<>(); checkLevels.add(LevelOfEvidence.LEVEL_2B); checkLevels.add(LevelOfEvidence.LEVEL_3B); for (Evidence highestEvi : highestEvis) { if (checkLevels.contains(highestEvi.getLevelOfEvidence())) { Set<Integer> evidenceIds = new HashSet<>(); Set<Gene> genes = new HashSet<>(); for (Evidence evidence : highestEvis) { evidenceIds.add(evidence.getId()); genes.add(evidence.getGene()); } Set<Evidence> originalEvis = EvidenceUtils.getEvidencesByGenesAndIds(genes, evidenceIds); Set<Evidence> highestOriginalEvis = EvidenceUtils.getOnlyHighestLevelEvidences(originalEvis, exactMatch); Set<Integer> filteredIds = new HashSet<>(); for (Evidence evidence : highestOriginalEvis) { filteredIds.add(evidence.getId()); } for (Evidence evidence : highestEvis) { if (filteredIds.contains(evidence.getId())) { filtered.add(evidence); // Only add one break; } } } else { filtered.add(highestEvi); } } } else { filtered.addAll(highestEvis); } } return filtered; } public static Set<Evidence> getEvidencesByUUID(String uuid) { if (uuid == null) { return new HashSet<>(); } if (CacheUtils.isEnabled()) { return CacheUtils.getEvidencesByUUID(uuid); } else { return new HashSet<>(evidenceBo.findEvidenceByUUIDs(Collections.singletonList(uuid))); } } public static Set<Evidence> getEvidencesByUUIDs(Set<String> uuids) { if (uuids == null) { return new HashSet<>(); } if (CacheUtils.isEnabled()) { return CacheUtils.getEvidencesByUUIDs(uuids); } else { return new HashSet<>(evidenceBo.findEvidenceByUUIDs(new ArrayList<>(uuids))); } } public static Evidence getEvidenceByEvidenceId(Integer id) { if (id == null) { return null; } Set<Evidence> evidences = new HashSet<>(); if (CacheUtils.isEnabled()) { evidences = CacheUtils.getEvidencesByIds(Collections.singleton(id)); } else { List<Evidence> evidenceList = evidenceBo.findEvidencesByIds(Collections.singletonList(id)); if (evidenceList == null) { evidences = null; } else { evidences = new HashSet<>(evidenceList); } } if (evidences == null || evidences.size() > 1) { return null; } return evidences.iterator().next(); } public static Set<Evidence> getEvidencesByGenesAndIds(Set<Gene> genes, Set<Integer> ids) { if (ids == null) { return new HashSet<>(); } if (CacheUtils.isEnabled()) { return CacheUtils.getEvidencesByGenesAndIds(genes, ids); } else { return new HashSet<>(evidenceBo.findEvidencesByIds(new ArrayList<>(ids))); } } public static Set<Evidence> getEvidenceByEvidenceIds(Set<Integer> ids) { if (ids == null) { return new HashSet<>(); } if (CacheUtils.isEnabled()) { return CacheUtils.getEvidencesByIds(ids); } else { return new HashSet<>(evidenceBo.findEvidencesByIds(new ArrayList<>(ids))); } } public static Set<Evidence> filterEvidenceByKnownEffect(Set<Evidence> evidences, String knownEffect) { if (knownEffect == null) { return null; } Set<Evidence> result = new HashSet<>(); for (Evidence evidence : evidences) { if (evidence.getKnownEffect() != null && evidence.getKnownEffect().equalsIgnoreCase(knownEffect)) { result.add(evidence); } } return result; } public static Set<Evidence> getSensitiveEvidences(Set<Evidence> evidences) { return filterEvidenceByKnownEffect(evidences, "sensitive"); } public static Set<Evidence> getResistanceEvidences(Set<Evidence> evidences) { return filterEvidenceByKnownEffect(evidences, "resistant"); } // Temporary move evidence process methods here in order to share the code between new APIs and legacies public static List<EvidenceQueryRes> processRequest(List<Query> requestQueries, Set<EvidenceType> evidenceTypes, String geneStatus, String source, Set<LevelOfEvidence> levelOfEvidences, Boolean highestLevelOnly) { List<EvidenceQueryRes> evidenceQueries = new ArrayList<>(); if (source == null) { source = "quest"; } if (evidenceTypes == null) { evidenceTypes = new HashSet<>(EvidenceTypeUtils.getAllEvidenceTypes()); } levelOfEvidences = levelOfEvidences == null ? levelOfEvidences : new HashSet<>(CollectionUtils.intersection(levelOfEvidences, LevelUtils.getPublicLevels())); // when the LoE and ET are empty, no info should be returned if ((levelOfEvidences != null && levelOfEvidences.size() == 0) || evidenceTypes.size() == 0) { if (requestQueries == null || requestQueries.size() == 0) { EvidenceQueryRes query = new EvidenceQueryRes(); return Collections.singletonList(query); } else { List<EvidenceQueryRes> evidenceQueryRes = new ArrayList<>(); for (Query query : requestQueries) { evidenceQueries.add(new EvidenceQueryRes()); } return evidenceQueryRes; } } if (requestQueries == null || requestQueries.size() == 0) { Set<Evidence> evidences = new HashSet<>(); if ((evidenceTypes != null && evidenceTypes.size() > 0) || levelOfEvidences.size() > 0) { evidences = EvidenceUtils.getEvidenceByEvidenceTypesAndLevels(evidenceTypes, levelOfEvidences); } EvidenceQueryRes query = new EvidenceQueryRes(); query.setEvidences(new ArrayList<>(evidences)); return Collections.singletonList(query); } else { for (Query requestQuery : requestQueries) { EvidenceQueryRes query = new EvidenceQueryRes(); requestQuery.enrich(); query.setQuery(requestQuery); query.setGene(GeneUtils.getGene(requestQuery.getEntrezGeneId(), requestQuery.getHugoSymbol())); if (query.getGene() != null) { if (requestQuery.getTumorType() != null && !requestQuery.getTumorType().isEmpty()) { query.setOncoTreeTypes( TumorTypeUtils.getMappedOncoTreeTypesBySource(requestQuery.getTumorType(), source)); } if (!com.mysql.jdbc.StringUtils.isNullOrEmpty(requestQuery.getAlteration())) { Alteration alt = AlterationUtils.findAlteration(query.getGene(), requestQuery.getAlteration()); if (alt == null) { alt = AlterationUtils.getAlteration(query.getGene().getHugoSymbol(), requestQuery.getAlteration(), null, requestQuery.getConsequence(), requestQuery.getProteinStart(), requestQuery.getProteinEnd()); AlterationUtils.annotateAlteration(alt, alt.getAlteration()); }else{ query.setExactMatchedAlteration(alt); } List<Alteration> relevantAlts = AlterationUtils.getRelevantAlterations(alt); // Look for Oncogenic Mutations if no relevantAlt found for alt and alt is hotspot if (relevantAlts.isEmpty() && HotspotUtils.isHotspot(alt)) { Alteration oncogenicMutations = AlterationUtils.findAlteration(alt.getGene(), "Oncogenic Mutations"); if (oncogenicMutations != null) { relevantAlts.add(oncogenicMutations); } } Alteration alteration = AlterationUtils.getAlteration(query.getGene().getHugoSymbol(), requestQuery.getAlteration(), AlterationType.MUTATION, requestQuery.getConsequence(), requestQuery.getProteinStart(), requestQuery.getProteinEnd()); AlterationUtils.annotateAlteration(alteration, alteration.getAlteration()); List<Alteration> allelesAlts = AlterationUtils.getAlleleAlterations(alteration); relevantAlts.removeAll(allelesAlts); query.setAlterations(relevantAlts); query.setAlleles(new ArrayList<>(allelesAlts)); } else { // if no alteration assigned, but has tumor type query.setAlterations(new ArrayList<Alteration>(AlterationUtils.getAllAlterations(query.getGene()))); } } query.setLevelOfEvidences(levelOfEvidences == null ? null : new ArrayList<LevelOfEvidence>(levelOfEvidences)); evidenceQueries.add(query); } } return assignEvidence(getEvidence(evidenceQueries, evidenceTypes, geneStatus, levelOfEvidences), evidenceQueries, highestLevelOnly); } private static List<EvidenceQueryRes> assignEvidence(Set<Evidence> evidences, List<EvidenceQueryRes> evidenceQueries, Boolean highestLevelOnly) { highestLevelOnly = highestLevelOnly == null ? false : highestLevelOnly; for (EvidenceQueryRes query : evidenceQueries) { if (highestLevelOnly) { Set<Evidence> allEvidences = new HashSet<>(query.getEvidences()); List<Evidence> filteredEvidences = new ArrayList<>(); // Get highest sensitive evidences Set<Evidence> sensitiveEvidences = EvidenceUtils.getSensitiveEvidences(allEvidences); filteredEvidences.addAll(EvidenceUtils.getOnlyHighestLevelEvidences(sensitiveEvidences, query.getExactMatchedAlteration())); // Get highest resistance evidences Set<Evidence> resistanceEvidences = EvidenceUtils.getResistanceEvidences(allEvidences); filteredEvidences.addAll(EvidenceUtils.getOnlyHighestLevelEvidences(resistanceEvidences, query.getExactMatchedAlteration())); // Also include all non-treatment evidences for (Evidence evidence : allEvidences) { if (!sensitiveEvidences.contains(evidence) && !resistanceEvidences.contains(evidence)) { filteredEvidences.add(evidence); } } query.setEvidences(filteredEvidences); } else { query.setEvidences( new ArrayList<>(keepHighestLevelForSameTreatments(filterEvidence(evidences, query), query.getExactMatchedAlteration()))); } CustomizeComparator.sortEvidenceBasedOnPriority(query.getEvidences(), LevelUtils.getIndexedTherapeuticLevels()); if (query.getGene() != null && query.getGene().getHugoSymbol().equals("KIT")) { CustomizeComparator.sortKitTreatmentByEvidence(query.getEvidences()); } } return evidenceQueries; } public static void annotateEvidence(Evidence evidence) throws ParserConfigurationException { // If evidence does not have gene info, we can not help with anything here. if (evidence.getGene() == null) { return; } // If the gene does not match with any one in our database, we can not help with anything here. Gene gene = GeneUtils.getGene(evidence.getGene().getEntrezGeneId(), evidence.getGene().getHugoSymbol()); if (gene == null) { return; } evidence.setGene(gene); Set<Alteration> queryAlterations = evidence.getAlterations(); if (queryAlterations != null && !queryAlterations.isEmpty()) { AlterationType type = AlterationType.MUTATION; Set<Alteration> alterations = new HashSet<Alteration>(); AlterationBo alterationBo = ApplicationContextSingleton.getAlterationBo(); for (Alteration alt : queryAlterations) { String proteinChange = alt.getAlteration(); String displayName = alt.getName(); Alteration alteration = alterationBo.findAlterationFromDao(gene, type, proteinChange, displayName); if (alteration == null) { alteration = new Alteration(); alteration.setGene(gene); alteration.setAlterationType(type); alteration.setAlteration(proteinChange); alteration.setName(displayName); AlterationUtils.annotateAlteration(alteration, proteinChange); alterationBo.save(alteration); } alterations.add(alteration); } evidence.setAlterations(alterations); } Set<Article> articles = evidence.getArticles(); if (evidence.getSubtype() != null && evidence.getSubtype().isEmpty()) { evidence.setSubtype(null); } if (evidence.getCancerType() != null && evidence.getCancerType().isEmpty()) { evidence.setCancerType(null); } if (articles != null && !articles.isEmpty()) { ArticleBo articleBo = ApplicationContextSingleton.getArticleBo(); Set<Article> annotatedArticles = new HashSet<>(); Set<String> articlesToBeAdded = new HashSet<>(); for (Article article : articles) { String tempPMID = article.getPmid(); if (tempPMID == null) { Article tempAT = articleBo.findArticleByAbstract(article.getAbstractContent()); if (tempAT == null) { articleBo.save(article); annotatedArticles.add(article); } else { annotatedArticles.add(tempAT); } } else { Article tempAT = articleBo.findArticleByPmid(tempPMID); if (tempAT == null) { articlesToBeAdded.add(tempPMID); } else { annotatedArticles.add(tempAT); } } } if (!articlesToBeAdded.isEmpty()) { for (Article article : NcbiEUtils.readPubmedArticles(articlesToBeAdded)) { articleBo.save(article); annotatedArticles.add(article); } } evidence.setArticles(annotatedArticles); } } /** * @param evidences * @param isDesc default is false * @return */ public static List<Evidence> sortTumorTypeEvidenceBasedNumOfAlts(List<Evidence> evidences, Boolean isDesc) { // Default multiplier for the sorting int flag = 1; if (evidences == null) { return new ArrayList<>(); } if (isDesc) { flag = -1; } final int multiplier = flag; final Map<Evidence, Integer> originalIndices = new HashedMap(); for (int i = 0; i < evidences.size(); i++) { originalIndices.put(evidences.get(i), i); } // Sort all tumor type summaries, the more specific tumor type summary will be picked. Collections.sort(evidences, new Comparator<Evidence>() { public int compare(Evidence x, Evidence y) { if (x.getAlterations() == null) { return 1; } if (y.getAlterations() == null) { return -1; } Integer result = x.getAlterations().size() - y.getAlterations().size(); if (result.equals(0)) { return originalIndices.get(x) - originalIndices.get(y); } return multiplier * result; } }); return evidences; } public static Set<Evidence> getAllEvidencesByAlterationsGenes(Collection<Alteration> alterations) { Set<Gene> genes = new HashSet<>(); Set<Evidence> evidences = new HashSet<>(); for (Alteration alteration : alterations) { genes.add(alteration.getGene()); } if (genes.size() == 1) { return CacheUtils.getEvidences(genes.iterator().next()); } for (Gene gene : genes) { evidences.addAll(CacheUtils.getEvidences(gene)); } return evidences; } }
package org.mskcc.cbio.oncokb.util; import com.google.common.collect.Sets; import org.apache.commons.collections.map.HashedMap; import org.apache.commons.lang3.StringUtils; import org.mskcc.cbio.oncokb.bo.AlterationBo; import org.mskcc.cbio.oncokb.bo.ArticleBo; import org.mskcc.cbio.oncokb.bo.EvidenceBo; import org.mskcc.cbio.oncokb.model.*; import org.mskcc.cbio.oncokb.model.oncotree.TumorType; import javax.xml.parsers.ParserConfigurationException; import java.util.*; public class EvidenceUtils { private static EvidenceBo evidenceBo = ApplicationContextSingleton.getEvidenceBo(); /** * Remove evidences if its alteration in the alteration list * * @param evidences * @param alterations * @return */ public static List<Evidence> removeByAlterations(List<Evidence> evidences, Collection<Alteration> alterations) { if (alterations != null) { Iterator<Evidence> i = evidences.iterator(); while (i.hasNext()) { Boolean contain = false; Evidence evidence = i.next(); for (Alteration alteration : alterations) { if (alteration != null) { for (Alteration eviAlt : evidence.getAlterations()) { if (eviAlt != null && alteration.equals(eviAlt)) { contain = true; break; } } if (contain) { i.remove(); break; } } } } } return evidences; } public static Set<Evidence> getRelevantEvidences( Query query, String source, String geneStatus, Set<EvidenceType> evidenceTypes, Set<LevelOfEvidence> levelOfEvidences) { if (query == null) { return new HashSet<>(); } Gene gene = GeneUtils.getGene(query.getEntrezGeneId(), query.getHugoSymbol()); if (gene != null) { String variantId = query.getQueryId() + (source != null ? ("&" + source) : "") + "&" + evidenceTypes.toString() + (levelOfEvidences == null ? "" : ("&" + levelOfEvidences.toString())); Alteration alt = AlterationUtils.getAlteration(gene.getHugoSymbol(), query.getAlteration(), AlterationType.getByName(query.getAlterationType()), query.getConsequence(), query.getProteinStart(), query.getProteinEnd()); List<Alteration> relevantAlterations = AlterationUtils.getRelevantAlterations(alt); List<Alteration> alleles = AlterationUtils.getAlleleAlterations(alt); Set<Evidence> relevantEvidences; List<TumorType> relevantTumorTypes = new ArrayList<>(); if (query.getTumorType() != null) { relevantTumorTypes = TumorTypeUtils.getMappedOncoTreeTypesBySource(query.getTumorType(), source); } EvidenceQueryRes evidenceQueryRes = new EvidenceQueryRes(); evidenceQueryRes.setGene(gene); evidenceQueryRes.setQuery(query); evidenceQueryRes.setAlterations(relevantAlterations); evidenceQueryRes.setOncoTreeTypes(relevantTumorTypes); evidenceQueryRes.setLevelOfEvidences(levelOfEvidences == null ? null : new ArrayList<>(levelOfEvidences)); List<EvidenceQueryRes> evidenceQueryResList = new ArrayList<>(); evidenceQueryResList.add(evidenceQueryRes); relevantEvidences = getEvidence(evidenceQueryResList, evidenceTypes, geneStatus, levelOfEvidences); Set<Evidence> evidencesToRemove = new HashSet<>(); Set<Alteration> excludeAlternativeAlleles = new HashSet<>(); for (Evidence tempEvidence : relevantEvidences) { if (LevelUtils.isResistanceLevel(tempEvidence.getLevelOfEvidence())) { excludeAlternativeAlleles.addAll(Sets.intersection(tempEvidence.getAlterations(), new HashSet<>(alleles))); } } for (Evidence tempEvidence : relevantEvidences) { if (!Collections.disjoint(excludeAlternativeAlleles, tempEvidence.getAlterations())) { evidencesToRemove.add(tempEvidence); } } relevantEvidences.removeAll(evidencesToRemove); return filterEvidence(relevantEvidences, evidenceQueryRes); } else { return new HashSet<>(); } } public static Set<Evidence> getEvidenceByEvidenceTypesAndLevels(Set<EvidenceType> types, Set<LevelOfEvidence> levels) { Set<Alteration> alterations = AlterationUtils.getAllAlterations(); List<Evidence> evidences = EvidenceUtils.getEvidence(new ArrayList<>(alterations), types, levels); return new HashSet<>(evidences); } private static List<Evidence> getEvidence(List<Alteration> alterations) { if (alterations == null || alterations.size() == 0) { return new ArrayList<>(); } if (CacheUtils.isEnabled()) { return getAlterationEvidences(alterations); } else { return evidenceBo.findEvidencesByAlteration(alterations); } } public static List<Evidence> getEvidence(List<Alteration> alterations, Set<EvidenceType> evidenceTypes, Set<LevelOfEvidence> levelOfEvidences) { if (alterations == null) { alterations = new ArrayList<>(); } if (evidenceTypes == null) { evidenceTypes = new HashSet<>(); } if (levelOfEvidences == null) { levelOfEvidences = new HashSet<>(); } if (alterations.size() == 0) { return new ArrayList<>(); } if (evidenceTypes.size() == 0 && levelOfEvidences.size() == 0) { return getEvidence(alterations); } if (CacheUtils.isEnabled()) { List<Evidence> alterationEvidences = getAlterationEvidences(alterations); List<Evidence> result = new ArrayList<>(); for (Evidence evidence : alterationEvidences) { if (evidenceTypes.size() > 0 && !evidenceTypes.contains(evidence.getEvidenceType())) { continue; } if (levelOfEvidences.size() > 0 && !levelOfEvidences.contains(evidence.getLevelOfEvidence())) { continue; } result.add(evidence); } return result; } else { if (levelOfEvidences.size() == 0) { return evidenceBo.findEvidencesByAlteration(alterations, evidenceTypes); } else { return evidenceBo.findEvidencesByAlterationWithLevels(alterations, evidenceTypes, levelOfEvidences); } } } public static List<Evidence> getEvidence(List<Alteration> alterations, Set<EvidenceType> evidenceTypes, Set<TumorType> tumorTypes, Set<LevelOfEvidence> levelOfEvidences) { if (alterations == null || alterations.size() == 0) { return new ArrayList<>(); } if (evidenceTypes == null || evidenceTypes.size() == 0) { return getEvidence(alterations); } if (tumorTypes == null || tumorTypes.size() == 0) { return getEvidence(alterations, evidenceTypes, levelOfEvidences); } if (levelOfEvidences == null || levelOfEvidences.size() == 0) { return evidenceBo.findEvidencesByAlteration(alterations, evidenceTypes, tumorTypes); } else { return evidenceBo.findEvidencesByAlteration(alterations, evidenceTypes, tumorTypes, levelOfEvidences); } } private static Set<Evidence> getEvidence(List<EvidenceQueryRes> queries, Set<EvidenceType> evidenceTypes, String geneStatus, Set<LevelOfEvidence> levelOfEvidences) { Set<Evidence> evidences = new HashSet<>(); Map<Integer, Gene> genes = new HashMap<>(); //Get gene evidences Map<Integer, Alteration> alterations = new HashMap<>(); Set<TumorType> tumorTypes = new HashSet<>(); for (EvidenceQueryRes query : queries) { if (query.getGene() != null) { int entrezGeneId = query.getGene().getEntrezGeneId(); if (!genes.containsKey(entrezGeneId)) { genes.put(entrezGeneId, query.getGene()); } Set<Alteration> allAlts = new HashSet<>(); if (query.getAlterations() != null) { allAlts.addAll(query.getAlterations()); } if (query.getAlleles() != null) { allAlts.addAll(query.getAlleles()); } for (Alteration alt : allAlts) { int altId = alt.getId(); if (!alterations.containsKey(altId)) { alterations.put(altId, alt); } } if (query.getOncoTreeTypes() != null) { for (TumorType tumorType : query.getOncoTreeTypes()) { if (!tumorTypes.contains(tumorType)) { tumorTypes.add(tumorType); } } } } } // Get all gene related evidences Map<Gene, Set<Evidence>> mappedEvidences = EvidenceUtils.getEvidenceByGenesAndEvidenceTypes(new HashSet<>(genes.values()), Sets.intersection(EvidenceTypeUtils.getGeneEvidenceTypes(), evidenceTypes)); for (Map.Entry<Gene, Set<Evidence>> cursor : mappedEvidences.entrySet()) { evidences.addAll(cursor.getValue()); } List<Alteration> uniqueAlterations = new ArrayList<>(alterations.values()); // Get all mutation related evidences Set<EvidenceType> common = Sets.intersection(EvidenceTypeUtils.getMutationEvidenceTypes(), evidenceTypes); if (common.size() > 0) { evidences.addAll(getEvidence(uniqueAlterations, common, null)); } // For sensitive evidences, get all ignore tumor types. They will be propagated to other tumor types // in assignEvidence function common = Sets.intersection(EvidenceTypeUtils.getSensitiveTreatmentEvidenceTypes(), evidenceTypes); if (common.size() > 0) { evidences.addAll(getEvidence(uniqueAlterations, common, levelOfEvidences)); } // Get other tumor type related evidences Set<EvidenceType> restTTevidenceTypes = EvidenceTypeUtils.getTumorTypeEvidenceTypes(); restTTevidenceTypes.removeAll(EvidenceTypeUtils.getSensitiveTreatmentEvidenceTypes()); common = Sets.intersection(restTTevidenceTypes, evidenceTypes); if (common.size() > 0) { evidences.addAll(getEvidence(uniqueAlterations, common, tumorTypes, levelOfEvidences)); } return evidences; } public static List<Evidence> getAlterationEvidences(List<Alteration> alterations) { List<Evidence> evidences = new ArrayList<>(); if (CacheUtils.isEnabled()) { Set<Evidence> geneEvidences = getAllEvidencesByAlterationsGenes(alterations); for (Evidence evidence : geneEvidences) { if (!Collections.disjoint(evidence.getAlterations(), alterations)) { evidences.add(evidence); } } } else { evidences = evidenceBo.findEvidencesByAlteration(alterations); } return evidences; } public static Map<Gene, Set<Evidence>> getEvidenceByGenes(Set<Gene> genes) { Map<Gene, Set<Evidence>> evidences = new HashMap<>(); if (CacheUtils.isEnabled()) { for (Gene gene : genes) { if (gene != null) { evidences.put(gene, CacheUtils.getEvidences(gene)); } } } else { evidences = EvidenceUtils.separateEvidencesByGene(genes, new HashSet<Evidence>(ApplicationContextSingleton.getEvidenceBo().findAll())); } return evidences; } public static Map<Gene, Set<Evidence>> getEvidenceByGenesAndEvidenceTypes(Set<Gene> genes, Set<EvidenceType> evidenceTypes) { Map<Gene, Set<Evidence>> result = new HashMap<>(); if (evidenceTypes == null && evidenceTypes.isEmpty()) return result; if (CacheUtils.isEnabled()) { for (Gene gene : genes) { if (gene != null) { Set<Evidence> evidences = CacheUtils.getEvidences(gene); Set<Evidence> filtered = new HashSet<>(); for (Evidence evidence : evidences) { if (evidenceTypes.contains(evidence.getEvidenceType())) { filtered.add(evidence); } } result.put(gene, filtered); } } } else { result = EvidenceUtils.separateEvidencesByGene(genes, new HashSet<Evidence>(ApplicationContextSingleton.getEvidenceBo().findAll())); for (Gene gene : genes) { Set<Evidence> evidences = result.get(gene); for (Evidence evidence : evidences) { if (!evidenceTypes.contains(evidence.getEvidenceType())) { evidences.remove(evidence); } } } } return result; } public static Set<Evidence> getEvidenceByGeneAndEvidenceTypes(Gene gene, Set<EvidenceType> evidenceTypes) { Set<Evidence> result = new HashSet<>(); if (gene != null) { if (CacheUtils.isEnabled()) { Set<Evidence> evidences = CacheUtils.getEvidences(gene); for (Evidence evidence : evidences) { if (evidenceTypes.contains(evidence.getEvidenceType())) { result.add(evidence); } } } else { List<Evidence> evidences = evidenceBo.findEvidencesByGene(Collections.singleton(gene), evidenceTypes); if (evidences != null) { result = new HashSet<>(evidences); } } } return result; } public static Set<Evidence> convertEvidenceLevel(List<Evidence> evidences, Set<TumorType> tumorTypes) { Set<Evidence> tmpEvidences = new HashSet<>(); for (Evidence evidence : evidences) { Evidence tmpEvidence = new Evidence(evidence, evidence.getId()); Boolean flag = true; if (Collections.disjoint(Collections.singleton(tmpEvidence.getOncoTreeType()), tumorTypes)) { if (tmpEvidence.getLevelOfEvidence() != null) { if (tmpEvidence.getPropagation() != null) { LevelOfEvidence propagationLevel = LevelOfEvidence.getByName(tmpEvidence.getPropagation()); if (propagationLevel != null) { tmpEvidence.setLevelOfEvidence(propagationLevel); } else { flag = false; } } // Don't include any resistance evidence if tumor type is not matched. if (LevelUtils.getResistanceLevels().contains(tmpEvidence.getLevelOfEvidence())) { flag = false; } } } if (flag) { tmpEvidences.add(tmpEvidence); } } return tmpEvidences; } private static Set<Evidence> filterEvidence(Set<Evidence> evidences, EvidenceQueryRes evidenceQuery) { Set<Evidence> filtered = new HashSet<>(); if (evidenceQuery.getGene() != null) { for (Evidence evidence : evidences) { if (evidence.getGene().equals(evidenceQuery.getGene())) { //Add all gene specific evidences if (evidence.getAlterations().isEmpty()) { filtered.add(evidence); } else { boolean hasjointed = !Collections.disjoint(evidence.getAlterations(), evidenceQuery.getAlterations()); if (!hasjointed) { hasjointed = !Collections.disjoint(evidence.getAlterations(), evidenceQuery.getAlleles()); } if (hasjointed) { if (evidence.getOncoTreeType() == null) { if (evidence.getEvidenceType().equals(EvidenceType.ONCOGENIC)) { if (evidence.getDescription() == null) { List<Alteration> alterations = new ArrayList<>(); alterations.addAll(evidence.getAlterations()); // tempEvidence.setDescription(SummaryUtils.variantSummary(Collections.singleton(tempEvidence.getGene()), alterations, evidenceQuery.getQueryAlteration(), Collections.singleton(tempEvidence.getTumorType()), evidenceQuery.getQueryTumorType())); } } filtered.add(evidence); } else { List<TumorType> tumorType = new ArrayList<>(); if (evidence.getOncoTreeType() != null) { tumorType.add(evidence.getOncoTreeType()); } hasjointed = !Collections.disjoint(evidenceQuery.getOncoTreeTypes(), tumorType); if (hasjointed || com.mysql.jdbc.StringUtils.isNullOrEmpty(evidenceQuery.getQuery().getTumorType())) { filtered.add(evidence); } else { if (evidence.getLevelOfEvidence() != null && evidence.getPropagation() != null) { LevelOfEvidence propagationLevel = LevelOfEvidence.getByName(evidence.getPropagation()); if (propagationLevel != null) { if (evidenceQuery.getLevelOfEvidences() == null || evidenceQuery.getLevelOfEvidences().size() == 0 || evidenceQuery.getLevelOfEvidences().contains(propagationLevel)) { Evidence tempEvidence = new Evidence(evidence, evidence.getId()); tempEvidence.setLevelOfEvidence(propagationLevel); filtered.add(tempEvidence); } } } } } } } } } } return filtered; } public static List<Evidence> filterAlteration(List<Evidence> evidences, List<Alteration> alterations) { for (Evidence evidence : evidences) { Set<Alteration> filterEvidences = new HashSet<>(); for (Alteration alt : evidence.getAlterations()) { if (alterations.contains(alt)) { filterEvidences.add(alt); } } evidence.getAlterations().clear(); evidence.setAlterations(filterEvidences); } return evidences; } public static Map<Gene, Set<Evidence>> separateEvidencesByGene(Set<Gene> genes, Set<Evidence> evidences) { Map<Gene, Set<Evidence>> result = new HashMap<>(); for (Gene gene : genes) { result.put(gene, new HashSet<Evidence>()); } for (Evidence evidence : evidences) { if (result.containsKey(evidence.getGene())) { result.get(evidence.getGene()).add(evidence); } } return result; } public static MutationEffect getMutationEffectFromEvidence(Set<Evidence> evidences) { Set<MutationEffect> result = new HashSet<>(); for (Evidence evidence : evidences) { if (evidence.getKnownEffect() != null) { result.add(MutationEffect.getByName(evidence.getKnownEffect())); } } if (result.size() > 1) { return MainUtils.findHighestMutationEffect(result); } else if (result.size() == 1) { return result.iterator().next(); } else { return null; } } public static Oncogenicity getOncogenicityFromEvidence(Set<Evidence> evidences) { Set<Oncogenicity> result = new HashSet<>(); for (Evidence evidence : evidences) { if (evidence.getKnownEffect() != null) { result.add(Oncogenicity.getByEvidence(evidence)); } } if (result.size() > 1) { return MainUtils.findHighestOncogenicity(result); } else if (result.size() == 1) { return result.iterator().next(); } else { return null; } } public static Set<String> getPmids(Set<Evidence> evidences) { Set<String> result = new HashSet<>(); for (Evidence evidence : evidences) { for (Article article : evidence.getArticles()) { if (article.getPmid() != null) { result.add(article.getPmid()); } } } return result; } public static Set<ArticleAbstract> getAbstracts(Set<Evidence> evidences) { Set<ArticleAbstract> result = new HashSet<>(); for (Evidence evidence : evidences) { for (Article article : evidence.getArticles()) { if (article.getAbstractContent() != null) { ArticleAbstract articleAbstract = new ArticleAbstract(); articleAbstract.setAbstractContent(article.getAbstractContent()); articleAbstract.setLink(article.getLink()); result.add(articleAbstract); } } } return result; } public static Set<String> getDrugs(Set<Evidence> evidences) { Set<String> result = new HashSet<>(); for (Evidence evidence : evidences) { for (Treatment treatment : evidence.getTreatments()) { Set<String> drugsInTreatment = new HashSet<>(); for (Drug drug : treatment.getDrugs()) { if (drug.getDrugName() != null) { drugsInTreatment.add(drug.getDrugName()); } } result.add(StringUtils.join(drugsInTreatment, " + ")); } } return result; } public static Map<Gene, Set<Evidence>> getAllGeneBasedEvidences() { Set<Gene> genes = GeneUtils.getAllGenes(); Map<Gene, Set<Evidence>> evidences = EvidenceUtils.getEvidenceByGenes(genes); return evidences; } public static Set<Evidence> getEvidenceBasedOnHighestOncogenicity(Set<Evidence> evidences) { Set<Evidence> filtered = new HashSet<>(); Map<Oncogenicity, Set<Evidence>> map = new HashMap<>(); if (evidences == null || evidences.size() == 0) return filtered; for (Evidence evidence : evidences) { if (evidence.getEvidenceType() != null && evidence.getEvidenceType().equals(EvidenceType.ONCOGENIC)) { Oncogenicity oncogenicity = Oncogenicity.getByEvidence(evidence); if (oncogenicity != null) { if (!map.containsKey(oncogenicity)) map.put(oncogenicity, new HashSet<Evidence>()); map.get(oncogenicity).add(evidence); } } } Oncogenicity highestOncogenicity = MainUtils.findHighestOncogenicByEvidences(evidences); if (map.get(highestOncogenicity) != null) filtered = map.get(highestOncogenicity); return filtered; } public static Set<Evidence> getOnlyHighestLevelEvidences(Set<Evidence> evidences) { Map<LevelOfEvidence, Set<Evidence>> levels = separateEvidencesByLevel(evidences); Set<LevelOfEvidence> keys = levels.keySet(); LevelOfEvidence highestLevel = LevelUtils.getHighestLevel(keys); if (highestLevel != null) { return levels.get(highestLevel); } else { return new HashSet<>(); } } public static Set<Evidence> getOnlySignificantLevelsEvidences(Set<Evidence> evidences) { Map<LevelOfEvidence, Set<Evidence>> levels = separateEvidencesByLevel(evidences); Set<LevelOfEvidence> keys = levels.keySet(); LevelOfEvidence highestLevel = LevelUtils.getHighestLevel(keys); Set<Evidence> result = new HashSet<>(); if (highestLevel != null) { if (highestLevel.equals(LevelOfEvidence.LEVEL_2B) && levels.containsKey(LevelOfEvidence.LEVEL_3A)) { result.addAll(levels.get(LevelOfEvidence.LEVEL_3A)); } result.addAll(levels.get(highestLevel)); } return result; } public static Map<LevelOfEvidence, Set<Evidence>> separateEvidencesByLevel(Set<Evidence> evidences) { Map<LevelOfEvidence, Set<Evidence>> levels = new HashMap<>(); for (Evidence evidence : evidences) { if (evidence.getLevelOfEvidence() != null) { if (!levels.containsKey(evidence.getLevelOfEvidence())) { levels.put(evidence.getLevelOfEvidence(), new HashSet<Evidence>()); } levels.get(evidence.getLevelOfEvidence()).add(evidence); } } return levels; } public static Set<Evidence> keepHighestLevelForSameTreatments(Set<Evidence> evidences) { Map<String, Set<Evidence>> maps = new HashedMap(); Set<Evidence> filtered = new HashSet<>(); for (Evidence evidence : evidences) { if (evidence.getTreatments() != null && evidence.getTreatments().size() > 0) { String treatmentsName = TreatmentUtils.getTreatmentName(new HashSet<>(evidence.getTreatments())); if (!maps.containsKey(treatmentsName)) { maps.put(treatmentsName, new HashSet<Evidence>()); } maps.get(treatmentsName).add(evidence); } else { // Keep all un-treatment evidences filtered.add(evidence); } } for (Map.Entry<String, Set<Evidence>> entry : maps.entrySet()) { Set<Evidence> highestEvis = EvidenceUtils.getOnlyHighestLevelEvidences(entry.getValue()); // If highestEvis has more than 1 items, find highest original level if the level is 2B, 3B if (highestEvis.size() > 1) { Set<LevelOfEvidence> checkLevels = new HashSet<>(); checkLevels.add(LevelOfEvidence.LEVEL_2B); checkLevels.add(LevelOfEvidence.LEVEL_3B); if (checkLevels.contains(highestEvis.iterator().next().getLevelOfEvidence())) { Set<Integer> evidenceIds = new HashSet<>(); Set<Gene> genes = new HashSet<>(); for (Evidence evidence : highestEvis) { evidenceIds.add(evidence.getId()); genes.add(evidence.getGene()); } Set<Evidence> originalEvis = EvidenceUtils.getEvidencesByGenesAndIds(genes, evidenceIds); Set<Evidence> highestOriginalEvis = EvidenceUtils.getOnlyHighestLevelEvidences(originalEvis); Set<Integer> filteredIds = new HashSet<>(); for (Evidence evidence : highestOriginalEvis) { filteredIds.add(evidence.getId()); } for (Evidence evidence : highestEvis) { if (filteredIds.contains(evidence.getId())) { filtered.add(evidence); // Only add one break; } } } else { filtered.add(highestEvis.iterator().next()); } } else { filtered.addAll(highestEvis); } } return filtered; } public static Set<Evidence> getEvidencesByUUID(String uuid) { if (uuid == null) { return new HashSet<>(); } if (CacheUtils.isEnabled()) { return CacheUtils.getEvidencesByUUID(uuid); } else { return new HashSet<>(evidenceBo.findEvidenceByUUIDs(Collections.singletonList(uuid))); } } public static Set<Evidence> getEvidencesByUUIDs(Set<String> uuids) { if (uuids == null) { return new HashSet<>(); } if (CacheUtils.isEnabled()) { return CacheUtils.getEvidencesByUUIDs(uuids); } else { return new HashSet<>(evidenceBo.findEvidenceByUUIDs(new ArrayList<>(uuids))); } } public static Evidence getEvidenceByEvidenceId(Integer id) { if (id == null) { return null; } Set<Evidence> evidences = new HashSet<>(); if (CacheUtils.isEnabled()) { evidences = CacheUtils.getEvidencesByIds(Collections.singleton(id)); } else { List<Evidence> evidenceList = evidenceBo.findEvidencesByIds(Collections.singletonList(id)); if (evidenceList == null) { evidences = null; } else { evidences = new HashSet<>(evidenceList); } } if (evidences == null || evidences.size() > 1) { return null; } return evidences.iterator().next(); } public static Set<Evidence> getEvidencesByGenesAndIds(Set<Gene> genes, Set<Integer> ids) { if (ids == null) { return new HashSet<>(); } if (CacheUtils.isEnabled()) { return CacheUtils.getEvidencesByGenesAndIds(genes, ids); } else { return new HashSet<>(evidenceBo.findEvidencesByIds(new ArrayList<>(ids))); } } public static Set<Evidence> getEvidenceByEvidenceIds(Set<Integer> ids) { if (ids == null) { return new HashSet<>(); } if (CacheUtils.isEnabled()) { return CacheUtils.getEvidencesByIds(ids); } else { return new HashSet<>(evidenceBo.findEvidencesByIds(new ArrayList<>(ids))); } } public static Set<Evidence> filterEvidenceByKnownEffect(Set<Evidence> evidences, String knownEffect) { if (knownEffect == null) { return null; } Set<Evidence> result = new HashSet<>(); for (Evidence evidence : evidences) { if (evidence.getKnownEffect() != null && evidence.getKnownEffect().equalsIgnoreCase(knownEffect)) { result.add(evidence); } } return result; } public static Set<Evidence> getSensitiveEvidences(Set<Evidence> evidences) { return filterEvidenceByKnownEffect(evidences, "sensitive"); } public static Set<Evidence> getResistanceEvidences(Set<Evidence> evidences) { return filterEvidenceByKnownEffect(evidences, "resistant"); } // Temporary move evidence process methods here in order to share the code between new APIs and legacies public static List<EvidenceQueryRes> processRequest(List<Query> requestQueries, Set<EvidenceType> evidenceTypes, String geneStatus, String source, Set<LevelOfEvidence> levelOfEvidences, Boolean highestLevelOnly) { List<EvidenceQueryRes> evidenceQueries = new ArrayList<>(); if (source == null) { source = "quest"; } if (evidenceTypes == null) { evidenceTypes = new HashSet<>(EvidenceTypeUtils.getAllEvidenceTypes()); } if (requestQueries == null || requestQueries.size() == 0) { Set<Evidence> evidences = new HashSet<>(); if ((evidenceTypes != null && evidenceTypes.size() > 0) || (levelOfEvidences != null && levelOfEvidences.size() > 0)) { evidences = EvidenceUtils.getEvidenceByEvidenceTypesAndLevels(evidenceTypes, levelOfEvidences); } EvidenceQueryRes query = new EvidenceQueryRes(); query.setEvidences(new ArrayList<>(evidences)); return Collections.singletonList(query); } else { if (levelOfEvidences == null) { levelOfEvidences = LevelUtils.getPublicLevels(); } for (Query requestQuery : requestQueries) { EvidenceQueryRes query = new EvidenceQueryRes(); requestQuery.enrich(); query.setQuery(requestQuery); query.setGene(GeneUtils.getGene(requestQuery.getEntrezGeneId(), requestQuery.getHugoSymbol())); if (query.getGene() != null) { if (requestQuery.getTumorType() != null && !requestQuery.getTumorType().isEmpty()) { query.setOncoTreeTypes( TumorTypeUtils.getMappedOncoTreeTypesBySource(requestQuery.getTumorType(), source)); } if (!com.mysql.jdbc.StringUtils.isNullOrEmpty(requestQuery.getAlteration())) { Alteration alt = AlterationUtils.findAlteration(query.getGene(), requestQuery.getAlteration()); if (alt == null) alt = AlterationUtils.getAlteration(query.getGene().getHugoSymbol(), requestQuery.getAlteration(), null, requestQuery.getConsequence(), requestQuery.getProteinStart(), requestQuery.getProteinEnd()); List<Alteration> relevantAlts = AlterationUtils.getRelevantAlterations(alt); // Look for Oncogenic Mutations if no relevantAlt found for alt and alt is hotspot if (relevantAlts.isEmpty() && HotspotUtils.isHotspot(alt)) { Alteration oncogenicMutations = AlterationUtils.findAlteration(alt.getGene(), "Oncogenic Mutations"); if (oncogenicMutations != null) { relevantAlts.add(oncogenicMutations); } } Alteration alteration = AlterationUtils.getAlteration(query.getGene().getHugoSymbol(), requestQuery.getAlteration(), AlterationType.MUTATION, requestQuery.getConsequence(), requestQuery.getProteinStart(), requestQuery.getProteinEnd()); List<Alteration> allelesAlts = AlterationUtils.getAlleleAlterations(alteration); relevantAlts.removeAll(allelesAlts); query.setAlterations(relevantAlts); query.setAlleles(new ArrayList<>(allelesAlts)); } else { // if no alteration assigned, but has tumor type query.setAlterations(new ArrayList<Alteration>(AlterationUtils.getAllAlterations(query.getGene()))); } } if (levelOfEvidences != null) { query.setLevelOfEvidences(new ArrayList<LevelOfEvidence>(levelOfEvidences)); } evidenceQueries.add(query); } } return assignEvidence(getEvidence(evidenceQueries, evidenceTypes, geneStatus, levelOfEvidences), evidenceQueries, highestLevelOnly); } private static List<EvidenceQueryRes> assignEvidence(Set<Evidence> evidences, List<EvidenceQueryRes> evidenceQueries, Boolean highestLevelOnly) { highestLevelOnly = highestLevelOnly == null ? false : highestLevelOnly; for (EvidenceQueryRes query : evidenceQueries) { if (highestLevelOnly) { Set<Evidence> allEvidences = new HashSet<>(query.getEvidences()); List<Evidence> filteredEvidences = new ArrayList<>(); // Get highest sensitive evidences Set<Evidence> sensitiveEvidences = EvidenceUtils.getSensitiveEvidences(allEvidences); filteredEvidences.addAll(EvidenceUtils.getOnlyHighestLevelEvidences(sensitiveEvidences)); // Get highest resistance evidences Set<Evidence> resistanceEvidences = EvidenceUtils.getResistanceEvidences(allEvidences); filteredEvidences.addAll(EvidenceUtils.getOnlyHighestLevelEvidences(resistanceEvidences)); // Also include all non-treatment evidences for (Evidence evidence : allEvidences) { if (!sensitiveEvidences.contains(evidence) && !resistanceEvidences.contains(evidence)) { filteredEvidences.add(evidence); } } query.setEvidences(filteredEvidences); } else { query.setEvidences( new ArrayList<>(keepHighestLevelForSameTreatments(filterEvidence(evidences, query)))); } CustomizeComparator.sortEvidenceBasedOnPriority(query.getEvidences()); if (query.getGene() != null && query.getGene().getHugoSymbol().equals("KIT")) { CustomizeComparator.sortKitTreatmentByEvidence(query.getEvidences()); } } return evidenceQueries; } public static void annotateEvidence(Evidence evidence) throws ParserConfigurationException { // If evidence does not have gene info, we can not help with anything here. if (evidence.getGene() == null) { return; } // If the gene does not match with any one in our database, we can not help with anything here. Gene gene = GeneUtils.getGene(evidence.getGene().getEntrezGeneId(), evidence.getGene().getHugoSymbol()); if (gene == null) { return; } evidence.setGene(gene); Set<Alteration> queryAlterations = evidence.getAlterations(); if (queryAlterations != null && !queryAlterations.isEmpty()) { AlterationType type = AlterationType.MUTATION; Set<Alteration> alterations = new HashSet<Alteration>(); AlterationBo alterationBo = ApplicationContextSingleton.getAlterationBo(); for (Alteration alt : queryAlterations) { String proteinChange = alt.getAlteration(); String displayName = alt.getName(); Alteration alteration = alterationBo.findAlteration(gene, type, proteinChange); if (alteration == null) { alteration = new Alteration(); alteration.setGene(gene); alteration.setAlterationType(type); alteration.setAlteration(proteinChange); alteration.setName(displayName); AlterationUtils.annotateAlteration(alteration, proteinChange); alterationBo.save(alteration); } alterations.add(alteration); } evidence.setAlterations(alterations); } Set<Article> articles = evidence.getArticles(); if (evidence.getSubtype() != null && evidence.getSubtype().isEmpty()) { evidence.setSubtype(null); } if (evidence.getCancerType() != null && evidence.getCancerType().isEmpty()) { evidence.setCancerType(null); } if (articles != null && !articles.isEmpty()) { ArticleBo articleBo = ApplicationContextSingleton.getArticleBo(); Set<Article> annotatedArticles = new HashSet<>(); for (Article article : articles) { String tempPMID = article.getPmid(); if (tempPMID == null) { Article tempAT = articleBo.findArticleByAbstract(article.getAbstractContent()); if (tempAT == null) { articleBo.save(article); annotatedArticles.add(article); } else { annotatedArticles.add(tempAT); } } else { Article tempAT = articleBo.findArticleByPmid(tempPMID); if (tempAT == null) { Article newArticle = NcbiEUtils.readPubmedArticle(tempPMID); if (newArticle != null) { articleBo.save(newArticle); annotatedArticles.add(newArticle); } } else { annotatedArticles.add(tempAT); } } } evidence.setArticles(annotatedArticles); } } /** * * @param evidences * @param isDesc default is false * @return */ public static List<Evidence> sortTumorTypeEvidenceBasedNumOfAlts(List<Evidence> evidences, Boolean isDesc) { // Default multiplier for the sorting int flag = 1; if (evidences == null) { return new ArrayList<>(); } if (isDesc) { flag = -1; } final int multiplier = flag; final Map<Evidence, Integer> originalIndices = new HashedMap(); for (int i = 0; i < evidences.size(); i++) { originalIndices.put(evidences.get(i), i); } // Sort all tumor type summaries, the more specific tumor type summary will be picked. Collections.sort(evidences, new Comparator<Evidence>() { public int compare(Evidence x, Evidence y) { if (x.getAlterations() == null) { return 1; } if (y.getAlterations() == null) { return -1; } Integer result = x.getAlterations().size() - y.getAlterations().size(); if (result.equals(0)) { return originalIndices.get(x) - originalIndices.get(y); } return multiplier * result; } }); return evidences; } public static Set<Evidence> getAllEvidencesByAlterationsGenes(Collection<Alteration> alterations) { Set<Gene> genes = new HashSet<>(); Set<Evidence> evidences = new HashSet<>(); for (Alteration alteration : alterations) { genes.add(alteration.getGene()); } if (genes.size() == 1) { return CacheUtils.getEvidences(genes.iterator().next()); } for (Gene gene : genes) { evidences.addAll(CacheUtils.getEvidences(gene)); } return evidences; } }
package org.torquebox.core.as; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.projectodd.polyglot.core.processors.RootedDeploymentProcessor.rootSafe; import java.io.IOException; import java.util.Hashtable; import java.util.List; import javax.management.MBeanServer; import org.jboss.as.controller.AbstractBoottimeAddStepHandler; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.ServiceVerificationHandler; import org.jboss.as.jmx.MBeanRegistrationService; import org.jboss.as.jmx.MBeanServerService; import org.jboss.as.jmx.ObjectNameFactory; import org.jboss.as.server.AbstractDeploymentChainStep; import org.jboss.as.server.DeploymentProcessorTarget; import org.jboss.as.server.deployment.Phase; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.jboss.msc.service.ServiceBuilder.DependencyType; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceController.Mode; import org.jboss.stdio.StdioContext; import org.projectodd.polyglot.core.processors.ApplicationExploder; import org.projectodd.polyglot.core.processors.ArchiveStructureProcessor; import org.projectodd.polyglot.core.processors.DescriptorRootMountProcessor; import org.torquebox.TorqueBox; import org.torquebox.TorqueBoxMBean; import org.torquebox.TorqueBoxStdioContextSelector; import org.torquebox.core.GlobalRuby; import org.torquebox.core.GlobalRubyMBean; import org.torquebox.core.app.processors.AppJarScanningProcessor; import org.torquebox.core.app.processors.AppKnobYamlParsingProcessor; import org.torquebox.core.app.processors.ApplicationYamlParsingProcessor; import org.torquebox.core.app.processors.EnvironmentYamlParsingProcessor; import org.torquebox.core.app.processors.RubyApplicationDefaultsProcessor; import org.torquebox.core.app.processors.RubyApplicationInstaller; import org.torquebox.core.app.processors.RubyApplicationRecognizer; import org.torquebox.core.app.processors.RubyYamlParsingProcessor; import org.torquebox.core.datasource.processors.DatabaseProcessor; import org.torquebox.core.datasource.processors.DatabaseYamlParsingProcessor; import org.torquebox.core.injection.analysis.InjectableHandlerRegistry; import org.torquebox.core.injection.analysis.processors.InjectionIndexingProcessor; import org.torquebox.core.injection.processors.CorePredeterminedInjectableInstaller; import org.torquebox.core.injection.processors.InjectionYamlParsingProcessor; import org.torquebox.core.injection.processors.PredeterminedInjectableProcessor; import org.torquebox.core.pool.processors.PoolingYamlParsingProcessor; import org.torquebox.core.processors.TorqueBoxRbProcessor; import org.torquebox.core.processors.TorqueBoxYamlParsingProcessor; import org.torquebox.core.runtime.processors.BaseRubyRuntimeInstaller; import org.torquebox.core.runtime.processors.RubyNamespaceContextSelectorProcessor; import org.torquebox.core.runtime.processors.RubyRuntimeFactoryInstaller; import org.torquebox.core.runtime.processors.RuntimePoolInstaller; class CoreSubsystemAdd extends AbstractBoottimeAddStepHandler { @Override protected void populateModel(ModelNode operation, ModelNode model) { model.get( "injector" ).setEmptyObject(); } @Override protected void performBoottime(OperationContext context, ModelNode operation, ModelNode model, ServiceVerificationHandler verificationHandler, List<ServiceController<?>> newControllers) throws OperationFailedException { final InjectableHandlerRegistry registry = new InjectableHandlerRegistry(); context.addStep( new AbstractDeploymentChainStep() { @Override protected void execute(DeploymentProcessorTarget processorTarget) { addDeploymentProcessors( processorTarget, registry ); } }, OperationContext.Stage.RUNTIME ); try { addCoreServices( context, verificationHandler, newControllers, registry ); addTorqueBoxStdioContext(); } catch (Exception e) { throw new OperationFailedException( e, null ); } } protected void addDeploymentProcessors(final DeploymentProcessorTarget processorTarget, final InjectableHandlerRegistry registry) { processorTarget.addDeploymentProcessor( CoreExtension.SUBSYSTEM_NAME, Phase.STRUCTURE, 0, new DescriptorRootMountProcessor( "-knob.yml" ) ); processorTarget.addDeploymentProcessor( CoreExtension.SUBSYSTEM_NAME, Phase.STRUCTURE, 0, new ArchiveStructureProcessor( ".knob" ) ); processorTarget.addDeploymentProcessor( CoreExtension.SUBSYSTEM_NAME, Phase.STRUCTURE, 800, new AppKnobYamlParsingProcessor() ); processorTarget.addDeploymentProcessor( CoreExtension.SUBSYSTEM_NAME, Phase.STRUCTURE, 900, rootSafe( new AppJarScanningProcessor() ) ); processorTarget.addDeploymentProcessor( CoreExtension.SUBSYSTEM_NAME, Phase.PARSE, 0, rootSafe( new RubyApplicationRecognizer() ) ); processorTarget.addDeploymentProcessor( CoreExtension.SUBSYSTEM_NAME, Phase.PARSE, 5, new TorqueBoxYamlParsingProcessor() ); processorTarget.addDeploymentProcessor( CoreExtension.SUBSYSTEM_NAME, Phase.PARSE, 10, new TorqueBoxRbProcessor() ); processorTarget.addDeploymentProcessor( CoreExtension.SUBSYSTEM_NAME, Phase.PARSE, 20, rootSafe( new ApplicationYamlParsingProcessor() ) ); processorTarget.addDeploymentProcessor( CoreExtension.SUBSYSTEM_NAME, Phase.PARSE, 30, new EnvironmentYamlParsingProcessor() ); processorTarget.addDeploymentProcessor( CoreExtension.SUBSYSTEM_NAME, Phase.PARSE, 35, rootSafe( new PoolingYamlParsingProcessor() ) ); processorTarget.addDeploymentProcessor( CoreExtension.SUBSYSTEM_NAME, Phase.PARSE, 36, rootSafe( new RubyYamlParsingProcessor() ) ); processorTarget.addDeploymentProcessor( CoreExtension.SUBSYSTEM_NAME, Phase.PARSE, 37, rootSafe( new InjectionYamlParsingProcessor() ) ); processorTarget.addDeploymentProcessor( CoreExtension.SUBSYSTEM_NAME, Phase.PARSE, 40, rootSafe( new RubyApplicationDefaultsProcessor() ) ); processorTarget.addDeploymentProcessor( CoreExtension.SUBSYSTEM_NAME, Phase.PARSE, 42, new DatabaseYamlParsingProcessor() ); processorTarget.addDeploymentProcessor( CoreExtension.SUBSYSTEM_NAME, Phase.PARSE, 100, new ApplicationExploder() ); processorTarget.addDeploymentProcessor( CoreExtension.SUBSYSTEM_NAME, Phase.PARSE, 4000, rootSafe( new BaseRubyRuntimeInstaller() ) ); processorTarget.addDeploymentProcessor( CoreExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, 0, rootSafe( new CoreDependenciesProcessor() ) ); // processorTarget.addDeploymentProcessor( Phase.DEPENDENCIES, 10, // rootSafe( new JdkDependenciesProcessor() ) ); processorTarget.addDeploymentProcessor( CoreExtension.SUBSYSTEM_NAME, Phase.CONFIGURE_MODULE, 1000, rootSafe( new PredeterminedInjectableProcessor( registry ) ) ); processorTarget.addDeploymentProcessor( CoreExtension.SUBSYSTEM_NAME, Phase.CONFIGURE_MODULE, 1001, rootSafe( new CorePredeterminedInjectableInstaller() ) ); processorTarget.addDeploymentProcessor( CoreExtension.SUBSYSTEM_NAME, Phase.CONFIGURE_MODULE, 1100, rootSafe( new InjectionIndexingProcessor( registry ) ) ); processorTarget.addDeploymentProcessor( CoreExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, 110, rootSafe( new RubyNamespaceContextSelectorProcessor() ) ); processorTarget.addDeploymentProcessor( CoreExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, 5000, rootSafe( new DatabaseProcessor() ) ); processorTarget.addDeploymentProcessor( CoreExtension.SUBSYSTEM_NAME, Phase.INSTALL, 0, rootSafe( new RubyRuntimeFactoryInstaller() ) ); processorTarget.addDeploymentProcessor( CoreExtension.SUBSYSTEM_NAME, Phase.INSTALL, 10, rootSafe( new RuntimePoolInstaller() ) ); processorTarget.addDeploymentProcessor( CoreExtension.SUBSYSTEM_NAME, Phase.INSTALL, 9000, rootSafe( new RubyApplicationInstaller() ) ); } protected void addCoreServices(final OperationContext context, ServiceVerificationHandler verificationHandler, List<ServiceController<?>> newControllers, InjectableHandlerRegistry registry) throws Exception { addTorqueBoxService( context, verificationHandler, newControllers, registry ); addGlobalRubyServices( context, verificationHandler, newControllers, registry ); addInjectionServices( context, verificationHandler, newControllers, registry ); } @SuppressWarnings("serial") protected void addTorqueBoxService(final OperationContext context, ServiceVerificationHandler verificationHandler, List<ServiceController<?>> newControllers, InjectableHandlerRegistry registry) throws IOException { TorqueBox torqueBox = new TorqueBox(); newControllers.add( context.getServiceTarget().addService( CoreServices.TORQUEBOX, torqueBox ) .setInitialMode( Mode.ACTIVE ) .addListener( verificationHandler ) .install() ); String mbeanName = ObjectNameFactory.create( "torquebox", new Hashtable<String, String>() { { put( "type", "version" ); } } ).toString(); MBeanRegistrationService<TorqueBoxMBean> mbeanService = new MBeanRegistrationService<TorqueBoxMBean>( mbeanName ); newControllers.add( context.getServiceTarget().addService( CoreServices.TORQUEBOX.append( "mbean" ), mbeanService ) .addDependency( DependencyType.OPTIONAL, MBeanServerService.SERVICE_NAME, MBeanServer.class, mbeanService.getMBeanServerInjector() ) .addDependency( CoreServices.TORQUEBOX, TorqueBoxMBean.class, mbeanService.getValueInjector() ) .addListener( verificationHandler ) .setInitialMode( Mode.PASSIVE ) .install() ); } @SuppressWarnings("serial") protected void addGlobalRubyServices(final OperationContext context, ServiceVerificationHandler verificationHandler, List<ServiceController<?>> newControllers, InjectableHandlerRegistry registry) { newControllers.add( context.getServiceTarget().addService( CoreServices.GLOBAL_RUBY, new GlobalRuby() ) .addListener( verificationHandler ) .setInitialMode( Mode.ACTIVE ) .install() ); String mbeanName = ObjectNameFactory.create( "torquebox", new Hashtable<String, String>() { { put( "type", "runtime" ); } } ).toString(); MBeanRegistrationService<GlobalRubyMBean> mbeanService = new MBeanRegistrationService<GlobalRubyMBean>( mbeanName ); newControllers.add( context.getServiceTarget().addService( CoreServices.GLOBAL_RUBY.append( "mbean" ), mbeanService ) .addDependency( DependencyType.OPTIONAL, MBeanServerService.SERVICE_NAME, MBeanServer.class, mbeanService.getMBeanServerInjector() ) .addDependency( CoreServices.GLOBAL_RUBY, GlobalRubyMBean.class, mbeanService.getValueInjector() ) .addListener( verificationHandler ) .setInitialMode( Mode.PASSIVE ) .install() ); } protected void addInjectionServices(final OperationContext context, ServiceVerificationHandler verificationHandler, List<ServiceController<?>> newControllers, InjectableHandlerRegistry registry) { newControllers.add( context.getServiceTarget().addService( CoreServices.INJECTABLE_HANDLER_REGISTRY, registry ) .addListener( verificationHandler ) .setInitialMode( Mode.PASSIVE ) .install() ); } protected void addTorqueBoxStdioContext() { // Grab the existing AS7 StdioContext final StdioContext defaultContext = StdioContext.getStdioContext(); // Uninstall to reset System.in, .out, .err to default values StdioContext.uninstall(); // Create debug StdioContext based on System streams final StdioContext debugContext = StdioContext.create( System.in, System.out, System.err ); TorqueBoxStdioContextSelector selector = new TorqueBoxStdioContextSelector( defaultContext, debugContext ); StdioContext.install(); StdioContext.setStdioContextSelector( selector ); } static ModelNode createOperation(ModelNode address) { final ModelNode subsystem = new ModelNode(); subsystem.get( OP ).set( ADD ); subsystem.get( OP_ADDR ).set( address ); return subsystem; } public CoreSubsystemAdd() { } static final CoreSubsystemAdd ADD_INSTANCE = new CoreSubsystemAdd(); static final Logger log = Logger.getLogger( "org.torquebox.core.as" ); }
package org.usergrid.persistence.cassandra; import static me.prettyprint.hector.api.factory.HFactory.createColumnFamilyDefinition; import static org.usergrid.persistence.cassandra.CassandraPersistenceUtils.getCfDefs; import static org.usergrid.persistence.cassandra.CassandraService.APPLICATIONS_CF; import static org.usergrid.persistence.cassandra.CassandraService.DEFAULT_APPLICATION; import static org.usergrid.persistence.cassandra.CassandraService.DEFAULT_APPLICATION_ID; import static org.usergrid.persistence.cassandra.CassandraService.MANAGEMENT_APPLICATION; import static org.usergrid.persistence.cassandra.CassandraService.MANAGEMENT_APPLICATION_ID; import static org.usergrid.persistence.cassandra.CassandraService.PROPERTIES_CF; import static org.usergrid.persistence.cassandra.CassandraService.STATIC_APPLICATION_KEYSPACE; import static org.usergrid.persistence.cassandra.CassandraService.SYSTEM_KEYSPACE; import static org.usergrid.persistence.cassandra.CassandraService.USE_VIRTUAL_KEYSPACES; import static org.usergrid.persistence.cassandra.CassandraService.keyspaceForApplication; import java.util.ArrayList; import java.util.List; import java.util.UUID; import me.prettyprint.hector.api.ddl.ColumnFamilyDefinition; import me.prettyprint.hector.api.ddl.ComparatorType; import org.apache.log4j.Logger; import org.usergrid.mq.cassandra.QueuesCF; // TODO: Auto-generated Javadoc /** * Cassandra-specific setup utilities. * * @author edanuff */ public class Setup { private static final Logger logger = Logger.getLogger(Setup.class); private final org.usergrid.persistence.EntityManagerFactory emf; private final CassandraService cass; /** * Instantiates a new setup object. * * @param emf * the emf * @param cass */ Setup(EntityManagerFactoryImpl emf, CassandraService cass) { this.emf = emf; this.cass = cass; } /** * Initialize. * * @throws Exception * the exception */ public synchronized void setup() throws Exception { cass.init(); setupSystemKeyspace(); setupStaticKeyspace(); ((EntityManagerFactoryImpl) emf).initializeApplication( DEFAULT_APPLICATION_ID, DEFAULT_APPLICATION, null); ((EntityManagerFactoryImpl) emf).initializeApplication( MANAGEMENT_APPLICATION_ID, MANAGEMENT_APPLICATION, null); } /** * Initialize system keyspace. * * @throws Exception * the exception */ public void setupSystemKeyspace() throws Exception { logger.info("Initialize system keyspace"); List<ColumnFamilyDefinition> cf_defs = new ArrayList<ColumnFamilyDefinition>(); cf_defs.add(createColumnFamilyDefinition(SYSTEM_KEYSPACE, APPLICATIONS_CF, ComparatorType.BYTESTYPE)); cf_defs.add(createColumnFamilyDefinition(SYSTEM_KEYSPACE, PROPERTIES_CF, ComparatorType.BYTESTYPE)); cass.createKeyspace(SYSTEM_KEYSPACE, cf_defs); logger.info("System keyspace initialized"); } /** * Initialize application keyspace. * * @param applicationId * the application id * @param applicationName * the application name * @throws Exception * the exception */ public void setupApplicationKeyspace(final UUID applicationId, String applicationName) throws Exception { if (!USE_VIRTUAL_KEYSPACES) { String app_keyspace = keyspaceForApplication(applicationId); logger.info("Creating application keyspace " + app_keyspace + " for " + applicationName + " application"); cass.createKeyspace( app_keyspace, getCfDefs(ApplicationCF.class, getCfDefs(QueuesCF.class, app_keyspace), app_keyspace)); /* * String messages_keyspace = app_keyspace + * APPLICATION_MESSAGES_KEYSPACE_SUFFIX; * cass.createKeyspace(messages_keyspace, getCfDefs(QueuesCF.class, * messages_keyspace)); */ } } public void setupStaticKeyspace() throws Exception { if (USE_VIRTUAL_KEYSPACES) { logger.info("Creating static application keyspace " + STATIC_APPLICATION_KEYSPACE); cass.createKeyspace( STATIC_APPLICATION_KEYSPACE, getCfDefs( ApplicationCF.class, getCfDefs(QueuesCF.class, STATIC_APPLICATION_KEYSPACE), STATIC_APPLICATION_KEYSPACE)); /* * cass.createKeyspace(STATIC_MESSAGES_KEYSPACE, * getCfDefs(QueuesCF.class, STATIC_MESSAGES_KEYSPACE)); */ } } public void checkKeyspaces() { cass.checkKeyspaces(); } public static void logCFPermissions() { System.out.println(SYSTEM_KEYSPACE + "." + APPLICATIONS_CF + ".<rw>=usergrid"); System.out.println(SYSTEM_KEYSPACE + "." + PROPERTIES_CF + ".<rw>=usergrid"); for (CFEnum cf : ApplicationCF.values()) { System.out.println(STATIC_APPLICATION_KEYSPACE + "." + cf + ".<rw>=usergrid"); } for (CFEnum cf : QueuesCF.values()) { System.out.println(STATIC_APPLICATION_KEYSPACE + "." + cf + ".<rw>=usergrid"); } } }
package uk.ac.cam.ch.wwmm.opsin; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import static uk.ac.cam.ch.wwmm.opsin.XmlDeclarations.*; import nu.xom.Element; import nu.xom.Elements; /** * * @author dl387 * */ class FusedRingBuilder { private static final Pattern matchSemiColon = Pattern.compile(";"); private static final Pattern matchColon = Pattern.compile(":"); private static final Pattern matchComma = Pattern.compile(","); private static final Pattern matchDash = Pattern.compile("-"); private static final Pattern matchSlash = Pattern.compile("/"); private static final Pattern matchC = Pattern.compile("C"); /** * Master method for processing fused rings. Fuses groups together * @param state: contains the current id and fragment manager * @param subOrRoot Element (substituent or root) * @throws StructureBuildingException */ static void processFusedRings(BuildState state, Element subOrRoot) throws StructureBuildingException { List<Element> groups = XOMTools.getChildElementsWithTagName(subOrRoot, GROUP_EL); if (groups.size() < 2){ return;//nothing to fuse } List<Element> groupsInFusedRing =new ArrayList<Element>(); for (int i = groups.size()-1; i >=0; i--) {//group groups into fused rings Element group =groups.get(i); groupsInFusedRing.add(0, group); if (i!=0){ Element startingEl = group; if ((group.getValue().equals("benz") || group.getValue().equals("benzo"))){ Element beforeBenzo = (Element) XOMTools.getPreviousSibling(group); if (beforeBenzo !=null && beforeBenzo.getLocalName().equals(LOCANT_EL)){ startingEl = beforeBenzo; } } Element possibleGroup = XOMTools.getPreviousSiblingIgnoringCertainElements(startingEl, new String[]{MULTIPLIER_EL, FUSION_EL}); if (!groups.get(i-1).equals(possibleGroup)){//end of fused ring system if (groupsInFusedRing.size()>=2){ processFusedRing(state, groupsInFusedRing); } groupsInFusedRing.clear(); } } } if (groupsInFusedRing.size()>=2){ processFusedRing(state, groupsInFusedRing); } } /** * Combined the fragments assoicated with the given groups into a fused ring * @param state * @param groups * @throws StructureBuildingException */ static void processFusedRing(BuildState state, List<Element> groups) throws StructureBuildingException{ Element lastGroup = groups.get(groups.size()-1); /* * Apply any nonstandard ring numbering and sort atomOrder by locant */ for (Element group : groups) { Fragment ring = state.xmlFragmentMap.get(group); if (ALKANESTEM_SUBTYPE_VAL.equals(group.getAttributeValue(SUBTYPE_ATR))){ aromatiseCyclicAlkane(state, group); } if (group == lastGroup) { //perform a quick check that every atom in this group is infact cyclic. Fusion components are enumerated and hence all guaranteed to be purely cyclic List<Atom> atomList = ring.getAtomList(); for (Atom atom : atomList) { if (!atom.getAtomIsInACycle()) { throw new StructureBuildingException("Inappropriate group used in fusion nomenclature. Only groups composed entirely of atoms in cycles may be used. i.e. not: " + group.getValue()); } } if (group.getAttribute(FUSEDRINGNUMBERING_ATR) != null) { String[] standardNumbering = matchSlash.split(group.getAttributeValue(FUSEDRINGNUMBERING_ATR), -1); for (int j = 0; j < standardNumbering.length; j++) { atomList.get(j).replaceLocant(standardNumbering[j]); } } else { ring.sortAtomListByLocant();//for those where the order the locants are in is sensible } } for (Atom atom : atomList) { atom.clearLocants();//the parentRing does not have locants, letters are used to indicate the edges } } else if (group.getAttribute(FUSEDRINGNUMBERING_ATR) == null) { ring.sortAtomListByLocant();//for those where the order the locants are in is sensible } } groups = processBenzoFusions(state, groups);//FR-2.2.8 e.g. in 2H-[1,3]benzodioxino[6',5',4':10,5,6]anthra[2,3-b]azepine benzodioxino is one component List<Element> nameComponents = new ArrayList<Element>(); Element currentEl = groups.get(0); while(currentEl != lastGroup){ if (currentEl.getLocalName().equals(GROUP_EL) || currentEl.getLocalName().equals(FUSION_EL)){ nameComponents.add(currentEl); } currentEl = (Element) XOMTools.getNextSibling(currentEl); } nameComponents.remove(lastGroup); Fragment parentRing = state.xmlFragmentMap.get(lastGroup); List<Fragment> componentFragments = new ArrayList<Fragment>();//all the ring fragments (other than the parentRing). These will later be merged into the parentRing Map<Integer,Fragment> fragmentInScopeForEachFusionLevel = new HashMap<Integer,Fragment>(); fragmentInScopeForEachFusionLevel.put(0, parentRing); int numberOfParents = 1; Element possibleMultiplier = (Element) XOMTools.getPreviousSibling(lastGroup); if (nameComponents.size()>0 && possibleMultiplier !=null && possibleMultiplier.getLocalName().equals(MULTIPLIER_EL)){ numberOfParents = Integer.parseInt(possibleMultiplier.getAttributeValue(VALUE_ATR)); possibleMultiplier.detach(); } List<Fragment> parentFragments = new ArrayList<Fragment>(); parentFragments.add(parentRing); for (int j = 1; j < numberOfParents; j++) { Fragment copyOfParentRing =state.fragManager.copyFragment(parentRing); parentFragments.add(copyOfParentRing); componentFragments.add(copyOfParentRing); } /* * The number of primes on the component to be connected. * This is initially 0 indicating fusion of unprimed locants with the letter locants of the parentRing * Subsequently it will switch to 1 indicating fusion of a second order component (primed locants) with a * first order component (unprimed locants) * Next would be double primed fusing to single primed locants etc. * */ int i = processMultiParentSystem(state, parentFragments, nameComponents, fragmentInScopeForEachFusionLevel, componentFragments);//handle multiparent systems int fusionLevel = (nameComponents.size()-1 -i)/2; for (; i>=0; i Element fusion = null; if (nameComponents.get(i).getLocalName().equals(FUSION_EL)){ fusion = nameComponents.get(i } if (i <0 || !nameComponents.get(i).getLocalName().equals(GROUP_EL)){ throw new StructureBuildingException("Group not found where group expected. This is probably a bug"); } Fragment nextComponent = state.xmlFragmentMap.get(nameComponents.get(i)); int multiplier = 1; Element possibleMultiplierEl = (Element) XOMTools.getPreviousSibling(nameComponents.get(i));//e.g. the di of difuro if (possibleMultiplierEl != null && possibleMultiplierEl.getLocalName().equals(MULTIPLIER_EL)){ multiplier = Integer.parseInt(possibleMultiplierEl.getAttributeValue(VALUE_ATR)); } String[] fusionDescriptors =null; if (fusion !=null){ String fusionDescriptorString = fusion.getValue().substring(1, fusion.getValue().length()-1); if (multiplier ==1){ fusionDescriptors = new String[]{fusionDescriptorString}; } else{ if (matchSemiColon.split(fusionDescriptorString).length >1){ fusionDescriptors = matchSemiColon.split(fusionDescriptorString); } else if (matchColon.split(fusionDescriptorString).length >1){ fusionDescriptors = matchColon.split(fusionDescriptorString); } else if (matchComma.split(fusionDescriptorString).length >1){ fusionDescriptors = matchComma.split(fusionDescriptorString); } else{//multiplier does not appear to mean multiplied component. Could be indicating multiplication of the whole fused ring system multiplier =1; fusionDescriptors = new String[]{fusionDescriptorString}; } } } if (multiplier >1){ possibleMultiplierEl.detach(); } Fragment[] fusionComponents = new Fragment[multiplier]; for (int j = 0; j < multiplier; j++) { if (j>0){ fusionComponents[j] = state.fragManager.copyAndRelabelFragment(nextComponent, StringTools.multiplyString("'", j)); } else{ fusionComponents[j] = nextComponent; } } for (int j = 0; j < multiplier; j++) { Fragment component = fusionComponents[j]; componentFragments.add(component); if (fusion !=null){ if (matchColon.split(fusionDescriptors[j]).length==1){//A fusion bracket without a colon is used when applying to the parent component (except in a special case where locants are ommitted) //check for case of omitted locant from a higher order fusion bracket e.g. cyclopenta[4,5]pyrrolo[2,3-c]pyridine if (matchDash.split(fusionDescriptors[j]).length==1 && matchComma.split(fusionDescriptors[j]).length >1 && allAtomsAreIdentical(component)){ relabelAccordingToFusionLevel(component, fusionLevel); List<String> numericalLocantsOfParent = Arrays.asList(matchComma.split(fusionDescriptors[j])); List<String> numericalLocantsOfChild = findPossibleNumericalLocants(component, numericalLocantsOfParent.size()-1); processHigherOrderFusionDescriptors(state, component, fragmentInScopeForEachFusionLevel.get(fusionLevel), numericalLocantsOfChild, numericalLocantsOfParent); } else{ fusionLevel = 0; relabelAccordingToFusionLevel(component, fusionLevel); String fusionDescriptor = fusionDescriptors[j]; String[] fusionArray = determineNumericalAndLetterComponents(fusionDescriptor); int numberOfPrimes =0; if (!fusionArray[1].equals("")){ numberOfPrimes =StringTools.countTerminalPrimes(fusionArray[1]); if (fusionArray[0].equals("")){ fusionDescriptor = fusionArray[1].replaceAll("'", ""); } else{ fusionDescriptor = fusionArray[0]+ "-" +fusionArray[1].replaceAll("'", ""); } if (numberOfPrimes >= parentFragments.size()){ throw new StructureBuildingException("Unexpected prime in fusion descriptor"); } } performSimpleFusion(state, fusionDescriptor, component, parentFragments.get(numberOfPrimes));//e.g. pyrano[3,2-b]imidazo[4,5-e]pyridine where both are level 0 fusions } } else{ String firstLocant = matchComma.split(fusionDescriptors[j])[0]; int numberOfPrimes = -j;//determine number of primes in fusor and hence determine fusion level for(int k = firstLocant.length() -1; k>0; k if (firstLocant.charAt(k)=='\''){ numberOfPrimes++; } } if (numberOfPrimes != fusionLevel){ if (fusionLevel == numberOfPrimes +1){ fusionLevel = numberOfPrimes; } else{ throw new StructureBuildingException("Incorrect number of primes in fusion bracket: " +fusionDescriptors[j]); } } relabelAccordingToFusionLevel(component, fusionLevel); performHigherOrderFusion(state, fusionDescriptors[j], component, fragmentInScopeForEachFusionLevel.get(fusionLevel)); } } else{ relabelAccordingToFusionLevel(component, fusionLevel); performSimpleFusion(state, null, component, fragmentInScopeForEachFusionLevel.get(fusionLevel)); } } fusionLevel++; if (multiplier ==1){//multiplied components may not be substituted onto fragmentInScopeForEachFusionLevel.put(fusionLevel, fusionComponents[0]); } } for (Fragment ring : componentFragments) { state.fragManager.incorporateFragment(ring, parentRing); } FusedRingNumberer.numberFusedRing(parentRing);//numbers the fused ring; state.fragManager.removeFragment(parentRing); Fragment fusedRing =state.fragManager.copyFragment(parentRing);//makes sure the IDs are continuous (not sure whether this is actually necessary anymore) StringBuilder fusedRingName = new StringBuilder(); for (Element element : nameComponents) { fusedRingName.append(element.getValue()); } fusedRingName.append(groups.get(groups.size()-1).getValue()); Element fusedRingEl =groups.get(groups.size()-1);//reuse this element to save having to remap suffixes... fusedRingEl.getAttribute(VALUE_ATR).setValue(fusedRingName.toString()); fusedRingEl.removeAttribute(fusedRingEl.getAttribute(VALTYPE_ATR)); fusedRingEl.getAttribute(TYPE_ATR).setValue(RING_TYPE_VAL); fusedRingEl.getAttribute(SUBTYPE_ATR).setValue(FUSEDRING_SUBTYPE_VAL); fusedRingEl.removeChildren(); fusedRingEl.appendChild(fusedRingName.toString()); state.xmlFragmentMap.put(fusedRingEl, fusedRing); for (Element element : nameComponents) { element.detach(); } } /** * Given a cyclicAlkaneGroup determines whether or not it should be aromatised. Unlocanted ene will be detached if it is an aromatisation hint * No unsaturators -->aromatise * Just ane -->don't * More than 1 ene or locants on ene -->don't * yne --> don't * @param state * @param cyclicAlkaneGroup */ private static void aromatiseCyclicAlkane(BuildState state, Element cyclicAlkaneGroup) { Element next = (Element) XOMTools.getNextSibling(cyclicAlkaneGroup); List<Element> unsaturators = new ArrayList<Element>(); while (next!=null && next.getLocalName().equals(UNSATURATOR_EL)){ unsaturators.add(next); next = (Element) XOMTools.getNextSibling(next); } boolean conjugate =true; if (unsaturators.size()==1){ int value = Integer.parseInt(unsaturators.get(0).getAttributeValue(VALUE_ATR)); if (value !=2){ conjugate =false; } else if (unsaturators.get(0).getAttribute(LOCANT_ATR)!=null){ conjugate =false; } } else if (unsaturators.size()==2){ int value1 = Integer.parseInt(unsaturators.get(0).getAttributeValue(VALUE_ATR)); if (value1 !=1){ conjugate =false; } else{ int value2 = Integer.parseInt(unsaturators.get(1).getAttributeValue(VALUE_ATR)); if (value2 !=2 || unsaturators.get(1).getAttribute(LOCANT_ATR)!=null){ conjugate =false; } } } else if (unsaturators.size() >2){ conjugate =false; } if (conjugate){ for (Element unsaturator : unsaturators) { unsaturator.detach(); } List<Atom> atomList =state.xmlFragmentMap.get(cyclicAlkaneGroup).getAtomList(); for (Atom atom : atomList) { atom.setSpareValency(true); } } } private static int processMultiParentSystem(BuildState state,List<Fragment> parentFragments, List<Element> nameComponents, Map<Integer, Fragment> fragmentInScopeForEachFusionLevel, List<Fragment> componentFragments) throws StructureBuildingException { int i = nameComponents.size()-1; int fusionLevel =0; if (i>=0 && parentFragments.size()>1){ List<Fragment> previousFusionLevelFragments = parentFragments; for (; i>=0; i if (previousFusionLevelFragments.size()==1){//completed multi parent system fragmentInScopeForEachFusionLevel.put(fusionLevel, previousFusionLevelFragments.get(0)); break; } Element fusion = null; if (nameComponents.get(i).getLocalName().equals(FUSION_EL)){ fusion = nameComponents.get(i } else{ throw new StructureBuildingException("Fusion bracket not found where fusion bracket expected"); } if (i <0 || !nameComponents.get(i).getLocalName().equals(GROUP_EL)){ throw new StructureBuildingException("Group not found where group expected. This is probably a bug"); } Fragment nextComponent = state.xmlFragmentMap.get(nameComponents.get(i)); relabelAccordingToFusionLevel(nextComponent, fusionLevel); int multiplier = 1; Element possibleMultiplierEl = (Element) XOMTools.getPreviousSibling(nameComponents.get(i)); if (possibleMultiplierEl != null && possibleMultiplierEl.getLocalName().equals(MULTIPLIER_EL)){ multiplier = Integer.parseInt(possibleMultiplierEl.getAttributeValue(VALUE_ATR)); } if (multiplier >1){ possibleMultiplierEl.detach(); } List<Fragment> fusionComponents = new ArrayList<Fragment>(); for (int j = 0; j < multiplier; j++) { if (j>0){ fusionComponents.add(state.fragManager.copyAndRelabelFragment(nextComponent, StringTools.multiplyString("'", j))); } else{ fusionComponents.add(nextComponent); } } fusionLevel+=multiplier; if (multiplier>1 && multiplier != previousFusionLevelFragments.size()){ throw new StructureBuildingException("Mismatch between number of components and number of parents in fused ring system"); } String fusionDescriptorString = fusion.getValue().substring(1, fusion.getValue().length()-1); String[] fusionDescriptors =null; if (matchSemiColon.split(fusionDescriptorString).length >1){ fusionDescriptors = matchSemiColon.split(fusionDescriptorString); } else if (matchColon.split(fusionDescriptorString).length >1){ fusionDescriptors = matchColon.split(fusionDescriptorString); } else if (matchComma.split(fusionDescriptorString).length >1){ fusionDescriptors = matchComma.split(fusionDescriptorString); } else{ throw new StructureBuildingException("Invalid fusion descriptor: " + fusionDescriptorString); } if (fusionDescriptors.length != previousFusionLevelFragments.size()){ throw new StructureBuildingException("Invalid fusion descriptor: "+fusionDescriptorString +"(Number of locants disagrees with number of parents)"); } for (int j = 0; j < fusionDescriptors.length; j++) { String fusionDescriptor = fusionDescriptors[j]; Fragment component = multiplier>1 ? fusionComponents.get(j) : nextComponent; Fragment parentToUse = previousFusionLevelFragments.get(j); boolean simpleFusion; simpleFusion = matchColon.split(fusionDescriptor).length <= 1; if (simpleFusion){ String[] fusionArray = determineNumericalAndLetterComponents(fusionDescriptor); if (!fusionArray[1].equals("")){ int numberOfPrimes =StringTools.countTerminalPrimes(fusionArray[1]); if (fusionArray[0].equals("")){ fusionDescriptor = fusionArray[1].replaceAll("'", ""); } else{ fusionDescriptor = fusionArray[0]+ "-" +fusionArray[1].replaceAll("'", ""); } if (numberOfPrimes !=j){//check the number of primes on the letter part agree with the parent to use e.g.[4,5-bcd:1,2-c']difuran throw new StructureBuildingException("Incorrect number of primes in fusion descriptor: " + fusionDescriptor); } } performSimpleFusion(state, fusionDescriptor, component, parentToUse); } else{ performHigherOrderFusion(state, fusionDescriptor, component, parentToUse); } } previousFusionLevelFragments = fusionComponents; componentFragments.addAll(fusionComponents); } if (previousFusionLevelFragments.size()!=1){ throw new StructureBuildingException("Invalid fused ring system. Incomplete multiparent system"); } } return i; } /** * Splits a first order fusion component into it's numerical and letter parts * Either one of these can be the blank string as they may have been omitted * The first entry in the array is the numbers and the second the letters * @param fusionDescriptor * @return */ private static String[] determineNumericalAndLetterComponents(String fusionDescriptor) { String[] fusionArray = matchDash.split(fusionDescriptor); if (fusionArray.length ==2){ return fusionArray; } else{ String[] components = new String[2]; if (fusionArray[0].contains(",")){//the digit section components[0]=fusionArray[0]; components[1]=""; } else{ components[0]=""; components[1]=fusionArray[0]; } return components; } } /** * Searches groups for benz(o) components and fuses them in accordance with * FR-2.2.8 Heterobicyclic components with a benzene ring * Returns the the list of group elements This will have been modified if this function has done anything * @param state * @param groups * @return * @throws StructureBuildingException */ private static List<Element> processBenzoFusions(BuildState state, List<Element> groups) throws StructureBuildingException { for(int i= groups.size() -2;i >=0; i if (groups.get(i).getValue().equals("benz") || groups.get(i).getValue().equals("benzo")){ Element possibleFusionbracket = (Element) XOMTools.getNextSibling(groups.get(i)); if (!possibleFusionbracket.getLocalName().equals(FUSION_EL)){ Element possibleMultiplier = (Element) XOMTools.getPreviousSibling(groups.get(i)); if (possibleMultiplier==null || !possibleMultiplier.getLocalName().equals(MULTIPLIER_EL)|| possibleMultiplier.getAttributeValue(TYPE_ATR).equals(GROUP_TYPE_VAL)){ //e.g. 2-benzofuran. Fused rings of this type are a special case treated as being a single component //and have a special convention for indicating the position of heteroatoms benzoSpecificFusion(state, groups.get(i), groups.get(i+1)); groups.get(i).detach(); groups.remove(i); } } } } return groups; } /** * Modifies nextComponent's locants according to the fusionLevel. * @param component * @param fusionLevel */ private static void relabelAccordingToFusionLevel(Fragment component, int fusionLevel) { if (fusionLevel > 0){ FragmentTools.relabelLocants(component.getAtomList(), StringTools.multiplyString("'", fusionLevel)); } } /** * Handles fusion between components where the fusion descriptor is of the form: * comma separated locants dash letters * e.g imidazo[4,5-d]pyridine * The fusionDescriptor may be given as null or the letter/numerical part omitted. * Sensible defaults will be found instead * @param state * @param fusionDescriptor * @param childRing * @param parentRing * @throws StructureBuildingException */ private static void performSimpleFusion(BuildState state, String fusionDescriptor, Fragment childRing, Fragment parentRing) throws StructureBuildingException { List<String> numericalLocantsOfChild = null; List<String> letterLocantsOfParent = null; if (fusionDescriptor != null){ String[] fusionArray = matchDash.split(fusionDescriptor); if (fusionArray.length ==2){ numericalLocantsOfChild = Arrays.asList(matchComma.split(fusionArray[0])); char[] tempLetterLocantsOfParent = fusionArray[1].toCharArray(); letterLocantsOfParent = new ArrayList<String>(); for (char letterLocantOfParent : tempLetterLocantsOfParent) { letterLocantsOfParent.add(String.valueOf(letterLocantOfParent)); } } else{ if (fusionArray[0].contains(",")){//only has digits String[] numericalLocantsOfChildTemp = matchComma.split(fusionArray[0]); numericalLocantsOfChild = Arrays.asList(numericalLocantsOfChildTemp); } else{//only has letters char[] tempLetterLocantsOfParentCharArray = fusionArray[0].toCharArray(); letterLocantsOfParent = new ArrayList<String>(); for (char letterLocantOfParentCharArray : tempLetterLocantsOfParentCharArray) { letterLocantsOfParent.add(String.valueOf(letterLocantOfParentCharArray)); } } } } int edgeLength =1; if (numericalLocantsOfChild != null){ if (numericalLocantsOfChild.size() <=1){ throw new StructureBuildingException("At least two numerical locants must be provided to perform fusion!"); } edgeLength = numericalLocantsOfChild.size()-1; } else if (letterLocantsOfParent != null){ edgeLength = letterLocantsOfParent.size(); } if (numericalLocantsOfChild == null){ numericalLocantsOfChild = findPossibleNumericalLocants(childRing, edgeLength); } if (letterLocantsOfParent == null){ letterLocantsOfParent = findPossibleLetterLocants(parentRing, edgeLength); } if (numericalLocantsOfChild == null || letterLocantsOfParent ==null){ throw new StructureBuildingException("Unable to find bond to form fused ring system. Some information for forming fused ring system was only supplyed implicitly"); } processFirstOrderFusionDescriptors(state, childRing, parentRing, numericalLocantsOfChild, letterLocantsOfParent);//fuse the rings } /** * Takes a ring an returns and array with one letter corresponding to a side/s * that contains two adjacent non bridgehead carbons * The number of sides is specified by edgeLength * @param ring * @param edgeLength The number of bonds to be fused along * @return */ private static List<String> findPossibleLetterLocants(Fragment ring, int edgeLength) { List<Atom> atomlist = ring.getAtomList(); List<String> letterLocantsOfParent = null; List<Atom> carbonAtoms = new ArrayList<Atom>(); atomlist.add(0, atomlist.get(atomlist.size()-1));//this atomList is a copy so we can safely do this for (int i =atomlist.size() -1; i >=0; i--) {//iterate backwards in list to use highest locanted edge in preference. //this retains what is currently locant 1 on the parent ring as locant 1 if the first two atoms found match Atom atom = atomlist.get(i); if (matchC.matcher(atom.getElement()).matches()){ if (atom.getIncomingValency()>=3){ carbonAtoms.clear(); continue;//don't want bridgehead carbons } carbonAtoms.add(atom); if (carbonAtoms.size() ==edgeLength +1 ){//as many in a row as edgelength ->use this side letterLocantsOfParent = new ArrayList<String>(); Collections.reverse(carbonAtoms); atomlist.remove(0); for (int j = 0; j < edgeLength; j++) { letterLocantsOfParent.add(String.valueOf((char)(97 +atomlist.indexOf(carbonAtoms.get(j)))));//97 is ascii for a } break; } } else{ carbonAtoms.clear(); } } return letterLocantsOfParent; } /** * Takes a ring and returns an array of numbers corresponding to a side/s * that contains two adjacent non bridgehead carbons * The number of sides is specified by edgeLength * @param ring * @param edgeLength The number of bonds to be fused along * @return */ private static List<String> findPossibleNumericalLocants(Fragment ring, int edgeLength) { List<Atom> atomlist = ring.getAtomList(); List<String> numericalLocantsOfChild = null; List<String> carbonLocants = new ArrayList<String>(); atomlist.add(atomlist.get(0));//this atomList is a copy so we can safely do this for (Atom atom : atomlist) { if (matchC.matcher(atom.getElement()).matches()){ if (atom.getIncomingValency()>=3){ carbonLocants.clear(); continue;//don't want bridgehead carbons } carbonLocants.add(atom.getFirstLocant()); if (carbonLocants.size()==edgeLength +1){//as many in a row as edgelength ->use this side numericalLocantsOfChild = new ArrayList<String>(); for (String locant : carbonLocants) { numericalLocantsOfChild.add(locant); } break; } } else{ carbonLocants.clear(); } } return numericalLocantsOfChild; } /** * Performs a single ring fusion using the values in numericalLocantsOfChild/letterLocantsOfParent * @param state * @param childRing * @param parentRing * @param numericalLocantsOfChild * @param letterLocantsOfParent * @throws StructureBuildingException */ private static void processFirstOrderFusionDescriptors(BuildState state, Fragment childRing, Fragment parentRing, List<String> numericalLocantsOfChild, List<String> letterLocantsOfParent) throws StructureBuildingException { List<Atom> childAtomList = childRing.getAtomList(); int indexfirst = childAtomList.indexOf(childRing.getAtomByLocantOrThrow(numericalLocantsOfChild.get(0))); int indexfinal = childAtomList.indexOf(childRing.getAtomByLocantOrThrow(numericalLocantsOfChild.get(numericalLocantsOfChild.size()-1))); CyclicAtomList cyclicListAtomsInChild = new CyclicAtomList(childAtomList, indexfirst); List<Atom> childAtoms = null; List<Atom> possibleChildAtoms = new ArrayList<Atom>(); possibleChildAtoms.add(cyclicListAtomsInChild.getCurrent()); while (cyclicListAtomsInChild.getIndice() != indexfinal){//assume numbers are ascending possibleChildAtoms.add(cyclicListAtomsInChild.getNext()); } if (letterLocantsOfParent.size() +1 == possibleChildAtoms.size()){ boolean notInPossibleChildAtoms =false; for (int i =1; i < numericalLocantsOfChild.size()-1 ; i ++){ if (!possibleChildAtoms.contains(childRing.getAtomByLocantOrThrow(numericalLocantsOfChild.get(i)))){ notInPossibleChildAtoms =true; } } if (!notInPossibleChildAtoms){ childAtoms = possibleChildAtoms; } } if (childAtoms ==null){//that didn't work, so try assuming the numbers are descending cyclicListAtomsInChild.setIndice(indexfirst); possibleChildAtoms.clear(); possibleChildAtoms.add(cyclicListAtomsInChild.getCurrent()); while (cyclicListAtomsInChild.getIndice() != indexfinal){//assume numbers are descending possibleChildAtoms.add(cyclicListAtomsInChild.getPrevious()); } if (letterLocantsOfParent.size() +1 == possibleChildAtoms.size()){ boolean notInPossibleChildAtoms =false; for (int i =1; i < numericalLocantsOfChild.size()-1 ; i ++){ if (!possibleChildAtoms.contains(childRing.getAtomByLocantOrThrow(numericalLocantsOfChild.get(i)))){ notInPossibleChildAtoms =true; } } if (!notInPossibleChildAtoms){ childAtoms = possibleChildAtoms; } } } if (childAtoms ==null){ throw new StructureBuildingException("Malformed fusion bracket!"); } List<Atom> parentAtoms = new ArrayList<Atom>(); List<Atom> parentAtomList = parentRing.getAtomList(); //find the indice of the last atom on the surface of the ring. This obviously connects to the first atom. The objective is to exclude any interior atoms. List<Atom> neighbours = parentAtomList.get(0).getAtomNeighbours(); int indice = Integer.MAX_VALUE; for (Atom atom : neighbours) { int indexOfAtom =parentAtomList.indexOf(atom); if (indexOfAtom ==1){//not the next atom continue; } else if (indexOfAtom ==-1){//not in parentRing continue; } if (parentAtomList.indexOf(atom)< indice){ indice = indexOfAtom; } } CyclicAtomList cyclicListAtomsOnSurfaceOfParent = new CyclicAtomList(parentAtomList.subList(0, indice +1), (int)letterLocantsOfParent.get(0).charAt(0) -97);//convert from lower case character through ascii to 0-23 parentAtoms.add(cyclicListAtomsOnSurfaceOfParent.getCurrent()); for (int i = 0; i < letterLocantsOfParent.size(); i++) { parentAtoms.add(cyclicListAtomsOnSurfaceOfParent.getNext()); } fuseRings(state, childAtoms, parentAtoms); } /** * Handles fusion between components where the fusion descriptor is of the form: * comma separated locants colon comma separated locants * e.g pyrido[1'',2'':1',2']imidazo * @param state * @param fusionDescriptor * @param nextComponent * @param fusedRing * @throws StructureBuildingException */ private static void performHigherOrderFusion(BuildState state, String fusionDescriptor, Fragment nextComponent, Fragment fusedRing) throws StructureBuildingException { List<String> numericalLocantsOfChild = null; List<String> numericalLocantsOfParent = null; String[] fusionArray = matchColon.split(fusionDescriptor); if (fusionArray.length ==2){ numericalLocantsOfChild = Arrays.asList(matchComma.split(fusionArray[0])); numericalLocantsOfParent = Arrays.asList(matchComma.split(fusionArray[1])); } else{ throw new StructureBuildingException("Malformed fusion bracket: This is an OPSIN bug, check regexTokens.xml"); } processHigherOrderFusionDescriptors(state, nextComponent, fusedRing, numericalLocantsOfChild, numericalLocantsOfParent);//fuse the rings } /** * Performs a single ring fusion using the values in numericalLocantsOfChild/numericalLocantsOfParent * @param state * @param childRing * @param parentRing * @param numericalLocantsOfChild * @param numericalLocantsOfParent * @throws StructureBuildingException */ private static void processHigherOrderFusionDescriptors(BuildState state, Fragment childRing, Fragment parentRing, List<String> numericalLocantsOfChild, List<String> numericalLocantsOfParent) throws StructureBuildingException { List<Atom> childAtomList = childRing.getAtomList(); int indexfirst = childAtomList.indexOf(childRing.getAtomByLocantOrThrow(numericalLocantsOfChild.get(0))); int indexfinal = childAtomList.indexOf(childRing.getAtomByLocantOrThrow(numericalLocantsOfChild.get(numericalLocantsOfChild.size()-1))); CyclicAtomList cyclicListAtomsInChild = new CyclicAtomList(childAtomList, indexfirst); List<Atom> childAtoms = null; //need to determine whether locants are ascending or descending...locants may be omitted! List<Atom> potentialChildAtomsAscending = new ArrayList<Atom>(); potentialChildAtomsAscending.add(cyclicListAtomsInChild.getCurrent()); while (cyclicListAtomsInChild.getIndice() != indexfinal){//assume numbers are ascending potentialChildAtomsAscending.add(cyclicListAtomsInChild.getNext()); } boolean notInPotentialChildAtoms =false; for (int i =1; i < numericalLocantsOfChild.size()-1 ; i ++){ if (!potentialChildAtomsAscending.contains(childRing.getAtomByLocantOrThrow(numericalLocantsOfChild.get(i)))){ notInPotentialChildAtoms =true; } } if (notInPotentialChildAtoms){ potentialChildAtomsAscending = null; } //and again for descending cyclicListAtomsInChild.setIndice(indexfirst); List<Atom> potentialChildAtomsDescending = new ArrayList<Atom>(); potentialChildAtomsDescending.add(cyclicListAtomsInChild.getCurrent()); while (cyclicListAtomsInChild.getIndice() != indexfinal){//assume numbers are descending potentialChildAtomsDescending.add(cyclicListAtomsInChild.getPrevious()); } notInPotentialChildAtoms =false; for (int i =1; i < numericalLocantsOfChild.size()-1 ; i ++){ if (!potentialChildAtomsDescending.contains(childRing.getAtomByLocantOrThrow(numericalLocantsOfChild.get(i)))){ notInPotentialChildAtoms =true; } } if (notInPotentialChildAtoms){ potentialChildAtomsDescending = null; } if (potentialChildAtomsAscending ==null){ childAtoms = potentialChildAtomsDescending; } else if (potentialChildAtomsDescending ==null){ childAtoms = potentialChildAtomsAscending; } else{ if (potentialChildAtomsDescending.size() < potentialChildAtomsAscending.size() ){ childAtoms = potentialChildAtomsDescending; } else{ childAtoms = potentialChildAtomsAscending; } } if (childAtoms ==null){ throw new StructureBuildingException("Malformed fusion bracket!"); } List<Atom> parentAtomList = parentRing.getAtomList(); indexfirst = parentAtomList.indexOf(parentRing.getAtomByLocantOrThrow(numericalLocantsOfParent.get(0))); indexfinal = parentAtomList.indexOf(parentRing.getAtomByLocantOrThrow(numericalLocantsOfParent.get(numericalLocantsOfParent.size()-1))); CyclicAtomList cyclicListAtomsInParent = new CyclicAtomList(parentAtomList, indexfirst); List<Atom> parentAtoms = null; List<Atom> potentialParentAtoms = new ArrayList<Atom>(); potentialParentAtoms.add(cyclicListAtomsInParent.getCurrent()); while (cyclicListAtomsInParent.getIndice() != indexfinal){//assume numbers are ascending potentialParentAtoms.add(cyclicListAtomsInParent.getNext()); } if (childAtoms.size() == potentialParentAtoms.size()){ boolean notInPotentialParentAtoms =false; for (int i =1; i < numericalLocantsOfParent.size()-1 ; i ++){ if (!potentialParentAtoms.contains(parentRing.getAtomByLocantOrThrow(numericalLocantsOfParent.get(i)))){ notInPotentialParentAtoms =true; } } if (!notInPotentialParentAtoms){ parentAtoms = potentialParentAtoms; } } if (parentAtoms ==null){//that didn't work, so try assuming the numbers are descending cyclicListAtomsInParent.setIndice(indexfirst); potentialParentAtoms.clear(); potentialParentAtoms.add(cyclicListAtomsInParent.getCurrent()); while (cyclicListAtomsInParent.getIndice() != indexfinal){//assume numbers are ascending potentialParentAtoms.add(cyclicListAtomsInParent.getPrevious()); } if (childAtoms.size() == potentialParentAtoms.size()){ boolean notInPotentialParentAtoms =false; for (int i =1; i < numericalLocantsOfParent.size()-1 ; i ++){ if (!potentialParentAtoms.contains(parentRing.getAtomByLocantOrThrow(numericalLocantsOfParent.get(i)))){ notInPotentialParentAtoms =true; } } if (!notInPotentialParentAtoms){ parentAtoms = potentialParentAtoms; } } } if (parentAtoms ==null){ throw new StructureBuildingException("Malformed fusion bracket!"); } fuseRings(state, childAtoms, parentAtoms); } /** * Fuses two rings together returning a fragment containing the fusedRing * @param state * @param childAtoms * @param parentAtoms * @throws StructureBuildingException */ private static void fuseRings(BuildState state, List<Atom> childAtoms, List<Atom> parentAtoms) throws StructureBuildingException { if (parentAtoms.size()!=childAtoms.size()){ throw new StructureBuildingException("Problem with fusion descriptors: Parent atoms specified: " + parentAtoms.size() +" Child atoms specified: " + childAtoms.size() + " These should have been identical!"); } Fragment childFrag =childAtoms.get(0).getFrag(); for (int i = 0; i < childAtoms.size() -1; i++) { Bond bondToBeRemoved = childFrag.findBondOrThrow(childAtoms.get(i), childAtoms.get(i+1)); state.fragManager.removeBond(bondToBeRemoved);//the bonds to be merged } Set<Bond> bondsToBeReplaced = new HashSet<Bond>(); for (Atom atom : childAtoms) { bondsToBeReplaced.addAll(atom.getBonds()); } //remove the childAtoms and sync spareValency for (int i = 0; i < childAtoms.size(); i++) { Atom parentAtom = parentAtoms.get(i); Atom childAtom = childAtoms.get(i); if (childAtom.hasSpareValency()){ parentAtom.setSpareValency(true); } state.fragManager.removeAtomAndAssociatedBonds(childAtom); if (!parentAtom.getElement().equals(childAtom.getElement())){ throw new StructureBuildingException("Invalid fusion descriptor: Heteroatom placement is ambigous as it is not present in both components of the fusion"); } } for (Bond bond : bondsToBeReplaced) { Atom from = bond.getFromAtom(); int indiceInChildAtoms = childAtoms.indexOf(from); if (indiceInChildAtoms !=-1){ from = parentAtoms.get(indiceInChildAtoms); } Atom to = bond.getToAtom(); indiceInChildAtoms = childAtoms.indexOf(to); if (indiceInChildAtoms !=-1){ to = parentAtoms.get(indiceInChildAtoms); } //System.out.println("Atom ID " + atom.getID() +" bonded to " + parentAtom.getID()); state.fragManager.createBond(from, to, 1); } } /** * Fuse the benzo with the subsequent ring * Uses locants in front of the benz/benzo group to assign heteroatoms on the now numbered fused ring system * @param state * @param benzoEl * @param parentEl * @throws StructureBuildingException */ private static void benzoSpecificFusion(BuildState state, Element benzoEl, Element parentEl) throws StructureBuildingException { /* * Perform the fusion, number it and associate it with the parentEl */ Fragment benzoRing = state.xmlFragmentMap.get(benzoEl); Fragment parentRing = state.xmlFragmentMap.get(parentEl); performSimpleFusion(state, null, benzoRing , parentRing); state.fragManager.incorporateFragment(benzoRing, parentRing); FusedRingNumberer.numberFusedRing(parentRing);//numbers the fused ring; state.fragManager.removeFragment(parentRing); Fragment fusedRing =state.fragManager.copyFragment(parentRing);//makes sure the IDs are continuous state.xmlFragmentMap.put(parentEl, fusedRing); /* * Check for locants and use these to set the heteroatom positions */ Element locantEl = (Element) XOMTools.getPreviousSibling(benzoEl); if (locantEl != null && locantEl.getLocalName().equals(LOCANT_EL)) { String[] locants = matchComma.split(locantEl.getValue()); Elements suffixes=((Element)benzoEl.getParent()).getChildElements(SUFFIX_EL); int suffixesWithoutLocants =0; for (int i = 0; i < suffixes.size(); i++) { if (suffixes.get(i).getAttribute(LOCANT_ATR)==null){ suffixesWithoutLocants++; } } if (locants.length != suffixesWithoutLocants){//In preference locants will be assigned to suffixes rather than to this nomenclature List<Atom> atomList =fusedRing.getAtomList(); LinkedList<Atom> heteroatoms =new LinkedList<Atom>(); LinkedList<String> elementOfHeteroAtom =new LinkedList<String>(); for (Atom atom : atomList) {//this iterates in the same order as the numbering system if (!atom.getElement().equals("C")){ heteroatoms.add(atom); elementOfHeteroAtom.add(atom.getElement()); } } if (locants.length == heteroatoms.size()){//as many locants as there are heteroatoms to assign for (Atom atom : heteroatoms) { atom.setElement("C"); } FragmentTools.pickUpIndicatedHydrogens(fusedRing); for (int i=0; i< heteroatoms.size(); i ++){ String elementSymbol =elementOfHeteroAtom.get(i); fusedRing.getAtomByLocantOrThrow(locants[i]).setElement(elementSymbol); } locantEl.detach(); } else if (locants.length > 1){ throw new StructureBuildingException("Unable to assign all locants to benzo-fused ring or multiplier was mising"); } } } } /** * Checks that all atoms in a ring appear to be equivalent * @param ring * @return true if all equivalent, else false */ private static boolean allAtomsAreIdentical(Fragment ring){ List<Atom> atomList = ring.getAtomList(); Atom firstAtom = atomList.get(0); String element = firstAtom.getElement(); int valency = firstAtom.getIncomingValency(); boolean spareValency = firstAtom.hasSpareValency(); for (Atom atom : atomList) { if (!atom.getElement().equals(element)){ return false; } if (atom.getIncomingValency() != valency){ return false; } if (atom.hasSpareValency() != spareValency){ return false; } } return true; } }
package edu.kit.iks.Cryptographics; import edu.kit.iks.CryptographicsLib.Logger; /** * Main Class containing the main()-method * * @author Christian Dreher */ public class Main { /** * Flag to define whether to enter debug mode or not. * Must be set to false in production. */ private static boolean debugMode = true; /** * Main method (hook for Java to start from) * * @param args Arguments */ public static void main(String[] args) { if (Main.debugMode) { Logger.setDebugMode(); } Logger.d("Main", "main", "Debugger running."); MainController mainController = new MainController(); mainController.loadView(); mainController.presentStartAction(); } }
package laas.openrobots.ontology.backends; //Imports import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.Vector; import laas.openrobots.ontology.OroServer; import laas.openrobots.ontology.PartialStatement; import laas.openrobots.ontology.exceptions.EventRegistrationException; import laas.openrobots.ontology.exceptions.IllegalStatementException; import laas.openrobots.ontology.exceptions.InconsistentOntologyException; import laas.openrobots.ontology.exceptions.InvalidQueryException; import laas.openrobots.ontology.exceptions.OntologyServerException; import laas.openrobots.ontology.helpers.Helpers; import laas.openrobots.ontology.helpers.Logger; import laas.openrobots.ontology.helpers.Namespaces; import laas.openrobots.ontology.helpers.Pair; import laas.openrobots.ontology.helpers.VerboseLevel; import laas.openrobots.ontology.modules.events.EventProcessor; import laas.openrobots.ontology.modules.events.IWatcher; import laas.openrobots.ontology.modules.events.IWatcher.EventType; import laas.openrobots.ontology.modules.memory.MemoryManager; import laas.openrobots.ontology.modules.memory.MemoryProfile; import laas.openrobots.ontology.service.RPCMethod; import org.mindswap.pellet.jena.PelletInfGraph; import org.mindswap.pellet.jena.PelletReasonerFactory; import org.mindswap.pellet.utils.VersionInfo; import com.hp.hpl.jena.ontology.ConversionException; import com.hp.hpl.jena.ontology.DatatypeProperty; import com.hp.hpl.jena.ontology.Individual; import com.hp.hpl.jena.ontology.ObjectProperty; import com.hp.hpl.jena.ontology.OntClass; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.OntModelSpec; import com.hp.hpl.jena.ontology.OntProperty; import com.hp.hpl.jena.ontology.OntResource; import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.QueryExecException; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.query.QueryExecutionFactory; import com.hp.hpl.jena.query.QueryFactory; import com.hp.hpl.jena.query.QueryParseException; import com.hp.hpl.jena.query.QuerySolution; import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.query.Syntax; import com.hp.hpl.jena.rdf.model.Literal; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Selector; import com.hp.hpl.jena.rdf.model.SimpleSelector; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.rdf.model.impl.ModelCom; import com.hp.hpl.jena.rdf.model.impl.StatementImpl; import com.hp.hpl.jena.reasoner.ReasonerException; import com.hp.hpl.jena.reasoner.ValidityReport; import com.hp.hpl.jena.reasoner.ValidityReport.Report; import com.hp.hpl.jena.shared.JenaException; import com.hp.hpl.jena.shared.Lock; import com.hp.hpl.jena.shared.NotFoundException; import com.hp.hpl.jena.util.FileManager; import com.hp.hpl.jena.util.iterator.ExtendedIterator; /** * The OpenRobotsOntology class is the main storage backend for oro-server.<br/> * * It maps useful methods for knowledge access in a robotic context to a * Jena-baked {@link com.hp.hpl.jena.ontology.OntModel ontology}.<br/> * <br/> * Amongst other feature, it offers an easy way to {@linkplain #query(String) * query} the ontology with standard SPARQL requests, it can try to * {@linkplain #find(String, Vector) find} resources matching a set of * statements or {@linkplain #checkConsistency() check the consistency} of the * knowledge storage.<br/><br/> * * Examples covering the various aspects of the API can be found in the * {@linkplain laas.openrobots.ontology.tests Unit Tests}. * * @author Severin Lemaignan <i>severin.lemaignan@laas.fr</i> */ public class OpenRobotsOntology implements IOntologyBackend { private OntModel onto; private ResultSet lastQueryResult; private String lastQuery; private boolean isInInconsistentState; private Properties parameters; private Map<String, Set<Pair<String, ResourceType>>> lookupTable; private boolean modelChanged = true; private boolean forceLookupTableUpdate = false; //useful to systematically rebuild the lookup table when a statement has been removed. /*This set stores *at initialization* the list of functional properties. * This is used by the update() method to quickly discard update on non- * functional properties. * * \TODO Attention: if a functional property is added at runtime, it won't * be correctly handled (ie, update() won't work for this property. This * could be fixed by updating this set when a FunctionalProperty is added. Or * use OntProperty#hasSubproperty() (but this will be slower) */ Set<OntProperty> functionalProperties; private MemoryManager memoryManager; private EventProcessor eventProcessor; public OpenRobotsOntology(){ this(OroServer.ServerParameters); } /** * Constructor which takes a config file as parameter.<br/> * The constructor first opens the ontology, then loads it into memory and * eventually bounds it to Jena internal reasoner. Thus, the instanciation * of OpenRobotsOntology may take some time (several seconds, depending on * the size on the ontology).<br/> * <br/> * Available options:<br/> * <ul> * <li><em>verbose = [true|false]</em>: set it to <em>true</em> to get more infos from the engine.</li> * <li><em>ontology = PATH</em>: the path to the OWL (or RDF) ontology to be loaded.</li> * <li><em>default_namespace = NAMESPACE</em>: set the default namespace. Don't forget the trailing #!</li> * <li><em>short_namespaces = [true|false]</em> (default: true): if true, the * ontology engine will return resource with prefix instead of full URI, or * nothing if the resource is in the default namespace.</li> * </ul> * The file may contain other options, related to the server configuration. * See {@link laas.openrobots.ontology.OroServer}. Have a look as well at the * config file itself for more details. * * @param parameters The set of parameters, read from the server configuration file. */ public OpenRobotsOntology(Properties parameters){ if (parameters == null) throw new IllegalArgumentException(); this.parameters = parameters; initialize(); } /** * Constructor which takes a Jena {@linkplain OntModel} as parameter.<br/> * * @param onto An already built ontology model. The OpenRobotsOntology will * wrap it. */ public OpenRobotsOntology(OntModel onto){ this(onto, OroServer.ServerParameters); } public OpenRobotsOntology(OntModel onto, Properties parameters){ if (onto == null) throw new IllegalArgumentException(); this.onto = onto; if (parameters == null) throw new IllegalArgumentException("No " + "parameters provided in OroServer to instanciate agent models"); this.parameters = parameters; initialize(); } /* (non-Javadoc) * @see laas.openrobots.ontology.backends.IOntologyBackend#createProperty(java.lang.String) */ public OntProperty createProperty(String lex_property){ onto.enterCriticalSection(Lock.WRITE); OntProperty p = onto.createOntProperty(Namespaces.expand(lex_property)); onto.leaveCriticalSection(); return p; } /* (non-Javadoc) * @see laas.openrobots.ontology.IOntologyServer#createResource(java.lang.String) */ public OntResource createResource(String lex_resource){ onto.enterCriticalSection(Lock.WRITE); OntResource r = onto.createOntResource(Namespaces.expand(lex_resource)); onto.leaveCriticalSection(); return r; } /* (non-Javadoc) * @see laas.openrobots.ontology.IOntologyServer#createStatement(java.lang.String) */ public Statement createStatement(String statement) throws IllegalStatementException { Resource subject; Property predicate; RDFNode object; List<String> tokens_statement = Helpers.tokenize(statement.trim(), ' '); if (tokens_statement.size() != 3) throw new IllegalStatementException( "Three tokens are expected in a statement, " + tokens_statement.size() + " found in " + statement + "."); //expand the namespaces for subject and predicate. for (int i = 0; i<2; i++){ tokens_statement.set(i, Namespaces.format(tokens_statement.get(i))); } onto.enterCriticalSection(Lock.WRITE); subject = onto.getResource(tokens_statement.get(0)); predicate = onto.getProperty(tokens_statement.get(1)); //Handle objects object = Helpers.parseLiteral(tokens_statement.get(2), (ModelCom)onto); assert(object!=null); Statement s =new StatementImpl(subject, predicate, object); onto.leaveCriticalSection(); return s; } /* (non-Javadoc) * @see laas.openrobots.ontology.IOntologyServer#createPartialStatement(java.lang.String) */ public PartialStatement createPartialStatement(String statement) throws IllegalStatementException { onto.enterCriticalSection(Lock.WRITE); PartialStatement p = new PartialStatement(statement, (ModelCom)getModel()); onto.leaveCriticalSection(); return p; } /* (non-Javadoc) * @see laas.openrobots.ontology.IOntologyServer#getModel() */ public OntModel getModel(){ return onto; } /* (non-Javadoc) * @see laas.openrobots.ontology.backends.IOntologyBackend#add(com.hp.hpl.jena.rdf.model.Statement, laas.openrobots.ontology.modules.memory.MemoryProfile) */ @Override public boolean add(Statement statement, MemoryProfile memProfile, boolean safe) throws IllegalStatementException { Set<Statement> toAdd = new HashSet<Statement>(); toAdd.add(statement); return add(toAdd, memProfile, safe); } /* (non-Javadoc) * @see laas.openrobots.ontology.backends.IOntologyBackend#add(com.hp.hpl.jena.rdf.model.Statement, laas.openrobots.ontology.modules.memory.MemoryProfile) */ @Override public boolean add(Set<Statement> statements, MemoryProfile memProfile, boolean safe) throws IllegalStatementException { boolean allHaveBeenInserted = true; Logger.demo("Adding", statements); for (Statement statement : statements) { try { Logger.log("Adding new statement in " + memProfile + " memory ["+Namespaces.toLightString(statement)+"]"); onto.enterCriticalSection(Lock.WRITE); onto.add(statement); //If we are in safe mode, we check that the ontology is not inconsistent. if (safe) { try { checkConsistency(); } catch (InconsistentOntologyException ioe) { onto.remove(statement); onto.leaveCriticalSection(); Logger.log("...I won't add " + statement + " because it " + "leads to inconsistencies!\n", VerboseLevel.IMPORTANT); allHaveBeenInserted = false; continue; } } Logger.cr(); if (!(memProfile == MemoryProfile.LONGTERM || memProfile == MemoryProfile.DEFAULT)) //not LONGTERM memory { //create a name for this reified statement (concatenation of "rs" with hash made from S + P + O) String rsName = "rs_" + Math.abs(statement.hashCode()); onto.createReifiedStatement(Namespaces.addDefault(rsName), statement); Statement metaStmt = createStatement(rsName + " stmtCreatedOn " + onto.createTypedLiteral(Calendar.getInstance())); //Statement metaStmt = oro.createStatement(rsName + " stmtCreatedOn " + toXSDDate(new Date())); //without timezone Statement metaStmt2 = createStatement(rsName + " stmtMemoryProfile " + memProfile + "^^xsd:string"); onto.add(metaStmt); onto.add(metaStmt2); } onto.leaveCriticalSection(); } catch (ConversionException e) { Logger.log("Impossible to assert " + statement + ". A concept can not be a class " + "and an instance at the same time in OWL DL.\n", VerboseLevel.ERROR); throw new IllegalStatementException("Impossible to assert " + statement + ". A concept can not be a class and an instance at the same time in OWL DL."); } catch (Exception e) { Logger.log("\nCouldn't add the statement for an unknown reason. \nDetails:\n ", VerboseLevel.FATAL_ERROR); e.printStackTrace(); Logger.log("\nBetter to exit now until proper handling of this exception is added by mainteners! You can help by sending a mail to openrobots@laas.fr with the exception stack.\n ", VerboseLevel.FATAL_ERROR); System.exit(1); } } //TODO: optimization possible for reified statement with onModelChange(rsName) try { //notify the events subscribers. onModelChange(); if (isInInconsistentState) { Logger.log("The ontology is back in a consistent state\n ", VerboseLevel.WARNING); isInInconsistentState = false; } } catch (org.mindswap.pellet.exceptions.InconsistentOntologyException ioe) { isInInconsistentState = true; Logger.log("The ontology is in an inconsistent state! I couldn't " + "update the events subscribers\n ", VerboseLevel.WARNING); } return allHaveBeenInserted; } /* (non-Javadoc) * @see laas.openrobots.ontology.backends.IOntologyBackend#check(com.hp.hpl.jena.rdf.model.Statement, boolean) */ @Override public boolean check(Statement statement) { Logger.demo("Checking", statement); onto.enterCriticalSection(Lock.READ); boolean status = onto.contains(statement); onto.leaveCriticalSection(); return status; } /* (non-Javadoc) * @see laas.openrobots.ontology.backends.IOntologyBackend#check(laas.openrobots.ontology.PartialStatement) */ @Override public boolean check(PartialStatement statement) { Logger.demo("Checking", statement); String resultQuery = "ASK { " + statement.asSparqlRow() + " }"; try { Query myQuery = QueryFactory.create(resultQuery, Syntax.syntaxSPARQL); QueryExecution myQueryExecution = QueryExecutionFactory.create(myQuery, onto); return myQueryExecution.execAsk(); } catch (QueryParseException e) { Logger.log("internal error during query parsing while trying to check a partial statement! ("+ e.getLocalizedMessage() +").\nPlease contact the maintainer :-)\n", VerboseLevel.SERIOUS_ERROR); throw e; } catch (QueryExecException e) { Logger.log("internal error during query execution while trying to check a partial statement! ("+ e.getLocalizedMessage() +").\nPlease contact the maintainer :-)\n", VerboseLevel.SERIOUS_ERROR); throw e; } } /* (non-Javadoc) * @see laas.openrobots.ontology.backends.IOntologyBackend#checkConsistency() */ @Override public void checkConsistency() throws InconsistentOntologyException { onto.enterCriticalSection(Lock.READ); ValidityReport report = onto.validate(); onto.leaveCriticalSection(); String cause = ""; if (!report.isValid()) { Logger.demo("Checking consistency:", "ontology is inconsistent!", false); isInInconsistentState = true; for (Iterator<Report> i = report.getReports(); i.hasNext(); ) { cause += " - " + i.next(); } throw new InconsistentOntologyException(cause); } isInInconsistentState = false; Logger.demo("Checking consistency:", "ontology is consistent", true); } @Override public boolean checkConsistency(Set<Statement> statements) { boolean consistent = true; Logger.log("Checking consistency of statements"); onto.enterCriticalSection(Lock.WRITE); for (Statement statement : statements) onto.add(statement); try { checkConsistency(); } catch (InconsistentOntologyException ioe) { consistent = false; } for (Statement statement : statements) onto.remove(statement); onto.leaveCriticalSection(); return consistent; } /* (non-Javadoc) * @see laas.openrobots.ontology.backends.IOntologyBackend#query(java.lang.String) */ //public Set<RDFNode> query(String query) throws InvalidQueryException public Set<RDFNode> query(String key, String query) throws InvalidQueryException { //TODO: do some detection to check that the first param is the key, and throw nice exceptions when required. Set<RDFNode> res = new HashSet<RDFNode>(); //Add the common prefixes. query = Namespaces.prefixes() + query; this.lastQuery = query; try { Query myQuery = QueryFactory.create(query, Syntax.syntaxSPARQL ); QueryExecution myQueryExecution = QueryExecutionFactory.create(myQuery, onto); this.lastQueryResult = myQueryExecution.execSelect(); } catch (QueryParseException e) { Logger.log("Error during query parsing ! ("+ e.getLocalizedMessage() +").", VerboseLevel.ERROR); throw new InvalidQueryException("Error during query parsing ! ("+ e.getLocalizedMessage() +")"); } catch (QueryExecException e) { Logger.log("Error during query execution ! ("+ e.getLocalizedMessage() +").", VerboseLevel.SERIOUS_ERROR); throw new InvalidQueryException("Error during query execution ! ("+ e.getLocalizedMessage() +")"); } while (this.lastQueryResult.hasNext()) { QuerySolution s = this.lastQueryResult.nextSolution(); res.add(s.get(key)); } return res; } @Override public Set<RDFNode> find( String varName, Set<PartialStatement> statements, Set<String> filters) throws InvalidQueryException { Logger.demo("Looking for '" + varName + "' such as:", statements); String query = "SELECT ?" + varName + "\n" + "WHERE {\n"; for (PartialStatement ps : statements) { query += ps.asSparqlRow(); } if (!(filters == null || filters.isEmpty())) { for (String filter :filters) { query += "FILTER (" + filter + ") .\n"; } } query += "}"; Set<RDFNode> res = query(varName, query); Logger.demo_nodes("Result", res); return res; } /* (non-Javadoc) * @see laas.openrobots.ontology.backends.IOntologyBackend#getResource(String) */ @Override public OntResource getResource(String lex_resource) throws NotFoundException { lex_resource = Namespaces.format(lex_resource); //TODO : is it necessary to check the node exists? if it doesn't exist, the SPARQL query will answer an empty resultset. // This check is only useful to throw an exception... onto.enterCriticalSection(Lock.READ); OntResource node = onto.getOntResource(lex_resource); onto.leaveCriticalSection(); if (node == null){ throw new NotFoundException("The node " + lex_resource + " was not found in the ontology (tip: check the namespaces!)."); } return node; } /* (non-Javadoc) * @see laas.openrobots.ontology.backends.IOntologyBackend#getSubmodel(com.hp.hpl.jena.rdf.model.Resource) */ @Override public Model getSubmodel(Resource node) throws NotFoundException { Model resultModel; String resultQuery = Namespaces.prefixes(); //we use the SPARQL query type "DESCRIBE" to get a RDF graph with all the links to this resource. // cf http://www.w3.org/TR/rdf-sparql-query/#describe for more details resultQuery += "DESCRIBE <" + node.getURI() +">"; onto.enterCriticalSection(Lock.READ); try { Query myQuery = QueryFactory.create(resultQuery, Syntax.syntaxSPARQL); QueryExecution myQueryExecution = QueryExecutionFactory.create(myQuery, onto); resultModel = myQueryExecution.execDescribe(); } catch (QueryParseException e) { Logger.log("internal error during query parsing while trying the get infos! ("+ e.getLocalizedMessage() +").\nPlease contact the maintainer :-)\n", VerboseLevel.SERIOUS_ERROR); return null; } catch (QueryExecException e) { Logger.log("internal error during query execution while try the get infos! ("+ e.getLocalizedMessage() +").\nPlease contact the maintainer :-)\n", VerboseLevel.SERIOUS_ERROR); return null; } finally { onto.leaveCriticalSection(); } return resultModel; } /* (non-Javadoc) * @see laas.openrobots.ontology.backends.IOntologyBackend#getSuperclassesOf(com.hp.hpl.jena.ontology.OntClass, boolean) */ @Override public Set<OntClass> getSuperclassesOf(OntClass type, boolean onlyDirect) throws NotFoundException { Set<OntClass> result = new HashSet<OntClass>(); onto.enterCriticalSection(Lock.READ); ExtendedIterator<OntClass> it = type.listSuperClasses(onlyDirect); while (it.hasNext()) { OntClass tmp = it.next(); if (tmp != null && !tmp.isAnon()){ result.add(tmp); } } onto.leaveCriticalSection(); if (onlyDirect) Logger.demo_nodes("Retrieving direct superclasses of " + Namespaces.toLightString(type), result); else Logger.demo_nodes("Retrieving all superclasses of " + Namespaces.toLightString(type), result); return result; } /* (non-Javadoc) * @see laas.openrobots.ontology.backends.IOntologyBackend#getSubclassesOf(com.hp.hpl.jena.ontology.OntClass, boolean) */ @Override public Set<OntClass> getSubclassesOf(OntClass type, boolean onlyDirect) throws NotFoundException { Set<OntClass> result = new HashSet<OntClass>(); onto.enterCriticalSection(Lock.READ); ExtendedIterator<OntClass> it = type.listSubClasses(onlyDirect); while (it.hasNext()) { OntClass tmp = it.next(); if (tmp != null && !tmp.isAnon() && !tmp.getURI().equals("http://www.w3.org/2002/07/owl#Nothing") ){ result.add(tmp); } } onto.leaveCriticalSection(); if (onlyDirect) Logger.demo_nodes("Retrieving direct subclasses of " + Namespaces.toLightString(type), result); else Logger.demo_nodes("Retrieving all subclasses of " + Namespaces.toLightString(type), result); return result; } /* (non-Javadoc) * @see laas.openrobots.ontology.backends.IOntologyBackend#getInstancesOf(com.hp.hpl.jena.ontology.OntClass, boolean) */ @Override public Set<OntResource> getInstancesOf(OntClass type, boolean onlyDirect) throws NotFoundException { Set<OntResource> result = new HashSet<OntResource>(); onto.enterCriticalSection(Lock.READ); ExtendedIterator<? extends OntResource> it = type.listInstances(onlyDirect); while (it.hasNext()) { OntResource tmp = it.next(); if (tmp != null && !tmp.isAnon()){ result.add(tmp); } } onto.leaveCriticalSection(); if (onlyDirect) Logger.demo_nodes("Retrieving direct instances of " + Namespaces.toLightString(type), result); else Logger.demo_nodes("Retrieving all instances of " + Namespaces.toLightString(type), result); return result; } /* (non-Javadoc) * @see laas.openrobots.ontology.backends.IOntologyBackend#getClassesOf(com.hp.hpl.jena.ontology.Individual, boolean) */ @Override public Set<OntClass> getClassesOf(OntResource resource, boolean onlyDirect) throws NotFoundException { Set<OntClass> result = new HashSet<OntClass>(); onto.enterCriticalSection(Lock.READ); Individual individual = resource.asIndividual(); ExtendedIterator<OntClass> it = individual.listOntClasses(onlyDirect); while (it.hasNext()) { OntClass tmp = it.next(); if (tmp != null && !tmp.isAnon()){ result.add(tmp); } } onto.leaveCriticalSection(); if (onlyDirect) Logger.demo_nodes("Retrieving direct classes of " + Namespaces.toLightString(resource), result); else Logger.demo_nodes("Retrieving all classes of " + Namespaces.toLightString(resource), result); return result; } /* (non-Javadoc) * @see laas.openrobots.ontology.backends.IOntologyBackend#lookup(java.lang.String) */ @Override public Set<List<String>> lookup(String id) { //if statements have been removed, we must force a rebuilt of the lookup //table else a former concept that doesn't exist anymore could be returned. //In any case, if we can not find the id, we try to rebuild the lookup //table, in case some changes occurred since the last lookup. if (forceLookupTableUpdate || !lookupTable.containsKey(id.toLowerCase())) { forceLookupTableUpdate = true; rebuildLookupTable(); } Set<List<String>> result = new HashSet<List<String>>(); if (lookupTable.containsKey(id.toLowerCase())) { for (Pair<String, ResourceType> p : lookupTable.get(id.toLowerCase())) { List<String> l = new ArrayList<String>(); l.add(p.getLeft()); l.add(p.getRight().toString()); result.add(l); } } return result; } /* (non-Javadoc) * @see laas.openrobots.ontology.backends.IOntologyBackend#lookup(java.lang.String, ResourceType) */ @Override public Set<String> lookup(String id, ResourceType type) { //if statements have been removed, we must force a rebuilt of the lookup //table else a former concept that doesn't exist anymore could be returned. //In any case, if we can not find the id, we try to rebuild the lookup //table, in case some changes occurred since the last lookup. if (forceLookupTableUpdate || !lookupTable.containsKey(id.toLowerCase())) { forceLookupTableUpdate = true; rebuildLookupTable(); } Set<String> result = new HashSet<String>(); if (lookupTable.containsKey(id.toLowerCase())) { for (Pair<String, ResourceType> p : lookupTable.get(id.toLowerCase())) if (p.getRight().equals(type)) result.add(p.getLeft()); } return result; } /** * Returns the current set of parameters. * * @return the current set of parameters, reflecting the content of the * configuration file. */ public Properties getParameters(){ return parameters; } /* (non-Javadoc) * @see laas.openrobots.ontology.backends.IOntologyBackend#clear(laas.openrobots.ontology.PartialStatement) */ @Override public void clear(PartialStatement partialStmt) { Logger.log("Clearing statements matching ["+ partialStmt + "]\n"); Selector selector = new SimpleSelector(partialStmt.getSubject(), partialStmt.getPredicate(), partialStmt.getObject()); onto.enterCriticalSection(Lock.READ); StmtIterator stmtsToRemove = onto.listStatements(selector); onto.leaveCriticalSection(); for (Statement s : stmtsToRemove.toList()) remove(s); } /* (non-Javadoc) * @see laas.openrobots.ontology.backends.IOntologyBackend#remove(com.hp.hpl.jena.rdf.model.Statement) */ @Override public void remove(Statement stmt) { Logger.log("Removing statement ["+ Namespaces.toLightString(stmt) + "]\n"); onto.enterCriticalSection(Lock.WRITE); onto.remove(stmt); onto.leaveCriticalSection(); //force the rebuilt of the lookup table at the next lookup. forceLookupTableUpdate = true; try { //notify the events subscribers. onModelChange(); if (isInInconsistentState) { Logger.log("The ontology is back in a consistent state\n ", VerboseLevel.WARNING); isInInconsistentState = false; } } catch (org.mindswap.pellet.exceptions.InconsistentOntologyException ioe) { isInInconsistentState = true; Logger.log("The ontology is in an inconsistent state! I couldn't " + "update the events subscribers\n ", VerboseLevel.WARNING); } } @Override public void update(Set<Statement> stmts) throws IllegalStatementException { for (Statement stmt : stmts) { if(functionalProperties.contains(stmt.getPredicate())) { Selector selector = new SimpleSelector(stmt.getSubject(), stmt.getPredicate(), (RDFNode)null); onto.enterCriticalSection(Lock.READ); StmtIterator stmtsToRemove = onto.listStatements(selector); onto.leaveCriticalSection(); onto.remove(stmtsToRemove); } } add(stmts, MemoryProfile.DEFAULT, false); } /* (non-Javadoc) * @see laas.openrobots.ontology.backends.IOntologyBackend#save(java.lang.String) */ @Override @RPCMethod( category = "administration", desc="exports the current ontology model to an OWL file. The provided path must be writable by the server." ) public void save(String path) throws OntologyServerException { Logger.log("Saving ontology to " + path +".\n", VerboseLevel.IMPORTANT); FileOutputStream file; try { file = new FileOutputStream(path); } catch (FileNotFoundException e) { throw new OntologyServerException("Error while opening " + path + " to output the ontology. Check it's a valid filename and a writable location!"); } onto.enterCriticalSection(Lock.READ); onto.write(file); onto.leaveCriticalSection(); } @RPCMethod( category = "administration", desc="exports the current ontology model to an OWL file. The file " + "will be saved to the current directory with an automatically" + "generated name." ) public void save() throws OntologyServerException { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss"); save(sdf.format(Calendar.getInstance().getTime()) + "-snapshot.owl"); } /* (non-Javadoc) * @see laas.openrobots.ontology.backends.IOntologyBackend#registerEventsHandlers(java.util.Set) */ public void registerEvent(IWatcher watcher) throws EventRegistrationException { eventProcessor.add(watcher); } @Override public Set<EventType> getSupportedEvents() { return eventProcessor.getSupportedEvents(); } private void initialize(){ this.lastQuery = ""; this.lastQueryResult = null; Namespaces.loadNamespaces(parameters); if (onto == null) this.load(); this.lookupTable = new HashMap<String, Set<Pair<String, ResourceType>>>(); this.rebuildLookupTable(); this.functionalProperties = new HashSet<OntProperty>(); this.rebuildFunctionalPropertiesList(); memoryManager = new MemoryManager(onto); memoryManager.start(); eventProcessor = new EventProcessor(this); } public void close() { memoryManager.close(); try { memoryManager.join(1000); } catch (InterruptedException e) { } onto.close(); } /** This protected method is called every time the ontology model changes * (ie upon addition or removal of statements in the ontology). * * It is mainly responsible for testing the various watchPatterns as * provided by the set of active {@link IWatcher} against the ontology. * * onModelChange() relies on a caching mechanism of requests to improve * performances. It remains however a serious performance bottleneck. * * @param rsName the name of the reified statements whose creation triggered * the update. Can be null if it does not apply. * * @see #onModelChange() */ protected void onModelChange(String rsName){ Logger.log("Model changed!\n", VerboseLevel.DEBUG); getModel().enterCriticalSection(Lock.WRITE); ((PelletInfGraph) getModel().getGraph()).classify(); getModel().leaveCriticalSection(); modelChanged = true; eventProcessor.process(); //TODO: do we need to update it every time? rebuildLookupTable(); if (rsName != null) memoryManager.watch(rsName); } /** * Simply call {@link #onModelChange(String)} with a {@code null} string. */ private void onModelChange() { onModelChange(null); } /** * Loads into memory the ontology which was specified in the constructor. */ private void load() { String oroCommonSenseUri = parameters.getProperty("oro_common_sense"); String oroRobotInstanceUri = parameters.getProperty("oro_robot_instance"); String oroScenarioUri = parameters.getProperty("oro_scenario"); OntModelSpec onto_model_reasonner; String onto_model_reasonner_name = parameters.getProperty("reasonner", "jena_internal_owl_rule"); //select the inference model and reasoner from the "reasonner" parameter specified in the configuration file. if ( onto_model_reasonner_name.equalsIgnoreCase("pellet")){ onto_model_reasonner = PelletReasonerFactory.THE_SPEC; onto_model_reasonner_name = "Pellet " + VersionInfo.getInstance().getVersionString() + " reasonner"; } else if(onto_model_reasonner_name.equalsIgnoreCase("jena_internal_rdfs")){ onto_model_reasonner = OntModelSpec.OWL_DL_MEM_RDFS_INF; onto_model_reasonner_name = "Jena internal reasonner - RDFS inference engine -"; } else { onto_model_reasonner = OntModelSpec.OWL_DL_MEM_RULE_INF; onto_model_reasonner_name = "Jena internal reasonner - OWL rule inference engine -"; } // loading of the OWL ontologies thanks Jena try { Model mainModel = null; Model robotInstancesModel = null; Model scenarioModel = null; try { mainModel = FileManager.get().loadModel(oroCommonSenseUri); Logger.log("Common sense ontology initialized with "+ oroCommonSenseUri +".\n", VerboseLevel.IMPORTANT); if (oroRobotInstanceUri != null) { robotInstancesModel = FileManager.get().loadModel(oroRobotInstanceUri); Logger.log("Robot-specific ontology loaded from " + oroRobotInstanceUri + ".\n", VerboseLevel.IMPORTANT); } if (oroScenarioUri != null) { scenarioModel = FileManager.get().loadModel(oroScenarioUri); Logger.log("Scenario-specific ontology loaded from " + oroScenarioUri + ".\n", VerboseLevel.IMPORTANT); } } catch (NotFoundException nfe) { Logger.log("Could not find one of these files:\n" + "\t- " + oroCommonSenseUri + ",\n\t- " + oroRobotInstanceUri + " or\n\t- " + oroScenarioUri + ".\nExiting.\n", VerboseLevel.FATAL_ERROR); System.exit(1); } //Ontology model and reasonner type // OWL_DL_MEM_RDFS_INF: RDFS reasoner -> quick and light // OWL_DL_MEM_RULE_INF: uses a more complete OWL reasonning scheme. REQUIRED for "useful" consistency checking // PelletReasonerFactory.THE_SPEC : uses Pellet as reasonner onto = ModelFactory.createOntologyModel(onto_model_reasonner, mainModel); onto.setStrictMode(true); onto.enterCriticalSection(Lock.WRITE); if (robotInstancesModel != null) onto.add(robotInstancesModel); if (scenarioModel != null) onto.add(scenarioModel); onto.leaveCriticalSection(); Logger.cr(); Logger.log("Ontology successfully loaded (using Jena " + com.hp.hpl.jena.Jena.VERSION + ").\n", VerboseLevel.IMPORTANT); if (robotInstancesModel != null) Logger.log("\t- Robot-specific knowledge loaded and merged.\n"); if (scenarioModel != null) Logger.log("\t- Scenario-specific knowledge loaded and merged.\n"); Logger.log("\t- " + onto_model_reasonner_name + " initialized.\n"); //Perform an initial classification try { checkConsistency(); Logger.log("\t- Good news: the initial ontology is consistent.\n"); isInInconsistentState = false; } catch (InconsistentOntologyException e) { Logger.log("Attention! The initial ontology is inconsistent!", VerboseLevel.IMPORTANT); isInInconsistentState = true; } Logger.cr(); } catch (ReasonerException re){ Logger.log("Fatal error at ontology initialization: error with the reasoner\n", VerboseLevel.FATAL_ERROR); re.printStackTrace(); System.exit(1); } catch (JenaException je){ Logger.log("Fatal error at ontology initialization: error with Jena\n", VerboseLevel.FATAL_ERROR); je.printStackTrace(); System.exit(1); } } private void addToLookupTable(String key, String id, ResourceType type) { if (!lookupTable.containsKey(key)) { lookupTable.put(key, new HashSet<Pair<String,ResourceType>>()); } lookupTable.get(key).add( new Pair<String, ResourceType>(id, type)); } /** * Rebuild the map that binds all the concepts to their labels and type * (instance, class, property...). This map is used for fast lookup of * concept, and rebuild only when (the model has changed AND an lookup failed) * OR (a concept has been removed AND a lookup is starting). * * @see {@link #lookup(String)} */ private void rebuildLookupTable() { if (modelChanged && forceLookupTableUpdate) { modelChanged = false; forceLookupTableUpdate = false; lookupTable.clear(); getModel().enterCriticalSection(Lock.READ); // if the ontology is inconsistent, do not update the lookup table. if (!getModel().validate().isValid()){ getModel().leaveCriticalSection(); return; } { ExtendedIterator<Individual> resources; resources = onto.listIndividuals(); while(resources.hasNext()) { Individual res = resources.next(); if (res.isAnon()) continue; ExtendedIterator<RDFNode> labels = res.listLabels(null); if (labels.hasNext()) while(labels.hasNext()) { String keyword = labels.next().as(Literal.class).getLexicalForm().toLowerCase(); addToLookupTable(keyword, Namespaces.toLightString(res), ResourceType.INSTANCE); } //Add the concept id itself. addToLookupTable(res.getLocalName().toLowerCase(), Namespaces.toLightString(res), ResourceType.INSTANCE); } } { ExtendedIterator<OntClass> resources = onto.listClasses(); while(resources.hasNext()) { OntClass res = resources.next(); if (res.isAnon()) continue; ExtendedIterator<RDFNode> labels = res.listLabels(null); if (labels.hasNext()) while(labels.hasNext()) { String keyword = labels.next().as(Literal.class).getLexicalForm().toLowerCase(); addToLookupTable(keyword, Namespaces.toLightString(res), ResourceType.CLASS); } else addToLookupTable(res.getLocalName().toLowerCase(), Namespaces.toLightString(res), ResourceType.CLASS); } } { ExtendedIterator<ObjectProperty> resources = onto.listObjectProperties(); while(resources.hasNext()) { ObjectProperty res = resources.next(); if (res.isAnon()) continue; ExtendedIterator<RDFNode> labels = res.listLabels(null); if (labels.hasNext()) while(labels.hasNext()) { String keyword = labels.next().as(Literal.class).getLexicalForm().toLowerCase(); addToLookupTable(keyword, Namespaces.toLightString(res), ResourceType.OBJECT_PROPERTY); } else addToLookupTable(res.getLocalName().toLowerCase(), Namespaces.toLightString(res), ResourceType.OBJECT_PROPERTY); } } { ExtendedIterator<DatatypeProperty> resources = onto.listDatatypeProperties(); while(resources.hasNext()) { DatatypeProperty res = resources.next(); if (res.isAnon()) continue; ExtendedIterator<RDFNode> labels = res.listLabels(null); if (labels.hasNext()) while(labels.hasNext()) { String keyword = labels.next().as(Literal.class).getLexicalForm().toLowerCase(); addToLookupTable(keyword, Namespaces.toLightString(res), ResourceType.DATATYPE_PROPERTY); } else addToLookupTable(res.getLocalName().toLowerCase(), Namespaces.toLightString(res), ResourceType.DATATYPE_PROPERTY); } } getModel().leaveCriticalSection(); } } /** * Initializes the list of functional properties */ private void rebuildFunctionalPropertiesList() { Set<PartialStatement> partialStatements = new HashSet<PartialStatement>(); try { partialStatements.add(createPartialStatement("?f rdf:type owl:FunctionalProperty")); } catch (IllegalStatementException e1) { Logger.log("Serious error while fetching functional properties! 'update()' won't work. Please contact the mainteners!", VerboseLevel.SERIOUS_ERROR); return; } Set<RDFNode> functionalProps = null; try { functionalProps = find("f", partialStatements, null); } catch (OntologyServerException e) { Logger.log("Serious error while fetching functional properties! 'update()' won't work. Please contact the mainteners!", VerboseLevel.SERIOUS_ERROR); return; } getModel().enterCriticalSection(Lock.READ); for (RDFNode s : functionalProps) functionalProperties.add(s.as(OntProperty.class)); getModel().leaveCriticalSection(); } }
package org.bouncycastle.pqc.crypto.lms; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.security.SecureRandom; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import org.bouncycastle.crypto.prng.FixedSecureRandom; import org.bouncycastle.pqc.crypto.ExhaustedPrivateKeyException; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Pack; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.io.Streams; public class HSSTests extends TestCase { public void testHssKeySerialzation() throws Exception { byte[] fixedSource = new byte[8192]; for (int t = 0; t < fixedSource.length; t++) { fixedSource[t] = 1; } SecureRandom rand = new FixedSecureRandom(fixedSource); HSSPrivateKeyParameters generatedPrivateKey = HSS.generateHSSKeyPair( HSSKeyGenerationParameters.builder(2) .setLmsParameters( new LMSParameters(LMSigParameters.lms_sha256_n32_h5, LMOtsParameters.sha256_n32_w4), new LMSParameters(LMSigParameters.lms_sha256_n32_h5, LMOtsParameters.sha256_n32_w2)) .setLmsEntropySource(rand) .build() ); HSSSignature sigFromGeneratedPrivateKey = HSS.generateSignature(generatedPrivateKey, Hex.decode("ABCDEF"), rand); byte[] keyPairEnc = generatedPrivateKey.getEncoded(); HSSPrivateKeyParameters reconstructedPrivateKey = HSSPrivateKeyParameters.getInstance(keyPairEnc, 2, 1024); assertTrue(reconstructedPrivateKey.equals(generatedPrivateKey)); reconstructedPrivateKey.getPublicKey(); generatedPrivateKey.getPublicKey(); // Are they still equal, public keys are only checked if they both // exist because they are only created when requested as they are derived from the private key. assertTrue(reconstructedPrivateKey.equals(generatedPrivateKey)); // Check the reconstructed key can verify a signature. assertTrue(HSS.verifySignature(reconstructedPrivateKey.getPublicKey(), sigFromGeneratedPrivateKey, Hex.decode("ABCDEF"))); } public void testHSSVector_1() throws Exception { ArrayList<byte[]> blocks = loadVector("/org/bouncycastle/pqc/crypto/test/lms/testcase_1.txt"); HSSPublicKeyParameters publicKey = HSSPublicKeyParameters.getInstance(blocks.get(0)); byte[] message = blocks.get(1); HSSSignature signature = HSSSignature.getInstance(blocks.get(2), 2); assertTrue("Test Case 1 ", HSS.verifySignature(publicKey, signature, message)); } public void testHSSVector_2() throws Exception { ArrayList<byte[]> blocks = loadVector("/org/bouncycastle/pqc/crypto/test/lms/testcase_2.txt"); HSSPublicKeyParameters publicKey = HSSPublicKeyParameters.getInstance(blocks.get(0)); byte[] message = blocks.get(1); byte[] sig = blocks.get(2); HSSSignature signature = HSSSignature.getInstance(sig, 2); assertTrue("Test Case 2 Signature", HSS.verifySignature(publicKey, signature, message)); LMSPublicKeyParameters lmsPub = LMSPublicKeyParameters.getInstance(blocks.get(3)); LMSSignature lmsSignature = LMSSignature.getInstance(blocks.get(4)); assertTrue("Test Case 2 Signature 2", LMS.verifySignature(lmsPub, lmsSignature, message)); } private ArrayList<byte[]> loadVector(String vector) throws Exception { InputStream inputStream = HSSTests.class.getResourceAsStream(vector); BufferedReader bin = new BufferedReader(new InputStreamReader(inputStream)); String line; ArrayList<byte[]> blocks = new ArrayList<byte[]>(); StringBuffer sw = new StringBuffer(); while ((line = bin.readLine()) != null) { if (line.startsWith("!")) { if (sw.length() > 0) { blocks.add(LMSVectorUtils.extract$PrefixedBytes(sw.toString())); sw.setLength(0); } } sw.append(line); sw.append("\n"); } if (sw.length() > 0) { blocks.add(LMSVectorUtils.extract$PrefixedBytes(sw.toString())); sw.setLength(0); } return blocks; } /** * Test the generation of public keys from private key SEED and I. * Level 0 * * @throws Exception */ public void testGenPublicKeys_L0() throws Exception { byte[] seed = Hex.decode("558b8966c48ae9cb898b423c83443aae014a72f1b1ab5cc85cf1d892903b5439"); int level = 0; LMSPrivateKeyParameters lmsPrivateKey = LMS.generateKeys(LMSigParameters.getParametersForType(6), LMOtsParameters.getParametersForType(3), level, Hex.decode("d08fabd4a2091ff0a8cb4ed834e74534"), seed); LMSPublicKeyParameters publicKey = lmsPrivateKey.getPublicKey(); assertTrue(Arrays.areEqual(publicKey.getT1(), Hex.decode("32a58885cd9ba0431235466bff9651c6c92124404d45fa53cf161c28f1ad5a8e"))); assertTrue(Arrays.areEqual(publicKey.getI(), Hex.decode("d08fabd4a2091ff0a8cb4ed834e74534"))); } /** * Test the generation of public keys from private key SEED and I. * Level 1; * * @throws Exception */ public void testGenPublicKeys_L1() throws Exception { byte[] seed = Hex.decode("a1c4696e2608035a886100d05cd99945eb3370731884a8235e2fb3d4d71f2547"); int level = 1; LMSPrivateKeyParameters lmsPrivateKey = LMS.generateKeys(LMSigParameters.getParametersForType(5), LMOtsParameters.getParametersForType(4), level, Hex.decode("215f83b7ccb9acbcd08db97b0d04dc2b"), seed); LMSPublicKeyParameters publicKey = lmsPrivateKey.getPublicKey(); assertTrue(Arrays.areEqual(publicKey.getT1(), Hex.decode("a1cd035833e0e90059603f26e07ad2aad152338e7a5e5984bcd5f7bb4eba40b7"))); assertTrue(Arrays.areEqual(publicKey.getI(), Hex.decode("215f83b7ccb9acbcd08db97b0d04dc2b"))); } public void testGenerate() throws Exception { // Generate an HSS key pair for a two level HSS scheme. // then use that to verify it compares with a value from the same reference implementation. // Then check components of it serialize and deserialize properly. byte[] fixedSource = new byte[8192]; for (int t = 0; t < fixedSource.length; t++) { fixedSource[t] = 1; } SecureRandom rand = new FixedSecureRandom(fixedSource); HSSPrivateKeyParameters keyPair = HSS.generateHSSKeyPair( HSSKeyGenerationParameters.builder(2) .setLmsParameters( new LMSParameters(LMSigParameters.lms_sha256_n32_h5, LMOtsParameters.sha256_n32_w4), new LMSParameters(LMSigParameters.lms_sha256_n32_h5, LMOtsParameters.sha256_n32_w2)) .setLmsEntropySource(rand) .build() ); // Generated from reference implementation. // check the encoded form of the public key matches. String expectedPk = "0000000200000005000000030101010101010101010101010101010166BF6F5816EEE4BBF33C50ACB480E09B4169EBB533372959BC4315C388E501AC"; byte[] pkEnc = keyPair.getPublicKey().getEncoded(); assertTrue(Arrays.areEqual(Hex.decode(expectedPk), pkEnc)); // Check that HSS public keys have value equality after deserialization. // Use external sourced pk for deserialization. assertTrue("HSSPrivateKeyParameterss equal are deserialization", keyPair.getPublicKey().equals(HSSPublicKeyParameters.getInstance(Hex.decode(expectedPk)))); // Generate, hopefully the same HSSKetPair for the same entropy. // This is a sanity test { SecureRandom rand1 = new FixedSecureRandom(fixedSource); HSSPrivateKeyParameters regenKeyPair = HSS.generateHSSKeyPair( HSSKeyGenerationParameters.builder(2) .setLmsParameters( new LMSParameters(LMSigParameters.lms_sha256_n32_h5, LMOtsParameters.sha256_n32_w4), new LMSParameters(LMSigParameters.lms_sha256_n32_h5, LMOtsParameters.sha256_n32_w2)) .setLmsEntropySource(rand1) .build() ); assertTrue("Both generated keys are the same", Arrays.areEqual(regenKeyPair.getPublicKey().getEncoded(), keyPair.getPublicKey().getEncoded())); assertTrue("same private key size", keyPair.getKeys().size() == regenKeyPair.getKeys().size()); for (int t = 0; t < keyPair.getKeys().size(); t++) { // Check the private keys can be encoded and are the same. byte[] pk1 = keyPair.getKeys().get(t).getEncoded(); byte[] pk2 = regenKeyPair.getKeys().get(t).getEncoded(); assertTrue(Arrays.areEqual(pk1, pk2)); // Deserialize them and see if they still equal. LMSPrivateKeyParameters pk1O = LMSPrivateKeyParameters.getInstance(pk1, 1024); LMSPrivateKeyParameters pk2O = LMSPrivateKeyParameters.getInstance(pk2, 1024); assertTrue("LmsPrivateKey still equal after deserialization", pk1O.equals(pk2O)); } } // This time we will generate another set of keys using a different entropy source. // they should be different! // Useful for detecting accidental hard coded things. { // Use a real secure random this time. SecureRandom rand1 = new SecureRandom(); HSSPrivateKeyParameters differentKey = HSS.generateHSSKeyPair( HSSKeyGenerationParameters.builder(2) .setLmsParameters( new LMSParameters(LMSigParameters.lms_sha256_n32_h5, LMOtsParameters.sha256_n32_w4), new LMSParameters(LMSigParameters.lms_sha256_n32_h5, LMOtsParameters.sha256_n32_w2)) .setLmsEntropySource(rand1) .build() ); assertFalse("Both generated keys are not the same", Arrays.areEqual(differentKey.getPublicKey().getEncoded(), keyPair.getPublicKey().getEncoded())); for (int t = 0; t < keyPair.getKeys().size(); t++) { // Check the private keys can be encoded and are the same. byte[] pk1 = keyPair.getKeys().get(t).getEncoded(); byte[] pk2 = differentKey.getKeys().get(t).getEncoded(); assertFalse("keys not the same", Arrays.areEqual(pk1, pk2)); // Deserialize them and see if they still equal. LMSPrivateKeyParameters pk1O = LMSPrivateKeyParameters.getInstance(pk1, 1024); LMSPrivateKeyParameters pk2O = LMSPrivateKeyParameters.getInstance(pk2, 1024); assertFalse("LmsPrivateKey not suddenly equal after deserialization", pk1O.equals(pk2O)); } } } /** * This test takes in a series of vectors generated by adding print statements to code called by * the "test_sign.c" test in the reference implementation. * <p> * The purpose of this test is to ensure that the signatures and public keys exactly match for the * same entropy source the values generated by the reference implementation. * <p> * It also verifies value equality between signature and public key objects as well as * complimentary serialization and deserialization. * * @throws Exception */ public void testVectorsFromReference() throws Exception { String[] lines = new String(Streams.readAll(HSSTests.class.getResourceAsStream("/org/bouncycastle/pqc/crypto/test/lms/depth_1.txt"))).split("\n"); int d = 0; List<LMSigParameters> lmsParameters = new ArrayList<LMSigParameters>(); List<LMOtsParameters> lmOtsParameters = new ArrayList<LMOtsParameters>(); byte[] message = null; byte[] hssPubEnc = null; byte[] encodedSigFromVector = null; ByteArrayOutputStream fixedESBuffer = new ByteArrayOutputStream(); int j = 0; for (String line : lines) { line = line.trim(); if (line.startsWith("#") || line.length() == 0) { continue; } if (line.startsWith("Depth:")) { d = Integer.parseInt(line.substring("Depth:".length()).trim()); } else if (line.startsWith("LMType:")) { int typ = Integer.parseInt(line.substring("LMType:".length()).trim()); lmsParameters.add(LMSigParameters.getParametersForType(typ)); } else if (line.startsWith("LMOtsType:")) { int typ = Integer.parseInt(line.substring("LMOtsType:".length()).trim()); lmOtsParameters.add(LMOtsParameters.getParametersForType(typ)); } else if (line.startsWith("Rand:")) { fixedESBuffer.write(Hex.decode(line.substring("Rand:".length()).trim())); } else if (line.startsWith("HSSPublicKey:")) { hssPubEnc = Hex.decode(line.substring("HSSPublicKey:".length()).trim()); } else if (line.startsWith("Message:")) { message = Hex.decode(line.substring("Message:".length()).trim()); } else if (line.startsWith("Signature:")) { j++; encodedSigFromVector = Hex.decode(line.substring("Signature:".length()).trim()); // Assumes Signature is the last element in the set of vectors. FixedSecureRandom fixRnd = new FixedSecureRandom(fixedESBuffer.toByteArray()); fixedESBuffer.reset(); // Deserialize pub key from reference impl. HSSPublicKeyParameters vectorSourcedPubKey = HSSPublicKeyParameters.getInstance(hssPubEnc); List<LMSParameters> lmsParams = new ArrayList<LMSParameters>(); for (int i = 0; i != lmsParameters.size(); i++) { lmsParams.add(new LMSParameters(lmsParameters.get(i), lmOtsParameters.get(i))); } // Using our fixed entropy source generate hss keypair HSSPrivateKeyParameters keyPair = HSS.generateHSSKeyPair( HSSKeyGenerationParameters.builder(d) .setLmsParameters(lmsParams) .setLmsEntropySource(fixRnd) .build() ); { // Public Key should match vector. // Encoded value equality. HSSPublicKeyParameters generatedPubKey = keyPair.getPublicKey(); assertTrue(Arrays.areEqual(hssPubEnc, generatedPubKey.getEncoded())); // Value equality. assertTrue(vectorSourcedPubKey.equals(generatedPubKey)); } // Generate a signature using the keypair we generated. HSSSignature sig = HSS.generateSignature(keyPair, message, fixRnd); if (!Arrays.areEqual(sig.getEncoded(), encodedSigFromVector)) { HSSSignature signatureFromVector = HSSSignature.getInstance(encodedSigFromVector, d); signatureFromVector.equals(sig); System.out.println(); } // check encoding signature matches. assertTrue(Arrays.areEqual(sig.getEncoded(), encodedSigFromVector)); // Check we can verify our generated signature with the vectors sourced public key. assertTrue(HSS.verifySignature(vectorSourcedPubKey, sig, message)); // Deserialize the signature from the vector. HSSSignature signatureFromVector = HSSSignature.getInstance(encodedSigFromVector, d); // Can we verify signature from vector with public key from vector. assertTrue(HSS.verifySignature(vectorSourcedPubKey, signatureFromVector, message)); // Check our generated signature and the one deserialized from the vector // have value equality. assertTrue(signatureFromVector.equals(sig)); // Other tests vandalise HSS signatures to check they fail when tampered with d = 0; lmOtsParameters.clear(); lmsParameters.clear(); message = null; hssPubEnc = null; encodedSigFromVector = null; } } // SecureRandom rand = new SecureRandom() // int c = 48; // @Override // public void nextBytes(byte[] bytes) // for (int t = 0; t < bytes.length; t++) // bytes[t] = (byte)c; } /** * Take an HSS key pair and exhaust its signing capacity. * * @throws Exception */ public void testSignUnitExhaustion() throws Exception { byte[] fixedSource = new byte[8192]; for (int t = 0; t < fixedSource.length; t++) { fixedSource[t] = 1; } SecureRandom rand = new SecureRandom() { @Override public void nextBytes(byte[] bytes) { for (int t = 0; t < bytes.length; t++) { bytes[t] = 1; } } }; HSSPrivateKeyParameters keyPair = HSS.generateHSSKeyPair( HSSKeyGenerationParameters.builder(2) .setLmsParameters( new LMSParameters(LMSigParameters.lms_sha256_n32_h5, LMOtsParameters.sha256_n32_w2), new LMSParameters(LMSigParameters.lms_sha256_n32_h5, LMOtsParameters.sha256_n32_w8)) .setLmsEntropySource(rand) .build() ); HSSPublicKeyParameters pk = keyPair.getPublicKey(); int msgCtr = 0; byte[] message = new byte[32]; // There should be a max of 1024 signatures for this key. assertTrue(keyPair.getUsagesRemaining() == 1024); try { while (msgCtr < 1025) // Just a number.. { Pack.intToBigEndian(msgCtr, message, 0); HSSSignature sig = HSS.generateSignature(keyPair, message, rand); assertTrue(HSS.verifySignature(pk, sig, message)); { // Vandalise hss signature. byte[] rawSig = sig.getEncoded(); rawSig[100] ^= 1; HSSSignature parsedSig = HSSSignature.getInstance(rawSig, 2); assertFalse(HSS.verifySignature(pk, parsedSig, message)); try { HSSSignature.getInstance(rawSig, 0); fail(); } catch (IllegalStateException ex) { assertTrue(ex.getMessage().contains("nspk exceeded maxNspk")); } } { // Vandalise hss message byte[] newMsg = message.clone(); newMsg[1] ^= 1; assertFalse(HSS.verifySignature(pk, sig, newMsg)); } { // Vandalise public key message byte[] pkEnc = pk.getEncoded(); pkEnc[35] ^= 1; HSSPublicKeyParameters rebuiltPk = HSSPublicKeyParameters.getInstance(pkEnc); assertFalse(HSS.verifySignature(rebuiltPk, sig, message)); } msgCtr++; } fail(); } catch (ExhaustedPrivateKeyException ex) { assertTrue(keyPair.getUsagesRemaining() == 0); assertTrue(msgCtr == 1024); assertTrue(ex.getMessage().contains("hss private key is exhausted")); } } }
package ru.job4j.string; /** * Class to search substring in string. * @author ssobolevsky * @since 23.04.2017 * @version 1 */ public class StringSearch { /** * Method to search substring in string. * @param origin - string whichis searched substring * @param sub - substring * @return the presence of a substring in a string */ boolean contains(String origin, String sub) { boolean isContained = false; char[] originString = origin.toCharArray(); char[] substring = sub.toCharArray(); if (originString.length >= substring.length) { for (int i = 0; i <= originString.length - substring.length; i++) { if (originString[i] == substring[0]) { int count = 0; for (int j = 0; j <substring.length; j++) { if (origingStrim[i + j] == subString[k]){ count++; } else { break; } } if (count == substring.length) { isContained = true; } } } } return isContained; } }
package ru.job4j.convert; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ConvertList { public List<Integer> toList(int[][] array) { List<Integer> list = new ArrayList<>(); for (int[] arr : array) { for (int item : arr) { list.add(item); } } return list; } public int[][] toArray(List<Integer> list, int rows) { int[][] array; if (list != null && rows > 0) { array = new int[rows][(int) Math.ceil((double) list.size() / rows)]; Iterator<Integer> iterator = list.iterator(); for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[0].length; j++) { if (iterator.hasNext()) { array[i][j] = iterator.next(); } else { array[i][j] = 0; } } } } else { throw new IllegalArgumentException("null pointer or illegal rows number"); } return array; } public List<Integer> convert(List<int[]> list) { List<Integer> listWithAllItems = new ArrayList<>(); for (int[] array : list) { for (int item : array) { listWithAllItems.add(item); } } return listWithAllItems; } }
package com.yubico.yubioath.fragments; import android.app.DialogFragment; import android.app.Fragment; import android.app.FragmentTransaction; import android.app.ListFragment; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.os.Bundle; import android.view.*; import android.view.animation.Animation; import android.view.animation.Transformation; import android.widget.*; import com.yubico.yubioath.MainActivity; import com.yubico.yubioath.R; import com.yubico.yubioath.model.KeyManager; import com.yubico.yubioath.model.YubiKeyNeo; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; public class ListCodesFragment extends ListFragment implements MainActivity.OnYubiKeyNeoListener, ActionMode.Callback { private static final int READ_LIST = 0; private static final int READ_SELECTED = 1; private static final int DELETE_SELECTED = 2; private final TimeoutAnimation timeoutAnimation = new TimeoutAnimation(); private CodeAdapter adapter; private ProgressBar timeoutBar; private ActionMode actionMode; private int state = READ_LIST; private OathCode selectedItem; private SwipeDialog swipeDialog; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.list_codes_fragment, container, false); timeoutBar = (ProgressBar) view.findViewById(R.id.timeRemaining); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); swipeDialog = new SwipeDialog(); adapter = new CodeAdapter(new ArrayList<OathCode>()); setListAdapter(adapter); getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (actionMode != null) { selectedItem = adapter.getItem(position); actionMode.setTitle(selectedItem.getLabel()); getListView().setItemChecked(position, true); } else { getListView().setItemChecked(position, false); } } }); getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { selectedItem = adapter.getItem(position); if (actionMode == null) { actionMode = getActivity().startActionMode(ListCodesFragment.this); } actionMode.setTitle(selectedItem.getLabel()); getListView().setItemChecked(position, true); return true; } }); } @Override public void onYubiKeyNeo(YubiKeyNeo neo) throws IOException { long timestamp = System.currentTimeMillis() / 1000 / 30; switch (state) { case READ_LIST: showCodes(neo.getCodes(timestamp)); break; case READ_SELECTED: selectedItem.setCode(neo.readHotpCode(selectedItem.getLabel())); adapter.notifyDataSetChanged(); swipeDialog.dismiss(); state = READ_LIST; break; case DELETE_SELECTED: neo.deleteCode(selectedItem.getLabel()); selectedItem = null; swipeDialog.dismiss(); Toast.makeText(getActivity(), R.string.deleted, Toast.LENGTH_SHORT).show(); showCodes(neo.getCodes(timestamp)); state = READ_LIST; break; } } public void showCodes(List<Map<String, String>> codeMap) { List<OathCode> codes = new ArrayList<OathCode>(); boolean hasTimeout = false; for (Map<String, String> code : codeMap) { OathCode oathCode = new OathCode(code.get("label"), code.get("code")); hasTimeout = hasTimeout || !oathCode.hotp; codes.add(oathCode); } if (actionMode != null) { actionMode.finish(); } adapter.setAll(codes); if (codes.size() == 0) { Toast.makeText(getActivity(), R.string.empty_list, Toast.LENGTH_LONG).show(); } if (hasTimeout) { timeoutBar.startAnimation(timeoutAnimation); } else { timeoutAnimation.setStartTime(0); } } @Override public void onPasswordMissing(KeyManager keyManager, byte[] id, boolean missing) { FragmentTransaction ft = getFragmentManager().beginTransaction(); Fragment prev = getFragmentManager().findFragmentByTag("dialog"); if (prev != null) { ft.remove(prev); } DialogFragment dialog = RequirePasswordDialog.newInstance(keyManager, id, missing); dialog.show(ft, "dialog"); } private void readHotp(OathCode code) { if (actionMode != null) { actionMode.finish(); } selectedItem = code; state = READ_SELECTED; swipeDialog.show(getFragmentManager(), "dialog"); } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { case R.id.delete: state = DELETE_SELECTED; swipeDialog.show(getFragmentManager(), "dialog"); break; default: return false; } actionMode.finish(); return true; } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { mode.getMenuInflater().inflate(R.menu.code_select_actions, menu); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } @Override public void onDestroyActionMode(ActionMode mode) { actionMode = null; getListView().setItemChecked(getListView().getCheckedItemPosition(), false); } private class CodeAdapter extends ArrayAdapter<OathCode> { private final Comparator<OathCode> comparator = new Comparator<OathCode>() { @Override public int compare(OathCode lhs, OathCode rhs) { return lhs.getLabel().toLowerCase().compareTo(rhs.getLabel().toLowerCase()); } }; private boolean expired = false; public CodeAdapter(List<OathCode> codes) { super(getActivity(), R.layout.oath_code_view, codes); } public void setAll(List<OathCode> codes) { clear(); expired = false; addAll(codes); sort(comparator); } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = getActivity().getLayoutInflater(); OathCode code = getItem(position); View view = convertView != null ? convertView : inflater.inflate(R.layout.oath_code_view, null); getListView().setItemChecked(position, actionMode != null && selectedItem == code); ((ViewGroup) view).setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); TextView labelView = (TextView) view.findViewById(R.id.label); TextView codeView = (TextView) view.findViewById(R.id.code); ImageButton readButton = (ImageButton) view.findViewById(R.id.readButton); ImageButton copyButton = (ImageButton) view.findViewById(R.id.copyButton); labelView.setText(code.getLabel()); codeView.setText(code.read ? code.getCode() : "<refresh to read>"); boolean valid = code.hotp && code.read || !code.hotp && !expired; codeView.setTextColor(getResources().getColor(valid ? android.R.color.primary_text_dark : android.R.color.secondary_text_light)); readButton.setOnClickListener(code.readAction); copyButton.setOnClickListener(code.copyAction); readButton.setVisibility(code.hotp ? View.VISIBLE : View.GONE); copyButton.setVisibility(code.read ? View.VISIBLE : View.GONE); return view; } } private class TimeoutAnimation extends Animation { public TimeoutAnimation() { setDuration(30000); setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { adapter.expired = true; adapter.notifyDataSetChanged(); } @Override public void onAnimationRepeat(Animation animation) { } }); } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { super.applyTransformation(interpolatedTime, t); timeoutBar.setProgress((int) ((1.0 - interpolatedTime) * 1000)); } } public class OathCode { private final String label; private String code; private boolean read; private boolean hotp = false; private final View.OnClickListener readAction = new ReadAction(); private final View.OnClickListener copyAction = new CopyAction(); public OathCode(String label, String code) { this.label = label; this.code = code; read = code != null; hotp = code == null; } public String getLabel() { return label; } public void setCode(String code) { this.code = code; read = code != null; } public String getCode() { return code; } private class CopyAction implements View.OnClickListener { @Override public void onClick(View v) { if (read) { ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText(label, code); clipboard.setPrimaryClip(clip); Toast.makeText(getActivity(), R.string.copied, Toast.LENGTH_SHORT).show(); } } } private class ReadAction implements View.OnClickListener { @Override public void onClick(View v) { readHotp(OathCode.this); } } } }
package ru.job4j.io; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.RandomAccessFile; public class FileEntrySort { /** * First temp file. */ private File first; /** * Second temp file. */ private File second; /** * Sorting file. * * @param source - file to analize. * @param distance - save sorted data to this file. */ public void sort(File source, File distance) { try { this.first = File.createTempFile("first", "01"); this.second = File.createTempFile("second", "01"); boolean complete; this.fillTempFiles(source); complete = !this.mergeTempFiles(distance); while (!complete) { this.fillTempFiles(distance); complete = !this.mergeTempFiles(distance); } } catch (IOException e) { e.printStackTrace(); } } /** * Fill two temp files, from array. * @param source - source file, to fill temp files. */ private void fillTempFiles(File source) { try (RandomAccessFile raf = new RandomAccessFile(source, "r"); FileWriter out1 = new FileWriter(this.first); FileWriter out2 = new FileWriter(this.second)) { String cur = ""; String prev = null; boolean queue = true; while ((cur = raf.readLine()) != null) { if (prev == null) { out1.write(String.format("%s\n", cur)); } else if (prev.length() <= cur.length()) { if (queue) { out1.write(String.format("%s\n", cur)); } else { out2.write(String.format("%s\n", cur)); } } else { queue = !queue; if (queue) { out1.write(String.format("%s\n", cur)); } else { out2.write(String.format("%s\n", cur)); } } prev = cur; } } catch (IOException e) { e.printStackTrace(); } } /** * Merge temp files to one file, with some kind of sort inside. * @param target - file to merger temp files. * @return - true if merge was completed, of false if no need of merge. */ private boolean mergeTempFiles(File target) { boolean cont = true; boolean result = true; if (this.first.length() > 0 && this.second.length() > 0) { try (RandomAccessFile rafOne = new RandomAccessFile(this.first, "r"); RandomAccessFile rafTwo = new RandomAccessFile(this.second, "r"); FileWriter writer = new FileWriter(target)) { String lineOne = rafOne.readLine(); String lineTwo = rafTwo.readLine(); while (cont) { if (lineOne == null) { writer.write(String.format("%s\n", lineTwo)); lineTwo = rafTwo.readLine(); } else if (lineTwo == null) { writer.write(String.format("%s\n", lineOne)); lineOne = rafOne.readLine(); } else { if (lineOne.length() <= lineTwo.length()) { writer.write(String.format("%s\n", lineOne)); lineOne = rafOne.readLine(); } else { writer.write(String.format("%s\n", lineTwo)); lineTwo = rafTwo.readLine(); } } if (lineOne == null && lineTwo == null) { cont = false; } } } catch (IOException e) { e.printStackTrace(); } } else { result = false; } return result; } }
package at.ac.tuwien.inso.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import at.ac.tuwien.inso.entity.Role; import at.ac.tuwien.inso.entity.UserAccount; import at.ac.tuwien.inso.service.UserAccountService; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled=true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserAccountService userAccountService; @Override protected void configure(HttpSecurity http) throws Exception { http.headers().frameOptions().disable(); http
package biz.neustar.discovery; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.openxri.XRI; import org.openxri.proxy.impl.AbstractProxy; import org.openxri.resolve.Resolver; import org.openxri.resolve.ResolverFlags; import org.openxri.resolve.ResolverState; import org.openxri.resolve.exception.PartialResolutionException; import org.openxri.util.PrioritizedList; import org.openxri.xml.SEPType; import org.openxri.xml.SEPUri; import org.openxri.xml.Service; import org.openxri.xml.Status; import org.openxri.xml.XRD; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import xdi2.core.features.equivalence.Equivalence; import xdi2.core.features.nodetypes.XdiAbstractMemberUnordered; import xdi2.core.features.nodetypes.XdiAttributeCollection; import xdi2.core.features.nodetypes.XdiAttributeMember; import xdi2.core.features.nodetypes.XdiAttributeSingleton; import xdi2.core.features.nodetypes.XdiLocalRoot; import xdi2.core.features.nodetypes.XdiPeerRoot; import xdi2.core.util.XRI2Util; import xdi2.core.xri3.CloudNumber; import xdi2.core.xri3.XDI3Segment; import xdi2.core.xri3.XDI3SubSegment; import xdi2.messaging.GetOperation; import xdi2.messaging.MessageResult; import xdi2.messaging.exceptions.Xdi2MessagingException; import xdi2.messaging.target.ExecutionContext; import xdi2.messaging.target.contributor.AbstractContributor; import xdi2.messaging.target.contributor.ContributorXri; @ContributorXri(addresses={"{()}"}) public class DiscoveryContributor extends AbstractContributor { private static final Logger log = LoggerFactory.getLogger(DiscoveryContributor.class); public static final XDI3Segment XRI_SELF = XDI3Segment.create("[=]"); public static final XDI3SubSegment XRI_URI = XDI3SubSegment.create("$uri"); private AbstractProxy proxy; public AbstractProxy getProxy() { return this.proxy; } public void setProxy(AbstractProxy proxy) { this.proxy = proxy; } @Override public boolean executeGetOnAddress(XDI3Segment[] contributorXris, XDI3Segment contributorsXri, XDI3Segment relativeTargetAddress, GetOperation operation, MessageResult messageResult, ExecutionContext executionContext) throws Xdi2MessagingException { // prepare XRI XDI3Segment requestedXdiPeerRootXri = contributorXris[contributorXris.length - 1]; XDI3Segment resolveXri = XdiPeerRoot.getXriOfPeerRootArcXri(requestedXdiPeerRootXri.getFirstSubSegment()); if (resolveXri == null) return false; CloudNumber resolveCloudNumber = CloudNumber.fromXri(resolveXri); String resolveINumber = resolveCloudNumber == null ? null : XRI2Util.cloudNumberToINumber(resolveCloudNumber); if (resolveINumber != null) resolveXri = XDI3Segment.create(resolveINumber); // resolve the XRI if (log.isDebugEnabled()) log.debug("Resolving " + resolveXri); Resolver resolver = DiscoveryContributor.this.proxy.getResolver(); ResolverFlags resolverFlags = new ResolverFlags(); ResolverState resolverState = new ResolverState(); XRD xrd; try { xrd = resolver.resolveSEPToXRD(new XRI(resolveXri.toString()), null, null, resolverFlags, resolverState); } catch (PartialResolutionException ex) { xrd = ex.getPartialXRDS().getFinalXRD(); } if (log.isDebugEnabled()) log.debug("XRD Status: " + xrd.getStatus().getCode()); if ((! Status.SUCCESS.equals(xrd.getStatusCode())) && (! Status.SEP_NOT_FOUND.equals(xrd.getStatusCode()))) { throw new Xdi2MessagingException("XRI Resolution 2.0 Problem: " + xrd.getStatusCode() + " (" + xrd.getStatus().getValue() + ")", null, executionContext); } // extract cloud number CloudNumber cloudNumber = XRI2Util.iNumberToCloudNumber(xrd.getCanonicalID().getValue()); if (log.isDebugEnabled()) log.debug("Cloud Number: " + cloudNumber); // extract URIs Map<String, List<String>> uriMap = new HashMap<String, List<String>> (); for (int i=0; i<xrd.getNumServices(); i++) { Service service = xrd.getServiceAt(i); if (service.getNumTypes() == 0) continue; for (int ii=0; ii<service.getNumTypes(); ii++) { SEPType type = service.getTypeAt(ii); if (type == null || type.getType() == null || type.getType().trim().isEmpty()) continue; List<String> uriList = uriMap.get(type.getType()); if (uriList == null) { uriList = new ArrayList<String> (); uriMap.put(type.getType(), uriList); } List<?> uris = service.getURIs(); Collections.sort(uris, new Comparator<Object> () { @Override public int compare(Object uri1, Object uri2) { Integer priority1 = ((SEPUri) uri1).getPriority(); Integer priority2 = ((SEPUri) uri2).getPriority(); if (priority1 == null && priority2 == null) return 0; if (priority1 == null && priority2 != null) return 1; if (priority1 != null && priority2 == null) return -1; if (priority1.intValue() == priority2.intValue()) return 0; return priority1.intValue() > priority2.intValue() ? 1 : -1; } }); for (int iii = 0; iii<uris.size(); iii++) { SEPUri uri = (SEPUri) uris.get(iii); if (uri == null || uri.getUriString() == null || uri.getUriString().trim().isEmpty()) continue; uriList.add(uri.getUriString()); } } } if (log.isDebugEnabled()) log.debug("URIs: " + uriMap); // extract default URI PrioritizedList defaultUriPrioritizedList = xrd.getSelectedServices(); ArrayList<?> defaultUriList = defaultUriPrioritizedList == null ? null : defaultUriPrioritizedList.getList(); Service defaultUriService = defaultUriList == null || defaultUriList.size() < 1 ? null : (Service) defaultUriList.get(0); String defaultUri = defaultUriService == null ? null : defaultUriService.getURIAt(0).getUriString(); if (log.isDebugEnabled()) log.debug("Default URI: " + defaultUri); // prepare result graph XdiPeerRoot requestedXdiPeerRoot = XdiPeerRoot.fromContextNode(messageResult.getGraph().setDeepContextNode(requestedXdiPeerRootXri)); // add original peer root if (! cloudNumber.equals(requestedXdiPeerRoot.getXriOfPeerRoot())) { XdiPeerRoot cloudNumberXdiPeerRoot = XdiLocalRoot.findLocalRoot(messageResult.getGraph()).findPeerRoot(cloudNumber.getXri(), true); Equivalence.setReferenceContextNode(requestedXdiPeerRoot.getContextNode(), cloudNumberXdiPeerRoot.getContextNode()); return false; } // add all URIs for all types XdiAttributeCollection uriXdiAttributeCollection = requestedXdiPeerRoot.getXdiAttributeCollection(XRI_URI, true); for (Entry<String, List<String>> uriMapEntry : uriMap.entrySet()) { String type = uriMapEntry.getKey(); List<String> uriList = uriMapEntry.getValue(); XDI3SubSegment typeXdiEntitySingletonArcXri = XRI2Util.typeToXdiEntitySingletonArcXri(type); for (String uri : uriList) { XDI3SubSegment uriXdiMemberUnorderedArcXri = XdiAbstractMemberUnordered.createHashArcXri(uri, true); XdiAttributeMember uriXdiAttributeMember = uriXdiAttributeCollection.setXdiMemberUnordered(uriXdiMemberUnorderedArcXri); uriXdiAttributeMember.getXdiValue(true).getContextNode().setLiteral(uri); XdiAttributeCollection typeXdiAttributeCollection = requestedXdiPeerRoot.getXdiEntitySingleton(typeXdiEntitySingletonArcXri, true).getXdiAttributeCollection(XRI_URI, true); XdiAttributeMember typeXdiAttributeMember = typeXdiAttributeCollection.setXdiMemberOrdered(-1); Equivalence.setReferenceContextNode(typeXdiAttributeMember.getContextNode(), uriXdiAttributeMember.getContextNode()); } // add default URI for this type if (uriList.size() > 0) { String defaultUriForType = uriList.get(0); XDI3SubSegment defaultUriForTypeXdiMemberUnorderedArcXri = XdiAbstractMemberUnordered.createHashArcXri(defaultUriForType, true); XdiAttributeMember defaultUriForTypeXdiAttributeMember = uriXdiAttributeCollection.setXdiMemberUnordered(defaultUriForTypeXdiMemberUnorderedArcXri); XdiAttributeSingleton defaultUriForTypeXdiAttributeSingleton = requestedXdiPeerRoot.getXdiEntitySingleton(typeXdiEntitySingletonArcXri, true).getXdiAttributeSingleton(XRI_URI, true); Equivalence.setReferenceContextNode(defaultUriForTypeXdiAttributeSingleton.getContextNode(), defaultUriForTypeXdiAttributeMember.getContextNode()); } } // add default URI if (defaultUri != null) { XDI3SubSegment defaultUriXdiMemberUnorderedArcXri = XdiAbstractMemberUnordered.createHashArcXri(defaultUri, true); XdiAttributeMember defaultUriXdiAttributeMember = uriXdiAttributeCollection.setXdiMemberUnordered(defaultUriXdiMemberUnorderedArcXri); XdiAttributeSingleton defaultUriXdiAttributeSingleton = requestedXdiPeerRoot.getXdiAttributeSingleton(XRI_URI, true); Equivalence.setReferenceContextNode(defaultUriXdiAttributeSingleton.getContextNode(), defaultUriXdiAttributeMember.getContextNode()); } // done return false; } }
package br.uff.ic.provviewer.GUI; import br.uff.ic.provviewer.Collapser; import br.uff.ic.utility.graph.Edge; import br.uff.ic.provviewer.Filter.Filters; import br.uff.ic.provviewer.Filter.PreFilters; import br.uff.ic.provviewer.GraphFrame; import br.uff.ic.provviewer.Variables; import br.uff.ic.utility.graph.Vertex; import edu.uci.ics.jung.graph.DirectedGraph; import edu.uci.ics.jung.visualization.control.DefaultModalGraphMouse; import java.util.Collection; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.ToolTipManager; /** * Class to initialize the interface operations * * @author Kohwalter */ public class GuiInitialization { /** * Method to initialize the tool components * * @param variables * @param graph * @param graphFrame * @param Layouts * @param agentLabel interface check-box state agent label * @param activityLabel interface check-box state activity label * @param entityLabel interface check-box state for entity label * @param timeLabel interface check-box state for time label */ public static void initGraphComponent(Variables variables, DirectedGraph<Object, Edge> graph, JFrame graphFrame, JComboBox Layouts, boolean agentLabel, boolean activityLabel, boolean entityLabel, boolean timeLabel, boolean showID) { variables.initConfig = true; variables.graph = graph; variables.collapsedGraph = variables.graph; GuiFunctions.SetView(variables, Layouts, graphFrame); variables.guiBackground.InitBackground(variables, Layouts); GuiFunctions.MouseInteraction(variables); GuiTooltip.Tooltip(variables); GuiFunctions.VertexLabel(variables, agentLabel, activityLabel, entityLabel, timeLabel, showID); GuiFunctions.Stroke(variables); GuiFunctions.GraphPaint(variables); GuiFunctions.VertexShape(variables); InitFilters(variables); NormalizeTime(variables); ToolTipManager.sharedInstance().setInitialDelay(10); ToolTipManager.sharedInstance().setDismissDelay(50000); GraphFrame.vertexFilterList.setSelectedIndex(0); } /** * Method to initialize the tool's variables * * @param variables */ public static void InitVariables(Variables variables) { variables.mouse = new DefaultModalGraphMouse(); variables.filterCredits = false; variables = new Variables(); variables.collapser = new Collapser(); variables.filter = new Filters(); variables.prologIsInitialized = false; variables.initLayout = true; variables.initConfig = false; } /** * Method to initialize the tool's filters * * @param variables */ public static void InitFilters(Variables variables) { variables.filter.filteredGraph = variables.graph; // variables.filter.FilterInit(); PreFilters.PreFilter(); variables.filter.Filters(variables); } /** * Method to normalize vertex's timestamps to start from 0 * @param variables */ public static void NormalizeTime(Variables variables) { Collection<Object> vertices = variables.graph.getVertices(); double minTime = Double.POSITIVE_INFINITY; for (Object v : vertices) { if (((Vertex) v).getTime() != -1) { minTime = Math.min(minTime, ((Vertex) v).getTime()); } } // Normalize time for (Object v : vertices) { if (((Vertex) v).getTime() != -1) { ((Vertex) v).setNormalizedTime((((Vertex) v).getTime() - minTime) + 1); } else { ((Vertex) v).setNormalizedTime(-1); } } } }
package controllers; import java.io.IOException; import java.io.InputStream; import java.sql.Array; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeCreator; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import play.*; import play.db.DB; import play.libs.WS; import play.libs.WS.Response; import play.mvc.*; import play.mvc.Http.RequestBody; import views.html.*; public class EventManager extends Controller{ public static final String EVENT_GET_SQL_UNRESTRICTED = "select distinct Event.id as id, Event.name as name, Event.location as location, UNIX_TIMESTAMP(Event.time) as time, Event.description as description, Event.visibility as visibility, Event_has_User.rsvp as rsvp from Event inner join Event_has_Tags on Event.id = Event_has_Tags.Event_id inner join Tags on Event_has_Tags.Tags_id = Tags.id inner join Event_has_User on Event.id = Event_has_User.event_id"; public static final String EVENT_GET_SQL = "select distinct Event.id as id, Event.name as name, Event.location as location, UNIX_TIMESTAMP(Event.time) as time, Event.description as description, Event.visibility as visibility, Event_has_User.rsvp as rsvp from Event inner join Event_has_Tags on Event.id = Event_has_Tags.Event_id inner join Tags on Event_has_Tags.Tags_id = Tags.id inner join Event_has_User on Event.id = Event_has_User.event_id WHERE (Event.visibility = 1 OR (Event_has_User.user_id = ? AND Event_has_User.rsvp = 1))"; public static ArrayNode buildEventResults(Connection conn, ResultSet rs) throws SQLException { ArrayNode arr = JsonNodeFactory.instance.arrayNode(); while(rs.next()) { ObjectNode eventRes = createEventJson(rs); try(PreparedStatement stmtTag = conn.prepareStatement("select Tags.tag from Tags INNER JOIN Event_has_Tags ON Tags.id = Event_has_Tags.Tags_id INNER JOIN Event ON Event.id = Event_has_Tags.Event_id WHERE Event.id = ?")) { stmtTag.setLong(1, rs.getLong("id")); stmtTag.execute(); ResultSet rsTag = stmtTag.getResultSet(); addCategoriesToEventJson(eventRes, rsTag); } arr.add(eventRes); } return arr; } public static Result create() { /* OAuth*/ JsonNode request = request().body().asJson(); try { Application.checkReqValid(request); } catch(AuthorizationException e) { return ok(JsonNodeFactory.instance.objectNode().put("error", e.getMessage())); } catch(SQLException e) { e.printStackTrace(); return ok(); } String title, desc, location; long timestamp; int visibility; ArrayNode categories; try { title = request.get("title").textValue(); desc = request.get("desc").textValue(); location = request.get("location").textValue(); timestamp = request.get("date_time").asLong(); visibility = request.get("visibility").intValue(); if(request.has("categories")) { categories = (ArrayNode) request.get("categories"); } else { throw new Exception("categories"); } } catch(Exception e) { return ok(JsonNodeFactory.instance.objectNode() .put("error", "Parameters: title (string), desc(string), location(string), date_time(long), visibility(int), categories(array)")); } // convert time to date java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(timestamp); Connection conn = DB.getConnection(); try { conn.setAutoCommit(false); PreparedStatement stmt = conn.prepareStatement("INSERT INTO CampusFeed.Event (name,location,time,description,visibility) VALUES (?,?,?,?,?)",Statement.RETURN_GENERATED_KEYS); stmt.setString(1, title); stmt.setString(2, location); stmt.setTimestamp(3, sqlTimestamp); stmt.setString(4, desc); stmt.setInt(5, visibility); stmt.executeUpdate(); ResultSet rs = stmt.getGeneratedKeys(); // get the generated primary key if(rs.next()) { long event_id = rs.getLong(1); long user_id =Application.getUserId(request); stmt = conn.prepareStatement("INSERT INTO CampusFeed.Event_has_User (event_id,user_id,is_admin) VALUES (?,?,?)"); stmt.setLong(1, event_id); stmt.setLong(2, user_id); stmt.setInt(3, 1); stmt.executeUpdate(); String[] categoriesStr = new String[categories.size()]; for(int i = 0; i < categories.size(); ++i) { categoriesStr[i] = categories.get(i).textValue(); } addTags(conn, event_id, categoriesStr); conn.commit(); conn.close(); return ok(JsonNodeFactory.instance.objectNode().put("event_id", event_id)); } else { throw new SQLException(); } } catch(SQLException e) { e.printStackTrace(); try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } return ok(); } } public static int createFromScrapedPage(JsonNode request) { /* OAuth*/ String title, desc, location; long timestamp; int visibility; ArrayNode categories; try { title = request.get("title").textValue(); desc = request.get("desc").textValue(); location = request.get("location").textValue(); timestamp = request.get("date_time").asLong(); visibility = request.get("visibility").intValue(); if(request.has("categories")) { categories = (ArrayNode) request.get("categories"); } else { throw new Exception("categories"); } } catch(Exception e) { return -1; } // convert time to date java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(timestamp); Connection conn = DB.getConnection(); try { conn.setAutoCommit(false); PreparedStatement stmt = conn.prepareStatement("INSERT INTO CampusFeed.Event (name,location,time,description,visibility) VALUES (?,?,?,?,?)",Statement.RETURN_GENERATED_KEYS); stmt.setString(1, title); stmt.setString(2, location); stmt.setTimestamp(3, sqlTimestamp); stmt.setString(4, desc); stmt.setInt(5, visibility); stmt.executeUpdate(); ResultSet rs = stmt.getGeneratedKeys(); // get the generated primary key if(rs.next()) { long event_id = rs.getLong(1); long user_id =Application.getUserId(request); stmt = conn.prepareStatement("INSERT INTO CampusFeed.Event_has_User (event_id,user_id,is_admin) VALUES (?,?,?)"); stmt.setLong(1, event_id); stmt.setLong(2, ScraperHandler.SCRAPER_ID); stmt.setInt(3, 1); stmt.executeUpdate(); String[] categoriesStr = new String[categories.size()]; for(int i = 0; i < categories.size(); ++i) { categoriesStr[i] = categories.get(i).textValue(); } addTags(conn, event_id, categoriesStr); conn.commit(); conn.close(); return 1; } else { throw new SQLException(); } } catch(SQLException e) { e.printStackTrace(); try { conn.rollback(); return 1; } catch (SQLException e1) { e1.printStackTrace(); return -1; } } } public static Result rsvp_to_event() { /* OAuth*/ JsonNode request = request().body().asJson(); if(request==null) { return ok(); } try { Application.checkReqValid(request); } catch(AuthorizationException e) { return ok(JsonNodeFactory.instance.objectNode().put("error", e.getMessage())); } catch(SQLException e) { e.printStackTrace(); return ok(); } // add user to rsvp // get the user id long user_id =Application.getUserId(request); // main thing, only need event_id long event_id = request.get("event_id").longValue(); // check if user has already rsvp'd boolean should_add = false; try(Connection conn = DB.getConnection()) { PreparedStatement stmt = conn.prepareStatement("SELECT rsvp FROM CampusFeed.Event_has_User WHERE user_id=? AND event_id=?"); stmt.setLong(1, user_id); stmt.setLong(2, event_id); stmt.execute(); ResultSet rs = stmt.getResultSet(); int rsvp=-1; if(rs.next()) { rsvp= rs.getInt("rsvp"); } else { should_add=true; } if(rsvp==1){ return ok("duplicate"); }else if(rsvp!=1 && should_add!=true) { // then only need to update, incase if undo rsvp or something. try(Connection conn2 = DB.getConnection()) { PreparedStatement stmt2 = conn2.prepareStatement("UPDATE `CampusFeed`.`Event_has_User` SET `rsvp` = '1' WHERE `event_has_user`.`event_id` = ? AND `event_has_user`.`user_id` = ?"); stmt2.setLong(2, user_id); stmt2.setLong(1, event_id); stmt2.executeUpdate(); } catch(SQLException e) { e.printStackTrace(); return ok("success"); } } } catch(SQLException e) { e.printStackTrace(); return ok(); } if(should_add){ // main thing, add to rsvp try(Connection conn = DB.getConnection()) { PreparedStatement stmt = conn.prepareStatement("INSERT INTO CampusFeed.Event_has_User (user_id,event_id,rsvp,is_admin) VALUES (?,?,1,0)"); stmt.setLong(1, user_id); stmt.setLong(2, event_id); stmt.executeUpdate(); } catch(SQLException e) { e.printStackTrace(); return ok("success"); } } return ok("success"); } /** * Helper function to create event json from results * @param rs result set from query on a valid event row * @return the json event * @throws SQLException */ private static ObjectNode createEventJson(ResultSet rs) throws SQLException { ObjectNode searchResult = JsonNodeFactory.instance.objectNode(); searchResult.put("id", rs.getString("id")); searchResult.put("name", rs.getString("name")); searchResult.put("location", rs.getString("location")); searchResult.put("time", rs.getInt("time")); searchResult.put("description", rs.getString("description")); //searchResult.put("category", rs.getString("category")); searchResult.put("visibility", rs.getInt("visibility")); searchResult.put("rsvp", rs.getInt("rsvp")); return searchResult; } /** * Helper function to add categories to event json * @param event * @param rs * @throws SQLException */ private static void addCategoriesToEventJson(ObjectNode event, ResultSet rs) throws SQLException { ArrayNode categories = JsonNodeFactory.instance.arrayNode(); while(rs.next()) { categories.add(rs.getString("tag")); } event.put("categories", categories); } public static Result advSearch() { JsonNode request = request().body().asJson(); try { Application.checkReqValid(request); } catch(AuthorizationException e) { return ok(JsonNodeFactory.instance.objectNode().put("error", e.getMessage())); } catch(SQLException e) { e.printStackTrace(); return ok(); } // get the user id long user_id =Application.getUserId(request); //check params if(!request.has("name") && !(request.has("start_date") && request.has("end_date")) && !request.has("desc") && !request.has("tags")){ return ok(JsonNodeFactory.instance.objectNode().put("error", "usage: name (text) or (start_date (date) and end_date (date)) or desc (text) or tags (array)")); } try(Connection conn = DB.getConnection()) { PreparedStatement stmt = null; List<Object> params = new ArrayList<Object>(); params.add(user_id); String sql = EVENT_GET_SQL; if(request.has("name")) { if(params.size() != 0) { sql += " AND "; } sql += "name like ?"; params.add("%" + request.get("name").textValue() + "%"); } if(request.has("start_date") && request.has("end_date")) { if(params.size() != 0) { sql += " AND "; } sql += "UNIX_TIMESTAMP(time) BETWEEN ? AND ?"; params.add(request.get("start_date").asLong()); params.add(request.get("end_date").asLong()); } if(request.has("desc")) { if(params.size() != 0) { sql += " AND "; } sql += "description like ?"; params.add("%" + request.get("desc").textValue() + "%"); } if(request.has("tags")) { ArrayNode tags = (ArrayNode) request.get("tags"); if(params.size() != 0) { sql += " AND ("; } for(int i = 0; i < tags.size(); ++i) { sql += "Tags.tag = ?"; params.add(tags.get(i).textValue()); if(i < tags.size() - 1) { sql += " OR "; } } sql += ")"; } stmt = conn.prepareStatement(sql); for(int i = 0; i < params.size(); ++i) { stmt.setObject(i + 1, params.get(i)); } System.out.println(sql); stmt.execute(); ResultSet rs = stmt.executeQuery(); return ok(buildEventResults(conn, rs)); } catch(Exception e) { e.printStackTrace(); return ok(); } } public static Result listEvent() { JsonNode request = request().body().asJson(); try { Application.checkReqValid(request); } catch(AuthorizationException e) { return ok(JsonNodeFactory.instance.objectNode().put("error", e.getMessage())); } catch(SQLException e) { e.printStackTrace(); return ok(); } // get the user id long user_id =Application.getUserId(request); //check params int page; try { page = request.get("page").intValue(); } catch(Exception e) { return ok(JsonNodeFactory.instance.objectNode().put("error", "usage: page (int)")); } try(Connection conn = DB.getConnection()) { try(PreparedStatement stmt = conn.prepareStatement(EVENT_GET_SQL + " LIMIT 25 OFFSET ?")) { stmt.setLong(1, user_id); stmt.setInt(2, page * 25); ResultSet rs = stmt.executeQuery(); return ok(buildEventResults(conn, rs)); } } catch(SQLException e) { e.printStackTrace(); return ok(); } } private static void addTags(Connection conn, long eventId, String[] tags) throws SQLException{ PreparedStatement lookupTag = conn.prepareStatement("SELECT id FROM Tags WHERE tag = ?"); PreparedStatement addTag = conn.prepareStatement("INSERT INTO Tags (tag) VALUES (?)", Statement.RETURN_GENERATED_KEYS); PreparedStatement linkTag = conn.prepareStatement("INSERT INTO Event_has_Tags (Event_id, Tags_id) VALUES (?, ?)", Statement.RETURN_GENERATED_KEYS); for(String tag : tags) { lookupTag.setString(1, tag); lookupTag.execute(); ResultSet rs; long tag_id = -1; if((rs = lookupTag.getResultSet()).next()) { tag_id = rs.getLong(1); } else { addTag.setString(1, tag); addTag.execute(); if((rs = addTag.getGeneratedKeys()).next()) { tag_id = rs.getLong(1); } } linkTag.setLong(1, eventId); linkTag.setLong(2, tag_id); linkTag.execute(); } lookupTag.close(); addTag.close(); linkTag.close(); } public static Result updateEvent() { /* OAuth*/ JsonNode request = request().body().asJson(); try { Application.checkReqValid(request); } catch(AuthorizationException e) { return ok(JsonNodeFactory.instance.objectNode().put("error", e.getMessage())); } catch(SQLException e) { e.printStackTrace(); return ok(); } String title, desc, location; long timestamp, id; int visibility; ArrayNode categories; try { title = request.get("title").textValue(); desc = request.get("desc").textValue(); location = request.get("location").textValue(); timestamp = request.get("date_time").asLong(); visibility = request.get("visibility").intValue(); id = request.get("id").longValue(); categories = (ArrayNode) request.get("categories"); if(categories == null) { throw new Exception("categories"); } } catch(Exception e) { e.printStackTrace(); return ok(JsonNodeFactory.instance.objectNode() .put("error", "Parameters: title (string), desc(string), location(string), date_time(long), visibility(int), categories(array)")); } long userId = Application.getUserId(request); Connection conn = DB.getConnection(); try { conn.setAutoCommit(false); PreparedStatement isAdminQuery = conn.prepareStatement("select is_admin from CampusFeed.Event_has_User where event_id = ? and user_id = ?"); isAdminQuery.setLong(1, id); isAdminQuery.setLong(2, userId); isAdminQuery.execute(); boolean isAdmin = false; if(isAdminQuery.getResultSet().next()) { isAdmin = isAdminQuery.getResultSet().getInt(0) != 0; } isAdminQuery.close(); if(!isAdmin) { conn.close(); return ok(JsonNodeFactory.instance.objectNode().put("no", "not admin")); } PreparedStatement stmt2 = conn.prepareStatement("UPDATE `CampusFeed`.`Event` SET name=?, location=?,description=?,time=?,visibility=? WHERE `Event`.`id` = ?"); stmt2.setString(1, title); stmt2.setString(2, location); stmt2.setString(3, desc); stmt2.setTimestamp(4, new Timestamp(timestamp)); stmt2.setInt(5, visibility); stmt2.setLong(6, id); stmt2.executeUpdate(); stmt2 = conn.prepareStatement("DELETE Event_has_Tags FROM Event_has_Tags INNER JOIN Event ON Event_has_Tags.Event_id = Event.id WHERE (Event.id = ?)"); stmt2.setLong(1, id); stmt2.executeUpdate(); String[] categoriesStr = new String[categories.size()]; for(int i = 0; i < categories.size(); ++i) { categoriesStr[i] = categories.get(i).textValue(); } addTags(conn, id, categoriesStr); conn.commit(); conn.close(); // send messages to all users GCMHandler.sendMessage(get_user_ids(),id); // end messaging. return ok(JsonNodeFactory.instance.objectNode().put("ok", "ok")); } catch(SQLException e) { e.printStackTrace(); return ok(); } } public static ArrayList<String> get_user_ids() { try(Connection conn = DB.getConnection()) { PreparedStatement stmt = conn.prepareStatement("SELECT * FROM `User` WHERE gcm_id IS NOT NULL"); ResultSet s =stmt.executeQuery(); ArrayList<String> user_ids = new ArrayList<String>(); while(s.next()) { String gcm_id = s.getString("gcm_id"); user_ids.add(gcm_id); System.out.println(gcm_id+"\n"); } s.close(); return user_ids; }catch(Exception e) { return null; } } public static Result allTags() { try(Connection conn = DB.getConnection()) { PreparedStatement stmt = conn.prepareStatement("SELECT * FROM Tags"); ResultSet s =stmt.executeQuery(); ArrayList<String> tags = new ArrayList<String>(); while(s.next()) { tags.add(s.getString("tag")); } s.close(); JsonNode tags_json= JsonNodeFactory.instance.objectNode().put("tags", tags.toString()); return ok(tags_json); }catch(Exception e) { return ok(); } } public static Result top5() { JsonNode request = request().body().asJson(); String category; try { category = request.get("category").textValue(); } catch(Exception e) { e.printStackTrace(); return ok(JsonNodeFactory.instance.objectNode() .put("error", "Parameters: category (text)")); } try(Connection conn = DB.getConnection()) { PreparedStatement stmt = conn.prepareStatement(EVENT_GET_SQL_UNRESTRICTED + " WHERE Tags.tag = ? ORDER BY Event.view_count DESC LIMIT 5"); stmt.setString(1, category); ResultSet rs = stmt.executeQuery(); return ok(buildEventResults(conn, rs)); } catch(SQLException e) { return ok(JsonNodeFactory.instance.objectNode().put("error", e.getMessage())); } } public static Result getEvent() { JsonNode request = request().body().asJson(); long event_id; try { event_id = request.get("event_id").longValue(); } catch(Exception e) { return ok(JsonNodeFactory.instance.objectNode().put("error", "usage: event_id (long)")); } try(Connection conn = DB.getConnection()) { PreparedStatement stmt = conn.prepareStatement(EVENT_GET_SQL_UNRESTRICTED + " WHERE Event.id = ?"); stmt.setLong(1, event_id); ResultSet rs = stmt.executeQuery(); return ok(buildEventResults(conn, rs).get(0)); } catch(Exception e) { return ok(JsonNodeFactory.instance.objectNode().put("error", e.getMessage())); } } }
package com.aif.language.sentence; import com.aif.language.common.ISplitter; import java.util.*; import java.util.stream.Collectors; public class SentenceSplitter implements ISplitter<List<String>, List<String>> { private final ISentenceSeparatorExtractor sentenceSeparatorExtractor; public SentenceSplitter(final ISentenceSeparatorExtractor sentenceSeparatorExtractor) { this.sentenceSeparatorExtractor = sentenceSeparatorExtractor; } public SentenceSplitter() { this(ISentenceSeparatorExtractor.Type.PREDEFINED.getInstance()); } @Override public List<List<String>> split(final List<String> tokens) { final Optional<List<Character>> optionalSeparators = sentenceSeparatorExtractor.extract(tokens); if (!optionalSeparators.isPresent()) { return new ArrayList<List<String>>(){{add(tokens);}}; } final List<Character> separators = optionalSeparators.get(); final List<Boolean> listOfPositions = mapToBooleans(tokens, separators); final SentenceIterator sentenceIterator = new SentenceIterator(tokens, listOfPositions); final List<List<String>> sentences = new ArrayList<>(); while (sentenceIterator.hasNext()) { sentences.add(sentenceIterator.next()); } sentences.forEach(sentence -> prepareSentences(sentence, separators)); return sentences .parallelStream() .map(sentence -> SentenceSplitter.prepareSentences(sentence, separators)) .collect(Collectors.toList()); } private static List<String> prepareSentences(final List<String> sentence, final List<Character> separators) { final String lastToken = sentence.get(sentence.size() - 1); int index = lastToken.length() - 1; while (index > 0 && separators.contains(lastToken.charAt(index))) { index } index++; if (index < lastToken.length()) { final String leftToken = lastToken.substring(0, index); final String rightToken = lastToken.substring(index); final List<String> preparedSentance = new ArrayList<>(sentence.size() + 1); for (int i = 0; i < sentence.size() - 1; i++) { preparedSentance.add(sentence.get(i)); } preparedSentance.add(leftToken); preparedSentance.add(rightToken); return preparedSentance; } return sentence; } private List<Boolean> mapToBooleans(final List<String> tokens, final List<Character> separators) { return tokens.stream() .map(token -> separators.contains(token.charAt(token.length() - 1))) .collect(Collectors.toList()); } private static class SentenceIterator implements Iterator<List<String>> { private final List<String> tokens; private final List<Boolean> endTokens; private int currentPosition = 0; private SentenceIterator(List<String> tokens, List<Boolean> endTokens) { this.tokens = tokens; this.endTokens = endTokens; } @Override public boolean hasNext() { return currentPosition != tokens.size(); } @Override public List<String> next() { final List<String> sentence = getNextSentence(); return sentence; } private List<String> getNextSentence() { final int oldIndex = currentPosition; currentPosition = getNextTrueIndex(); return this.tokens.subList(oldIndex, currentPosition); } private int getNextTrueIndex() { int startIndex = currentPosition; do { if (endTokens.get(startIndex)) { startIndex++; return startIndex; } startIndex++; } while(startIndex < endTokens.size() - 1); return startIndex + 1; } } }
package com.akiban.sql.pg; import com.akiban.ais.model.AkibanInformationSchema; import com.akiban.sql.server.ServerServiceRequirements; import com.akiban.sql.server.ServerSessionBase; import com.akiban.sql.server.ServerSessionMonitor; import com.akiban.sql.server.ServerStatement; import com.akiban.sql.server.ServerStatementCache; import com.akiban.sql.server.ServerTransaction; import com.akiban.sql.server.ServerValueDecoder; import com.akiban.sql.StandardException; import com.akiban.sql.parser.ParameterNode; import com.akiban.sql.parser.SQLParserException; import com.akiban.sql.parser.StatementNode; import com.akiban.qp.operator.QueryContext; import com.akiban.qp.operator.StoreAdapter; import com.akiban.qp.persistitadapter.PersistitAdapter; import com.akiban.server.api.DDLFunctions; import com.akiban.server.error.*; import com.akiban.server.service.monitor.MonitorStage; import static com.akiban.server.service.dxl.DXLFunctionsHook.DXLFunction; import com.akiban.util.tap.InOutTap; import com.akiban.util.tap.Tap; import com.persistit.exception.RollbackException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.*; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import java.io.*; import java.util.*; /** * Connection to a Postgres server client. * Runs in its own thread; has its own AkServer Session. * */ public class PostgresServerConnection extends ServerSessionBase implements PostgresServerSession, Runnable { private static final Logger logger = LoggerFactory.getLogger(PostgresServerConnection.class); private static final InOutTap READ_MESSAGE = Tap.createTimer("PostgresServerConnection: read message"); private static final InOutTap PROCESS_MESSAGE = Tap.createTimer("PostgresServerConnection: process message"); private final PostgresServer server; private boolean running = false, ignoreUntilSync = false; private Socket socket; private PostgresMessenger messenger; private OutputFormat outputFormat = OutputFormat.TABLE; private int sessionId, secret; private int version; private Map<String,PostgresStatement> preparedStatements = new HashMap<String,PostgresStatement>(); private Map<String,PostgresBoundQueryContext> boundPortals = new HashMap<String,PostgresBoundQueryContext>(); private ServerStatementCache<PostgresStatement> statementCache; private PostgresStatementParser[] unparsedGenerators; private PostgresStatementGenerator[] parsedGenerators; private Thread thread; private volatile String cancelForKillReason, cancelByUser; public PostgresServerConnection(PostgresServer server, Socket socket, int sessionId, int secret, ServerServiceRequirements reqs) { super(reqs); this.server = server; this.socket = socket; this.sessionId = sessionId; this.secret = secret; this.sessionMonitor = new ServerSessionMonitor(PostgresServer.SERVER_TYPE, sessionId); sessionMonitor.setRemoteAddress(socket.getInetAddress().getHostAddress()); reqs.monitor().registerSessionMonitor(sessionMonitor); } public void start() { running = true; thread = new Thread(this); thread.start(); } public void stop() { running = false; // Can only wake up stream read by closing down socket. try { socket.close(); } catch (IOException ex) { } if ((thread != null) && (thread != Thread.currentThread())) { try { // Wait a bit, but don't hang up shutdown if thread is wedged. thread.join(500); if (thread.isAlive()) logger.warn("Connection " + sessionId + " still running."); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } thread = null; } } public void run() { try { createMessenger(); topLevel(); } catch (Exception ex) { if (running) logger.warn("Error in server", ex); } finally { try { socket.close(); } catch (IOException ex) { } } } protected void createMessenger() throws IOException { messenger = new PostgresMessenger(socket) { @Override public void beforeIdle() throws IOException { super.beforeIdle(); sessionMonitor.enterStage(MonitorStage.IDLE); } @Override public void afterIdle() throws IOException { sessionMonitor.leaveStage(); super.afterIdle(); } @Override public void idle() { if (cancelForKillReason != null) { String msg = cancelForKillReason; cancelForKillReason = null; if (cancelByUser != null) { msg += " by " + cancelByUser; cancelByUser = null; } throw new ConnectionTerminatedException(msg); } } }; } protected void topLevel() throws IOException, Exception { logger.info("Connect from {}" + socket.getRemoteSocketAddress()); boolean startupComplete = false; try { while (running) { READ_MESSAGE.in(); PostgresMessages type; try { type = messenger.readMessage(startupComplete); } catch (ConnectionTerminatedException ex) { logError(ErrorLogLevel.DEBUG, "About to terminate", ex); notifyClient(QueryContext.NotificationLevel.WARNING, ex.getCode(), ex.getShortMessage()); stop(); continue; } finally { READ_MESSAGE.out(); } PROCESS_MESSAGE.in(); if (ignoreUntilSync) { if ((type != PostgresMessages.EOF_TYPE) && (type != PostgresMessages.SYNC_TYPE)) continue; ignoreUntilSync = false; } long startNsec = System.nanoTime(); try { switch (type) { case EOF_TYPE: // EOF stop(); break; case SYNC_TYPE: readyForQuery(); break; case STARTUP_MESSAGE_TYPE: startupComplete = processStartupMessage(); break; case PASSWORD_MESSAGE_TYPE: processPasswordMessage(); break; case QUERY_TYPE: processQuery(); break; case PARSE_TYPE: processParse(); break; case BIND_TYPE: processBind(); break; case DESCRIBE_TYPE: processDescribe(); break; case EXECUTE_TYPE: processExecute(); break; case FLUSH_TYPE: processFlush(); break; case CLOSE_TYPE: processClose(); break; case TERMINATE_TYPE: processTerminate(); break; } } catch (QueryCanceledException ex) { InvalidOperationException nex = ex; boolean forKill = false; if (cancelForKillReason != null) { nex = new ConnectionTerminatedException(cancelForKillReason); nex.initCause(ex); cancelForKillReason = null; forKill = true; } logError(ErrorLogLevel.INFO, "Query canceled", nex); String msg = nex.getShortMessage(); if (cancelByUser != null) { if (!forKill) msg = "Query canceled"; msg += " by " + cancelByUser; cancelByUser = null; } sendErrorResponse(type, nex, nex.getCode(), msg); if (forKill) stop(); } catch (ConnectionTerminatedException ex) { logError(ErrorLogLevel.DEBUG, "Query terminated self", ex); sendErrorResponse(type, ex, ex.getCode(), ex.getShortMessage()); stop(); } catch (InvalidOperationException ex) { logError(ErrorLogLevel.WARN, "Error in query", ex); sendErrorResponse(type, ex, ex.getCode(), ex.getShortMessage()); } catch (RollbackException ex) { QueryRollbackException qe = new QueryRollbackException(); qe.initCause(ex); logError(ErrorLogLevel.INFO, "Query rollback", qe); sendErrorResponse(type, qe, qe.getCode(), qe.getMessage()); } catch (Exception ex) { logError(ErrorLogLevel.WARN, "Unexpected error in query", ex); String message = (ex.getMessage() == null ? ex.getClass().toString() : ex.getMessage()); sendErrorResponse(type, ex, ErrorCode.UNEXPECTED_EXCEPTION, message); } finally { long stopNsec = System.nanoTime(); if (logger.isTraceEnabled()) { logger.trace("Executed {}: {} usec", type, (stopNsec - startNsec) / 1000); } } PROCESS_MESSAGE.out(); } } finally { if (transaction != null) { transaction.abort(); transaction = null; } server.removeConnection(sessionId); reqs.monitor().deregisterSessionMonitor(sessionMonitor); } } private enum ErrorLogLevel { WARN, INFO, DEBUG }; private void logError(ErrorLogLevel level, String msg, Exception ex) { if (reqs.config().testing()) { level = ErrorLogLevel.DEBUG; } switch (level) { case DEBUG: logger.debug(msg, ex); break; case INFO: logger.info(msg, ex); break; case WARN: default: logger.warn(msg, ex); break; } } protected void sendErrorResponse(PostgresMessages type, Exception exception, ErrorCode errorCode, String message) throws Exception { if (type.errorMode() == PostgresMessages.ErrorMode.NONE) throw exception; else { messenger.beginMessage(PostgresMessages.ERROR_RESPONSE_TYPE.code()); messenger.write('S'); messenger.writeString((type.errorMode() == PostgresMessages.ErrorMode.FATAL) ? "FATAL" : "ERROR"); messenger.write('C'); messenger.writeString(errorCode.getFormattedValue()); messenger.write('M'); messenger.writeString(message); if (exception instanceof BaseSQLException) { int pos = ((BaseSQLException)exception).getErrorPosition(); if (pos > 0) { messenger.write('P'); messenger.writeString(Integer.toString(pos)); } } messenger.write(0); messenger.sendMessage(true); } if (type.errorMode() == PostgresMessages.ErrorMode.EXTENDED) ignoreUntilSync = true; else readyForQuery(); } protected void readyForQuery() throws IOException { messenger.beginMessage(PostgresMessages.READY_FOR_QUERY_TYPE.code()); char mode = 'I'; // Idle if (isTransactionActive()) mode = isTransactionRollbackPending() ? 'E' : 'T'; messenger.writeByte(mode); messenger.sendMessage(true); } protected boolean processStartupMessage() throws IOException { int version = messenger.readInt(); switch (version) { case PostgresMessenger.VERSION_CANCEL: processCancelRequest(); return false; case PostgresMessenger.VERSION_SSL: processSSLMessage(); return false; default: this.version = version; logger.debug("Version {}.{}", (version >> 16), (version & 0xFFFF)); } Properties clientProperties = new Properties(server.getProperties()); while (true) { String param = messenger.readString(); if (param.length() == 0) break; String value = messenger.readString(); clientProperties.put(param, value); } logger.debug("Properties: {}", clientProperties); setProperties(clientProperties); session = reqs.sessionService().createSession(); // TODO: Not needed right now and not a convenient time to // encounter schema lock from long-running DDL. // But see comment in initParser(): what if we wanted to warn // or error when schema does not exist? //updateAIS(null); if (Boolean.parseBoolean(properties.getProperty("require_password", "false"))) { messenger.beginMessage(PostgresMessages.AUTHENTICATION_TYPE.code()); messenger.writeInt(PostgresMessenger.AUTHENTICATION_CLEAR_TEXT); messenger.sendMessage(true); } else { String user = properties.getProperty("user"); logger.info("Login {}", user); authenticationOkay(user); } return true; } protected void processCancelRequest() throws IOException { int sessionId = messenger.readInt(); int secret = messenger.readInt(); PostgresServerConnection connection = server.getConnection(sessionId); if ((connection != null) && (secret == connection.secret)) { connection.cancelQuery(null, null); } stop(); // That's all for this connection. } protected void processSSLMessage() throws IOException { OutputStream raw = messenger.getOutputStream(); if (System.getProperty("javax.net.ssl.keyStore") == null) { // JSSE doesn't have a keystore; TLSv1 handshake is gonna fail. Deny support. raw.write('N'); raw.flush(); } else { // Someone seems to have configured for SSL. Wrap the // socket and start server mode negotiation. Client should // then use SSL socket to start regular server protocol. raw.write('S'); raw.flush(); SSLSocketFactory sslFactory = (SSLSocketFactory)SSLSocketFactory.getDefault(); SSLSocket sslSocket = (SSLSocket)sslFactory.createSocket(socket, socket.getLocalAddress().toString(), socket.getLocalPort(), true); socket = sslSocket; createMessenger(); sslSocket.setUseClientMode(false); sslSocket.startHandshake(); } } protected void processPasswordMessage() throws IOException { String user = properties.getProperty("user"); String pass = messenger.readString(); logger.info("Login {}/{}", user, pass); authenticationOkay(user); } protected void authenticationOkay(String user) throws IOException { Properties status = new Properties(); // This is enough to make the JDBC driver happy. status.put("client_encoding", properties.getProperty("client_encoding", "UTF8")); status.put("server_encoding", messenger.getEncoding()); status.put("server_version", "8.4.7"); // Not sure what the min it'll accept is. status.put("session_authorization", user); status.put("DateStyle", "ISO, MDY"); { messenger.beginMessage(PostgresMessages.AUTHENTICATION_TYPE.code()); messenger.writeInt(PostgresMessenger.AUTHENTICATION_OK); messenger.sendMessage(); } for (String prop : status.stringPropertyNames()) { messenger.beginMessage(PostgresMessages.PARAMETER_STATUS_TYPE.code()); messenger.writeString(prop); messenger.writeString(status.getProperty(prop)); messenger.sendMessage(); } { messenger.beginMessage(PostgresMessages.BACKEND_KEY_DATA_TYPE.code()); messenger.writeInt(sessionId); messenger.writeInt(secret); messenger.sendMessage(); } readyForQuery(); } protected void processQuery() throws IOException { long startTime = System.currentTimeMillis(); String sql = messenger.readString(); logger.info("Query: {}", sql); if (sql.length() == 0) { emptyQuery(); return; } sessionMonitor.startStatement(sql, startTime); PostgresQueryContext context = new PostgresQueryContext(this); updateAIS(context); PostgresStatement pstmt = null; if (statementCache != null) pstmt = statementCache.get(sql); if (pstmt == null) { for (PostgresStatementParser parser : unparsedGenerators) { // Try special recognition first; only allowed to turn // into one statement. pstmt = parser.parse(this, sql, null); if (pstmt != null) { pstmt.setAISGeneration(ais.getGeneration()); break; } } } int rowsProcessed = 0; if (pstmt != null) { pstmt.sendDescription(context, false); rowsProcessed = executeStatementWithAutoTxn(pstmt, context, -1); } else { // Parse as a _list_ of statements and process each in turn. List<StatementNode> stmts; try { sessionMonitor.enterStage(MonitorStage.PARSE); stmts = parser.parseStatements(sql); } catch (SQLParserException ex) { throw new SQLParseException(ex); } catch (StandardException ex) { throw new SQLParserInternalException(ex); } finally { sessionMonitor.leaveStage(); } boolean singleStmt = (stmts.size() == 1); for (StatementNode stmt : stmts) { String stmtSQL; if (singleStmt) stmtSQL = sql; else stmtSQL = sql.substring(stmt.getBeginOffset(), stmt.getEndOffset() + 1); pstmt = generateStatementStub(stmtSQL, stmt, null, null); ServerTransaction local = beforeExecute(pstmt); boolean success = false; try { pstmt = finishGenerating(context, pstmt, stmtSQL, stmt, null, null); if ((statementCache != null) && (stmts.size() == 1)) statementCache.put(stmtSQL, pstmt); pstmt.sendDescription(context, false); rowsProcessed = executeStatement(pstmt, context, -1); success = true; } finally { afterExecute(pstmt, local, success); } } } readyForQuery(); sessionMonitor.endStatement(rowsProcessed); logger.debug("Query complete"); if (reqs.monitor().isQueryLogEnabled()) { reqs.monitor().logQuery(sessionMonitor); } } protected void processParse() throws IOException { String stmtName = messenger.readString(); String sql = messenger.readString(); short nparams = messenger.readShort(); int[] paramTypes = new int[nparams]; for (int i = 0; i < nparams; i++) paramTypes[i] = messenger.readInt(); sessionMonitor.startStatement(sql); logger.info("Parse: {}", sql); PostgresQueryContext context = new PostgresQueryContext(this); updateAIS(context); PostgresStatement pstmt = null; if (statementCache != null) pstmt = statementCache.get(sql); if (pstmt == null) { StatementNode stmt; List<ParameterNode> params; try { sessionMonitor.enterStage(MonitorStage.PARSE); stmt = parser.parseStatement(sql); params = parser.getParameterList(); } catch (SQLParserException ex) { throw new SQLParseException(ex); } catch (StandardException ex) { throw new SQLParserInternalException(ex); } finally { sessionMonitor.leaveStage(); } pstmt = generateStatementStub(sql, stmt, params, paramTypes); ServerTransaction local = beforeExecute(pstmt); boolean success = false; try { pstmt = finishGenerating(context, pstmt, sql, stmt, params, paramTypes); success = true; } finally { afterExecute(pstmt, local, success); } if (statementCache != null) statementCache.put(sql, pstmt); } preparedStatements.put(stmtName, pstmt); messenger.beginMessage(PostgresMessages.PARSE_COMPLETE_TYPE.code()); messenger.sendMessage(); } protected void processBind() throws IOException { String portalName = messenger.readString(); String stmtName = messenger.readString(); byte[][] params = null; boolean[] paramsBinary = null; { short nformats = messenger.readShort(); if (nformats > 0) { paramsBinary = new boolean[nformats]; for (int i = 0; i < nformats; i++) paramsBinary[i] = (messenger.readShort() == 1); } short nparams = messenger.readShort(); if (nparams > 0) { params = new byte[nparams][]; for (int i = 0; i < nparams; i++) { int len = messenger.readInt(); if (len < 0) continue; // Null byte[] param = new byte[len]; messenger.readFully(param, 0, len); params[i] = param; } } } boolean[] resultsBinary = null; boolean defaultResultsBinary = false; { short nresults = messenger.readShort(); if (nresults == 1) defaultResultsBinary = (messenger.readShort() == 1); else if (nresults > 0) { resultsBinary = new boolean[nresults]; for (int i = 0; i < nresults; i++) { resultsBinary[i] = (messenger.readShort() == 1); } defaultResultsBinary = resultsBinary[nresults-1]; } } PostgresStatement pstmt = preparedStatements.get(stmtName); PostgresBoundQueryContext bound = new PostgresBoundQueryContext(this, pstmt); if (params != null) { ServerValueDecoder decoder = new ServerValueDecoder(messenger.getEncoding()); PostgresType[] parameterTypes = null; boolean usePValues = false; if (pstmt instanceof PostgresBaseStatement) { PostgresDMLStatement dml = (PostgresDMLStatement)pstmt; parameterTypes = dml.getParameterTypes(); usePValues = dml.usesPValues(); } for (int i = 0; i < params.length; i++) { PostgresType pgType = null; if (parameterTypes != null) pgType = parameterTypes[i]; boolean binary = false; if ((paramsBinary != null) && (i < paramsBinary.length)) binary = paramsBinary[i]; if (usePValues) decoder.decodePValue(params[i], pgType, binary, bound, i); else decoder.decodeValue(params[i], pgType, binary, bound, i); } } bound.setColumnBinary(resultsBinary, defaultResultsBinary); boundPortals.put(portalName, bound); messenger.beginMessage(PostgresMessages.BIND_COMPLETE_TYPE.code()); messenger.sendMessage(); } protected void processDescribe() throws IOException{ byte source = messenger.readByte(); String name = messenger.readString(); PostgresStatement pstmt; PostgresQueryContext context; switch (source) { case (byte)'S': pstmt = preparedStatements.get(name); context = new PostgresQueryContext(this); break; case (byte)'P': { PostgresBoundQueryContext bound = boundPortals.get(name); pstmt = bound.getStatement(); context = bound; } break; default: throw new IOException("Unknown describe source: " + (char)source); } pstmt.sendDescription(context, true); } protected void processExecute() throws IOException { long startTime = System.currentTimeMillis(); String portalName = messenger.readString(); int maxrows = messenger.readInt(); PostgresBoundQueryContext context = boundPortals.get(portalName); PostgresStatement pstmt = context.getStatement(); logger.info("Execute: {}", pstmt); // TODO: save SQL in prepared statement and get it here. sessionMonitor.startStatement(null, startTime); int rowsProcessed = executeStatementWithAutoTxn(pstmt, context, maxrows); sessionMonitor.endStatement(rowsProcessed); logger.debug("Execute complete"); if (reqs.monitor().isQueryLogEnabled()) { reqs.monitor().logQuery(sessionMonitor); } } protected void processFlush() throws IOException { messenger.flush(); } protected void processClose() throws IOException { byte source = messenger.readByte(); String name = messenger.readString(); PostgresStatement pstmt; switch (source) { case (byte)'S': pstmt = preparedStatements.remove(name); break; case (byte)'P': pstmt = boundPortals.remove(name).getStatement(); break; default: throw new IOException("Unknown describe source: " + (char)source); } messenger.beginMessage(PostgresMessages.CLOSE_COMPLETE_TYPE.code()); messenger.sendMessage(); } protected void processTerminate() throws IOException { stop(); } public void cancelQuery(String forKillReason, String byUser) { this.cancelForKillReason = forKillReason; this.cancelByUser = byUser; // A running query checks session state for query cancelation during Cursor.next() calls. If the // query is stuck in a blocking operation, then thread interruption should unstick it. Either way, // the query should eventually throw QueryCanceledException which will be caught by topLevel(). if (session != null) { session.cancelCurrentQuery(true); } if (thread != null) { thread.interrupt(); } } public void waitAndStop() { // Wait a little bit for the connection to stop itself. for (int i = 0; i < 5; i++) { if (!running) return; try { Thread.sleep(50); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); break; } } // Force stop. stop(); } // When the AIS changes, throw everything away, since it might // point to obsolete objects. protected void updateAIS(PostgresQueryContext context) { boolean locked = false; try { if (context != null) { // If there is long-running DDL like creating an index, this is almost // always where other queries will lock. context.lock(DXLFunction.UNSPECIFIED_DDL_READ); locked = true; } DDLFunctions ddl = reqs.dxl().ddlFunctions(); AkibanInformationSchema newAIS = ddl.getAIS(session); if ((ais != null) && (ais.getGeneration() == newAIS.getGeneration())) return; // Unchanged. ais = newAIS; } finally { if (locked) { context.unlock(DXLFunction.UNSPECIFIED_DDL_READ); } } rebuildCompiler(); } protected void rebuildCompiler() { Object parserKeys = initParser(); PostgresOperatorCompiler compiler; String format = getProperty("OutputFormat", "table"); if (format.equals("table")) outputFormat = OutputFormat.TABLE; else if (format.equals("json")) outputFormat = OutputFormat.JSON; else if (format.equals("json_with_meta_data")) outputFormat = OutputFormat.JSON_WITH_META_DATA; else throw new InvalidParameterValueException(format); switch (outputFormat) { case TABLE: default: compiler = PostgresOperatorCompiler.create(this); break; case JSON: case JSON_WITH_META_DATA: compiler = PostgresJsonCompiler.create(this); break; } initAdapters(compiler); unparsedGenerators = new PostgresStatementParser[] { new PostgresEmulatedMetaDataStatementParser(this) }; parsedGenerators = new PostgresStatementGenerator[] { // Can be ordered by frequency so long as there is no overlap. compiler, new PostgresDDLStatementGenerator(this), new PostgresSessionStatementGenerator(this), new PostgresCallStatementGenerator(this), new PostgresExplainStatementGenerator(this), new PostgresServerStatementGenerator(this) }; statementCache = getStatementCache(); } protected ServerStatementCache<PostgresStatement> getStatementCache() { // Statement cache depends on some connection settings. return server.getStatementCache(Arrays.asList(parser.getFeatures(), defaultSchemaName, getProperty("OutputFormat", "table"), getBooleanProperty("cbo", true), getBooleanProperty("newtypes", false)), ais.getGeneration()); } @Override protected void sessionChanged() { if (parsedGenerators == null) return; // setAttribute() from generator's ctor. for (PostgresStatementParser parser : unparsedGenerators) { parser.sessionChanged(this); } for (PostgresStatementGenerator generator : parsedGenerators) { generator.sessionChanged(this); } statementCache = getStatementCache(); } protected PostgresStatement generateStatementStub(String sql, StatementNode stmt, List<ParameterNode> params, int[] paramTypes) { try { sessionMonitor.enterStage(MonitorStage.OPTIMIZE); for (PostgresStatementGenerator generator : parsedGenerators) { PostgresStatement pstmt = generator.generateStub(this, sql, stmt, params, paramTypes); if (pstmt != null) return pstmt; } } finally { sessionMonitor.leaveStage(); } throw new UnsupportedSQLException ("", stmt); } protected PostgresStatement finishGenerating(PostgresQueryContext context, PostgresStatement pstmt, String sql, StatementNode stmt, List<ParameterNode> params, int[] paramTypes) { try { sessionMonitor.enterStage(MonitorStage.OPTIMIZE); updateAIS(context); PostgresStatement newpstmt = pstmt.finishGenerating(this, sql, stmt, params, paramTypes); if (!newpstmt.hasAISGeneration()) newpstmt.setAISGeneration(ais.getGeneration()); return newpstmt; } finally { sessionMonitor.leaveStage(); } } protected int executeStatementWithAutoTxn(PostgresStatement pstmt, PostgresQueryContext context, int maxrows) throws IOException { ServerTransaction localTransaction = beforeExecute(pstmt); int rowsProcessed = 0; boolean success = false; try { executeStatement(pstmt, context, maxrows); success = true; } finally { afterExecute(pstmt, localTransaction, success); sessionMonitor.leaveStage(); } return rowsProcessed; } protected int executeStatement(PostgresStatement pstmt, PostgresQueryContext context, int maxrows) throws IOException { int rowsProcessed = 0; PersistitAdapter persistitAdapter = null; if ((transaction != null) && // As opposed to WRITE_STEP_ISOLATED. (pstmt.getTransactionMode() == PostgresStatement.TransactionMode.WRITE)) { persistitAdapter = (PersistitAdapter)adapters.get(StoreAdapter.AdapterType.PERSISTIT_ADAPTER); persistitAdapter.withStepChanging(false); } try { if (pstmt.getAISGenerationMode() == ServerStatement.AISGenerationMode.NOT_ALLOWED) { updateAIS(context); if (pstmt.getAISGeneration() != ais.getGeneration()) throw new StaleStatementException(); } session.setTimeoutAfterSeconds(getQueryTimeoutSec()); sessionMonitor.enterStage(MonitorStage.EXECUTE); rowsProcessed = pstmt.execute(context, maxrows); } finally { if (persistitAdapter != null) persistitAdapter.withStepChanging(true); // Keep conservative default. sessionMonitor.leaveStage(); } return rowsProcessed; } protected void emptyQuery() throws IOException { messenger.beginMessage(PostgresMessages.EMPTY_QUERY_RESPONSE_TYPE.code()); messenger.sendMessage(); readyForQuery(); } @Override public Date currentTime() { Date override = server.getOverrideCurrentTime(); if (override != null) return override; else return super.currentTime(); } @Override public void notifyClient(QueryContext.NotificationLevel level, ErrorCode errorCode, String message) throws IOException { if (shouldNotify(level)) { Object state = messenger.suspendMessage(); messenger.beginMessage(PostgresMessages.NOTICE_RESPONSE_TYPE.code()); messenger.write('S'); switch (level) { case WARNING: messenger.writeString("WARN"); break; case INFO: messenger.writeString("INFO"); break; case DEBUG: messenger.writeString("DEBUG"); break; // Other possibilities are "NOTICE" and "LOG". } if (errorCode != null) { messenger.write('C'); messenger.writeString(errorCode.getFormattedValue()); } messenger.write('M'); messenger.writeString(message); messenger.write(0); messenger.sendMessage(true); messenger.resumeMessage(state); } } /* PostgresServerSession */ @Override public int getVersion() { return version; } @Override public PostgresMessenger getMessenger() { return messenger; } @Override public OutputFormat getOutputFormat() { return outputFormat; } @Override protected boolean propertySet(String key, String value) { if ("client_encoding".equals(key)) { messenger.setEncoding(value); return true; } if ("OutputFormat".equals(key) || "parserInfixBit".equals(key) || "parserInfixLogical".equals(key) || "parserDoubleQuoted".equals(key) || "columnAsFunc".equals(key) || "cbo".equals(key) || "newtypes".equals(key)) { if (parsedGenerators != null) rebuildCompiler(); return true; } return super.propertySet(key, value); } public PostgresServer getServer() { return server; } }
package com.blackbuild.klum.common; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.AnnotatedNode; import org.codehaus.groovy.ast.AnnotationNode; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.GenericsType; import org.codehaus.groovy.ast.MethodNode; import org.codehaus.groovy.ast.Parameter; import org.codehaus.groovy.ast.PropertyNode; import org.codehaus.groovy.ast.expr.ArgumentListExpression; import org.codehaus.groovy.ast.expr.ClassExpression; import org.codehaus.groovy.ast.expr.ClosureExpression; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.ListExpression; import org.codehaus.groovy.ast.expr.MapEntryExpression; import org.codehaus.groovy.ast.expr.MapExpression; import org.codehaus.groovy.ast.expr.PropertyExpression; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.classgen.Verifier; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.messages.SyntaxErrorMessage; import org.codehaus.groovy.control.messages.WarningMessage; import org.codehaus.groovy.syntax.SyntaxException; import org.codehaus.groovy.syntax.Token; import org.codehaus.groovy.syntax.Types; import org.codehaus.groovy.transform.AbstractASTTransformation; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import static groovyjarjarasm.asm.Opcodes.ACC_ABSTRACT; import static org.codehaus.groovy.ast.ClassHelper.STRING_TYPE; import static org.codehaus.groovy.ast.ClassHelper.makeWithoutCaching; import static org.codehaus.groovy.ast.expr.CastExpression.asExpression; import static org.codehaus.groovy.ast.tools.GeneralUtils.args; import static org.codehaus.groovy.ast.tools.GeneralUtils.closureX; import static org.codehaus.groovy.ast.tools.GeneralUtils.ctorX; import static org.codehaus.groovy.ast.tools.GeneralUtils.param; import static org.codehaus.groovy.ast.tools.GeneralUtils.params; import static org.codehaus.groovy.ast.tools.GeneralUtils.varX; import static org.codehaus.groovy.ast.tools.GenericsUtils.makeClassSafe; public class CommonAstHelper { public static final ClassNode[] NO_EXCEPTIONS = ClassNode.EMPTY_ARRAY; public static final FieldNode NO_SUCH_FIELD = new FieldNode(null, 0, null, null, null); public static ClassNode COLLECTION_TYPE = makeWithoutCaching(Collection.class); public static ClassNode SORTED_MAP_TYPE = makeWithoutCaching(SortedMap.class); public static AnnotationNode getAnnotation(AnnotatedNode field, ClassNode type) { List<AnnotationNode> annotation = field.getAnnotations(type); return annotation.isEmpty() ? null : annotation.get(0); } public static boolean isCollectionOrMap(ClassNode type) { return isCollection(type) || isMap(type); } public static boolean isCollection(ClassNode type) { return type.equals(COLLECTION_TYPE) || type.implementsInterface(COLLECTION_TYPE); } public static boolean isMap(ClassNode type) { return type.equals(ClassHelper.MAP_TYPE) || type.implementsInterface(ClassHelper.MAP_TYPE); } public static boolean isAbstract(ClassNode classNode) { return (classNode.getModifiers() & ACC_ABSTRACT) != 0; } public static ListExpression listExpression(Expression... expressions) { return new ListExpression(Arrays.asList(expressions)); } static ArgumentListExpression argsWithOptionalKey(FieldNode keyField, String... otherArgs) { if (keyField == null) return args(otherArgs); ArgumentListExpression result = new ArgumentListExpression(varX("key")); for (String next : otherArgs) result.addExpression(varX(next)); return result; } public static ArgumentListExpression argsWithEmptyMapAndOptionalKey(AnnotatedNode keyField, String... otherArgs) { ArgumentListExpression result = new ArgumentListExpression(new MapExpression()); if (keyField != null) result.addExpression(varX("key")); for (String next : otherArgs) result.addExpression(varX(next)); return result; } public static ArgumentListExpression argsWithEmptyMapClassAndOptionalKey(AnnotatedNode keyField, String... otherArgs) { ArgumentListExpression result = new ArgumentListExpression(new MapExpression()); result.addExpression(varX("typeToCreate")); if (keyField != null) result.addExpression(varX("key")); for (String next : otherArgs) result.addExpression(varX(next)); return result; } public static void addCompileError(SourceUnit sourceUnit, String msg, ASTNode node) { SyntaxException se = new SyntaxException(msg, node.getLineNumber(), node.getColumnNumber()); sourceUnit.getErrorCollector().addFatalError(new SyntaxErrorMessage(se, sourceUnit)); } public static void addCompileError(String msg, AnnotatedNode node) { addCompileError(msg, node, node); } public static void addCompileError(String msg, AnnotatedNode node, ASTNode sourcePosition) { if (node instanceof FieldNode) addCompileError(msg, (FieldNode) node); else if (node instanceof ClassNode) addCompileError(msg, (ClassNode) node); else throw new IllegalStateException(node.toString() + " must be either a ClassNode or a FieldNode"); } public static void addCompileError(String msg, FieldNode node) { addCompileError(msg, node, node); } public static void addCompileError(String msg, FieldNode node, ASTNode sourcePosition) { addCompileError(node.getOwner().getModule().getContext(), msg, sourcePosition); } public static void addCompileError(String msg, ClassNode node) { addCompileError(msg, node, node); } public static void addCompileError(String msg, ClassNode node, ASTNode sourcePosition) { addCompileError(node.getModule().getContext(), msg, sourcePosition); } public static void addCompileWarning(SourceUnit sourceUnit, String msg, ASTNode node) { Token token = new Token(Types.UNKNOWN, node.getText(), node.getLineNumber(), node.getColumnNumber()); sourceUnit.getErrorCollector().addWarning(WarningMessage.LIKELY_ERRORS, msg, token, sourceUnit); } public static void assertMethodIsParameterless(MethodNode method, SourceUnit sourceUnit) { if (method.getParameters().length > 0) addCompileError(sourceUnit, "Lifecycle/Validate methods must be parameterless!", method); } public static void assertMethodIsNotPrivate(MethodNode method, SourceUnit sourceUnit) { if (method.isPrivate()) addCompileError(sourceUnit, "Lifecycle methods must not be private!", method); } public static void replaceMethod(ClassNode target, MethodNode method) { MethodNode oldMethod = target.getDeclaredMethod(method.getName(), method.getParameters()); if (oldMethod != null) target.removeMethod(oldMethod); target.addMethod(method); } public static ClosureExpression toStronglyTypedClosure(ClosureExpression validationClosure, ClassNode fieldNodeType) { String closureParameterName = validationClosure.isParameterSpecified() ? validationClosure.getParameters()[0].getName() : "it"; ClosureExpression typeValidationClosure = closureX(params(param(fieldNodeType, closureParameterName)), validationClosure.getCode()); typeValidationClosure.copyNodeMetaData(validationClosure); typeValidationClosure.setSourcePosition(validationClosure); typeValidationClosure.visit(new StronglyTypingClosureParameterVisitor(closureParameterName, fieldNodeType)); return typeValidationClosure; } static void addPropertyAsFieldWithAccessors(ClassNode cNode, PropertyNode pNode) { final FieldNode fn = pNode.getField(); cNode.getFields().remove(fn); cNode.addField(fn); Statement getterBlock = pNode.getGetterBlock(); Statement setterBlock = pNode.getSetterBlock(); int modifiers = pNode.getModifiers(); String capitalizedName = Verifier.capitalize(pNode.getName()); if (getterBlock != null) { MethodNode getter = new MethodNode("get" + capitalizedName, modifiers, pNode.getType(), Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, getterBlock); getter.setSynthetic(true); addPropertyMethod(cNode, getter); if (ClassHelper.boolean_TYPE == pNode.getType() || ClassHelper.Boolean_TYPE == pNode.getType()) { String secondGetterName = "is" + capitalizedName; MethodNode secondGetter = new MethodNode(secondGetterName, modifiers, pNode.getType(), Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, getterBlock); secondGetter.setSynthetic(true); addPropertyMethod(cNode, secondGetter); } } if (setterBlock != null) { Parameter[] setterParameterTypes = {new Parameter(pNode.getType(), "value")}; MethodNode setter = new MethodNode("set" + capitalizedName, modifiers, ClassHelper.VOID_TYPE, setterParameterTypes, ClassNode.EMPTY_ARRAY, setterBlock); setter.setSynthetic(true); addPropertyMethod(cNode, setter); } } // from Verifier static void addPropertyMethod(ClassNode classNode, MethodNode method) { classNode.addMethod(method); // GROOVY-4415 / GROOVY-4645: check that there's no abstract method which corresponds to this one List<MethodNode> abstractMethods = classNode.getAbstractMethods(); if (abstractMethods==null) return; String methodName = method.getName(); Parameter[] parameters = method.getParameters(); ClassNode methodReturnType = method.getReturnType(); for (MethodNode node : abstractMethods) { if (!node.getDeclaringClass().equals(classNode)) continue; if (node.getName().equals(methodName) && node.getParameters().length==parameters.length) { if (parameters.length==1) { // setter ClassNode abstractMethodParameterType = node.getParameters()[0].getType(); ClassNode methodParameterType = parameters[0].getType(); if (!methodParameterType.isDerivedFrom(abstractMethodParameterType) && !methodParameterType.implementsInterface(abstractMethodParameterType)) { continue; } } ClassNode nodeReturnType = node.getReturnType(); if (!methodReturnType.isDerivedFrom(nodeReturnType) && !methodReturnType.implementsInterface(nodeReturnType)) { continue; } // matching method, remove abstract status and use the same body node.setModifiers(node.getModifiers() ^ ACC_ABSTRACT); node.setCode(method.getCode()); } } } public static void replaceProperties(ClassNode annotatedClass, List<PropertyNode> newNodes) { for (PropertyNode pNode : newNodes) { annotatedClass.getProperties().remove(pNode); addPropertyAsFieldWithAccessors(annotatedClass, pNode); } } public static List<ClassNode> findAllKnownSubclassesOf(ClassNode type) { List<ClassNode> result = new ArrayList<ClassNode>(); for (ClassNode classInCU : (List<ClassNode>) type.getCompileUnit().getClasses()) if (classInCU.isDerivedFrom(type)) result.add(classInCU); return result; } @SuppressWarnings("ConstantConditions") public static GenericsType[] getGenericsTypes(FieldNode fieldNode) { GenericsType[] types = fieldNode.getType().getGenericsTypes(); if (types == null) addCompileError(fieldNode.getOwner().getModule().getContext(), "Lists and Maps need to be assigned an explicit Generic Type", fieldNode); return types; } public static ClassNode getElementType(FieldNode fieldNode) { if (isMap(fieldNode.getType())) return getGenericsTypes(fieldNode)[1].getType(); else if (isCollection(fieldNode.getType())) return getGenericsTypes(fieldNode)[0].getType(); else return fieldNode.getType(); } public static String getNullSafeMemberStringValue(AnnotationNode fieldAnnotation, String name, String defaultValue) { return fieldAnnotation == null ? defaultValue : AbstractASTTransformation.getMemberStringValue(fieldAnnotation, name, defaultValue); } public static <T extends Enum> T getNullSafeEnumMemberValue(AnnotationNode node, String name, T defaultValue) { if (node == null) return defaultValue; Expression member = node.getMember(name); if (member == null) return defaultValue; if (!(member instanceof PropertyExpression)) return defaultValue; String value = ((PropertyExpression) member).getPropertyAsString(); return (T) Enum.valueOf(defaultValue.getClass(), value); } public static void initializeCollectionOrMap(FieldNode fieldNode) { ClassNode fieldType = fieldNode.getType(); if (isCollection(fieldType)) initializeField(fieldNode, asExpression(fieldType, new ListExpression())); else if (fieldType.equals(CommonAstHelper.SORTED_MAP_TYPE)) initializeField(fieldNode, ctorX(makeClassSafe(TreeMap.class))); else if (isMap(fieldType)) initializeField(fieldNode, asExpression(fieldType, new MapExpression())); else throw new IllegalStateException("FieldNode " + fieldNode + " is no collection or Map"); } private static void initializeField(FieldNode fieldNode, Expression init) { if (!fieldNode.hasInitialExpression()) fieldNode.setInitialValueExpression(init); } public static String getQualifiedName(FieldNode node) { return node.getOwner().getName() + "." + node.getName(); } public static MapExpression getLiteralMapExpressionFromClosure(ClosureExpression closure) { BlockStatement code = (BlockStatement) closure.getCode(); if (code.getStatements().size() != 1) return null; Statement statement = code.getStatements().get(0); if (!(statement instanceof ExpressionStatement)) return null; Expression expression = ((ExpressionStatement) statement).getExpression(); if (!(expression instanceof MapExpression)) return null; return (MapExpression) expression; } public static Map<String, ClassNode> getStringClassMapFromClosure(ClosureExpression closureExpression, AnnotatedNode source) { MapExpression map = getLiteralMapExpressionFromClosure(closureExpression); if (map == null) return null; Map<String, ClassNode> result = new LinkedHashMap<String, ClassNode>(); for (MapEntryExpression entry : map.getMapEntryExpressions()) { String key = getKeyStringFromLiteralMapEntry(entry, source); ClassNode value = getClassNodeValueFromLiteralMapEntry(entry, source); result.put(key, value); } return result; } public static String getKeyStringFromLiteralMapEntry(MapEntryExpression entryExpression, AnnotatedNode source) { Expression result = entryExpression.getKeyExpression(); if (result instanceof ConstantExpression && result.getType().equals(STRING_TYPE)) return result.getText(); CommonAstHelper.addCompileError("Map keys may only be Strings.", source, entryExpression); return null; } public static ClassNode getClassNodeValueFromLiteralMapEntry(MapEntryExpression entryExpression, AnnotatedNode source) { Expression result = entryExpression.getValueExpression(); if (result instanceof ClassExpression) return result.getType(); CommonAstHelper.addCompileError("Map values may only be classes.", source, entryExpression); return null; } }
package imagej.command; import imagej.Cancelable; import imagej.module.AbstractModule; import imagej.module.ModuleException; import java.util.Map; import org.scijava.Context; import org.scijava.Contextual; import org.scijava.InstantiableException; import org.scijava.plugin.PluginInfo; import org.scijava.util.ClassUtils; /** * Module class for working with a {@link Command} instance. * * @author Curtis Rueden * @author Johannes Schindelin * @author Grant Harris */ public class CommandModule extends AbstractModule implements Cancelable, Contextual { /** The metadata describing the command. */ private final CommandInfo info; /** The command instance handled by this module. */ private final Command command; /** Creates a command module for the given {@link PluginInfo}. */ public CommandModule(final CommandInfo info) throws ModuleException { super(); this.info = info; command = instantiateCommand(); assignPresets(); } /** * Creates a command module for the given {@link CommandInfo}, around the * specified {@link Command} instance. */ public CommandModule(final CommandInfo info, final Command command) { super(); this.info = info; this.command = command; assignPresets(); } // -- CommandModule methods -- /** Gets the command instance handled by this module. */ public Command getCommand() { return command; } // -- Module methods -- /** * Computes a preview of the command's results. For this method to do * anything, the command must implement the {@link Previewable} interface. */ @Override public void preview() { if (!(command instanceof Previewable)) return; // cannot preview final Previewable previewPlugin = (Previewable) command; previewPlugin.preview(); } /** * Cancels the command, undoing the effects of any {@link #preview()} calls. * For this method to do anything, the command must implement the * {@link Previewable} interface. */ @Override public void cancel() { if (!(command instanceof Previewable)) return; // nothing to cancel final Previewable previewPlugin = (Previewable) command; previewPlugin.cancel(); } @Override public CommandInfo getInfo() { return info; } @Override public Object getDelegateObject() { return command; } @Override public Object getInput(final String name) { final CommandModuleItem<?> item = info.getInput(name); return ClassUtils.getValue(item.getField(), command); } @Override public Object getOutput(final String name) { final CommandModuleItem<?> item = info.getOutput(name); return ClassUtils.getValue(item.getField(), command); } @Override public void setInput(final String name, final Object value) { final CommandModuleItem<?> item = info.getInput(name); ClassUtils.setValue(item.getField(), command, value); } @Override public void setOutput(final String name, final Object value) { final CommandModuleItem<?> item = info.getOutput(name); ClassUtils.setValue(item.getField(), command, value); } // -- Object methods -- @Override public String toString() { return command.getClass().getName(); } // -- Runnable methods -- @Override public void run() { command.run(); } // -- Cancelable methods -- @Override public boolean isCanceled() { if (!(command instanceof Cancelable)) return false; return ((Cancelable) command).isCanceled(); } @Override public String getCancelReason() { if (!(command instanceof Cancelable)) return null; return ((Cancelable) command).getCancelReason(); } // -- Contextual methods -- @Override public Context getContext() { if (!(command instanceof Contextual)) return null; return ((Contextual) command).getContext(); } @Override public void setContext(final Context context) { if (!(command instanceof Contextual)) return; // ignore context injection ((Contextual) command).setContext(context); } // -- Helper methods -- private Command instantiateCommand() throws ModuleException { try { return info.createInstance(); } catch (final InstantiableException exc) { throw new ModuleException(exc); } } private void assignPresets() { final Map<String, Object> presets = info.getPresets(); for (final String name : presets.keySet()) { final Object value = presets.get(name); setInput(name, value); setResolved(name, true); } } }
package com.comandante.creeper.Items; import com.comandante.creeper.managers.GameManager; import com.comandante.creeper.player.Player; import com.comandante.creeper.server.Color; import com.comandante.creeper.world.Area; import com.comandante.creeper.world.Room; import org.apache.log4j.Logger; import java.util.Random; import java.util.Set; import static java.lang.Math.pow; import static java.lang.StrictMath.sqrt; public class ForageManager { public final GameManager gameManager; private static final Random random = new Random(); private static final Logger log = Logger.getLogger(ForageManager.class); public ForageManager(GameManager gameManager) { this.gameManager = gameManager; } public void addForageToArea(Area area, ForageBuilder forageBuilder) { Set<Room> roomsByArea = gameManager.getRoomManager().getRoomsByArea(area); for (Room room: roomsByArea) { Forage newForage = forageBuilder.createForage(); room.addForage(newForage); gameManager.getEntityManager().addEntity(newForage); } } public void forageDelay(Player player) { gameManager.getChannelUtils().write(player.getPlayerId(), "You scan the ground for plants, herbs and fungi...\r\n"); final int foragingLevel = getLevel(gameManager.getPlayerManager().getPlayerMetadata(player.getPlayerId()).getStats().getForaging()); final int scourTime = 1000 - getForageDelayTime(foragingLevel); for (int i = 0; i < 3; i++) { try { if (scourTime > 0) { Thread.sleep(scourTime); } if (i==0){ gameManager.getChannelUtils().write(player.getPlayerId(), "\r\n"); } else if (i==1) { gameManager.getChannelUtils().write(player.getPlayerId(), "searching..." + "\r\n"); } else { gameManager.getChannelUtils().write(player.getPlayerId(), "\r\n"); } } catch (InterruptedException e) { log.error(e); } } } public void getForageForRoom(Room room, Player player) { forageDelay(player); int countOfForagesFound = 0; int totalForageXp = 0; try { for (Forage forage : room.getForages().values()) { int foragingLevel = getLevel(gameManager.getPlayerManager().getPlayerMetadata(player.getPlayerId()).getStats().getForaging()); if (forage.getMinLevel() > foragingLevel) { // System.out.println("Foraging level not high enough."); return; } if (forage.getCoolDownTicksLeft() > 0) { //System.out.println("Forage is still cooling down. Ticks left: " + forage.getCoolDownTicksLeft()); return; } forage.setCoolDownTicksLeft(forage.getCoolDownTicks()); double foragePctOfSuccess = forage.getPctOfSuccess(); int modifiedLevelForForage = getLevel(gameManager.getEquipmentManager().getPlayerStatsWithEquipment(player).getForaging()); int pctSuccessBoostForLevel = getPctSuccessBoostForLevel(modifiedLevelForForage); //System.out.println("you get a boost of " + pctSuccessBoostForLevel); foragePctOfSuccess = foragePctOfSuccess + pctSuccessBoostForLevel; //System.out.println("final pct of success for forage: " + foragePctOfSuccess); if (getRandPercent(foragePctOfSuccess)) { gameManager.getPlayerManager().updatePlayerForageExperience(player, forage.getForageExperience()); int numberToHarvest = randInt(forage.getMinAmt(), forage.getMaxAmt()); totalForageXp += forage.getForageExperience(); for (int i = 0; i < numberToHarvest; i++) { countOfForagesFound++; Item item = forage.getItemType().create(); gameManager.getEntityManager().saveItem(item); gameManager.acquireItem(player, item.getItemId()); } gameManager.writeToRoom(room.getRoomId(), player.getPlayerName() + " foraged (" + numberToHarvest + ") " + forage.getItemType().getItemName() + "\r\n"); } else { gameManager.getChannelUtils().write(player.getPlayerId(), "Attempt to forage " + forage.getItemType().getItemName() + " failed.\r\n"); //System.out.println("failed to obtain forage, random pctsuccess failed."); } } } finally { if (totalForageXp > 0) { gameManager.getChannelUtils().write(player.getPlayerId(), "You gained " + Color.GREEN + "+" + totalForageXp + Color.RESET + " forage experience points." + "\r\n", true); } if (countOfForagesFound == 0) { gameManager.getChannelUtils().write(player.getPlayerId(), "Nothing foraged." + "\r\n"); return; } } } private static int randInt(int min, int max) { return random.nextInt((max - min) + 1) + min; } public static boolean getRandPercent(double percent) { double rangeMin = 0; double rangeMax = 100; double randomValue = rangeMin + (rangeMax - rangeMin) * random.nextDouble(); return randomValue <= percent; } private static double FORAGE_EXP_CONSTANT_MODIFIER = 0.05; private static double FORAGE_LEVEL_PCT_BOOST_MODIFIER = 3; private static double FORAGE_DELAY_TIME_CALCULATION_MODIFIER = 1.91; public static int getPctSuccessBoostForLevel(int level) { double v = FORAGE_LEVEL_PCT_BOOST_MODIFIER * sqrt(level); return (int) Math.ceil(v); } public static int getLevel(int experience) { double v = FORAGE_EXP_CONSTANT_MODIFIER * sqrt(experience); return (int) Math.floor(v); } public static int getXp(int level) { double v = pow(level, 2) / pow(FORAGE_EXP_CONSTANT_MODIFIER, 2); return (int) Math.ceil(v); } public static int getForageDelayTime(int level) { double v = pow(level, 2) / pow(FORAGE_DELAY_TIME_CALCULATION_MODIFIER, 2); return (int) Math.ceil(v); } public static void main(String[] args) throws InterruptedException { int i = 0; while (i < 1000000) { int level = getLevel(i); System.out.println("xp is: " + i + " level is: " + level + " double checking math: " + getXp(level)); i = i + 1000; } int level = 0; while (level < 60) { level++; int xp = getXp(level); System.out.println("level: " + level + " is " + xp + "exp."); } level = 0; while (level < 60) { level++; int xp = getPctSuccessBoostForLevel(level); System.out.println("level: " + level + " is bosted by " + xp + "pct."); } level = 0; while (level < 60) { level++; int xp = getForageDelayTime(level); System.out.println("level: " + level + " will delay by: " + xp + "ms"); } Thread.sleep(-1000); } }
package de.dentrassi.pm.r5; import static de.dentrassi.osgi.utils.Filters.and; import static de.dentrassi.osgi.utils.Filters.pair; import static de.dentrassi.osgi.utils.Filters.versionRange; import java.io.IOException; import java.io.OutputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.function.Supplier; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.osgi.framework.Version; import de.dentrassi.osgi.utils.Filters; import de.dentrassi.osgi.utils.Filters.Node; import de.dentrassi.pm.VersionInformation; import de.dentrassi.pm.aspect.common.osgi.OsgiAspectFactory; import de.dentrassi.pm.aspect.common.spool.OutputSpooler; import de.dentrassi.pm.aspect.common.spool.SpoolOutTarget; import de.dentrassi.pm.common.ArtifactInformation; import de.dentrassi.pm.common.MetaKey; import de.dentrassi.pm.common.utils.IOConsumer; import de.dentrassi.pm.osgi.bundle.BundleInformation; import de.dentrassi.pm.osgi.bundle.BundleInformation.BundleRequirement; import de.dentrassi.pm.osgi.bundle.BundleInformation.PackageExport; import de.dentrassi.pm.osgi.bundle.BundleInformation.PackageImport; public class RepositoryCreator { private static final MetaKey KEY_SHA_256 = new MetaKey ( "hasher", "sha256" ); private static final DateFormat OBR_DATE_FORMAT = new SimpleDateFormat ( "YYYYMMDDHHmmss.SSS" ); private static final String FRAMEWORK_PACKAGE = "org.osgi.framework"; private final OutputSpooler indexStreamBuilder; private final String name; private final Function<ArtifactInformation, String> urlProvider; private final Supplier<XMLOutputFactory> outputFactory; private final OutputSpooler obrStreamBuilder; public static interface Context { public void addArtifact ( ArtifactInformation artifact ) throws IOException; } private static class ContextImpl implements Context { private final XMLStreamWriter indexWriter; private final XMLStreamWriter obrWriter; private final Function<ArtifactInformation, String> urlProvider; public ContextImpl ( final XMLStreamWriter indexWriter, final XMLStreamWriter obrWriter, final Function<ArtifactInformation, String> urlProvider ) { this.indexWriter = indexWriter; this.obrWriter = obrWriter; this.urlProvider = urlProvider; } @Override public void addArtifact ( final ArtifactInformation art ) throws IOException { final Map<MetaKey, String> md = art.getMetaData (); final BundleInformation bi = OsgiAspectFactory.fetchBundleInformation ( md ); if ( bi == null ) { return; } if ( bi.getId () == null || bi.getVersion () == null ) { return; } try { addIndexEntry ( art, bi ); addObrEntry ( art, bi ); } catch ( final XMLStreamException e ) { throw new IOException ( e ); } } private void addIndexEntry ( final ArtifactInformation art, final BundleInformation bi ) throws XMLStreamException { this.indexWriter.writeStartElement ( "resource" ); this.indexWriter.writeCharacters ( "\n" ); addIndexIdentity ( this.indexWriter, bi ); addIndexContent ( this.indexWriter, art, this.urlProvider.apply ( art ) ); addIndexDependencies ( this.indexWriter, bi ); this.indexWriter.writeEndElement (); this.indexWriter.writeCharacters ( "\n\n" ); } private void addObrEntry ( final ArtifactInformation art, final BundleInformation bi ) throws XMLStreamException { this.obrWriter.writeStartElement ( "resource" ); this.obrWriter.writeAttribute ( "id", art.getId () ); this.obrWriter.writeAttribute ( "symbolicname", bi.getId () ); this.obrWriter.writeAttribute ( "version", "" + bi.getVersion () ); if ( bi.getName () != null ) { this.obrWriter.writeAttribute ( "presentationname", bi.getName () ); } this.obrWriter.writeAttribute ( "uri", this.urlProvider.apply ( art ) ); this.obrWriter.writeCharacters ( "\n" ); // resource addObrMainTag ( this.obrWriter, "size", "" + art.getSize () ); if ( bi.getDocUrl () != null && !bi.getDocUrl ().isEmpty () ) { addObrMainTag ( this.obrWriter, "documentation", "" + bi.getDocUrl () ); } if ( bi.getDescription () != null && !bi.getDescription ().isEmpty () ) { addObrMainTag ( this.obrWriter, "description", "" + bi.getDescription () ); } addObrDependencies ( this.obrWriter, bi ); this.obrWriter.writeEndElement (); this.obrWriter.writeCharacters ( "\n\n" ); } private static void addObrMainTag ( final XMLStreamWriter obrWriter, final String name, final String value ) throws XMLStreamException { if ( value == null ) { return; } obrWriter.writeCharacters ( "\t" ); obrWriter.writeStartElement ( name ); obrWriter.writeCharacters ( value ); obrWriter.writeEndElement (); obrWriter.writeCharacters ( "\n" ); } } private static void addIndexIdentity ( final XMLStreamWriter writer, final BundleInformation bi ) throws XMLStreamException { final Map<String, Object> caps = new HashMap<> (); caps.put ( "osgi.identity", bi.getId () ); caps.put ( "version", bi.getVersion () ); caps.put ( "type", "osgi.bundle" ); addIndexCapability ( writer, "osgi.identity", caps ); } public static void addIndexDependencies ( final XMLStreamWriter writer, final BundleInformation bi ) throws XMLStreamException { { final List<Node> nodes = new LinkedList<> (); for ( final String ee : bi.getRequiredExecutionEnvironments () ) { nodes.add ( pair ( "osgi.ee", ee ) ); } if ( !nodes.isEmpty () ) { final Map<String, String> reqs = new HashMap<> ( 1 ); reqs.put ( "filter", Filters.or ( nodes ) ); addIndexRequirement ( writer, "osgi.ee", reqs ); } } { final Map<String, Object> caps = new HashMap<> (); caps.put ( "osgi.wiring.bundle", bi.getId () ); caps.put ( "bundle-version", bi.getVersion () ); addIndexCapability ( writer, "osgi.wiring.bundle", caps ); } { final Map<String, Object> caps = new HashMap<> (); caps.put ( "osgi.wiring.host", bi.getId () ); caps.put ( "bundle-version", bi.getVersion () ); addIndexCapability ( writer, "osgi.wiring.host", caps ); } for ( final BundleRequirement br : bi.getBundleRequirements () ) { final Map<String, String> reqs = new HashMap<> (); final String filter = and ( pair ( "osgi.wiring.bundle", br.getId () ), versionRange ( "bundle-version", br.getVersionRange () ) ); reqs.put ( "filter", filter ); addIndexRequirement ( writer, "osgi.wiring.bundle", reqs ); } for ( final PackageExport pe : bi.getPackageExports () ) { final Map<String, Object> caps = new HashMap<> (); caps.put ( "osgi.wiring.package", pe.getName () ); if ( pe.getVersion () != null ) { caps.put ( "version", pe.getVersion () ); } addIndexCapability ( writer, "osgi.wiring.package", caps ); // Add a 'osgi.contract' capability if this bundle is a framework package if ( FRAMEWORK_PACKAGE.equals ( pe.getName() ) ) { Version specVersion = mapFrameworkPackageVersion ( pe.getVersion () ); if ( specVersion != null ) { final Map<String, Object> frameworkCaps = new HashMap<> (); frameworkCaps.put ( "osgi.contract", "OSGiFramework" ); frameworkCaps.put ( "version", specVersion ); addIndexCapability ( writer, "osgi.contract", frameworkCaps ); } } } for ( final PackageImport pi : bi.getPackageImports () ) { final Map<String, String> reqs = new HashMap<> (); final String filter = and ( pair ( "osgi.wiring.package", pi.getName () ), versionRange ( "version", pi.getVersionRange () ) ); reqs.put ( "filter", filter ); if(pi.isOptional()) { reqs.put ( "resolution", "optional"); } addIndexRequirement ( writer, "osgi.wiring.package", reqs ); } } public static void addObrDependencies ( final XMLStreamWriter writer, final BundleInformation bi ) throws XMLStreamException { { final List<Node> nodes = new LinkedList<> (); for ( final String ee : bi.getRequiredExecutionEnvironments () ) { nodes.add ( pair ( "ee", ee ) ); } if ( !nodes.isEmpty () ) { final String filter = Filters.or ( nodes ); addObrRequirement ( writer, "ee", filter, false, false, false, String.format ( "Execution Environment %s", filter ) ); } } { final Map<String, Object> caps = new HashMap<> (); caps.put ( "symbolicname", bi.getId () ); if ( bi.getName () != null ) { caps.put ( "presentationname", bi.getName () ); } caps.put ( "version", bi.getVersion () ); caps.put ( "manifestversion", "2" ); // FIXME: provide real manifest version addObrCapability ( writer, "bundle", caps ); } for ( final BundleRequirement br : bi.getBundleRequirements () ) { final String filter = and ( pair ( "symbolicname", br.getId () ), versionRange ( "version", br.getVersionRange () ) ); addObrRequirement ( writer, "bundle", filter, false, false, br.isOptional (), br.toString () ); } for ( final PackageExport pe : bi.getPackageExports () ) { final Map<String, Object> caps = new HashMap<> (); caps.put ( "package", pe.getName () ); if ( pe.getVersion () != null ) { caps.put ( "version", pe.getVersion () ); } else { caps.put ( "version", "0.0.0" ); } if ( pe.getUses () != null ) { caps.put ( ":uses", pe.getUses () ); } addObrCapability ( writer, "package", caps ); } for ( final PackageImport pi : bi.getPackageImports () ) { final String filter = and ( pair ( "package", pi.getName () ), versionRange ( "version", pi.getVersionRange () ) ); addObrRequirement ( writer, "package", filter, false, false, pi.isOptional (), pi.toString () ); } } private static void addIndexRequirement ( final XMLStreamWriter writer, final String id, final Map<String, String> caps ) throws XMLStreamException { writer.writeCharacters ( "\t" ); writer.writeStartElement ( "requirement" ); writer.writeAttribute ( "namespace", id ); writer.writeCharacters ( "\n" ); for ( final Map.Entry<String, String> entry : caps.entrySet () ) { writer.writeCharacters ( "\t\t" ); writer.writeEmptyElement ( "directive" ); writer.writeAttribute ( "name", entry.getKey () ); writer.writeAttribute ( "value", entry.getValue () ); writer.writeCharacters ( "\n" ); } writer.writeCharacters ( "\t" ); writer.writeEndElement (); writer.writeCharacters ( "\n" ); } private static void addObrRequirement ( final XMLStreamWriter writer, final String id, final String filter, final boolean extend, final boolean multiple, final boolean optional, final String text ) throws XMLStreamException { writer.writeCharacters ( "\t" ); writer.writeStartElement ( "require" ); writer.writeAttribute ( "name", id ); writer.writeAttribute ( "filter", filter ); writer.writeAttribute ( "extend", "" + extend ); writer.writeAttribute ( "multiple", "" + multiple ); writer.writeAttribute ( "optional", "" + optional ); writer.writeCharacters ( text ); writer.writeEndElement (); writer.writeCharacters ( "\n" ); } private static void addIndexContent ( final XMLStreamWriter writer, final ArtifactInformation a, final String url ) throws XMLStreamException { final String sha256 = a.getMetaData ().get ( KEY_SHA_256 ); if ( sha256 == null ) { return; } final Map<String, Object> caps = new HashMap<> ( 4 ); caps.put ( "osgi.content", sha256 ); caps.put ( "size", a.getSize () ); caps.put ( "mime", "application/vnd.osgi.bundle" ); caps.put ( "url", url ); addIndexCapability ( writer, "osgi.content", caps ); } private static void addIndexCapability ( final XMLStreamWriter writer, final String id, final Map<String, Object> caps ) throws XMLStreamException { writer.writeCharacters ( "\t" ); writer.writeStartElement ( "capability" ); writer.writeAttribute ( "namespace", id ); writer.writeCharacters ( "\n" ); for ( final Map.Entry<String, Object> entry : caps.entrySet () ) { writer.writeCharacters ( "\t\t" ); writer.writeEmptyElement ( "attribute" ); writer.writeAttribute ( "name", entry.getKey () ); final Object v = entry.getValue (); if ( ! ( v instanceof String ) ) { writer.writeAttribute ( "type", v.getClass ().getSimpleName () ); } writer.writeAttribute ( "value", "" + v ); writer.writeCharacters ( "\n" ); } writer.writeCharacters ( "\t" ); writer.writeEndElement (); writer.writeCharacters ( "\n" ); } private static void addObrCapability ( final XMLStreamWriter writer, final String id, final Map<String, Object> caps ) throws XMLStreamException { writer.writeCharacters ( "\t" ); writer.writeStartElement ( "capability" ); writer.writeAttribute ( "name", id ); writer.writeCharacters ( "\n" ); for ( final Map.Entry<String, Object> entry : caps.entrySet () ) { writer.writeCharacters ( "\t\t" ); writer.writeEmptyElement ( "p" ); writer.writeAttribute ( "n", entry.getKey () ); final Object v = entry.getValue (); if ( v instanceof Version ) { writer.writeAttribute ( "t", v.getClass ().getSimpleName ().toLowerCase () ); } writer.writeAttribute ( "v", "" + v ); writer.writeCharacters ( "\n" ); } writer.writeCharacters ( "\t" ); writer.writeEndElement (); writer.writeCharacters ( "\n" ); } public RepositoryCreator ( final String name, final SpoolOutTarget target, final Function<ArtifactInformation, String> urlProvider, final Supplier<XMLOutputFactory> outputFactory ) { this.name = name; this.urlProvider = urlProvider; this.outputFactory = outputFactory; this.indexStreamBuilder = new OutputSpooler ( target ); this.indexStreamBuilder.addOutput ( "index.xml", "application/xml" ); this.obrStreamBuilder = new OutputSpooler ( target ); this.obrStreamBuilder.addOutput ( "obr.xml", "application/xml" ); } public RepositoryCreator ( final String name, final SpoolOutTarget target, final Function<ArtifactInformation, String> urlProvider ) { this ( name, target, urlProvider, XMLOutputFactory::newFactory ); } public void process ( final IOConsumer<Context> consumer ) throws IOException { final XMLOutputFactory xml = this.outputFactory.get (); this.indexStreamBuilder.open ( indexStream -> { this.obrStreamBuilder.open ( obrStream -> { try { processStreams ( consumer, xml, indexStream, obrStream ); } catch ( final Exception e ) { throw new IOException ( e ); } } ); } ); } private void processStreams ( final IOConsumer<Context> consumer, final XMLOutputFactory xml, final OutputStream indexStream, final OutputStream obrStream ) throws XMLStreamException, IOException { final XMLStreamWriter indexWriter = xml.createXMLStreamWriter ( indexStream ); final XMLStreamWriter obrWriter = xml.createXMLStreamWriter ( obrStream ); try { startIndex ( indexWriter ); startObr ( obrWriter ); final ContextImpl ctx = new ContextImpl ( indexWriter, obrWriter, this.urlProvider ); consumer.accept ( ctx ); endObr ( obrWriter ); endIndex ( indexWriter ); } finally { indexWriter.close (); obrWriter.close (); } } private void startIndex ( final XMLStreamWriter xsw ) throws XMLStreamException { xsw.writeStartDocument (); xsw.writeCharacters ( "\n\n" ); xsw.writeComment ( String.format ( "Created by Package Drone %s - %tc", VersionInformation.VERSION, new Date () ) ); xsw.writeStartElement ( "repository" ); xsw.writeDefaultNamespace ( "http: xsw.writeAttribute ( "increment", "" + System.currentTimeMillis () ); xsw.writeAttribute ( "name", this.name ); xsw.writeCharacters ( "\n\n" ); } private void endIndex ( final XMLStreamWriter xsw ) throws XMLStreamException { xsw.writeEndElement (); // repository xsw.writeEndDocument (); } private void startObr ( final XMLStreamWriter xsw ) throws XMLStreamException { xsw.writeStartDocument (); xsw.writeCharacters ( "\n\n" ); xsw.writeComment ( String.format ( "Created by Package Drone %s - %tc", VersionInformation.VERSION, new Date () ) ); xsw.writeStartElement ( "repository" ); xsw.writeAttribute ( "lastmodified", OBR_DATE_FORMAT.format ( new Date () ) ); xsw.writeAttribute ( "name", this.name ); xsw.writeCharacters ( "\n\n" ); } private void endObr ( final XMLStreamWriter xsw ) throws XMLStreamException { xsw.writeEndElement (); // repository xsw.writeEndDocument (); } private static Version mapFrameworkPackageVersion ( final Version pv ) { if (pv.getMajor() != 1) return null; Version version; switch (pv.getMinor()) { case 7: version = new Version(5, 0, 0); break; case 6: version = new Version(4, 3, 0); break; case 5: version = new Version(4, 2, 0); break; case 4: version = new Version(4, 1, 0); break; case 3: version = new Version(4, 0, 0); break; case 2: version = new Version(3, 0, 0); break; case 1: version = new Version(2, 0, 0); break; case 0: version = new Version(1, 0, 0); break; default: version = null; break; } return version; } }
package com.conveyal.r5.analyst.cluster; import com.conveyal.r5.transit.TransitLayer; import com.conveyal.r5.transit.path.Path; import com.conveyal.r5.transit.path.PatternSequence; import com.conveyal.r5.transit.path.RouteSequence; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import gnu.trove.list.TIntList; import org.apache.commons.lang3.ArrayUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.StringJoiner; import java.util.stream.Collectors; import java.util.stream.IntStream; import static com.google.common.base.Preconditions.checkState; /** * Holds paths and associated details from an origin to destination target(s) at every Raptor iteration. For * single-point tasks, paths to only a single destination (specified by toLon and toLat coordinates in the task) are * recorded. * * This class is used to accumulate paths to be returned to the broker (similar to TravelTimeResult). In contrast, * workers use PathWriter to write paths directly to S3 for Taui sites. */ public class PathResult { private final int nDestinations; /** * Array with one entry per destination. Each entry is a map from a "path template" (i.e. a route-based path * ignoring per-iteration details such as wait time) to the associated iteration details. */ private final Multimap<RouteSequence, Iteration>[] iterationsForPathTemplates; private final TransitLayer transitLayer; public static String[] DATA_COLUMNS = new String[]{ "routes", "boardStops", "alightStops", "rideTimes", "accessTime", "egressTime", "transferTime", "waitTimes", "totalTime", "nIterations" }; public PathResult(AnalysisWorkerTask task, TransitLayer transitLayer) { if (task instanceof TravelTimeSurfaceTask) { // In interactive single-point tasks, paths are only returned for one destination nDestinations = 1; } else { // In regional analyses, return paths to all destinations nDestinations = task.nTargetsPerOrigin(); // This limitation reflects the initial design, for use with freeform pointset destinations if (nDestinations > 5000) throw new UnsupportedOperationException("Path results are limited to 5000 " + "destinations"); } iterationsForPathTemplates = new Multimap[nDestinations]; this.transitLayer = transitLayer; } public void setTarget(int targetIndex, Multimap<PatternSequence, Iteration> patterns) { Multimap<RouteSequence, Iteration> routes = HashMultimap.create(); // Not a lambda because map is also read when summarizing iterations? // for (Map.Entry<PatternSequence, Iteration> entry : patterns.entries()) { // routes.put(new RouteSequence(entry.getKey(), this.transitLayer), entry.getValue()); patterns.forEach(((patternSequence, iteration) -> routes.put(new RouteSequence(patternSequence, transitLayer), iteration))); iterationsForPathTemplates[targetIndex] = routes; } public static class Iteration { public int departureTime; public TIntList waitTimes; public int totalTime; public Iteration(Path path, int totalTime) { this.departureTime = path.departureTime; this.waitTimes = path.waitTimes; this.totalTime = totalTime; } } public static class HumanReadableIteration { public String departureTime; public double[] waitTimes; public double totalTime; HumanReadableIteration(Iteration iteration) { this.departureTime = String.format("%02d:%02d", Math.floorDiv(iteration.departureTime, 3600), (int) (iteration.departureTime / 60.0 % 60)); this.waitTimes = Arrays.stream(iteration.waitTimes.toArray()).mapToDouble( wait -> Math.round(wait / 60f * 10) / 10.0 ).toArray(); this.totalTime = Math.round(iteration.totalTime / 60f * 10) / 10.0; } } /** * Summary of iterations for each destination. Conversion to strings happens here (on distributed workers) to * minimize pressure on central assembler. * * @param stat whether the reported per-leg wait times should correspond to the iteration with the minimum or mean * total waiting time. * @return For each destination, a list of String[]s summarizing path templates. For each path template, details * of the itinerary with waiting time closest to the requested stat are included. */ public ArrayList<String[]>[] summarizeIterations(Stat stat) { ArrayList<String[]>[] summary = new ArrayList[nDestinations]; for (int d = 0; d < nDestinations; d++) { summary[d] = new ArrayList<>(); Multimap<RouteSequence, Iteration> iterationMap = iterationsForPathTemplates[d]; if (iterationMap != null) { for (Map.Entry<RouteSequence, Collection<Iteration>> entry : iterationMap.asMap().entrySet()) { Collection<Iteration> iterations = entry.getValue(); int nIterations = iterations.size(); checkState(nIterations > 0, "A path was stored without any iterations"); String waitTimes = null; String totalTime = null; String[] path = entry.getKey().detailsWithGtfsIds(transitLayer); double targetValue; IntStream totalWaits = iterations.stream().mapToInt(i -> i.waitTimes.sum()); if (stat == Stat.MINIMUM) { targetValue = totalWaits.min().orElse(-1); } else if (stat == Stat.MEAN){ targetValue = totalWaits.average().orElse(-1); } else { throw new RuntimeException("Unrecognized statistic for path summary"); } double score = Double.MAX_VALUE; for (Iteration iteration: iterations) { StringJoiner waits = new StringJoiner("|"); // TODO clean up, maybe re-using approaches from PathScore? double thisScore = Math.abs(targetValue - iteration.waitTimes.sum()); if (thisScore < score) { iteration.waitTimes.forEach(w -> { waits.add(String.format("%.1f", w / 60f)); return true; }); waitTimes = waits.toString(); totalTime = String.format("%.1f", iteration.totalTime / 60f); if (thisScore == 0) break; score = thisScore; } } String[] row = ArrayUtils.addAll(path, waitTimes, totalTime, String.valueOf(nIterations)); checkState(row.length == DATA_COLUMNS.length); summary[d].add(row); } } } return summary; } public enum Stat { MEAN, MINIMUM } /** * Wraps path and iteration details for JSON serialization */ public static class PathIterations { public String access; // StreetTimesAndModes.StreetTimeAndMode would be more machine-readable. public String egress; public Collection<RouteSequence.TransitLeg> transitLegs; public Collection<HumanReadableIteration> iterations; PathIterations(RouteSequence pathTemplate, TransitLayer transitLayer, Collection<Iteration> iterations) { this.access = pathTemplate.stopSequence.access.toString(); this.egress = pathTemplate.stopSequence.egress.toString(); this.transitLegs = pathTemplate.transitLegs(transitLayer); this.iterations = iterations.stream().map(HumanReadableIteration::new).collect(Collectors.toList()); } } /** * Returns human-readable details of path iterations, for JSON representation (e.g. in the UI console). */ List<PathIterations> getPathIterationsForDestination() { checkState(iterationsForPathTemplates.length == 1, "Paths were stored for multiple " + "destinations, but only one is being requested"); List<PathIterations> detailsForDestination = new ArrayList<>(); Multimap<RouteSequence, Iteration> iterationMap = iterationsForPathTemplates[0]; if (iterationMap != null) { for (RouteSequence pathTemplate : iterationMap.keySet()) { detailsForDestination.add(new PathIterations(pathTemplate, transitLayer, iterationMap.get(pathTemplate).stream().sorted(Comparator.comparingInt(p -> p.departureTime)) .collect(Collectors.toList()) )); } } return detailsForDestination; } }
package org.drools.reteoo; import java.util.ArrayList; import java.util.List; import org.drools.common.InternalFactHandle; import org.drools.rule.Declaration; import org.drools.spi.Activation; import org.drools.spi.Tuple; import org.drools.util.BaseEntry; public class ReteTuple extends BaseEntry implements Tuple { private static final long serialVersionUID = 320L; private int index; private final InternalFactHandle handle; private ReteTuple parent; private Activation activation; private long recency; private int hashCode; // Constructors public ReteTuple(final InternalFactHandle handle) { this.index = 0; this.parent = null; this.recency = handle.getRecency(); this.handle = handle; this.hashCode = handle.hashCode(); } public ReteTuple(final ReteTuple tuple) { this.index = tuple.index; this.parent = tuple.parent; this.recency = tuple.recency; this.handle = tuple.handle; this.hashCode = tuple.hashCode(); } public ReteTuple(final ReteTuple parentTuple, final InternalFactHandle handle) { this.index = parentTuple.index + 1; this.parent = parentTuple; this.recency = parentTuple.recency + handle.getRecency(); this.handle = handle; this.hashCode = parentTuple.hashCode ^( handle.hashCode() * 31 ); } public InternalFactHandle get(int index) { ReteTuple entry = this; while ( entry.index != index ) { entry = entry.parent; } return entry.handle; } public InternalFactHandle getLastHandle() { return this.handle; } public InternalFactHandle get(Declaration declaration) { return get( declaration.getColumn().getIndex() ); } public Activation getActivation() { return this.activation; } public InternalFactHandle[] getFactHandles() { List list = new ArrayList(); ReteTuple entry = this; while ( entry != null ) { list.add( entry.handle ); entry = entry.parent; } return (InternalFactHandle[]) list.toArray( new InternalFactHandle[list.size()] ); } public long getRecency() { return this.recency; } public void setActivation(Activation activation) { this.activation = activation; } public int hashCode() { return this.handle.hashCode(); } /** * We use this equals method to avoid the cast * @param tuple * @return */ public boolean equals(ReteTuple other) { // we know the object is never null and always of the type ReteTuple if ( other == this ) { return true; } // A ReteTuple is only the same if it has the same hashCode, factId and parent if ( this.hashCode != other.hashCode ) { return false; } if ( this.handle.getId() != other.handle.getId() ) { return false; } return this.parent.equals( other.parent ); } public boolean equals(Object object) { // we know the object is never null and always of the type ReteTuple return equals((ReteTuple)object); } }
package backtype.storm.topology.base; import backtype.storm.transactional.ITransactionalSpout; import java.util.Map; public abstract class BaseTransactionalSpout implements ITransactionalSpout { String _id; public BaseTransactionalSpout(String id) { _id = id; } @Override public Map<String, Object> getComponentConfiguration() { return null; } @Override public String getId() { return _id; } }
package com.elmakers.mine.bukkit.entity; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.logging.Level; import org.bukkit.Art; import org.bukkit.DyeColor; import org.bukkit.Location; import org.bukkit.Rotation; import org.bukkit.block.BlockFace; import org.bukkit.entity.*; import org.bukkit.entity.Skeleton.SkeletonType; import org.bukkit.inventory.ItemStack; import org.bukkit.material.Colorable; import org.bukkit.potion.PotionEffect; import org.bukkit.util.Vector; /** * This class stores information about an Entity. * */ public class EntityData implements com.elmakers.mine.bukkit.api.entity.EntityData { protected static Map<UUID, WeakReference<Entity>> respawned = new HashMap<UUID, WeakReference<Entity>>(); protected WeakReference<Entity> entity = null; protected UUID uuid = null; protected Location location; protected boolean hasMoved = false; protected boolean isTemporary = false; protected String name = null; protected EntityType type; protected Art art; protected BlockFace facing; protected Rotation rotation; protected ItemStack item; protected double health = 1; protected boolean isBaby; protected int fireTicks; protected DyeColor dyeColor; protected Horse.Color horseColor; protected Horse.Variant horseVariant; protected Horse.Style horseStyle; protected SkeletonType skeletonType; protected Ocelot.Type ocelotType; protected Villager.Profession villagerProfession; protected Collection<PotionEffect> potionEffects = null; protected boolean hasPotionEffects = false; protected Vector velocity = null; protected boolean hasVelocity = false; protected boolean isHanging = false; protected boolean isLiving = false; protected boolean isProjectile = false; public EntityData(Entity entity) { this(entity.getLocation(), entity); } public EntityData(Location location, Entity entity) { setEntity(entity); this.isTemporary = entity.hasMetadata("temporary"); this.isLiving = entity instanceof LivingEntity; this.isHanging = entity instanceof Hanging; this.isProjectile = entity instanceof Projectile; this.type = entity.getType(); this.location = location; this.fireTicks = entity.getFireTicks(); this.velocity = entity.getVelocity(); if (entity instanceof Hanging) { Hanging hanging = (Hanging)entity; try { facing = hanging.getFacing(); this.location = location.getBlock().getLocation(); } catch (Exception ex) { org.bukkit.Bukkit.getLogger().log(Level.WARNING, "Error reading HangingEntity " + entity + " of type " + (entity == null ? "null" : entity.getType()), ex); } } if (entity instanceof ItemFrame) { this.rotation = ((ItemFrame)entity).getRotation(); } if (entity instanceof LivingEntity) { LivingEntity li = (LivingEntity)entity; name = li.getCustomName(); this.health = li.getHealth(); this.potionEffects = li.getActivePotionEffects(); } if (entity instanceof Ageable) { Ageable ageable = (Ageable)entity; this.isBaby = !ageable.isAdult(); } if (entity instanceof Colorable) { Colorable colorable = (Colorable)entity; dyeColor = colorable.getColor(); } if (entity instanceof Painting) { Painting painting = (Painting)entity; art = painting.getArt(); } else if (entity instanceof ItemFrame) { ItemFrame itemFrame = (ItemFrame)entity; item = itemFrame.getItem(); } else if (entity instanceof Horse) { Horse horse = (Horse)entity; horseVariant = horse.getVariant(); horseColor = horse.getColor(); horseStyle = horse.getStyle(); } else if (entity instanceof Skeleton) { Skeleton skeleton = (Skeleton)entity; skeletonType = skeleton.getSkeletonType(); } else if (entity instanceof Villager) { Villager villager = (Villager)entity; villagerProfession = villager.getProfession(); } else if (entity instanceof Wolf) { Wolf wolf = (Wolf)entity; dyeColor = wolf.getCollarColor(); } else if (entity instanceof Ocelot) { Ocelot ocelot = (Ocelot)entity; ocelotType = ocelot.getCatType(); } } public void setEntity(Entity entity) { this.entity = entity == null ? null : new WeakReference<Entity>(entity); this.uuid = entity == null ? null : entity.getUniqueId(); } /** * Thanks you, Chilinot! * @param loc * @param art * @param facing * @return */ private Location getPaintingOffset(Location loc, Art art, BlockFace facing) { switch(art) { // 1x1 case ALBAN: case AZTEC: case AZTEC2: case BOMB: case KEBAB: case PLANT: case WASTELAND: return loc; // No calculation needed. // 1x2 case GRAHAM: case WANDERER: return loc.getBlock().getLocation().add(0, -1, 0); // 2x1 case CREEBET: case COURBET: case POOL: case SEA: case SUNSET: // Use same as 4x3 // 4x3 case DONKEYKONG: case SKELETON: if(facing == BlockFace.WEST) return loc.getBlock().getLocation().add(0, 0, -1); else if(facing == BlockFace.SOUTH) return loc.getBlock().getLocation().add(-1, 0, 0); else return loc; // 2x2 case BUST: case MATCH: case SKULL_AND_ROSES: case STAGE: case VOID: case WITHER: // Use same as 4x2 // 4x2 case FIGHTERS: // Use same as 4x4 // 4x4 case BURNINGSKULL: case PIGSCENE: case POINTER: if(facing == BlockFace.WEST) return loc.getBlock().getLocation().add(0, -1, -1); else if(facing == BlockFace.SOUTH) return loc.getBlock().getLocation().add(-1, -1, 0); else return loc.add(0, -1, 0); // Unsupported artwork default: return loc; } } /** * API Implementation */ @Override public Location getLocation() { return location; } @Override public EntityType getType() { return type; } @Override public Art getArt() { return art; } @Override public BlockFace getFacing() { return facing; } @Override public ItemStack getItem() { return item; } @Override public double getHealth() { return health; } protected Entity trySpawn() { Entity spawned = null; try { switch (type) { case PLAYER: // Nope! break; case PAINTING: Location attach = location.getBlock().getRelative(facing.getOppositeFace()).getLocation(); spawned = location.getWorld().spawn(attach, Painting.class); Painting painting = (Painting)spawned; // Not sure why the double-offset is needed here.. but it seems to work! :P Location offset = getPaintingOffset(getPaintingOffset(location, art, facing), art, facing); painting.teleport(offset); painting.setFacingDirection(facing, true); painting.setArt(art, true); break; case ITEM_FRAME: Location frameAttach = location.getBlock().getRelative(facing.getOppositeFace()).getLocation(); spawned = location.getWorld().spawn(frameAttach, ItemFrame.class); ItemFrame frame = (ItemFrame)spawned; frame.teleport(location); frame.setRotation(rotation); frame.setFacingDirection(facing, true); frame.setItem(item); break; case DROPPED_ITEM: // TODO: Handle this, would need to store item data. spawned = null; break; default: spawned = location.getWorld().spawnEntity(location, type); } } catch (Exception ex) { } return spawned; } @Override public Entity spawn() { Entity spawned = trySpawn(); if (spawned != null) { modify(spawned); } return spawned; } @Override public Entity undo() { Entity entity = this.getEntity(); // Re-spawn if dead or missing if (!isTemporary && uuid != null && (entity == null || !entity.isValid() || entity.isDead()) && !(entity instanceof Player)) { // Avoid re-re-spawning an entity WeakReference<Entity> respawnedEntity = respawned.get(uuid); if (respawnedEntity != null) { entity = respawnedEntity.get(); } else { entity = trySpawn(); if (entity != null) { respawned.put(uuid, new WeakReference<Entity>(entity)); } } setEntity(entity); } modify(entity); return entity; } @Override public boolean modify(Entity entity) { if (entity == null || entity.getType() != type) return false; entity.setFireTicks(fireTicks); if (entity instanceof Ageable) { Ageable ageable = (Ageable)entity; if (isBaby) { ageable.setBaby(); } else { ageable.setAdult(); } } if (entity instanceof Colorable) { Colorable colorable = (Colorable)entity; colorable.setColor(dyeColor); } if (entity instanceof Painting) { Painting painting = (Painting) entity; painting.setArt(art, true); painting.setFacingDirection(facing, true); } else if (entity instanceof ItemFrame) { ItemFrame itemFrame = (ItemFrame)entity; itemFrame.setItem(item); itemFrame.setFacingDirection(facing, true); } else if (entity instanceof Horse) { Horse horse = (Horse)entity; horse.setVariant(horseVariant); horse.setStyle(horseStyle); horse.setColor(horseColor); } else if (entity instanceof Skeleton) { Skeleton skeleton = (Skeleton)entity; skeleton.setSkeletonType(skeletonType); } else if (entity instanceof Villager) { Villager villager = (Villager)entity; villager.setProfession(villagerProfession); } else if (entity instanceof Wolf) { Wolf wolf = (Wolf)entity; wolf.setCollarColor(dyeColor); } else if (entity instanceof Ocelot) { Ocelot ocelot = (Ocelot)entity; ocelot.setCatType(ocelotType); } if (entity instanceof LivingEntity) { LivingEntity li = (LivingEntity)entity; if (hasPotionEffects) { Collection<PotionEffect> currentEffects = li.getActivePotionEffects(); for (PotionEffect effect : currentEffects) { li.removePotionEffect(effect.getType()); } if (potionEffects != null) { for (PotionEffect effect : potionEffects) { li.addPotionEffect(effect); } } } if (name != null && name.length() > 0) { li.setCustomName(name); } try { li.setHealth(Math.min(health, li.getMaxHealth())); } catch (Throwable ex) { } } if (hasMoved) { entity.teleport(location); } if (hasVelocity) { entity.setVelocity(velocity); } return true; } public void setHasMoved(boolean moved) { this.hasMoved = moved; } public void setHasPotionEffects(boolean changed) { this.hasPotionEffects = changed; } public void setHasVelocity(boolean hasVelocity) { this.hasVelocity = hasVelocity; } public boolean isHanging() { return isHanging; } public boolean isLiving() { return isLiving; } public boolean isProjectile() { return isProjectile; } public Entity getEntity() { return entity == null ? null : entity.get(); } }
package com.marcelherd.oot.gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.SystemColor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Date; import java.util.List; import java.util.Map; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.LineBorder; import com.marcelherd.oot.game.Game; import com.marcelherd.oot.game.GameFactory; import com.marcelherd.oot.game.HighscoresFactory; import com.marcelherd.oot.persistence.domain.Highscore; public class PlayView extends JPanel { private GameWindow parent; private Game game; private String playerName; private JLabel potentialPrize; private JLabel questionCounter; private JLabel question; private JButton answerA, answerB, answerC, answerD; private JButton forfeit; private JButton audienceJoker, fiftyFiftyJoker, telephoneJoker; public PlayView(GameWindow parent, String playerName) { PlayController controller = new PlayController(); this.parent = parent; this.playerName = playerName; this.game = GameFactory.newInstance(); setLayout(new BorderLayout()); JPanel upperPanel = new JPanel(); potentialPrize = new JLabel(); potentialPrize.setFont(new Font("Tahoma", Font.BOLD, 30)); upperPanel.add(potentialPrize); upperPanel.setBorder(new LineBorder(Color.black)); questionCounter = new JLabel(); question = new JLabel(); question.setBorder(new LineBorder(Color.BLACK)); answerA = new JButton(); answerB = new JButton(); answerC = new JButton(); answerD = new JButton(); answerA.addActionListener(controller); answerB.addActionListener(controller); answerC.addActionListener(controller); answerD.addActionListener(controller); JPanel questionPanel = new JPanel(new GridLayout(2, 2, 10, 10)); questionPanel.add(answerA); questionPanel.add(answerB); questionPanel.add(answerC); questionPanel.add(answerD); JPanel jokerPanel = new JPanel(); audienceJoker = new JButton("Audience"); fiftyFiftyJoker = new JButton("Fifty Fifty"); telephoneJoker = new JButton("Telephone"); audienceJoker.addActionListener(controller); fiftyFiftyJoker.addActionListener(controller); telephoneJoker.addActionListener(controller); jokerPanel.add(audienceJoker); jokerPanel.add(fiftyFiftyJoker); jokerPanel.add(telephoneJoker); JPanel footerPanel = new JPanel(new GridLayout(1, 2)); forfeit = new JButton("Forfeit"); forfeit.addActionListener(controller); footerPanel.add(jokerPanel); footerPanel.add(forfeit); JPanel gamePanel = new JPanel(new GridLayout(4, 1, 10, 10)); gamePanel.add(questionCounter); gamePanel.add(question); gamePanel.add(questionPanel); gamePanel.add(footerPanel); add(upperPanel, BorderLayout.NORTH); add(gamePanel, BorderLayout.CENTER); setBackground(SystemColor.white); questionPanel.setBackground(SystemColor.white); footerPanel.setBackground(SystemColor.white); jokerPanel.setBackground(SystemColor.white); for (Component c : getComponents()) { c.setBackground(SystemColor.white); } update(); } private void update() { potentialPrize.setText(game.getPotentialPrize() + "€"); questionCounter.setText("Question " + (game.getIndex() + 1) + "/15"); question.setText(game.getCurrentQuestion().getQuestion()); answerA.setText(game.getCurrentQuestion().getAnswerA()); answerB.setText(game.getCurrentQuestion().getAnswerB()); answerC.setText(game.getCurrentQuestion().getAnswerC()); answerD.setText(game.getCurrentQuestion().getAnswerD()); answerA.setEnabled(true); answerB.setEnabled(true); answerC.setEnabled(true); answerD.setEnabled(true); } private class PlayController implements ActionListener { @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == answerA || e.getSource() == answerB || e.getSource() == answerC || e.getSource() == answerD) { if (game.answer(((JButton) e.getSource()).getText().split(" - ")[0])) { if (game.getIndex() == 14) { gameOver(game.getPotentialPrize(), true); } else { game.incrementIndex(); update(); } } else { gameOver(game.getPrize(), false); } } else if (e.getSource() == forfeit) { gameOver(game.forfeit(), true); } else if (e.getSource() == audienceJoker) { useAudienceJoker(); } else if (e.getSource() == telephoneJoker) { useTelephoneJoker(); } else if (e.getSource() == fiftyFiftyJoker) { useFiftyFiftyJoker(); } } private void gameOver(double prize, boolean won) { Highscore highscore = new Highscore(); highscore.setName(playerName); highscore.setDate(new Date()); highscore.setSum((int) prize); HighscoresFactory.getInstance().save(highscore); parent.setView(new GameOverView(parent, prize, playerName, won)); } private void useTelephoneJoker() { JDialog telephoneDialog = new JDialog(); telephoneDialog.setLayout(new FlowLayout()); JLabel answerLabel = new JLabel(game.useTelephoneJoker()); answerLabel.setFont(new Font("Tahama", Font.BOLD, 16)); telephoneDialog.add(answerLabel); telephoneDialog.setSize(400, 80); telephoneDialog.setLocationRelativeTo(null); telephoneDialog.setVisible(true); telephoneJoker.setEnabled(false); } private void useAudienceJoker() { Map<String, Double> audienceMap = game.useAudienceJoker(); answerA.setText(game.getCurrentQuestion().getAnswerA() + " - " + (int) (audienceMap.get(game.getCurrentQuestion().getAnswerA()) * 100) / 100d + "%"); answerB.setText(game.getCurrentQuestion().getAnswerB() + " - " + (int) (audienceMap.get(game.getCurrentQuestion().getAnswerB()) * 100) / 100d + "%"); answerC.setText(game.getCurrentQuestion().getAnswerC() + " - " + (int) (audienceMap.get(game.getCurrentQuestion().getAnswerC()) * 100) / 100d + "%"); answerD.setText(game.getCurrentQuestion().getAnswerD() + " - " + (int) (audienceMap.get(game.getCurrentQuestion().getAnswerD()) * 100) / 100d + "%"); audienceJoker.setEnabled(false); } private void useFiftyFiftyJoker() { List<String> wrongAnswers = game.useFiftyFiftyJoker(); for (String wrongAnswer : wrongAnswers) { if (wrongAnswer.equals(answerA.getText().split(" - ")[0])) { answerA.setEnabled(false); } else if (wrongAnswer.equals(answerB.getText().split(" - ")[0])) { answerB.setEnabled(false); } else if (wrongAnswer.equals(answerC.getText().split(" - ")[0])) { answerC.setEnabled(false); } else if (wrongAnswer.equals(answerD.getText().split(" - ")[0])) { answerD.setEnabled(false); } } fiftyFiftyJoker.setEnabled(false); } } }
package com.elmakers.mine.bukkit.spell; import com.elmakers.mine.bukkit.action.ActionHandler; import com.elmakers.mine.bukkit.api.block.MaterialBrush; import com.elmakers.mine.bukkit.api.spell.SpellResult; import com.elmakers.mine.bukkit.batch.ActionBatch; import com.elmakers.mine.bukkit.utility.Target; import org.bukkit.Location; import org.bukkit.configuration.ConfigurationSection; import java.util.Collection; import java.util.HashMap; import java.util.Map; public class ActionSpell extends BrushSpell { private Map<String, ActionHandler> actions = new HashMap<String, ActionHandler>(); private boolean undoable = false; private boolean requiresBuildPermission = false; private ActionHandler currentHandler = null; private int workThreshold = 500; @Override protected void processResult(SpellResult result, ConfigurationSection castParameters) { if (!result.isSuccess()) { ActionHandler handler = actions.get(result.name().toLowerCase()); if (handler != null) { handler.start(currentCast, castParameters); } } super.processResult(result, castParameters); } @Override public SpellResult onCast(ConfigurationSection parameters) { currentCast.setWorkAllowed(workThreshold); SpellResult result = SpellResult.CAST; currentHandler = actions.get("cast"); ActionHandler downHandler = actions.get("alternate_down"); ActionHandler upHandler = actions.get("alternate_up"); ActionHandler sneakHandler = actions.get("alternate_sneak"); workThreshold = parameters.getInt("work_threshold", 500); if (downHandler != null && isLookingDown()) { result = SpellResult.ALTERNATE_DOWN; currentHandler = downHandler; } else if (upHandler != null && isLookingUp()) { result = SpellResult.ALTERNATE_UP; currentHandler = upHandler; } else if (sneakHandler != null && mage.isSneaking()) { result = SpellResult.ALTERNATE_SNEAK; currentHandler = sneakHandler; } Target target = getTarget(); Location targetLocation = target.getLocation(); if (targetLocation != null && currentHandler.usesBrush()) { MaterialBrush brush = currentCast.getBrush(); brush.setTarget(targetLocation); brush.update(getMage(), targetLocation); } if (currentHandler != null) { result = result.max(currentHandler.start(currentCast, parameters)); } return result; } @Override public void load(ConfigurationSection data) { super.load(data); for (ActionHandler handler : actions.values()) { handler.loadData(getMage(), data); } } @Override public void save(ConfigurationSection data) { super.save(data); for (ActionHandler handler : actions.values()) { handler.saveData(getMage(), data); } } @Override protected void loadTemplate(ConfigurationSection template) { usesBrush = false; undoable = false; requiresBuildPermission = false; castOnNoTarget = true; if (template.contains("actions")) { ConfigurationSection parameters = template.getConfigurationSection("parameters"); ConfigurationSection actionsNode = template.getConfigurationSection("actions"); Collection<String> actionKeys = actionsNode.getKeys(false); for (String actionKey : actionKeys) { ActionHandler handler = new ActionHandler(); handler.load(actionsNode, actionKey); handler.initialize(parameters); usesBrush = usesBrush || handler.usesBrush(); undoable = undoable || handler.isUndoable(); requiresBuildPermission = requiresBuildPermission || handler.requiresBuildPermission(); actions.put(actionKey, handler); } } undoable = template.getBoolean("undoable", undoable); super.loadTemplate(template); } @Override public boolean isUndoable() { return undoable; } @Override public void getParameters(Collection<String> parameters) { super.getParameters(parameters); for (ActionHandler handler : actions.values()) { handler.getParameterNames(parameters); } } @Override public void getParameterOptions(Collection<String> examples, String parameterKey) { super.getParameterOptions(examples, parameterKey); for (ActionHandler handler : actions.values()) { handler.getParameterOptions(examples, parameterKey); } } @Override public String getMessage(String messageKey, String def) { String message = super.getMessage(messageKey, def); if (currentHandler != null) { message = currentHandler.transformMessage(message); } return message; } @Override public boolean requiresBuildPermission() { return requiresBuildPermission; } }
package lucee.runtime.net.http; import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.Method; import java.net.InetAddress; import java.net.URL; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Enumeration; import java.util.LinkedList; import java.util.List; import javax.servlet.ServletContext; import javax.servlet.ServletInputStream; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import lucee.commons.io.CharsetUtil; import lucee.commons.io.IOUtil; import lucee.commons.lang.ExceptionUtil; import lucee.commons.lang.Pair; import lucee.commons.lang.StringUtil; import lucee.commons.lang.mimetype.MimeType; import lucee.commons.net.HTTPUtil; import lucee.commons.net.URLDecoder; import lucee.commons.net.URLEncoder; import lucee.runtime.PageContext; import lucee.runtime.config.Config; import lucee.runtime.converter.JavaConverter; import lucee.runtime.converter.WDDXConverter; import lucee.runtime.engine.ThreadLocalPageContext; import lucee.runtime.exp.PageException; import lucee.runtime.functions.decision.IsLocalHost; import lucee.runtime.interpreter.CFMLExpressionInterpreter; import lucee.runtime.interpreter.JSONExpressionInterpreter; import lucee.runtime.listener.ApplicationContext; import lucee.runtime.op.Caster; import lucee.runtime.security.ScriptProtect; import lucee.runtime.text.xml.XMLCaster; import lucee.runtime.text.xml.XMLUtil; import lucee.runtime.type.UDF; import org.xml.sax.InputSource; public final class ReqRspUtil { private static final Object NULL = new Object(); private static final Cookie[] EMPTY = new Cookie[0]; public static String get(Pair<String, Object>[] items, String name) { for (int i = 0; i < items.length; i++) { if(items[i].getName().equalsIgnoreCase(name)) return Caster.toString(items[i].getValue(), null); } return null; } public static Pair<String, Object>[] add(Pair<String, Object>[] items, String name, Object value) { Pair<String, Object>[] tmp = new Pair[items.length + 1]; for (int i = 0; i < items.length; i++) { tmp[i] = items[i]; } tmp[items.length] = new Pair<String, Object>(name, value); return tmp; } public static Pair<String, Object>[] set(Pair<String, Object>[] items, String name, Object value) { for (int i = 0; i < items.length; i++) { if(items[i].getName().equalsIgnoreCase(name)) { items[i] = new Pair<String, Object>(name, value); return items; } } return add(items, name, value); } /** * return path to itself * * @param req */ public static String self(HttpServletRequest req) { StringBuffer sb = new StringBuffer(req.getServletPath()); String qs = req.getQueryString(); if(!StringUtil.isEmpty(qs)) sb.append('?').append(qs); return sb.toString(); } public static void setContentLength(HttpServletResponse rsp, int length) { rsp.setContentLength(length); } public static void setContentLength(HttpServletResponse rsp, long length) { if(length <= Integer.MAX_VALUE) { setContentLength(rsp, (int)length); } else { rsp.addHeader("Content-Length", Caster.toString(length)); } } public static void setContentType(HttpServletResponse rsp, String contentType) { rsp.setContentType(contentType); } public static Cookie[] getCookies(HttpServletRequest req, Charset charset) { Cookie[] cookies = req.getCookies(); if(cookies != null) { Cookie cookie; String tmp; for (int i = 0; i < cookies.length; i++) { cookie = cookies[i]; // value (is decoded by the servlet engine with iso-8859-1) if(!StringUtil.isAscii(cookie.getValue())) { tmp = encode(cookie.getValue(), "iso-8859-1"); cookie.setValue(decode(tmp, charset.name(), false)); } } } else { String str = req.getHeader("Cookie"); if(str != null) { try { String[] arr = lucee.runtime.type.util.ListUtil.listToStringArray(str, ';'), tmp; java.util.List<Cookie> list = new ArrayList<Cookie>(); Cookie c; for (int i = 0; i < arr.length; i++) { tmp = lucee.runtime.type.util.ListUtil.listToStringArray(arr[i], '='); if(tmp.length > 0) { c = ReqRspUtil.toCookie(dec(tmp[0], charset.name(), false), tmp.length > 1 ? dec(tmp[1], charset.name(), false) : "", null); if(c != null) list.add(c); } } cookies = list.toArray(new Cookie[list.size()]); } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); } } } if(cookies == null) return EMPTY; return cookies; } public static void setCharacterEncoding(HttpServletResponse rsp, String charset) { try { Method setCharacterEncoding = rsp.getClass().getMethod("setCharacterEncoding", new Class[0]); setCharacterEncoding.invoke(rsp, new Object[0]); } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); throw ExceptionUtil.toRuntimeException(t); } } public static String getQueryString(HttpServletRequest req) { // String qs = req.getAttribute("javax.servlet.include.query_string"); return req.getQueryString(); } public static String getHeader(HttpServletRequest request, String name, String defaultValue) { try { return request.getHeader(name); } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); return defaultValue; } } public static String getHeaderIgnoreCase(PageContext pc, String name, String defaultValue) { String charset = pc.getWebCharset().name(); HttpServletRequest req = pc.getHttpServletRequest(); Enumeration e = req.getHeaderNames(); String keyDecoded, key; while(e.hasMoreElements()) { key = e.nextElement().toString(); keyDecoded = ReqRspUtil.decode(key, charset, false); if(name.equalsIgnoreCase(key) || name.equalsIgnoreCase(keyDecoded)) return ReqRspUtil.decode(req.getHeader(key), charset, false); } return defaultValue; } public static List<String> getHeadersIgnoreCase(PageContext pc, String name) { String charset = pc.getWebCharset().name(); HttpServletRequest req = pc.getHttpServletRequest(); Enumeration e = req.getHeaderNames(); List<String> rtn = new ArrayList<String>(); String keyDecoded, key; while(e.hasMoreElements()) { key = e.nextElement().toString(); keyDecoded = ReqRspUtil.decode(key, charset, false); if(name.equalsIgnoreCase(key) || name.equalsIgnoreCase(keyDecoded)) rtn.add(ReqRspUtil.decode(req.getHeader(key), charset, false)); } return rtn; } public static String getScriptName(PageContext pc, HttpServletRequest req) { String sn = StringUtil.emptyIfNull(req.getContextPath()) + StringUtil.emptyIfNull(req.getServletPath()); if(pc == null) pc = ThreadLocalPageContext.get(); if(pc != null && ((pc.getApplicationContext().getScriptProtect() & ApplicationContext.SCRIPT_PROTECT_URL) > 0 || (pc.getApplicationContext().getScriptProtect() & ApplicationContext.SCRIPT_PROTECT_CGI) > 0)) { sn = ScriptProtect.translate(sn); } return sn; } private static boolean isHex(char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); } private static String dec(String str, String charset, boolean force) { str = str.trim(); if(StringUtil.startsWith(str, '"') && StringUtil.endsWith(str, '"') && str.length() > 1) str = str.substring(1, str.length() - 1); return decode(str, charset, force);// java.net.URLDecoder.decode(str.trim(), charset); } public static String decode(String str, String charset, boolean force) { try { if(str == null) return null; return URLDecoder.decode(str, charset, force); } catch (UnsupportedEncodingException e) { return str; } } public static String encode(String str, String charset) { try { return URLEncoder.encode(str, charset); } catch (UnsupportedEncodingException e) { return str; } } public static String encode(String str, Charset charset) { try { return URLEncoder.encode(str, charset); } catch (UnsupportedEncodingException e) { return str; } } public static boolean needEncoding(String str, boolean allowPlus) { if(StringUtil.isEmpty(str, false)) return false; int len = str.length(); char c; for (int i = 0; i < len; i++) { c = str.charAt(i); if(c >= '0' && c <= '9') continue; if(c >= 'a' && c <= 'z') continue; if(c >= 'A' && c <= 'Z') continue; if(c == '-') continue; if(c == '_') continue; if(c == '.') continue; if(c == '*') continue; if(c == '/') continue; if(allowPlus && c == '+') continue; if(c == '%') { if(i + 2 >= len) return true; try { Integer.parseInt(str.substring(i + 1, i + 3), 16); } catch (NumberFormatException nfe) { return true; } i += 3; continue; } return true; } return false; } public static boolean needDecoding(String str) { if(StringUtil.isEmpty(str, false)) return false; boolean need = false; int len = str.length(); char c; for (int i = 0; i < len; i++) { c = str.charAt(i); if(c >= '0' && c <= '9') continue; if(c >= 'a' && c <= 'z') continue; if(c >= 'A' && c <= 'Z') continue; if(c == '-') continue; if(c == '_') continue; if(c == '.') continue; if(c == '*') continue; if(c == '+') { need = true; continue; } if(c == '%') { if(i + 2 >= len) return false; try { Integer.parseInt(str.substring(i + 1, i + 3), 16); } catch (NumberFormatException nfe) { return false; } i += 3; need = true; continue; } return false; } return need; } public static boolean isThis(HttpServletRequest req, String url) { try { return isThis(req, HTTPUtil.toURL(url, true)); } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); return false; } } public static boolean isThis(HttpServletRequest req, URL url) { try { // Port int reqPort = req.getServerPort(); int urlPort = url.getPort(); if(urlPort <= 0) urlPort = HTTPUtil.isSecure(url) ? 443 : 80; if(reqPort <= 0) reqPort = req.isSecure() ? 443 : 80; if(reqPort != urlPort) return false; // host String reqHost = req.getServerName(); String urlHost = url.getHost(); if(reqHost.equalsIgnoreCase(urlHost)) return true; if(IsLocalHost.invoke(reqHost) && IsLocalHost.invoke(reqHost)) return true; InetAddress urlAddr = InetAddress.getByName(urlHost); InetAddress reqAddr = InetAddress.getByName(reqHost); if(reqAddr.getHostName().equalsIgnoreCase(urlAddr.getHostName())) return true; if(reqAddr.getHostAddress().equalsIgnoreCase(urlAddr.getHostAddress())) return true; reqAddr = InetAddress.getByName(req.getRemoteAddr()); if(reqAddr.getHostName().equalsIgnoreCase(urlAddr.getHostName())) return true; if(reqAddr.getHostAddress().equalsIgnoreCase(urlAddr.getHostAddress())) return true; } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); } return false; } public static LinkedList<MimeType> getAccept(PageContext pc) { LinkedList<MimeType> accept = new LinkedList<MimeType>(); java.util.Iterator<String> it = ReqRspUtil.getHeadersIgnoreCase(pc, "accept").iterator(); String value; while(it.hasNext()) { value = it.next(); MimeType[] mtes = MimeType.getInstances(value, ','); if(mtes != null) for (int i = 0; i < mtes.length; i++) { accept.add(mtes[i]); } } return accept; } public static MimeType getContentType(PageContext pc) { java.util.Iterator<String> it = ReqRspUtil.getHeadersIgnoreCase(pc, "content-type").iterator(); String value; MimeType rtn = null; while(it.hasNext()) { value = it.next(); MimeType[] mtes = MimeType.getInstances(value, ','); if(mtes != null) for (int i = 0; i < mtes.length; i++) { rtn = mtes[i]; } } if(rtn == null) return MimeType.ALL; return rtn; } public static String getContentTypeAsString(PageContext pc, String defaultValue) { MimeType mt = getContentType(pc); if(mt == MimeType.ALL) return defaultValue; return mt.toString(); } /** * returns the body of the request * * @param pc * @param deserialized * if true lucee tries to deserialize the body based on the content-type, for example when the content type is "application/json" * @param defaultValue * value returned if there is no body * @return */ public static Object getRequestBody(PageContext pc, boolean deserialized, Object defaultValue) { HttpServletRequest req = pc.getHttpServletRequest(); MimeType contentType = getContentType(pc); String strContentType = contentType == MimeType.ALL ? null : contentType.toString(); Charset cs = getCharacterEncoding(pc, req); boolean isBinary = !(strContentType == null || HTTPUtil.isTextMimeType(contentType) || strContentType.toLowerCase().startsWith("application/x-www-form-urlencoded")); if(req.getContentLength() > -1) { ServletInputStream is = null; try { byte[] data = IOUtil.toBytes(is = req.getInputStream());// new byte[req.getContentLength()]; Object obj = NULL; if(deserialized) { int format = MimeType.toFormat(contentType, -1); obj = toObject(pc, data, format, cs, obj); } if(obj == NULL) { if(isBinary) obj = data; else obj = toString(data, cs); } return obj; } catch (Exception e) { return defaultValue; } finally { IOUtil.closeEL(is); } } return defaultValue; } private static String toString(byte[] data, Charset cs) { if(cs != null) return new String(data, cs).trim(); return new String(data).trim(); } /** * returns the full request URL * * @param req * - the HttpServletRequest * @param includeQueryString * - if true, the QueryString will be appended if one exists */ public static String getRequestURL(HttpServletRequest req, boolean includeQueryString) { StringBuffer sb = req.getRequestURL(); int maxpos = sb.indexOf("/", 8); if(maxpos > -1) { if(req.isSecure()) { if(sb.substring(maxpos - 4, maxpos).equals(":443")) sb.delete(maxpos - 4, maxpos); } else { if(sb.substring(maxpos - 3, maxpos).equals(":80")) sb.delete(maxpos - 3, maxpos); } if(includeQueryString && !StringUtil.isEmpty(req.getQueryString())) sb.append('?').append(req.getQueryString()); } return sb.toString(); } public static String getRootPath(ServletContext sc) { if(sc == null) throw new RuntimeException("cannot determinate webcontext root, because the ServletContext is null"); String root = sc.getRealPath("/"); if(root == null) throw new RuntimeException("cannot determinate webcontext root, the ServletContext from class [" + sc.getClass().getName() + "] is returning null for the method call sc.getRealPath(\"/\"), possibly due to configuration problem."); return root; } public static Object toObject(PageContext pc, byte[] data, int format, Charset charset, Object defaultValue) { switch (format) { case UDF.RETURN_FORMAT_JSON: try { return new JSONExpressionInterpreter().interpret(pc, toString(data, charset)); } catch (PageException pe) { } break; case UDF.RETURN_FORMAT_SERIALIZE: try { return new CFMLExpressionInterpreter().interpret(pc, toString(data, charset)); } catch (PageException pe) { } break; case UDF.RETURN_FORMAT_WDDX: try { WDDXConverter converter = new WDDXConverter(pc.getTimeZone(), false, true); converter.setTimeZone(pc.getTimeZone()); return converter.deserialize(toString(data, charset), false); } catch (Exception pe) { } break; case UDF.RETURN_FORMAT_XML: try { InputSource xml = XMLUtil.toInputSource(pc, toString(data, charset)); InputSource validator = null; return XMLCaster.toXMLStruct(XMLUtil.parse(xml, validator, false), true); } catch (Exception pe) { } break; case UDF.RETURN_FORMAT_JAVA: try { return JavaConverter.deserialize(new ByteArrayInputStream(data)); } catch (Exception pe) { } break; } return defaultValue; } public static boolean identical(HttpServletRequest left, HttpServletRequest right) { if(left == right) return true; if(left instanceof HTTPServletRequestWrap) left = ((HTTPServletRequestWrap)left).getOriginalRequest(); if(right instanceof HTTPServletRequestWrap) right = ((HTTPServletRequestWrap)right).getOriginalRequest(); if(left == right) return true; return false; } public static Charset getCharacterEncoding(PageContext pc, ServletRequest req) { return _getCharacterEncoding(pc, req.getCharacterEncoding()); } public static Charset getCharacterEncoding(PageContext pc, ServletResponse rsp) { return _getCharacterEncoding(pc, rsp.getCharacterEncoding()); } private static Charset _getCharacterEncoding(PageContext pc, String ce) { if(!StringUtil.isEmpty(ce, true)) { Charset c = CharsetUtil.toCharset(ce, null); if(c != null) return c; } pc = ThreadLocalPageContext.get(pc); if(pc != null) return pc.getWebCharset(); Config config = ThreadLocalPageContext.getConfig(pc); return config.getWebCharset(); } public static void removeCookie(HttpServletResponse rsp, String name) { javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie(name, ""); cookie.setMaxAge(0); cookie.setSecure(false); cookie.setPath("/"); rsp.addCookie(cookie); } /** * if encodings fails the given url is returned * * @param rsp * @param url * @return */ public static String encodeRedirectURLEL(HttpServletResponse rsp, String url) { try { return rsp.encodeRedirectURL(url); } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); return url; } } public static String getDomain(HttpServletRequest req) { // DIFF 23 StringBuilder sb = new StringBuilder(); sb.append(req.isSecure() ? "https: sb.append(req.getServerName()); sb.append(':'); sb.append(req.getServerPort()); if(!StringUtil.isEmpty(req.getContextPath())) sb.append(req.getContextPath()); return sb.toString(); } public static Cookie toCookie(String name, String value, Cookie defaultValue) { try { return new Cookie(name, value); } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); return defaultValue; } } }
package slib.platform.android.ui.window; import slib.platform.android.Logger; import slib.platform.android.SlibActivity; import slib.platform.android.ui.UiThread; import slib.platform.android.ui.Util; import slib.platform.android.ui.view.IView; import slib.platform.android.ui.view.UiScrollView; import slib.platform.android.ui.view.UiView; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.graphics.Point; import android.graphics.Rect; import android.os.Build; import android.os.Build.VERSION; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.ViewTreeObserver; import android.widget.EditText; import android.widget.FrameLayout; public class UiWindow extends FrameLayout implements ViewTreeObserver.OnGlobalLayoutListener { private Activity activity; public long instance; private int backgroundColor; private boolean flagFullScreen; private int mLeft, mTop, mRight, mBottom; private UiWindow(Context context) { super(context); instance = 0; backgroundColor = 0; if (context instanceof SlibActivity) { ((SlibActivity) context).onCreateWindow(this); } setFocusableInTouchMode(true); } static UiWindow create(Activity activity , boolean flagFullScreen, boolean flagCenterScreen , int x, int y, int width, int height) { try { final UiWindow ret = new UiWindow(activity); ret.flagFullScreen = flagFullScreen; FrameLayout.LayoutParams params; if (flagFullScreen) { Logger.info("FullScreen Window Created"); params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT); } else { ret.mLeft = x; ret.mTop = y; ret.mRight = x + width; ret.mBottom = y + height; Logger.info("Window Created (" + x + ", " + y + ") - Size(" + width + "," + height + ")"); params = new FrameLayout.LayoutParams(width, height); if (flagCenterScreen) { params.gravity = Gravity.CENTER; } else { params.leftMargin = x; params.topMargin = y; } } activity.addContentView(ret, params); ret.activity = activity; return ret; } catch (Exception e) { Logger.exception(e); return null; } } public View getContentView() { return this; } public void close() { try { instance = 0; ViewParent parent = getParent(); if (parent != null && parent instanceof ViewGroup) { ((ViewGroup) parent).removeView(this); } if (activity instanceof SlibActivity) { ((SlibActivity) activity).onCloseWindow(this); } } catch (Exception e) { Logger.exception(e); } } int getWindowBackgroundColor() { return backgroundColor; } public void setWindowBackgroundColor(int color) { backgroundColor = color; setBackgroundColor(color); } public Rect getFrame() { Rect ret = new Rect(); if (flagFullScreen) { int[] off = new int[2]; getLocationOnScreen(off); ret.left = off[0]; ret.top = off[1]; ret.right = ret.left + getWidth(); ret.bottom = ret.top + getHeight(); } else { ret.left = mLeft; ret.top = mTop; ret.right = mRight; ret.bottom = mBottom; } return ret; } public void setFrame(int left, int top, int right, int bottom) { if (flagFullScreen) { return; } mLeft = left; mTop = top; mRight = right; mBottom = bottom; try { final FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(right - left, bottom - top); params.leftMargin = left; params.topMargin = top; if (UiThread.isUiThread()) { setLayoutParams(params); } else { activity.runOnUiThread(new Runnable() { public void run() { setLayoutParams(params); } }); } } catch (Exception e) { Logger.exception(e); } } public Point getSize() { Point ret = new Point(); ret.x = getWidth(); ret.y = getHeight(); return ret; } public void setSize(int width, int height) { if (flagFullScreen) { return; } mRight = mLeft + width; mBottom = mTop + height; try { final FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) (getLayoutParams()); if (params != null) { params.width = width; params.height = height; } if (UiThread.isUiThread()) { setLayoutParams(params); } else { activity.runOnUiThread(new Runnable() { public void run() { setLayoutParams(params); } }); } } catch (Exception e) { Logger.exception(e); } } public boolean isVisible() { return getVisibility() != View.VISIBLE; } public void setVisible(boolean flag) { setVisibility(flag ? View.VISIBLE : View.INVISIBLE); } public boolean isAlwaysOnTop() { return false; } public void setAlwaysOnTop(boolean flag) { } @TargetApi(Build.VERSION_CODES.HONEYCOMB) float _getAlpha() { return getAlpha(); } public float getWindowAlpha() { if (VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { return _getAlpha(); } else { return 1; } } @TargetApi(Build.VERSION_CODES.HONEYCOMB) void _setAlpha(float alpha) { setAlpha(alpha); } public void setWindowAlpha(float alpha) { if (alpha < 0) { alpha = 0; } if (alpha > 1) { alpha = 1; } if (VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { _setAlpha(alpha); } } public void focus() { requestFocus(); } public Point convertCoordinateFromScreenToWindow(int x, int y) { Point ret = new Point(); int[] location = new int[2]; getLocationOnScreen(location); ret.x = x - location[0]; ret.y = y - location[1]; return ret; } public Point convertCoordinateFromWindowToScreen(int x, int y) { Point ret = new Point(); int[] location = new int[2]; getLocationOnScreen(location); ret.x = location[0] + x; ret.y = location[1] + y; return ret; } private static native void nativeOnResize(long instance, int w, int h); public void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); if (instance != 0) { nativeOnResize(instance, w, h); } } private static native boolean nativeOnClose(long instance); public void onClose() { if (instance != 0) { if (nativeOnClose(instance)) { close(); } } } static int resolveFullSize(int measureSpec) { final int specMode = MeasureSpec.getMode(measureSpec); final int specSize = MeasureSpec.getSize(measureSpec); final int result; switch (specMode) { case MeasureSpec.AT_MOST: result = specSize; break; case MeasureSpec.EXACTLY: result = specSize; break; case MeasureSpec.UNSPECIFIED: default: result = 0; } return result; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { measureChildren(widthMeasureSpec, heightMeasureSpec); if (flagFullScreen) { setMeasuredDimension(resolveFullSize(widthMeasureSpec), resolveFullSize(heightMeasureSpec)); } else { setMeasuredDimension(UiView.resolveMeasure(mRight - mLeft, widthMeasureSpec), UiView.resolveMeasure(mBottom - mTop, heightMeasureSpec)); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int count = getChildCount(); for (int i = 0; i < count; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { if (child instanceof IView) { IView view = (IView)child; Rect frame = view.getUIFrame(); child.layout(frame.left, frame.top, frame.right, frame.bottom); } } } } boolean flagAttachedGlobalLayoutListener = false; boolean flagAttachedNativeWindow = false; @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); Logger.info("UiWindow is attached to native window"); flagAttachedNativeWindow = true; if (!flagAttachedGlobalLayoutListener) { getViewTreeObserver().addOnGlobalLayoutListener(this); flagAttachedGlobalLayoutListener = true; } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); Logger.info("UiWindow is detached from native window"); flagAttachedNativeWindow = false; } @Override public void onGlobalLayout() { try { checkLayoutChanges(); } catch (Exception e) { Logger.exception(e); } } static int savedRootViewBottom = 0; public void checkLayoutChanges() { if (!flagAttachedNativeWindow) { return; } Rect rc = new Rect(); View rootView = getRootView(); rootView.getWindowVisibleDisplayFrame(rc); if (savedRootViewBottom == 0) { savedRootViewBottom = rc.bottom; return; } if (savedRootViewBottom == rc.bottom) { return; } savedRootViewBottom = rc.bottom; int heightKeyboard = Util.getDisplaySize(activity).y - rc.bottom; int heightKeyboardMin = (int)(60 * Util.getDisplayDensity(activity)); if (heightKeyboard > heightKeyboardMin) { processKeyboardAppeared(activity, heightKeyboard); } else { processKeyboardDisappeared(); } } static UiScrollView keyboardScrollView = null; static Rect originalFrame_keyboardScrollView = null; static void processKeyboardAppeared(Activity activity, int keyboardHeight) { Logger.info("Keyboard is appeared, height=" + keyboardHeight); View focusedView = activity.getCurrentFocus(); if (focusedView instanceof EditText) { UiScrollView scroll = null; ViewParent _parent = focusedView.getParent(); View parent = null; if (_parent instanceof View) { parent = (View)_parent; } while (parent != null) { if (parent instanceof UiScrollView) { scroll = (UiScrollView)parent; break; } _parent = parent.getParent(); if (_parent instanceof View) { parent = (View)_parent; } else { parent = null; } } if (keyboardScrollView != scroll) { restoreKeyboardScrollView(); } int heightScreen = Util.getDisplaySize(activity).y; int heightView = focusedView.getHeight(); int yViewScreen = UiView.convertCoordinateFromViewToScreen(focusedView, 0, heightView).y; if (scroll != null) { Rect scrollFrame = scroll.getUIFrame(); if (keyboardScrollView == scroll) { scrollFrame = originalFrame_keyboardScrollView; } int yScroll = UiView.convertCoordinateFromViewToScreen(scroll, 0, scrollFrame.height()).y; if (yScroll > heightScreen - keyboardHeight) { originalFrame_keyboardScrollView = new Rect(scrollFrame); scrollFrame.bottom -= yScroll - (heightScreen - keyboardHeight); UiView.setFrame(scroll, scrollFrame.left, scrollFrame.top, scrollFrame.right, scrollFrame.bottom); keyboardScrollView = scroll; } } } else { restoreKeyboardScrollView(); } } static void processKeyboardDisappeared() { Logger.info("Keyboard is disappeared"); restoreKeyboardScrollView(); } static void restoreKeyboardScrollView() { if (keyboardScrollView != null) { Rect frame = originalFrame_keyboardScrollView; UiView.setFrame(keyboardScrollView, frame.left, frame.top, frame.right, frame.bottom); keyboardScrollView = null; } } }
package com.example.filelist; import javax.swing.*; import java.awt.*; import java.io.File; import java.io.IOException; import java.util.UUID; import static javax.swing.SwingConstants.LEFT; import static org.apache.commons.io.FilenameUtils.getExtension; /** * @author innokenty */ class FileListEntryRenderer implements ListCellRenderer<FileListEntry> { @Override public Component getListCellRendererComponent( JList<? extends FileListEntry> list, FileListEntry file, int index, boolean isSelected, boolean cellHasFocus ) { JLabel label = new JLabel(file.getName(), getIcon(file), LEFT); if (isSelected) { label.setOpaque(true); label.setBackground(list.getSelectionBackground()); label.setForeground(list.getSelectionForeground()); } return label; } private static Icon getIcon(FileListEntry file) { Icon icon; if (file.isDirectory()) { icon = UIManager.getDefaults().getIcon("FileView.directoryIcon"); } else { try { File tempFile = File.createTempFile( UUID.randomUUID().toString(), "." + getExtension(file.getName()) ); tempFile.deleteOnExit(); icon = new JFileChooser().getIcon(tempFile); } catch (IOException e) { icon = UIManager.getDefaults().getIcon("FileView.fileIcon"); } } return icon; } }
package net.katsuster.ememu.riscv.core; import net.katsuster.ememu.generic.*; public class DecodeStageRVI extends Stage64 { /** * RVI * * @param c CPU */ public DecodeStageRVI(RV64 c) { super(c); } /** * RVI CPU * * @return CPU */ @Override public RV64 getCore() { return (RV64)super.getCore(); } /** * RISC-V * * @return RV32 32RV64 64 */ public int getRVBits() { return getCore().getRVBits(); } /** * 32bit LOAD * * @param inst 32bit * @return */ public OpIndex decodeLoad(InstructionRV32 inst) { int funct3 = inst.getFunct3(); switch (funct3) { case InstructionRV32.FUNC_LOAD_LB: return OpIndex.INS_RV32I_LB; case InstructionRV32.FUNC_LOAD_LH: return OpIndex.INS_RV32I_LH; case InstructionRV32.FUNC_LOAD_LW: return OpIndex.INS_RV32I_LW; case InstructionRV32.FUNC_LOAD_LD: if (getRVBits() == 64) { return OpIndex.INS_RV64I_LD; } else { throw new IllegalArgumentException("Unknown LOAD, LD " + String.format("funct3 %d. RV%d", funct3, getRVBits())); } case InstructionRV32.FUNC_LOAD_LBU: return OpIndex.INS_RV32I_LBU; case InstructionRV32.FUNC_LOAD_LHU: return OpIndex.INS_RV32I_LHU; case InstructionRV32.FUNC_LOAD_LWU: if (getRVBits() == 64) { return OpIndex.INS_RV64I_LWU; } else { throw new IllegalArgumentException("Unknown LOAD, LWU " + String.format("funct3 %d. RV%d", funct3, getRVBits())); } default: throw new IllegalArgumentException("Unknown LOAD " + String.format("funct3 %d.", funct3)); } } /** * 32bit MISC-MEM * * @param inst 32bit * @return */ public OpIndex decodeMiscMem(InstructionRV32 inst) { int funct3 = inst.getFunct3(); switch (funct3) { case InstructionRV32.FUNC_MISC_MEM_FENCE: return OpIndex.INS_RV32I_FENCE; case InstructionRV32.FUNC_MISC_MEM_FENCE_I: return OpIndex.INS_RV32I_FENCE_I; default: throw new IllegalArgumentException("Unknown MISC-MEM " + String.format("funct3 %d.", funct3)); } } /** * 32bit OP-IMM * * @param inst 32bit * @return */ public OpIndex decodeOpImm(InstructionRV32 inst) { int funct3 = inst.getFunct3(); switch (funct3) { case InstructionRV32.FUNC_OP_IMM_ADDI: return OpIndex.INS_RV32I_ADDI; case InstructionRV32.FUNC_OP_IMM_SLTI: return OpIndex.INS_RV32I_SLTI; case InstructionRV32.FUNC_OP_IMM_SLTIU: return OpIndex.INS_RV32I_SLTIU; case InstructionRV32.FUNC_OP_IMM_XORI: return OpIndex.INS_RV32I_XORI; case InstructionRV32.FUNC_OP_IMM_ORI: return OpIndex.INS_RV32I_ORI; case InstructionRV32.FUNC_OP_IMM_ANDI: return OpIndex.INS_RV32I_ANDI; case InstructionRV32.FUNC_OP_IMM_SLLI: if (getRVBits() == 64) { int imm6 = inst.getImm6I(); if (imm6 == 0) { //RV64I SLLI return OpIndex.INS_RV64I_SLLI; } throw new IllegalArgumentException("Unknown OP-IMM SLI 64bit " + String.format("imm6 0x%x.", imm6)); } else if (getRVBits() == 32) { int imm7 = inst.getImm7I(); if (imm7 == 0) { //RV32I SLLI return OpIndex.INS_RV32I_SLLI; } throw new IllegalArgumentException("Unknown OP-IMM SLI 32bit " + String.format("imm7 0x%x.", imm7)); } throw new IllegalArgumentException("Unknown OP-IMM SLI " + String.format("%dbit.", getRVBits())); case InstructionRV32.FUNC_OP_IMM_SRLI_SRAI: if (getCore().getRVBits() == 64) { int imm6 = inst.getImm6I(); if (imm6 == 0) { //RV64I SRLI (imm6 = 0b000000) return OpIndex.INS_RV64I_SRLI; } else if (imm6 == 16) { //RV64I SRAI (imm6 = 0b010000) return OpIndex.INS_RV64I_SRAI; } throw new IllegalArgumentException("Unknown OP-IMM SRI 64bit " + String.format("imm6 0x%x.", imm6)); } else if (getRVBits() == 32) { int imm7 = inst.getImm7I(); if (imm7 == 0) { //RV32I SRAI (imm7 = 0b0100000) return OpIndex.INS_RV32I_SRLI; } else if (imm7 == 32) { //RV32I SRAI (imm7 = 0b0100000) return OpIndex.INS_RV32I_SRAI; } throw new IllegalArgumentException("Unknown OP-IMM SRI 32bit " + String.format("imm7 0x%x.", imm7)); } throw new IllegalArgumentException("Unknown OP-IMM SRI " + String.format("%dbit.", getRVBits())); default: throw new IllegalArgumentException("Unknown OP-IMM " + String.format("funct3 %d.", funct3)); } } /** * OP-IMM-32 * * @param inst 32bit * @return */ public OpIndex decodeOpImm32(InstructionRV32 inst) { int funct3 = inst.getFunct3(); switch (funct3) { case InstructionRV32.FUNC_OP_IMM_32_ADDIW: return OpIndex.INS_RV64I_ADDIW; case InstructionRV32.FUNC_OP_IMM_32_SLLIW: if (getRVBits() == 64) { int imm7 = inst.getImm7I(); if (imm7 == 0) { //RV64I SLLIW return OpIndex.INS_RV64I_SLLIW; } throw new IllegalArgumentException("Unknown OP-IMM-32 SLLIW 64bit " + String.format("imm7 0x%x.", imm7)); } throw new IllegalArgumentException("Unknown OP-IMM-32 SLLIW " + String.format("%dbit.", getRVBits())); case InstructionRV32.FUNC_OP_IMM_32_SRLIW_SRAIW: if (getRVBits() == 64) { int imm7 = inst.getImm7I(); if (imm7 == 0) { //RV64I SRLIW return OpIndex.INS_RV64I_SRLIW; } else if (imm7 == 32) { //RV64I SRAIW (imm7 = 0b0100000) return OpIndex.INS_RV64I_SRAIW; } throw new IllegalArgumentException("Unknown OP-IMM-32 SRLIW/SRAIW 64bit " + String.format("imm7 0x%x.", imm7)); } throw new IllegalArgumentException("Unknown OP-IMM-32 SRLIW/SRAIW " + String.format("%dbit.", getRVBits())); default: throw new IllegalArgumentException("Unknown OP-IMM-32 " + String.format("funct3 %d.", funct3)); } } /** * 32bit STORE * * @param inst 32bit * @return */ public OpIndex decodeStore(InstructionRV32 inst) { int funct3 = inst.getFunct3(); switch (funct3) { case InstructionRV32.FUNC_STORE_SB: return OpIndex.INS_RV32I_SB; case InstructionRV32.FUNC_STORE_SH: return OpIndex.INS_RV32I_SH; case InstructionRV32.FUNC_STORE_SW: return OpIndex.INS_RV32I_SW; case InstructionRV32.FUNC_STORE_SD: if (getRVBits() == 64) { return OpIndex.INS_RV64I_SD; } else { throw new IllegalArgumentException("Unknown STORE, SD " + String.format("funct3 %d. RV%d", funct3, getRVBits())); } default: throw new IllegalArgumentException("Unknown STORE " + String.format("funct3 %d.", funct3)); } } /** * 32bit AMO * * @param inst 32bit * @return */ public OpIndex decodeAmo(InstructionRV32 inst) { int funct3 = inst.getFunct3(); int funct5 = inst.getFunct7R() >>> 2; if (funct3 == InstructionRV32.FUNC_AMO_W) { switch (funct5) { case InstructionRV32.FUNC5_AMO_LR_W: return OpIndex.INS_RV32A_LR_W; case InstructionRV32.FUNC5_AMO_SC_W: return OpIndex.INS_RV32A_SC_W; case InstructionRV32.FUNC5_AMO_AMOSWAP_W: return OpIndex.INS_RV32A_AMOSWAP_W; case InstructionRV32.FUNC5_AMO_AMOADD_W: return OpIndex.INS_RV32A_AMOADD_W; case InstructionRV32.FUNC5_AMO_AMOXOR_W: return OpIndex.INS_RV32A_AMOXOR_W; case InstructionRV32.FUNC5_AMO_AMOAND_W: return OpIndex.INS_RV32A_AMOAND_W; case InstructionRV32.FUNC5_AMO_AMOOR_W: return OpIndex.INS_RV32A_AMOOR_W; case InstructionRV32.FUNC5_AMO_AMOMIN_W: return OpIndex.INS_RV32A_AMOMIN_W; case InstructionRV32.FUNC5_AMO_AMOMAX_W: return OpIndex.INS_RV32A_AMOMAX_W; case InstructionRV32.FUNC5_AMO_AMOMINU_W: return OpIndex.INS_RV32A_AMOMINU_W; case InstructionRV32.FUNC5_AMO_AMOMAXU_W: return OpIndex.INS_RV32A_AMOMAXU_W; } } throw new IllegalArgumentException("Unknown AMO " + String.format("funct3 %d funct5 0x%x.", funct3, funct5)); } /** * 32bit OP * * @param inst 32bit * @return */ public OpIndex decodeOp(InstructionRV32 inst) { int funct3 = inst.getFunct3(); int funct7 = inst.getFunct7R(); String opname = "unknown"; switch (funct7) { case 0: switch (funct3) { case InstructionRV32.FUNC_OP_ADD_SUB: return OpIndex.INS_RV32I_ADD; case InstructionRV32.FUNC_OP_SLL: return OpIndex.INS_RV32I_SLL; case InstructionRV32.FUNC_OP_SLT: return OpIndex.INS_RV32I_SLT; case InstructionRV32.FUNC_OP_SLTU: return OpIndex.INS_RV32I_SLTU; case InstructionRV32.FUNC_OP_XOR: return OpIndex.INS_RV32I_XOR; case InstructionRV32.FUNC_OP_SRL_SRA: return OpIndex.INS_RV32I_SRL; case InstructionRV32.FUNC_OP_OR: return OpIndex.INS_RV32I_OR; case InstructionRV32.FUNC_OP_AND: return OpIndex.INS_RV32I_AND; } break; case 32: switch (funct3) { case InstructionRV32.FUNC_OP_ADD_SUB: return OpIndex.INS_RV32I_SUB; case InstructionRV32.FUNC_OP_SRL_SRA: return OpIndex.INS_RV32I_SRA; } break; case 1: switch (funct3) { case InstructionRV32.FUNC_OP_MUL: return OpIndex.INS_RV32M_MUL; case InstructionRV32.FUNC_OP_MULH: return OpIndex.INS_RV32M_MULH; case InstructionRV32.FUNC_OP_MULHSU: return OpIndex.INS_RV32M_MULHSU; case InstructionRV32.FUNC_OP_MULHU: return OpIndex.INS_RV32M_MULHU; case InstructionRV32.FUNC_OP_DIV: return OpIndex.INS_RV32M_DIV; case InstructionRV32.FUNC_OP_DIVU: return OpIndex.INS_RV32M_DIVU; case InstructionRV32.FUNC_OP_REM: return OpIndex.INS_RV32M_REM; case InstructionRV32.FUNC_OP_REMU: return OpIndex.INS_RV32M_REMU; } break; } throw new IllegalArgumentException("Unknown OP " + String.format("funct3 %d funct7 0x%x.", funct3, funct7)); } /** * 32bit OP-32 (opcode = 0b0111011) * * @param inst 32bit * @return */ public OpIndex decodeOp32(InstructionRV32 inst) { int funct3 = inst.getFunct3(); int funct7 = inst.getFunct7R(); switch (funct7) { case 0: switch (funct3) { case InstructionRV32.FUNC_OP_32_ADDW_SUBW: return OpIndex.INS_RV64I_ADDW; case InstructionRV32.FUNC_OP_32_SLLW: return OpIndex.INS_RV64I_SLLW; case InstructionRV32.FUNC_OP_32_SRLW_SRAW: return OpIndex.INS_RV64I_SRLW; } break; case 32: switch (funct3) { case InstructionRV32.FUNC_OP_32_ADDW_SUBW: return OpIndex.INS_RV64I_SUBW; case InstructionRV32.FUNC_OP_32_SRLW_SRAW: return OpIndex.INS_RV64I_SRAW; } break; case 1: switch (funct3) { case InstructionRV32.FUNC_OP_32_MULW: return OpIndex.INS_RV64M_MULW; case InstructionRV32.FUNC_OP_32_DIVW: return OpIndex.INS_RV64M_DIVW; case InstructionRV32.FUNC_OP_32_DIVUW: return OpIndex.INS_RV64M_DIVUW; case InstructionRV32.FUNC_OP_32_REMW: return OpIndex.INS_RV64M_REMW; case InstructionRV32.FUNC_OP_32_REMUW: return OpIndex.INS_RV64M_REMUW; } break; } throw new IllegalArgumentException("Unknown OP-32 " + String.format("funct3 %d funct7 0x%x.", funct3, funct7)); } /** * 32bit BRANCH * * @param inst 32bit * @return */ public OpIndex decodeBranch(InstructionRV32 inst) { int funct3 = inst.getFunct3(); switch (funct3) { case InstructionRV32.FUNC_BRANCH_BEQ: return OpIndex.INS_RV32I_BEQ; case InstructionRV32.FUNC_BRANCH_BNE: return OpIndex.INS_RV32I_BNE; case InstructionRV32.FUNC_BRANCH_BLT: return OpIndex.INS_RV32I_BLT; case InstructionRV32.FUNC_BRANCH_BGE: return OpIndex.INS_RV32I_BGE; case InstructionRV32.FUNC_BRANCH_BLTU: return OpIndex.INS_RV32I_BLTU; case InstructionRV32.FUNC_BRANCH_BGEU: return OpIndex.INS_RV32I_BGEU; default: throw new IllegalArgumentException("Unknown BRANCH " + String.format("funct3 %d.", funct3)); } } /** * 32bit JALR * * @param inst 32bit * @return */ public OpIndex decodeJalr(InstructionRV32 inst) { int funct3 = inst.getFunct3(); switch (funct3) { case InstructionRV32.FUNC_JALR_JALR: return OpIndex.INS_RV32I_JALR; default: throw new IllegalArgumentException("Unknown JALR " + String.format("funct3 %d.", funct3)); } } /** * 32bit SYSTEM * * @param inst 32bit * @return */ public OpIndex decodeSystem(InstructionRV32 inst) { int funct3 = inst.getFunct3(); switch (funct3) { case InstructionRV32.FUNC_SYSTEM_EX: { int rd = inst.getRd(); int rs1 = inst.getRs1(); int imm12 = inst.getImm12I(); if (imm12 == 0 && rs1 == 0 && rd == 0) { //ECALL return OpIndex.INS_RV32I_ECALL; } else if (imm12 == 1 && rs1 == 0 && rd == 0) { //EBREAK return OpIndex.INS_RV32I_EBREAK; } else if (imm12 == 0x105 && rs1 == 0 && rd == 0) { //WFI, imm12 = 0b0001_0000_0101 return OpIndex.INS_RV32I_WFI; } throw new IllegalArgumentException("Unknown SYSTEM " + String.format("imm12 0x%x, rs1 0x%x, rd 0x%x.", imm12, rs1, rd)); } case InstructionRV32.FUNC_SYSTEM_CSRRW: return OpIndex.INS_RV32I_CSRRW; case InstructionRV32.FUNC_SYSTEM_CSRRS: return OpIndex.INS_RV32I_CSRRS; case InstructionRV32.FUNC_SYSTEM_CSRRC: return OpIndex.INS_RV32I_CSRRC; case InstructionRV32.FUNC_SYSTEM_CSRRWI: return OpIndex.INS_RV32I_CSRRWI; case InstructionRV32.FUNC_SYSTEM_CSRRSI: return OpIndex.INS_RV32I_CSRRSI; case InstructionRV32.FUNC_SYSTEM_CSRRCI: return OpIndex.INS_RV32I_CSRRCI; default: throw new IllegalArgumentException("Unknown SYSTEM " + String.format("funct3 %d.", funct3)); } } /** * 32bit * * @param inst 32bit * @return */ public OpIndex decode(InstructionRV32 inst) { int code = inst.getOpcode(); switch (code) { case InstructionRV32.OPCODE_LOAD: return decodeLoad(inst); case InstructionRV32.OPCODE_MISC_MEM: return decodeMiscMem(inst); case InstructionRV32.OPCODE_OP_IMM: return decodeOpImm(inst); case InstructionRV32.OPCODE_AUIPC: return OpIndex.INS_RV32I_AUIPC; case InstructionRV32.OPCODE_OP_IMM_32: return decodeOpImm32(inst); case InstructionRV32.OPCODE_STORE: return decodeStore(inst); case InstructionRV32.OPCODE_AMO: return decodeAmo(inst); case InstructionRV32.OPCODE_OP: return decodeOp(inst); case InstructionRV32.OPCODE_LUI: return OpIndex.INS_RV32I_LUI; case InstructionRV32.OPCODE_OP_32: return decodeOp32(inst); case InstructionRV32.OPCODE_BRANCH: return decodeBranch(inst); case InstructionRV32.OPCODE_JALR: return decodeJalr(inst); case InstructionRV32.OPCODE_JAL: return OpIndex.INS_RV32I_JAL; case InstructionRV32.OPCODE_SYSTEM: return decodeSystem(inst); default: throw new IllegalArgumentException("Unknown opcode " + String.format("%d.", code)); } } }
package lucee.runtime.net.mail; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.text.Normalizer; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.BodyPart; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.Header; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Part; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Store; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; import lucee.commons.digest.HashUtil; import lucee.commons.io.CharsetUtil; import lucee.commons.io.IOUtil; import lucee.commons.io.SystemUtil; import lucee.commons.io.res.Resource; import lucee.commons.io.res.util.ResourceUtil; import lucee.commons.lang.ExceptionUtil; import lucee.commons.lang.Md5; import lucee.commons.lang.StringUtil; import lucee.runtime.engine.ThreadLocalPageContext; import lucee.runtime.exp.ApplicationException; import lucee.runtime.exp.PageException; import lucee.runtime.net.imap.ImapClient; import lucee.runtime.net.pop.PopClient; import lucee.runtime.op.Caster; import lucee.runtime.op.OpUtil; import lucee.runtime.pool.Pool; import lucee.runtime.pool.PoolItem; import lucee.runtime.type.Array; import lucee.runtime.type.ArrayImpl; import lucee.runtime.type.Collection; import lucee.runtime.type.KeyImpl; import lucee.runtime.type.Query; import lucee.runtime.type.QueryImpl; import lucee.runtime.type.Struct; import lucee.runtime.type.StructImpl; import lucee.runtime.type.util.ArrayUtil; import lucee.runtime.type.util.KeyConstants; import lucee.runtime.type.util.ListUtil; public abstract class MailClient implements PoolItem { @Override public boolean isValid() { if (_store != null && !_store.isConnected()) { // goal is to be valid if requested so we try to be try { start(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return _store != null && _store.isConnected(); } private static final Collection.Key FULLNAME = KeyImpl.getInstance("FULLNAME"); private static final Collection.Key UNREAD = KeyImpl.getInstance("UNREAD"); private static final Collection.Key PARENT = KeyImpl.getInstance("PARENT"); private static final Collection.Key TOTALMESSAGES = KeyImpl.getInstance("TOTALMESSAGES"); private static final Collection.Key NEW = KeyImpl.getInstance("NEW"); /** * Simple authenicator implmentation */ private final class _Authenticator extends Authenticator { private String _fldif = null; private String a = null; @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(_fldif, a); } public _Authenticator(String s, String s1) { _fldif = s; a = s1; } } private static final Collection.Key DATE = KeyImpl.getInstance("date"); private static final Collection.Key SUBJECT = KeyImpl.getInstance("subject"); private static final Collection.Key SIZE = KeyImpl.getInstance("size"); private static final Collection.Key FROM = KeyImpl.getInstance("from"); private static final Collection.Key MESSAGE_NUMBER = KeyImpl.getInstance("messagenumber"); private static final Collection.Key MESSAGE_ID = KeyImpl.getInstance("messageid"); private static final Collection.Key REPLYTO = KeyImpl.getInstance("replyto"); private static final Collection.Key CC = KeyImpl.getInstance("cc"); private static final Collection.Key BCC = KeyImpl.getInstance("bcc"); private static final Collection.Key TO = KeyImpl.getInstance("to"); private static final Collection.Key UID = KeyImpl.getInstance("uid"); private static final Collection.Key HEADER = KeyImpl.getInstance("header"); private static final Collection.Key BODY = KeyImpl.getInstance("body"); private static final Collection.Key CIDS = KeyImpl.getInstance("cids"); private static final Collection.Key TEXT_BODY = KeyImpl.getInstance("textBody"); private static final Collection.Key HTML_BODY = KeyImpl.getInstance("HTMLBody"); private static final Collection.Key ATTACHMENTS = KeyImpl.getInstance("attachments"); private static final Collection.Key ATTACHMENT_FILES = KeyImpl.getInstance("attachmentfiles"); public static final int TYPE_POP3 = 0; public static final int TYPE_IMAP = 1; private String _flddo[] = { "date", "from", "messagenumber", "messageid", "replyto", "subject", "cc", "to", "size", "header", "uid" }; private String _fldnew[] = { "date", "from", "messagenumber", "messageid", "replyto", "subject", "cc", "to", "size", "header", "uid", "body", "textBody", "HTMLBody", "attachments", "attachmentfiles", "cids" }; private String server = null; private String username = null; private String password = null; private Session _session = null; private Store _store = null; private int port = 0; private int timeout = 0; private int startrow = 0; private int maxrows = 0; private boolean uniqueFilenames = false; private Resource attachmentDirectory = null; private final boolean secure; private static Pool pool = new Pool(60000, 100, 5000); public static MailClient getInstance(int type, String server, int port, String username, String password, boolean secure, String name, String id) throws Exception { String uid; if (StringUtil.isEmpty(name)) uid = createName(type, server, port, username, password, secure); else uid = name; uid = type + ";" + uid + ";" + id; PoolItem item = pool.get(uid); if (item == null) { if (StringUtil.isEmpty(server)) { if (StringUtil.isEmpty(name)) throw new ApplicationException("missing mail server information"); else throw new ApplicationException("There is no connection available with name [" + name + "]"); } if (TYPE_POP3 == type) pool.put(uid, item = new PopClient(server, port, username, password, secure)); if (TYPE_IMAP == type) pool.put(uid, item = new ImapClient(server, port, username, password, secure)); } return (MailClient) item; } public static void removeInstance(MailClient client) throws Exception { pool.remove(client); // this will also call the stop method of the } private static String createName(int type, String server, int port, String username, String password, boolean secure) { return HashUtil.create64BitHashAsString( new StringBuilder().append(server).append(';').append(port).append(';').append(username).append(';').append(password).append(';').append(secure).append(';'), 16); } /** * constructor of the class * * @param server * @param port * @param username * @param password * @param secure */ public MailClient(String server, int port, String username, String password, boolean secure) { timeout = 60000; startrow = 0; maxrows = -1; uniqueFilenames = false; this.server = server; this.port = port; this.username = username; this.password = password; this.secure = secure; } /** * @param maxrows The maxrows to set. */ public void setMaxrows(int maxrows) { this.maxrows = maxrows; } /** * @param startrow The startrow to set. */ public void setStartrow(int startrow) { this.startrow = startrow; } /** * @param timeout The timeout to set. */ public void setTimeout(int timeout) { this.timeout = timeout; } /** * @param uniqueFilenames The uniqueFilenames to set. */ public void setUniqueFilenames(boolean uniqueFilenames) { this.uniqueFilenames = uniqueFilenames; } /** * @param attachmentDirectory The attachmentDirectory to set. */ public void setAttachmentDirectory(Resource attachmentDirectory) { this.attachmentDirectory = attachmentDirectory; } /** * connects to pop server * * @throws MessagingException */ @Override public void start() throws MessagingException { Properties properties = new Properties(); String type = getTypeAsString(); properties.setProperty("mail." + type + ".host", server); properties.setProperty("mail." + type + ".port", String.valueOf(port)); properties.setProperty("mail." + type + ".connectiontimeout", String.valueOf(timeout)); properties.setProperty("mail." + type + ".timeout", String.valueOf(timeout)); // properties.setProperty("mail.mime.charset", "UTF-8"); if (secure) { properties.setProperty("mail." + type + ".ssl.enable", "true"); // properties.setProperty("mail."+type+".starttls.enable", "true" ); // allow using untrusted certs, good for CI if (!Caster.toBooleanValue(SystemUtil.getSystemPropOrEnvVar("lucee.ssl.checkserveridentity", null), true)){ properties.setProperty("mail." + type + ".ssl.trust", "*"); properties.setProperty("mail." + type + ".ssl.checkserveridentity", "false"); } } if (TYPE_IMAP == getType()) { properties.setProperty("mail.imap.partialfetch", "false"); } // if(TYPE_POP3==getType()){} _session = username != null ? Session.getInstance(properties, new _Authenticator(username, password)) : Session.getInstance(properties); Thread t = Thread.currentThread(); ClassLoader ccl = t.getContextClassLoader(); t.setContextClassLoader(_session.getClass().getClassLoader()); try { _store = _session.getStore(type); if (!StringUtil.isEmpty(username)) _store.connect(server, port, username, password); else _store.connect(); } finally { t.setContextClassLoader(ccl); } } protected abstract String getTypeAsString(); protected abstract int getType(); /** * delete all message in ibox that match given criteria * * @param messageNumbers * @param uIds * @throws MessagingException * @throws IOException * @throws PageException */ public void deleteMails(String as[], String as1[]) throws MessagingException, IOException, PageException { Folder folder; Message amessage[]; folder = _store.getFolder("INBOX"); folder.open(2); Map<String, Message> map = getMessages(null, folder, as1, as, startrow, maxrows, false); Iterator<String> iterator = map.keySet().iterator(); amessage = new Message[map.size()]; int i = 0; while (iterator.hasNext()) { amessage[i++] = map.get(iterator.next()); } try { folder.setFlags(amessage, new Flags(javax.mail.Flags.Flag.DELETED), true); } finally { folder.close(true); } } /** * return all messages from inbox * * @param messageNumbers all messages with this ids * @param uIds all messages with this uids * @param withBody also return body * @return all messages from inbox * @throws MessagingException * @throws IOException * @throws PageException */ public Query getMails(String[] messageNumbers, String[] uids, boolean all, String folderName) throws MessagingException, IOException, PageException { Query qry = new QueryImpl(all ? _fldnew : _flddo, 0, "query"); if (StringUtil.isEmpty(folderName, true)) folderName = "INBOX"; else folderName = folderName.trim(); Folder folder = _store.getFolder(folderName); folder.open(Folder.READ_ONLY); try { getMessages(qry, folder, uids, messageNumbers, startrow, maxrows, all); } finally { folder.close(false); } return qry; } private void toQuery(Query qry, Message message, Object uid, boolean all) { int row = qry.addRow(); // date try { qry.setAtEL(DATE, row, Caster.toDate(message.getSentDate(), true, null, null)); } catch (MessagingException e) { } // subject try { qry.setAtEL(SUBJECT, row, message.getSubject()); } catch (MessagingException e) { qry.setAtEL(SUBJECT, row, "MessagingException:" + e.getMessage()); } // size try { qry.setAtEL(SIZE, row, new Double(message.getSize())); } catch (MessagingException e) { } qry.setAtEL(FROM, row, toList(getHeaderEL(message, "from"))); qry.setAtEL(MESSAGE_NUMBER, row, new Double(message.getMessageNumber())); qry.setAtEL(MESSAGE_ID, row, toList(getHeaderEL(message, "Message-ID"))); String s = toList(getHeaderEL(message, "reply-to")); if (s.length() == 0) { s = Caster.toString(qry.getAt(FROM, row, null), ""); } qry.setAtEL(REPLYTO, row, s); qry.setAtEL(CC, row, toList(getHeaderEL(message, "cc"))); qry.setAtEL(BCC, row, toList(getHeaderEL(message, "bcc"))); qry.setAtEL(TO, row, toList(getHeaderEL(message, "to"))); qry.setAtEL(UID, row, uid); StringBuffer content = new StringBuffer(); try { for (Enumeration enumeration = message.getAllHeaders(); enumeration.hasMoreElements(); content.append('\n')) { Header header = (Header) enumeration.nextElement(); content.append(header.getName()); content.append(": "); content.append(header.getValue()); } } catch (MessagingException e) { } qry.setAtEL(HEADER, row, content.toString()); if (all) { getContentEL(qry, message, row); } } private String[] getHeaderEL(Message message, String key) { try { return message.getHeader(key); } catch (MessagingException e) { return null; } } /** * gets all messages from given Folder that match given criteria * * @param qry * @param folder * @param uIds * @param messageNumbers * @param all * @param startrow * @param maxrows * @return * @return matching Messages * @throws MessagingException * @throws PageException */ private Map<String, Message> getMessages(Query qry, Folder folder, String[] uids, String[] messageNumbers, int startRow, int maxRow, boolean all) throws MessagingException, PageException { Message[] messages = folder.getMessages(); Map<String, Message> map = qry == null ? new HashMap<String, Message>() : null; int k = 0; if (uids != null || messageNumbers != null) { startRow = 0; maxRow = -1; } Message message; for (int l = startRow; l < messages.length; l++) { if (maxRow != -1 && k == maxRow) { break; } message = messages[l]; int messageNumber = message.getMessageNumber(); String id = getId(folder, message); if (uids == null ? messageNumbers == null || contains(messageNumbers, messageNumber) : contains(uids, id)) { k++; if (qry != null) { toQuery(qry, message, id, all); } else map.put(id, message); } } return map; } protected String getId(Folder folder, Message message) throws MessagingException { return _getId(folder, message); } protected abstract String _getId(Folder folder, Message message) throws MessagingException; private void getContentEL(Query query, Message message, int row) { try { getContent(query, message, row); } catch (Exception e) { String st = ExceptionUtil.getStacktrace(e, true); query.setAtEL(BODY, row, st); } } /** * write content data to query * * @param qry * @param content * @param row * @throws MessagingException * @throws IOException */ private void getContent(Query query, Message message, int row) throws MessagingException, IOException { StringBuffer body = new StringBuffer(); Struct cids = new StructImpl(); query.setAtEL(CIDS, row, cids); if (message.isMimeType("text/plain")) { String content = getConent(message); query.setAtEL(TEXT_BODY, row, content); body.append(content); } else if (message.isMimeType("text/html")) { String content = getConent(message); query.setAtEL(HTML_BODY, row, content); body.append(content); } else { Object content = message.getContent(); if (content instanceof MimeMultipart) { Array attachments = new ArrayImpl(); Array attachmentFiles = new ArrayImpl(); getMultiPart(query, row, attachments, attachmentFiles, cids, (MimeMultipart) content, body); if (attachments.size() > 0) { try { query.setAtEL(ATTACHMENTS, row, ListUtil.arrayToList(attachments, "\t")); } catch (PageException pageexception) { } } if (attachmentFiles.size() > 0) { try { query.setAtEL(ATTACHMENT_FILES, row, ListUtil.arrayToList(attachmentFiles, "\t")); } catch (PageException pageexception1) { } } } } query.setAtEL(BODY, row, body.toString()); } private void getMultiPart(Query query, int row, Array attachments, Array attachmentFiles, Struct cids, Multipart multiPart, StringBuffer body) throws MessagingException, IOException { int j = multiPart.getCount(); for (int k = 0; k < j; k++) { BodyPart bodypart = multiPart.getBodyPart(k); Object content; if (bodypart.getFileName() != null) { String filename = bodypart.getFileName(); try { filename = Normalizer.normalize(MimeUtility.decodeText(filename), Normalizer.Form.NFC); } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); } if (bodypart.getHeader("Content-ID") != null) { String[] ids = bodypart.getHeader("Content-ID"); String cid = ids[0].substring(1, ids[0].length() - 1); cids.setEL(KeyImpl.init(filename), cid); } if (filename != null && ArrayUtil.find(attachments, filename) >= 0) { attachments.appendEL(filename); if (attachmentDirectory != null) { Resource file = attachmentDirectory.getRealResource(filename); int l = 1; String s2; for (; uniqueFilenames && file.exists(); file = attachmentDirectory.getRealResource(s2)) { String as[] = ResourceUtil.splitFileName(filename); s2 = as.length != 1 ? as[0] + l++ + '.' + as[1] : as[0] + l++; } IOUtil.copy(bodypart.getInputStream(), file, true); attachmentFiles.appendEL(file.getAbsolutePath()); } } } else if (bodypart.isMimeType("text/plain")) { content = getConent(bodypart); query.setAtEL(TEXT_BODY, row, content); if (body.length() == 0) body.append(content); } else if (bodypart.isMimeType("text/html")) { content = getConent(bodypart); query.setAtEL(HTML_BODY, row, content); if (body.length() == 0) body.append(content); } else if ((content = bodypart.getContent()) instanceof Multipart) { getMultiPart(query, row, attachments, attachmentFiles, cids, (Multipart) content, body); } else if (bodypart.getHeader("Content-ID") != null) { String[] ids = bodypart.getHeader("Content-ID"); String cid = ids[0].substring(1, ids[0].length() - 1); String filename = "cid:" + cid; attachments.appendEL(filename); if (attachmentDirectory != null) { filename = "_" + Md5.getDigestAsString(filename); Resource file = attachmentDirectory.getRealResource(filename); int l = 1; String s2; for (; uniqueFilenames && file.exists(); file = attachmentDirectory.getRealResource(s2)) { String as[] = ResourceUtil.splitFileName(filename); s2 = as.length != 1 ? as[0] + l++ + '.' + as[1] : as[0] + l++; } IOUtil.copy(bodypart.getInputStream(), file, true); attachmentFiles.appendEL(file.getAbsolutePath()); } cids.setEL(KeyImpl.init(filename), cid); } else if((content = bodypart.getContent()) instanceof MimeMessage) { content = getConent(bodypart); if (body.length() == 0) body.append(content); } } } /* * * writes BodyTag data to query, if there is a problem with encoding, encoding will removed a do * it again * * @param qry * * @param columnName * * @param row * * @param bp * * @param body * * @throws IOException * * @throws MessagingException / private void setBody(Query qry, String columnName, int row, BodyPart * bp, StringBuffer body) throws IOException, MessagingException { String content = getConent(bp); * * qry.setAtEL(columnName,row,content); if(body.length()==0)body.append(content); * * } */ private String getConent(Part bp) throws MessagingException { InputStream is = null; try { if((bp.getContent()) instanceof MimeMessage) { MimeMessage mimeContent = (MimeMessage) bp.getContent(); is = mimeContent.getInputStream(); } else { is = bp.getInputStream(); } return getContent(is, CharsetUtil.toCharset(getCharsetFromContentType(bp.getContentType()))); } catch (IOException mie) { IOUtil.closeEL(is); try { return getContent(is, SystemUtil.getCharset()); } catch (IOException e) { return "Cannot read body of this message: " + e.getMessage(); } } finally { IOUtil.closeEL(is); } } private String getContent(InputStream is, Charset charset) throws IOException { return MailUtil.decode(IOUtil.toString(is, charset)); } private static String getCharsetFromContentType(String contentType) { Array arr = ListUtil.listToArrayRemoveEmpty(contentType, "; "); for (int i = 1; i <= arr.size(); i++) { Array inner = ListUtil.listToArray((String) arr.get(i, null), "= "); if (inner.size() == 2 && ((String) inner.get(1, "")).trim().equalsIgnoreCase("charset")) { String charset = (String) inner.get(2, ""); charset = charset.trim(); if (!StringUtil.isEmpty(charset)) { if (StringUtil.startsWith(charset, '"') && StringUtil.endsWith(charset, '"')) { charset = charset.substring(1, charset.length() - 1); } if (StringUtil.startsWith(charset, '\'') && StringUtil.endsWith(charset, '\'')) { charset = charset.substring(1, charset.length() - 1); } } return charset; } } return "us-ascii"; } /** * checks if a String Array (ids) has one element that is equal to id * * @param ids * @param id * @return has element found or not * @throws PageException */ private boolean contains(String ids[], String id) throws PageException { for (int i = 0; i < ids.length; i++) { if (OpUtil.compare(ThreadLocalPageContext.get(), ids[i], id) == 0) return true; } return false; } /** * checks if a String Array (ids) has one element that is equal to id * * @param ids * @param id * @return has element found or not * @throws PageException */ private boolean contains(String ids[], int id) throws PageException { for (int i = 0; i < ids.length; i++) { if (OpUtil.compare(ThreadLocalPageContext.get(), ids[i], id) == 0) return true; } return false; } /** * translate a String Array to String List * * @param arr Array to translate * @return List from Array */ private String toList(String ids[]) { if (ids == null) return ""; return ListUtil.arrayToList(ids, ","); } /** * disconnect without an exception */ @Override public void end() { try { if (_store != null) _store.close(); } catch (Exception exception) { } } // IMAP only public void createFolder(String folderName) throws MessagingException, ApplicationException { if (folderExists(folderName)) throw new ApplicationException("Cannot create imap folder [" + folderName + "], the folder already exists."); Folder folder = getFolder(folderName, null, false, true); if (!folder.exists()) folder.create(Folder.HOLDS_MESSAGES); } private boolean folderExists(String folderName) throws MessagingException { String[] folderNames = toFolderNames(folderName); Folder folder = null; for (int i = 0; i < folderNames.length; i++) { folder = folder == null ? _store.getFolder(folderNames[i]) : folder.getFolder(folderNames[i]); if (!folder.exists()) return false; } return true; } private String[] toFolderNames(String folderName) { if (StringUtil.isEmpty(folderName)) return new String[0]; return ListUtil.trimItems(ListUtil.trim(ListUtil.listToStringArray(folderName, '/'))); } public void deleteFolder(String folderName) throws MessagingException, ApplicationException { if (folderName.equalsIgnoreCase("INBOX") || folderName.equalsIgnoreCase("OUTBOX")) throw new ApplicationException("Cannot delete folder [" + folderName + "], this folder is protected."); String[] folderNames = toFolderNames(folderName); Folder folder = _store.getFolder(folderNames[0]); if (!folder.exists()) { throw new ApplicationException("There is no folder with name [" + folderName + "]."); } folder.delete(true); } public void renameFolder(String srcFolderName, String trgFolderName) throws MessagingException, ApplicationException { if (srcFolderName.equalsIgnoreCase("INBOX") || srcFolderName.equalsIgnoreCase("OUTBOX")) throw new ApplicationException("Cannot rename folder [" + srcFolderName + "], this folder is protected."); if (trgFolderName.equalsIgnoreCase("INBOX") || trgFolderName.equalsIgnoreCase("OUTBOX")) throw new ApplicationException("Cannot rename folder to [" + trgFolderName + "], this folder name is protected."); Folder src = getFolder(srcFolderName, true, true, false); Folder trg = getFolder(trgFolderName, null, false, true); if (!src.renameTo(trg)) throw new ApplicationException("Cannot rename folder [" + srcFolderName + "] to [" + trgFolderName + "]."); } public Query listAllFolder(String folderName, boolean recurse, int startrow, int maxrows) throws MessagingException, PageException { Query qry = new QueryImpl(new Collection.Key[] { FULLNAME, KeyConstants._NAME, TOTALMESSAGES, UNREAD, PARENT, NEW }, 0, "folders"); // if(StringUtil.isEmpty(folderName)) folderName="INBOX"; Folder folder = (StringUtil.isEmpty(folderName)) ? _store.getDefaultFolder() : _store.getFolder(folderName); // Folder folder=_store.getFolder(folderName); if (!folder.exists()) throw new ApplicationException("There is no folder with name [" + folderName + "]."); list(folder, qry, recurse, startrow, maxrows, 0); return qry; } public void moveMail(String srcFolderName, String trgFolderName, String as[], String as1[]) throws MessagingException, PageException { if (StringUtil.isEmpty(srcFolderName, true)) srcFolderName = "INBOX"; Folder srcFolder = getFolder(srcFolderName, true, true, false); Folder trgFolder = getFolder(trgFolderName, true, true, false); try { srcFolder.open(2); trgFolder.open(2); Message amessage[]; Map<String, Message> map = getMessages(null, srcFolder, as1, as, startrow, maxrows, false); Iterator<String> iterator = map.keySet().iterator(); amessage = new Message[map.size()]; int i = 0; while (iterator.hasNext()) { amessage[i++] = map.get(iterator.next()); } srcFolder.copyMessages(amessage, trgFolder); srcFolder.setFlags(amessage, new Flags(javax.mail.Flags.Flag.DELETED), true); } finally { srcFolder.close(true); trgFolder.close(true); } } public void markRead(String folderName) throws MessagingException, ApplicationException { if (StringUtil.isEmpty(folderName)) folderName = "INBOX"; Folder folder = null; try { folder = getFolder(folderName, true, true, false); folder.open(2); Message[] msgs = folder.getMessages(); folder.setFlags(msgs, new Flags(Flags.Flag.SEEN), true); } finally { if (folder != null) folder.close(false); } } private Folder getFolder(String folderName, Boolean existingParent, Boolean existing, boolean createParentIfNotExists) throws MessagingException, ApplicationException { String[] folderNames = toFolderNames(folderName); Folder folder = null; String fn; for (int i = 0; i < folderNames.length; i++) { fn = folderNames[i]; folder = folder == null ? _store.getFolder(fn) : folder.getFolder(fn); // top if (i + 1 == folderNames.length) { if (existing != null) { if (existing.booleanValue() && !folder.exists()) throw new ApplicationException("There is no folder with name [" + folderName + "]."); if (!existing.booleanValue() && folder.exists()) throw new ApplicationException("There is already a folder with name [" + folderName + "]."); } } // parent else { if (existingParent != null) { if (existingParent.booleanValue() && !folder.exists()) throw new ApplicationException("There is no parent folder for folder with name [" + folderName + "]."); if (!existingParent.booleanValue() && folder.exists()) throw new ApplicationException("There is already a parent folder for folder with name [" + folderName + "]."); } if (createParentIfNotExists && !folder.exists()) { folder.create(Folder.HOLDS_MESSAGES); } } } return folder; } private void list(Folder folder, Query qry, boolean recurse, int startrow, int maxrows, int rowsMissed) throws MessagingException, PageException { Folder[] folders = folder.list(); if (ArrayUtil.isEmpty(folders)) return; for (Folder f: folders) { // start row if ((startrow - 1) > rowsMissed) { rowsMissed++; continue; } // max rows if (maxrows > 0 && qry.getRecordcount() >= maxrows) break; if ((f.getType() & Folder.HOLDS_MESSAGES) == 0) continue; int row = qry.addRow(); Folder p = null; try { p = f.getParent(); } catch (MessagingException me) { } qry.setAt(KeyConstants._NAME, row, f.getName()); qry.setAt(FULLNAME, row, f.getFullName()); qry.setAt(UNREAD, row, Caster.toDouble(f.getUnreadMessageCount())); qry.setAt(TOTALMESSAGES, row, Caster.toDouble(f.getMessageCount())); qry.setAt(NEW, row, Caster.toDouble(f.getNewMessageCount())); qry.setAt(PARENT, row, p != null ? p.getName() : null); if (recurse) list(f, qry, recurse, startrow, maxrows, rowsMissed); } } /** * Open: Initiates an open session or connection with the IMAP server. * * Close: Terminates the open session or connection with the IMAP server. * */ }
package at.ac.ait.ariadne.routeformat; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.TreeMap; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Preconditions; import at.ac.ait.ariadne.routeformat.Constants.Status; import at.ac.ait.ariadne.routeformat.util.Utils; /** * {@link RouteFormatRoot} is, as the name suggests, the top-level container * class of the ariadne-json-route-format. Typically this will be returned by * routing services. It contains, amongst others, an optional * {@link RoutingRequest} and one or several {@link Route}(s). * <p> * Since most attributes are mandatory no <code>createMinimal</code> method is * offered. * <p> * The coordinate reference system is not directly set in the GeoJSON elements * (as the specification would allow) because this would lead to unnecessarily * big file sizes. Instead the CRS can optionally be set with the attribute * {@link RouteFormatRoot#getCoordinateReferenceSystem()}. * * @author AIT Austrian Institute of Technology GmbH */ @JsonInclude(Include.NON_EMPTY) public class RouteFormatRoot implements Validatable { private String routeFormatVersion; private String requestId; private ZonedDateTime processedTime; private Status status; private Optional<String> debugMessage = Optional.empty(); private String coordinateReferenceSystem; private Optional<RoutingRequest> request = Optional.empty(); private List<Route> routes = new ArrayList<>(); private Map<String, Object> additionalInfo = new TreeMap<>(); // -- getters @JsonProperty(required = true) public String getRouteFormatVersion() { return routeFormatVersion; } @JsonProperty(required = true) public String getRequestId() { return requestId; } /** * Time when request / calculations were finished or deemed not possible in * case of an error. */ @JsonProperty(required = true) public String getProcessedTime() { return processedTime.toString(); } @JsonIgnore public ZonedDateTime getProcessedTimeAsZonedDateTime() { return processedTime; } @JsonProperty(required = true) public Status getStatus() { return status; } /** debug message explaining errors */ public Optional<String> getDebugMessage() { return debugMessage; } /** in the form of EPSG:*, e.g. EPSG:4326 */ @JsonProperty(required = true) public String getCoordinateReferenceSystem() { return coordinateReferenceSystem; } /** * @return The original request used to calculate the route(s). It is * guaranteed that if at least one route is returned there is also a * request here. The request will only be omitted if the request * itself could not be created due to invalid request parameters. */ public Optional<RoutingRequest> getRequest() { return request; } public Map<String, Object> getAdditionalInfo() { return additionalInfo; } @JsonProperty(required = true) public List<Route> getRoutes() { return routes; } // -- setters public RouteFormatRoot setRouteFormatVersion(String routeFormatVersion) { this.routeFormatVersion = routeFormatVersion; return this; } public RouteFormatRoot setRequestId(String requestId) { this.requestId = requestId; return this; } public RouteFormatRoot setProcessedTimeNow() { this.processedTime = ZonedDateTime.now(); return this; } @JsonIgnore public RouteFormatRoot setProcessedTime(ZonedDateTime processedTime) { this.processedTime = processedTime; return this; } @JsonProperty public RouteFormatRoot setProcessedTime(String processedTime) { this.processedTime = Utils.parseZonedDateTime(processedTime, "processedTime"); return this; } public RouteFormatRoot setStatus(Status status) { this.status = status; return this; } public RouteFormatRoot setDebugMessage(String debugMessage) { this.debugMessage = Optional.ofNullable(debugMessage); return this; } public RouteFormatRoot setCoordinateReferenceSystem(String coordinateReferenceSystem) { this.coordinateReferenceSystem = coordinateReferenceSystem; return this; } public RouteFormatRoot setDefaultCoordinateReferenceSystem() { this.coordinateReferenceSystem = "EPSG:4326"; return this; } public RouteFormatRoot setRequest(RoutingRequest request) { this.request = Optional.ofNullable(request); return this; } public RouteFormatRoot setRoutes(List<Route> routes) { this.routes = new ArrayList<>(routes); return this; } public RouteFormatRoot setAdditionalInfo(Map<String, Object> additionalInfo) { this.additionalInfo = new TreeMap<>(additionalInfo); return this; } // no createMinimal! see javadoc for explanation. @Override public void validate() { Preconditions.checkArgument(routeFormatVersion != null, "routeFormatVersion is mandatory but missing"); Preconditions.checkArgument(requestId != null, "requestId is mandatory but missing"); Preconditions.checkArgument(processedTime != null, "processedTime is mandatory but missing"); Preconditions.checkArgument(status != null, "status is mandatory but missing"); Preconditions.checkArgument(coordinateReferenceSystem != null, "coordinateReferenceSystem is mandatory but missing"); Preconditions.checkArgument(coordinateReferenceSystem.startsWith("EPSG:"), "coordinateReferenceSystem must start with EPSG:"); request.ifPresent(r -> r.validate()); routes.forEach(r -> r.validate()); } @Override public String toString() { return "RouteFormatRoot [requestId=" + requestId + ", processedTime=" + processedTime + ", status=" + status + ", routes=" + routes.size() + "]"; } }
package de.lmu.ifi.dbs.algorithm.clustering; import de.lmu.ifi.dbs.algorithm.AbstractAlgorithm; import de.lmu.ifi.dbs.algorithm.Algorithm; import de.lmu.ifi.dbs.algorithm.result.clustering.ClustersPlusNoise; import de.lmu.ifi.dbs.data.RealVector; import de.lmu.ifi.dbs.database.AssociationID; import de.lmu.ifi.dbs.database.Database; import de.lmu.ifi.dbs.distance.DoubleDistance; import de.lmu.ifi.dbs.distance.LocallyWeightedDistanceFunction; import de.lmu.ifi.dbs.logging.LoggingConfiguration; import de.lmu.ifi.dbs.logging.ProgressLogRecord; import de.lmu.ifi.dbs.pca.AbstractLocalPCA; import de.lmu.ifi.dbs.preprocessing.VarianceAnalysisPreprocessor; import de.lmu.ifi.dbs.utilities.Progress; import de.lmu.ifi.dbs.utilities.QueryResult; import de.lmu.ifi.dbs.utilities.Util; import de.lmu.ifi.dbs.utilities.optionhandling.AttributeSettings; import de.lmu.ifi.dbs.utilities.optionhandling.OptionHandler; import de.lmu.ifi.dbs.utilities.optionhandling.ParameterException; import de.lmu.ifi.dbs.utilities.optionhandling.WrongParameterValueException; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; /** * Provides an abstract algorithm requiring a VarianceAnalysisPreprocessor. * * @author Arthur Zimek (<a href="mailto:zimek@dbs.ifi.lmu.de">zimek@dbs.ifi.lmu.de</a>) */ public abstract class ProjectedDBSCAN<P extends VarianceAnalysisPreprocessor> extends AbstractAlgorithm<RealVector> implements Clustering<RealVector> { /** * Holds the class specific debug status. */ private static final boolean DEBUG = LoggingConfiguration.DEBUG; /** * The logger of this class. */ private Logger logger = Logger.getLogger(this.getClass().getName()); /** * Parameter for epsilon. */ public static final String EPSILON_P = DBSCAN.EPSILON_P; /** * Description for parameter epsilon. */ public static final String EPSILON_D = "<epsilon> the maximum radius of the neighborhood to be considered, must be suitable to " + LocallyWeightedDistanceFunction.class.getName(); /** * Parameter minimum points. */ public static final String MINPTS_P = DBSCAN.MINPTS_P; /** * Description for parameter minimum points. */ public static final String MINPTS_D = DBSCAN.MINPTS_D; /** * Epsilon. */ protected String epsilon; /** * Minimum points. */ protected int minpts; /** * Parameter lambda. */ public static final String LAMBDA_P = "lambda"; /** * Description for parameter lambda. */ public static final String LAMBDA_D = "<lambda> a positive integer specifiying the intrinsic dimensionality of clusters to be found."; /** * Keeps lambda. */ private int lambda; /** * Holds a list of clusters found. */ private List<List<Integer>> resultList; /** * Provides the result of the algorithm. */ private ClustersPlusNoise<RealVector> result; /** * Holds a set of noise. */ private Set<Integer> noise; /** * Holds a set of processed ids. */ private Set<Integer> processedIDs; /** * The distance function. */ private LocallyWeightedDistanceFunction distanceFunction = new LocallyWeightedDistanceFunction(); /** * Provides the abstract algorithm for variance analysis based DBSCAN. */ protected ProjectedDBSCAN() { super(); parameterToDescription.put(EPSILON_P + OptionHandler.EXPECTS_VALUE, EPSILON_D); parameterToDescription.put(MINPTS_P + OptionHandler.EXPECTS_VALUE, MINPTS_D); parameterToDescription.put(LAMBDA_P + OptionHandler.EXPECTS_VALUE, LAMBDA_D); parameterToDescription.put(VarianceAnalysisPreprocessor.DELTA_P + OptionHandler.EXPECTS_VALUE, VarianceAnalysisPreprocessor.DELTA_D); optionHandler = new OptionHandler(parameterToDescription, this.getClass().getName()); } /** * @see AbstractAlgorithm#runInTime(Database) */ protected void runInTime(Database<RealVector> database) throws IllegalStateException { if(isVerbose()) { logger.info("\n"); } try { Progress progress = new Progress("Clustering",database.size()); resultList = new ArrayList<List<Integer>>(); noise = new HashSet<Integer>(); processedIDs = new HashSet<Integer>(database.size()); distanceFunction.setDatabase(database, isVerbose(), isTime()); if(isVerbose()) { logger.info("\nClustering:\n"); } if(database.size() >= minpts) { for(Iterator<Integer> iter = database.iterator(); iter.hasNext();) { Integer id = iter.next(); if(!processedIDs.contains(id)) { expandCluster(database, id, progress); if(processedIDs.size() == database.size() && noise.size() == 0) { break; } } if(isVerbose()) { progress.setProcessed(processedIDs.size()); logger.log(new ProgressLogRecord(Level.INFO,Util.status(progress,resultList.size()),progress.getTask(),progress.status())); } } } else { for(Iterator<Integer> iter = database.iterator(); iter.hasNext();) { Integer id = iter.next(); noise.add(id); if(isVerbose()) { progress.setProcessed(processedIDs.size()); logger.log(new ProgressLogRecord(Level.INFO,Util.status(progress,resultList.size()),progress.getTask(),progress.status())); } } } if(isVerbose()) { progress.setProcessed(processedIDs.size()); logger.log(new ProgressLogRecord(Level.INFO,Util.status(progress,resultList.size()),progress.getTask(),progress.status())); } Integer[][] resultArray = new Integer[resultList.size() + 1][]; int i = 0; for(Iterator<List<Integer>> resultListIter = resultList.iterator(); resultListIter.hasNext(); i++) { resultArray[i] = resultListIter.next().toArray(new Integer[0]); } resultArray[resultArray.length - 1] = noise.toArray(new Integer[0]); result = new ClustersPlusNoise<RealVector>(resultArray, database); if(isVerbose()) { progress.setProcessed(processedIDs.size()); logger.log(new ProgressLogRecord(Level.INFO,Util.status(progress,resultList.size()),progress.getTask(),progress.status())); } } catch(Exception e) { throw new IllegalStateException(e); } } /** * ExpandCluster function of DBSCAN. */ protected void expandCluster(Database<RealVector> database, Integer startObjectID, Progress progress) { List<QueryResult<DoubleDistance>> neighborhoodIDs = database.rangeQuery(startObjectID, epsilon, distanceFunction); if(neighborhoodIDs.size() < minpts) { noise.add(startObjectID); processedIDs.add(startObjectID); if(isVerbose()) { progress.setProcessed(processedIDs.size()); logger.log(new ProgressLogRecord(Level.INFO,Util.status(progress,resultList.size()),progress.getTask(),progress.status())); } } else { List<Integer> currentCluster = new ArrayList<Integer>(); if((Integer) database.getAssociation(AssociationID.LOCAL_DIMENSIONALITY, startObjectID) > lambda) { noise.add(startObjectID); processedIDs.add(startObjectID); if(isVerbose()) { progress.setProcessed(processedIDs.size()); logger.log(new ProgressLogRecord(Level.INFO,Util.status(progress,resultList.size()),progress.getTask(),progress.status())); } } else { List<QueryResult<DoubleDistance>> seeds = database.rangeQuery(startObjectID, epsilon, distanceFunction); if(seeds.size() < minpts) { noise.add(startObjectID); processedIDs.add(startObjectID); if(isVerbose()) { progress.setProcessed(processedIDs.size()); logger.log(new ProgressLogRecord(Level.INFO,Util.status(progress,resultList.size()),progress.getTask(),progress.status())); } } else { for(QueryResult<DoubleDistance> nextSeed : seeds) { Integer nextID = nextSeed.getID(); if(!processedIDs.contains(nextID)) { currentCluster.add(nextID); processedIDs.add(nextID); } else if(noise.contains(nextID)) { currentCluster.add(nextID); noise.remove(nextID); } if(isVerbose()) { progress.setProcessed(processedIDs.size()); logger.log(new ProgressLogRecord(Level.INFO,Util.status(progress,resultList.size()),progress.getTask(),progress.status())); } } seeds.remove(0); processedIDs.add(startObjectID); if(isVerbose()) { progress.setProcessed(processedIDs.size()); logger.log(new ProgressLogRecord(Level.INFO,Util.status(progress,resultList.size()),progress.getTask(),progress.status())); } while(seeds.size() > 0) { Integer seedID = seeds.remove(0).getID(); List<QueryResult<DoubleDistance>> seedNeighborhoodIDs = database.rangeQuery(seedID, epsilon, distanceFunction); if(seedNeighborhoodIDs.size() >= minpts) { if((Integer) database.getAssociation(AssociationID.LOCAL_DIMENSIONALITY, seedID) <= lambda) { List<QueryResult<DoubleDistance>> reachables = database.rangeQuery(seedID, epsilon, distanceFunction); if(reachables.size() >= minpts) { for(QueryResult<DoubleDistance> reachable : reachables) { boolean inNoise = noise.contains(reachable.getID()); boolean unclassified = !processedIDs.contains(reachable.getID()); if(inNoise || unclassified) { if(unclassified) { seeds.add(reachable); } currentCluster.add(reachable.getID()); processedIDs.add(reachable.getID()); if(inNoise) { noise.remove(reachable.getID()); } if(isVerbose()) { progress.setProcessed(processedIDs.size()); logger.log(new ProgressLogRecord(Level.INFO,Util.status(progress,resultList.size()),progress.getTask(),progress.status())); } } } } } } } if(currentCluster.size() >= minpts) { resultList.add(currentCluster); } else { for(Integer id : currentCluster) { noise.add(id); } noise.add(startObjectID); processedIDs.add(startObjectID); } if(isVerbose()) { progress.setProcessed(processedIDs.size()); logger.log(new ProgressLogRecord(Level.INFO,Util.status(progress,resultList.size()),progress.getTask(),progress.status())); } } } } } /** * @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#setParameters(String[]) */ public String[] setParameters(String[] args) throws ParameterException { String[] remainingParameters = super.setParameters(args); epsilon = optionHandler.getOptionValue(EPSILON_P); try { // test whether epsilon is compatible with distance function distanceFunction.valueOf(epsilon); } catch(IllegalArgumentException e) { throw new WrongParameterValueException(EPSILON_P, epsilon, EPSILON_D); } // minpts String minptsString = optionHandler.getOptionValue(MINPTS_P); try { minpts = Integer.parseInt(minptsString); if(minpts <= 0) { throw new WrongParameterValueException(MINPTS_P, minptsString, MINPTS_D); } } catch(NumberFormatException e) { throw new WrongParameterValueException(MINPTS_P, minptsString, MINPTS_D, e); } // lambda String lambdaString = optionHandler.getOptionValue(LAMBDA_P); try { lambda = Integer.parseInt(lambdaString); if(lambda <= 0) { throw new WrongParameterValueException(LAMBDA_P, lambdaString, LAMBDA_D); } } catch(NumberFormatException e) { throw new WrongParameterValueException(LAMBDA_P, lambdaString, LAMBDA_D, e); } // delta String deltaString; if(optionHandler.isSet(VarianceAnalysisPreprocessor.DELTA_P)) { deltaString = optionHandler.getOptionValue(VarianceAnalysisPreprocessor.DELTA_P); } else { deltaString = Double.toString(VarianceAnalysisPreprocessor.DEFAULT_DELTA); } // parameters for the distance function List<String> distanceFunctionParameters = new ArrayList<String>(); // big value for PCA distanceFunctionParameters.add(OptionHandler.OPTION_PREFIX + AbstractLocalPCA.BIG_VALUE_P); distanceFunctionParameters.add("50"); // small value for PCA distanceFunctionParameters.add(OptionHandler.OPTION_PREFIX + AbstractLocalPCA.SMALL_VALUE_P); distanceFunctionParameters.add("1"); // delta distanceFunctionParameters.add(OptionHandler.OPTION_PREFIX + VarianceAnalysisPreprocessor.DELTA_P); distanceFunctionParameters.add(deltaString); // preprocessor distanceFunctionParameters.add(OptionHandler.OPTION_PREFIX + LocallyWeightedDistanceFunction.PREPROCESSOR_CLASS_P); distanceFunctionParameters.add(preprocessorClass().getName()); // preprocessor epsilon distanceFunctionParameters.add(OptionHandler.OPTION_PREFIX + VarianceAnalysisPreprocessor.EPSILON_P); distanceFunctionParameters.add(epsilon); distanceFunction.setParameters(distanceFunctionParameters.toArray(new String[distanceFunctionParameters.size()])); setParameters(args, remainingParameters); return remainingParameters; } /** * @see Algorithm#getAttributeSettings() */ @Override public List<AttributeSettings> getAttributeSettings() { List<AttributeSettings> attributeSettings = super.getAttributeSettings(); AttributeSettings mySettings = attributeSettings.get(0); mySettings.addSetting(LAMBDA_P, Integer.toString(lambda)); mySettings.addSetting(EPSILON_P, epsilon); mySettings.addSetting(MINPTS_P, Integer.toString(minpts)); attributeSettings.addAll(distanceFunction.getAttributeSettings()); return attributeSettings; } /** * Returns the class actually used as * {@link VarianceAnalysisPreprocessor VarianceAnalysisPreprocessor}. * * @return the class actually used as * {@link VarianceAnalysisPreprocessor VarianceAnalysisPreprocessor} */ public abstract Class<P> preprocessorClass(); /** * @see de.lmu.ifi.dbs.algorithm.Algorithm#getResult() */ public ClustersPlusNoise<RealVector> getResult() { return result; } }
package com.foursquare.fongo.impl; import com.foursquare.fongo.FongoException; import com.foursquare.fongo.impl.geo.GeoUtil; import com.foursquare.fongo.impl.geo.LatLong; import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.DBRefBase; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ExpressionParser { final static Logger LOG = LoggerFactory.getLogger(ExpressionParser.class); public final static String LT = "$lt"; public final static String LTE = "$lte"; public final static String GT = "$gt"; public final static String GTE = "$gte"; public final static String NE = "$ne"; public final static String ALL = "$all"; public final static String EXISTS = "$exists"; public final static String MOD = "$mod"; public final static String IN = "$in"; public final static String NIN = "$nin"; public final static String SIZE = "$size"; public final static String NOT = "$not"; public final static String OR = "$or"; public final static String AND = "$and"; public final static String REGEX = "$regex"; public final static String REGEX_OPTIONS = "$options"; public final static String NEAR = "$near"; public final static String NEARSPHERE = "$nearSphere"; public final static String MAXDISTANCE = "$maxDistance"; // TODO : http://docs.mongodb.org/manual/reference/operator/geoWithin/#op._S_geoWithin public class ObjectComparator implements Comparator { private final int asc; ObjectComparator(boolean asc) { this.asc = asc ? 1 : -1; } @Override public int compare(Object o1, Object o2) { return asc * compareObjects(o1, o2); } } public Filter buildFilter(DBObject ref) { AndFilter andFilter = new AndFilter(); for (String key : ref.keySet()) { Object expression = ref.get(key); andFilter.addFilter(buildExpressionFilter(key, expression)); } return andFilter; } /** * Only build the filter for this keys. * * @param ref query for filter. * @param keys must match to build the filter. * @return */ public Filter buildFilter(DBObject ref, Collection<String> keys) { AndFilter andFilter = new AndFilter(); for (String key : ref.keySet()) { if (keys.contains(key)) { Object expression = ref.get(key); andFilter.addFilter(buildExpressionFilter(key, expression)); } } return andFilter; } interface FilterFactory { public boolean matchesCommand(DBObject refExpression); public Filter createFilter(List<String> path, DBObject refExpression); } abstract class BasicCommandFilterFactory implements FilterFactory { public final String command; public BasicCommandFilterFactory(final String command) { this.command = command; } public boolean matchesCommand(DBObject refExpression) { return refExpression.containsField(command); } } abstract class BasicFilterFactory extends BasicCommandFilterFactory { public BasicFilterFactory(final String command) { super(command); } public boolean matchesCommand(DBObject refExpression) { return refExpression.containsField(command); } @Override public Filter createFilter(final List<String> path, final DBObject refExpression) { return new Filter() { public boolean apply(DBObject o) { List<Object> storedList = getEmbeddedValues(path, o); if (storedList.isEmpty()) { return false; } else { for (Object storedValue : storedList) { if (compare(refExpression.get(command), storedValue)) { return true; } } return false; } } }; } abstract boolean compare(Object queryValue, Object storedValue); } @SuppressWarnings("all") private final class InFilterFactory extends BasicCommandFilterFactory { private final boolean direction; public InFilterFactory(String command, boolean direction) { super(command); this.direction = direction; } @Override public Filter createFilter(final List<String> path, final DBObject refExpression) { List queryList = typecast(command + " clause", refExpression.get(command), List.class); final Set querySet = new HashSet(queryList); return new Filter() { public boolean apply(DBObject o) { List<Object> storedList = getEmbeddedValues(path, o); if (storedList.isEmpty()) { return !direction; } else { for (Object storedValue : storedList) { if (compare(refExpression.get(command), storedValue, querySet) == direction) { return direction; } } return !direction; } } }; } boolean compare(Object queryValueIgnored, Object storedValue, Set querySet) { if (storedValue instanceof List) { for (Object valueItem : (List) storedValue) { if (querySet.contains(valueItem)) return direction; } return !direction; } else { return !(direction ^ querySet.contains(storedValue)); } } } private final class NearCommandFilterFactory extends BasicCommandFilterFactory { final boolean spherical; public NearCommandFilterFactory(final String command, boolean spherical) { super(command); this.spherical = spherical; } // http://docs.mongodb.org/manual/reference/operator/near/#op._S_near @Override public Filter createFilter(final List<String> path, DBObject refExpression) { LOG.debug("path:{}, refExp:{}", path, refExpression); Number maxDistance = typecast(MAXDISTANCE, refExpression.get(MAXDISTANCE), Number.class); final List<LatLong> coordinates; if (refExpression.get(command) instanceof BasicDBList) { coordinates = GeoUtil.latLon(Collections.singletonList(command), refExpression);// typecast(command, refExpression.get(command), List.class); } else { DBObject dbObject = typecast(command, refExpression.get(command), DBObject.class); coordinates = GeoUtil.latLon(Arrays.asList("$geometry", "coordinates"), dbObject); } return createNearFilter(path, coordinates, maxDistance, spherical); } } public <T> T typecast(String fieldName, Object obj, Class<T> clazz) { try { return clazz.cast(obj); } catch (Exception e) { throw new FongoException(fieldName + " expected to be of type " + clazz.getName() + " but is " + obj); } } private void enforce(boolean check, String message) { if (!check) { throw new FongoException(message); } } abstract class ConditionalOperatorFilterFactory extends BasicFilterFactory { public ConditionalOperatorFilterFactory(String command) { super(command); } final boolean compare(Object queryValue, Object storedValue) { if (storedValue instanceof List) { for (Object aValue : (List) storedValue) { if (aValue != null && singleCompare(queryValue, aValue)) { return true; } } return false; } else { return storedValue != null && singleCompare(queryValue, storedValue); } } abstract boolean singleCompare(Object queryValue, Object storedValue); } @SuppressWarnings("all") List<FilterFactory> filterFactories = Arrays.<FilterFactory>asList( new ConditionalOperatorFilterFactory(GTE) { boolean singleCompare(Object queryValue, Object storedValue) { return compareObjects(queryValue, storedValue) <= 0; } }, new ConditionalOperatorFilterFactory(LTE) { boolean singleCompare(Object queryValue, Object storedValue) { return compareObjects(queryValue, storedValue) >= 0; } }, new ConditionalOperatorFilterFactory(GT) { boolean singleCompare(Object queryValue, Object storedValue) { return compareObjects(queryValue, storedValue) < 0; } }, new ConditionalOperatorFilterFactory(LT) { boolean singleCompare(Object queryValue, Object storedValue) { return compareObjects(queryValue, storedValue) > 0; } }, new BasicCommandFilterFactory(NE) { public Filter createFilter(final List<String> path, final DBObject refExpression) { return new Filter() { public boolean apply(DBObject o) { Object queryValue = refExpression.get(command); List<Object> storedList = getEmbeddedValues(path, o); if (storedList.isEmpty()) { return true; } else { for (Object storedValue : storedList) { if (storedValue instanceof List) { for (Object aValue : (List) storedValue) { if (queryValue.equals(aValue)) { return false; } } } else { if (queryValue.equals(storedValue)) { return false; } } } return true; } } }; } }, new BasicFilterFactory(ALL) { boolean compare(Object queryValue, Object storedValue) { List queryList = typecast(command + " clause", queryValue, List.class); List storedList = typecast("value", storedValue, List.class); if (storedList == null) { return false; } for (Object queryObject : queryList) { if (queryObject instanceof Pattern) { if (!listContainsPattern(storedList, (Pattern) queryObject)) { return false; } } else { if (!storedList.contains(queryObject)) { return false; } } } return true; } }, new BasicCommandFilterFactory(EXISTS) { public Filter createFilter(final List<String> path, final DBObject refExpression) { return new Filter() { public boolean apply(DBObject o) { List<Object> storedOption = getEmbeddedValues(path, o); return typecast(command + " clause", refExpression.get(command), Boolean.class) == !storedOption.isEmpty(); } }; } }, new BasicFilterFactory(MOD) { boolean compare(Object queryValue, Object storedValue) { List<Integer> queryList = typecast(command + " clause", queryValue, List.class); enforce(queryList.size() == 2, command + " clause must be a List of size 2"); int modulus = queryList.get(0); int expectedValue = queryList.get(1); return (storedValue != null) && (typecast("value", storedValue, Number.class).longValue()) % modulus == expectedValue; } }, new InFilterFactory(IN, true), new InFilterFactory(NIN, false), new BasicFilterFactory(SIZE) { boolean compare(Object queryValue, Object storedValue) { Integer size = typecast(command + " clause", queryValue, Integer.class); List storedList = typecast("value", storedValue, List.class); return storedList != null && storedList.size() == size; } }, new BasicCommandFilterFactory(REGEX) { @Override public Filter createFilter(final List<String> path, DBObject refExpression) { String flagStr = typecast(REGEX_OPTIONS, refExpression.get(REGEX_OPTIONS), String.class); int flags = parseRegexOptionsToPatternFlags(flagStr); final Pattern pattern = Pattern.compile(refExpression.get(this.command).toString(), flags); return createPatternFilter(path, pattern); } }, new NearCommandFilterFactory(NEARSPHERE, true), new NearCommandFilterFactory(NEAR, false) ); boolean objectMatchesPattern(Object obj, Pattern pattern) { if (obj instanceof CharSequence) { if (pattern.matcher((CharSequence) obj).find()) { return true; } } return false; } boolean listContainsPattern(List<Object> list, Pattern pattern) { for (Object obj : list) { if (objectMatchesPattern(obj, pattern)) { return true; } } return false; } public List<Object> getEmbeddedValues(List<String> path, DBObject dbo) { return getEmbeddedValues(path, 0, dbo); } public List<Object> getEmbeddedValues(String key, DBObject dbo) { return getEmbeddedValues(Util.split(key), 0, dbo); } public List<Object> extractDBRefValue(DBRefBase ref, String refKey) { if ("$id".equals(refKey)) { return Collections.singletonList(ref.getId()); } else if ("$ref".equals(refKey)) { return Collections.<Object>singletonList(ref.getRef()); } else if ("$db".equals(refKey)) { return Collections.<Object>singletonList(ref.getDB()); } else return Collections.emptyList(); } public List<Object> getEmbeddedValues(List<String> path, int startIndex, DBObject dbo) { String subKey = path.get(startIndex); if (path.size() > 1 && LOG.isDebugEnabled()) { LOG.debug("getEmbeddedValue looking for {} in {}", path, dbo); } for (int i = startIndex; i < path.size() - 1; i++) { Object value = dbo.get(subKey); if (value instanceof DBObject && !(value instanceof List)) { dbo = (DBObject) value; } else if (value instanceof List && Util.isPositiveInt(path.get(i + 1))) { BasicDBList newList = Util.wrap((List) value); dbo = newList; } else if (value instanceof List) { List<Object> results = new ArrayList<Object>(); for (Object listValue : (List) value) { if (listValue instanceof DBObject) { List<Object> embeddedListValue = getEmbeddedValues(path, i + 1, (DBObject) listValue); results.addAll(embeddedListValue); } else if (listValue instanceof DBRefBase) { results.addAll(extractDBRefValue((DBRefBase) listValue, path.get(i + 1))); } } if (!results.isEmpty()) { return results; } } else if (value instanceof DBRefBase) { return extractDBRefValue((DBRefBase) value, path.get(i + 1)); } else { return Collections.emptyList(); } subKey = path.get(i + 1); } if (dbo.containsField(subKey)) { return Collections.singletonList((dbo.get(subKey))); } else { return Collections.emptyList(); } } private Filter buildExpressionFilter(final String key, final Object expression) { return buildExpressionFilter(Util.split(key), expression); } private Filter buildExpressionFilter(final List<String> path, Object expression) { if (OR.equals(path.get(0))) { List<DBObject> queryList = typecast(path + " operator", expression, List.class); OrFilter orFilter = new OrFilter(); for (DBObject query : queryList) { orFilter.addFilter(buildFilter(query)); } return orFilter; } else if (AND.equals(path.get(0))) { List<DBObject> queryList = typecast(path + " operator", expression, List.class); AndFilter andFilter = new AndFilter(); for (DBObject query : queryList) { andFilter.addFilter(buildFilter(query)); } return andFilter; } else if (expression instanceof DBObject || expression instanceof Map) { DBObject ref = expression instanceof DBObject ? (DBObject) expression : new BasicDBObject((Map) expression); if (ref.containsField(NOT)) { return new NotFilter(buildExpressionFilter(path, ref.get(NOT))); } else { AndFilter andFilter = new AndFilter(); int matchCount = 0; for (FilterFactory filterFactory : filterFactories) { if (filterFactory.matchesCommand(ref)) { matchCount++; andFilter.addFilter(filterFactory.createFilter(path, ref)); } } if (matchCount == 0) { return simpleFilter(path, expression); } if (matchCount > 2) { throw new FongoException("Invalid expression for key " + path + ": " + expression); } return andFilter; } } else if (expression instanceof Pattern) { return createPatternFilter(path, (Pattern) expression); } else { return simpleFilter(path, expression); } } public Filter simpleFilter(final List<String> path, final Object expression) { return new Filter() { public boolean apply(DBObject o) { List<Object> storedOption = getEmbeddedValues(path, o); if (storedOption.isEmpty()) { return (expression == null); } else { for (Object storedValue : storedOption) { if (storedValue instanceof List) { if (((List) storedValue).contains(expression)) { return true; } } else { if (expression == null) { return (storedValue == null); } if (expression.equals(storedValue)) { return true; } } } return false; } } }; } @SuppressWarnings("all") public int compareObjects(Object queryValue, Object storedValue) { LOG.debug("comparing {} and {}", queryValue, storedValue); if (queryValue instanceof DBObject && storedValue instanceof DBObject) { return compareDBObjects((DBObject) queryValue, (DBObject) storedValue); } else if (queryValue instanceof List && storedValue instanceof List) { List queryList = (List) queryValue; List storedList = (List) storedValue; return compareLists(queryList, storedList); } else { Comparable queryComp = typecast("query value", queryValue, Comparable.class); Comparable storedComp = typecast("stored value", storedValue, Comparable.class); if (storedComp == null) { return 1; } return queryComp.compareTo(storedComp); } } public int compareLists(List queryList, List storedList) { int sizeDiff = queryList.size() - storedList.size(); if (sizeDiff != 0) { return sizeDiff; } for (int i = 0; i < queryList.size(); i++) { int compareValue = compareObjects(queryList.get(i), storedList.get(i)); if (compareValue != 0) { return compareValue; } } return 0; } private int compareDBObjects(DBObject db0, DBObject db1) { for (String key : db0.keySet()) { int compareValue = compareObjects(db0.get(key), db1.get(key)); if (compareValue != 0) { return compareValue; } } return 0; } public Filter createPatternFilter(final List<String> path, final Pattern pattern) { return new Filter() { public boolean apply(DBObject o) { List<Object> storedOption = getEmbeddedValues(path, o); if (storedOption.isEmpty()) { return false; } else { for (Object storedValue : storedOption) { if (storedValue != null) { if (storedValue instanceof List) { if (listContainsPattern((List) storedValue, pattern)) { return true; } } else if (objectMatchesPattern(storedValue, pattern)) { return true; } } } return false; } } }; } public Filter createNearFilter(final List<String> path, final List<LatLong> coordinates, final Number maxDistance, final boolean sphere) { return new Filter() { final LatLong coordinate = coordinates.get(0); // TODO(twillouer) try to get all coordinate. int limit = 100; public boolean apply(DBObject o) { if (limit <= 0) { return false; } boolean result = false; List<Object> storedOption = getEmbeddedValues(path, o); if (!storedOption.isEmpty()) { if (maxDistance == null) { result = true; } else { for (Object storedValue : storedOption) { List<Number> numberValue = (List<Number>) storedValue; LatLong point = new LatLong(numberValue.get(1).doubleValue(), numberValue.get(0).doubleValue()); double distance = GeoUtil.distanceInRadians(point, coordinate, sphere); LOG.debug("distance : {}", distance); result = distance < maxDistance.doubleValue(); if (result) { break; } } } } if (result) { limit } return result; } }; } static class NotFilter implements Filter { private final Filter filter; public NotFilter(Filter filter) { this.filter = filter; } public boolean apply(DBObject o) { return !filter.apply(o); } } static abstract class ConjunctionFilter implements Filter { List<Filter> filters = new ArrayList<Filter>(); public void addFilter(Filter filter) { filters.add(filter); } } static class AndFilter extends ConjunctionFilter { @Override public boolean apply(DBObject o) { for (Filter f : filters) { if (!f.apply(o)) { return false; } } return true; } } static class OrFilter extends ConjunctionFilter { @Override public boolean apply(DBObject o) { for (Filter f : filters) { if (f.apply(o)) { return true; } } return false; } } public static Filter AllFilter = new Filter() { @Override public boolean apply(DBObject o) { return true; } }; public int parseRegexOptionsToPatternFlags(String flagString) { int flags = 0; for (int i = 0; flagString != null && i < flagString.length(); i++) { switch (flagString.charAt(i)) { case 'i': flags |= Pattern.CASE_INSENSITIVE; break; case 'x': flags |= Pattern.COMMENTS; break; case 'm': flags |= Pattern.MULTILINE; break; case 's': flags |= Pattern.DOTALL; break; } } return flags; } public ObjectComparator buildObjectComparator(boolean asc) { return new ObjectComparator(asc); } }
package com.malhartech.dag; import com.malhartech.api.Sink; import java.util.ArrayList; import java.util.List; /** * A sink implementation to collect expected test results. */ public class TestCountSink<T> extends TestSink<T> { public Integer numTuples = new Integer(0); /** * * @param payload */ @Override public void process(T payload) { if (payload instanceof Tuple) { } else { numTuples = numTuples + 1; } } @Override public void waitForResultCount(int count, long timeoutMillis) throws InterruptedException { while (this.numTuples < count && timeoutMillis > 0) { timeoutMillis -= 20; synchronized (this.numTuples) { if (this.numTuples < count) { numTuples.wait(20); } } } } }
package org.javarosa.core.model; import org.javarosa.core.model.instance.TreeReference; import java.util.Vector; /** * A Form Index is an immutable index into a specific question definition that * will appear in an interaction with a user. * * An index is represented by different levels into hierarchical groups. * * Indices can represent both questions and groups. * * It is absolutely essential that there be no circularity of reference in * FormIndex's, IE, no form index's ancestor can be itself. * * Datatype Productions: * FormIndex = BOF | EOF | CompoundIndex(nextIndex:FormIndex,Location) * Location = Empty | Simple(localLevel:int) | WithMult(localLevel:int, multiplicity:int) * * @author Clayton Sims */ public class FormIndex { private boolean beginningOfForm = false; private boolean endOfForm = false; /** * The index of the questiondef in the current context */ private int localIndex; /** * The multiplicity of the current instance of a repeated question or group */ private int instanceIndex = -1; /** * The next level of this index */ private FormIndex nextLevel; private TreeReference reference; public static FormIndex createBeginningOfFormIndex() { FormIndex begin = new FormIndex(-1, null); begin.beginningOfForm = true; return begin; } public static FormIndex createEndOfFormIndex() { FormIndex end = new FormIndex(-1, null); end.endOfForm = true; return end; } /** * Constructs a simple form index that references a specific element in * a list of elements. * * @param localIndex An integer index into a flat list of elements * @param reference A reference to the instance element identified by this index; */ public FormIndex(int localIndex, TreeReference reference) { this.localIndex = localIndex; this.reference = reference; } /** * Constructs a simple form index that references a specific element in * a list of elements. * * @param localIndex An integer index into a flat list of elements * @param instanceIndex An integer index expressing the multiplicity * of the current level * @param reference A reference to the instance element identified by this index; */ public FormIndex(int localIndex, int instanceIndex, TreeReference reference) { this.localIndex = localIndex; this.instanceIndex = instanceIndex; this.reference = reference; } /** * Constructs an index which indexes an element, and provides an index * into that elements children * * @param nextLevel An index into the referenced element's index * @param localIndex An index to an element at the current level, a child * element of which will be referenced by the nextLevel index. * @param reference A reference to the instance element identified by this index; */ public FormIndex(FormIndex nextLevel, int localIndex, TreeReference reference) { this(localIndex, reference); this.nextLevel = nextLevel; } /** * Constructs an index which references an element past the level of * specificity of the current context, founded by the currentLevel * index. * (currentLevel, (nextLevel...)) */ public FormIndex(FormIndex nextLevel, FormIndex currentLevel) { if (currentLevel == null) { this.nextLevel = nextLevel.nextLevel; this.localIndex = nextLevel.localIndex; this.instanceIndex = nextLevel.instanceIndex; this.reference = nextLevel.reference; } else { this.nextLevel = nextLevel; this.localIndex = currentLevel.getLocalIndex(); this.instanceIndex = currentLevel.getInstanceIndex(); this.reference = currentLevel.reference; } } /** * Constructs an index which indexes an element, and provides an index * into that elements children, along with the current index of a * repeated instance. * * @param nextLevel An index into the referenced element's index * @param localIndex An index to an element at the current level, a child * element of which will be referenced by the nextLevel index. * @param instanceIndex How many times the element referenced has been * repeated. * @param reference A reference to the instance element identified by this index; */ public FormIndex(FormIndex nextLevel, int localIndex, int instanceIndex, TreeReference reference) { this(nextLevel, localIndex, reference); this.instanceIndex = instanceIndex; } public boolean isInForm() { return !beginningOfForm && !endOfForm; } /** * @return The index of the element in the current context */ public int getLocalIndex() { return localIndex; } /** * @return The multiplicity of the current instance of a repeated question or group */ public int getInstanceIndex() { return instanceIndex; } /** * For the fully qualified element, get the multiplicity of the element's reference * * @return The terminal element (fully qualified)'s instance index */ public int getElementMultiplicity() { return getTerminal().instanceIndex; } /** * @return An index into the next level of specificity past the current context. An * example would be an index into an element that is a child of the element referenced * by the local index. */ public FormIndex getNextLevel() { return nextLevel; } public TreeReference getLocalReference() { return reference; } /** * @return The TreeReference of the fully qualified element described by this * FormIndex. */ public TreeReference getReference() { return getTerminal().reference; } public FormIndex getTerminal() { FormIndex walker = this; while (walker.nextLevel != null) { walker = walker.nextLevel; } return walker; } /** * Identifies whether this is a terminal index, in other words whether this * index references with more specificity than the current context */ public boolean isTerminal() { return nextLevel == null; } public boolean isEndOfFormIndex() { return endOfForm; } public boolean isBeginningOfFormIndex() { return beginningOfForm; } public boolean equals(Object o) { if (!(o instanceof FormIndex)) return false; FormIndex a = this; FormIndex b = (FormIndex)o; return (a.compareTo(b) == 0); // //TODO: while(true) loops freak me out, this should probably // //get written more safely. -ctsims // //Iterate over each level of reference, and identify whether // //each object stays in sync // while(true) { // if(index.isTerminal() != local.isTerminal() || // index.getLocalIndex() != local.getLocalIndex() || // index.getInstanceIndex() != local.getInstanceIndex()) { // return false; // if(index.isTerminal()) { // return true; // local = local.getNextLevel(); // index = index.getNextLevel(); } public int compareTo(Object o) { if (!(o instanceof FormIndex)) throw new IllegalArgumentException("Attempt to compare Object of type " + o.getClass().getName() + " to a FormIndex"); FormIndex a = this; FormIndex b = (FormIndex)o; if (a.beginningOfForm) { return (b.beginningOfForm ? 0 : -1); } else if (a.endOfForm) { return (b.endOfForm ? 0 : 1); } else { //a is in form if (b.beginningOfForm) { return 1; } else if (b.endOfForm) { return -1; } } if (a.localIndex != b.localIndex) { return (a.localIndex < b.localIndex ? -1 : 1); } else if (a.instanceIndex != b.instanceIndex) { return (a.instanceIndex < b.instanceIndex ? -1 : 1); } else if ((a.getNextLevel() == null) != (b.getNextLevel() == null)) { return (a.getNextLevel() == null ? -1 : 1); } else if (a.getNextLevel() != null) { return a.getNextLevel().compareTo(b.getNextLevel()); } else { return 0; } // int comp = 0; // //TODO: while(true) loops freak me out, this should probably // //get written more safely. -ctsims // while(comp == 0) { // if(index.isTerminal() != local.isTerminal() || // index.getLocalIndex() != local.getLocalIndex() || // index.getInstanceIndex() != local.getInstanceIndex()) { // if(local.localIndex > index.localIndex) { // return 1; // } else if(local.localIndex < index.localIndex) { // return -1; // } else if (local.instanceIndex > index.instanceIndex) { // return 1; // } else if (local.instanceIndex < index.instanceIndex) { // return -1; // //This case is here as a fallback, but it shouldn't really // //ever be the case that two references have the same chain // //of indices without terminating at the same level. // else if (local.isTerminal() && !index.isTerminal()) { // return -1; // } else { // return 1; // else if(local.isTerminal()) { // break; // local = local.getNextLevel(); // index = index.getNextLevel(); // return comp; } /** * @return Only the local component of this Form Index. */ public FormIndex snip() { FormIndex retval = new FormIndex(localIndex, instanceIndex, reference); return retval; } /** * Takes in a form index which is a subset of this index, and returns the * total difference between them. This is useful for stepping up the level * of index specificty. If the subIndex is not a valid subIndex of this index, * null is returned. Since the FormIndex represented by null is always a subset, * if null is passed in as a subIndex, the full index is returned * * For example: * Indices * a = 1_0,2,1,3 * b = 1,3 * * a.diff(b) = 1_0,2 */ public FormIndex diff(FormIndex subIndex) { if (subIndex == null) { return this; } if (!isSubIndex(this, subIndex)) { return null; } if (subIndex.equals(this)) { return null; } return new FormIndex(nextLevel.diff(subIndex), this.snip()); } public String toString() { String ret = ""; FormIndex ref = this; while (ref != null) { ret += ref.getLocalIndex(); ret += ref.getInstanceIndex() == -1 ? ", " : "_" + ref.getInstanceIndex() + ", "; ref = ref.nextLevel; } return ret; } /** * @return the level of this index relative to the top level of the form */ public int getDepth() { int depth = 0; FormIndex ref = this; while (ref != null) { ref = ref.nextLevel; depth++; } return depth; } /** * Trims any negative indices from the end of the passed in index. */ public static FormIndex trimNegativeIndices(FormIndex index) { if (!index.isTerminal()) { return new FormIndex(trimNegativeIndices(index.nextLevel), index); } else { if (index.getLocalIndex() < 0) { return null; } else { return index; } } } public static boolean isSubIndex(FormIndex parent, FormIndex child) { if (child.equals(parent)) { return true; } else { if (parent == null) { return false; } return isSubIndex(parent.nextLevel, child); } } public static boolean isSubElement(FormIndex parent, FormIndex child) { while (!parent.isTerminal() && !child.isTerminal()) { if (parent.getLocalIndex() != child.getLocalIndex()) { return false; } if (parent.getInstanceIndex() != child.getInstanceIndex()) { return false; } parent = parent.nextLevel; child = child.nextLevel; } //If we've gotten this far, at least one of the two is terminal if (!parent.isTerminal() && child.isTerminal()) { //can't be the parent if the child is earlier on return false; } else if (parent.getLocalIndex() != child.getLocalIndex()) { //Either they're at the same level, in which case only //identical indices should match, or they should have //the same root return false; } else if (parent.getInstanceIndex() != -1 && (parent.getInstanceIndex() != child.getInstanceIndex())) { return false; } //Barring all of these cases, it should be true. return true; } /** * @return Do all the entries of two FormIndexes match except for the last instance index? */ public static boolean areSiblings(FormIndex a, FormIndex b) { if (a.isTerminal() && b.isTerminal() && a.getLocalIndex() == b.getLocalIndex()) { return true; } if (!a.isTerminal() && !b.isTerminal()) { if (a.getLocalIndex() != b.getLocalIndex()) { return false; } return areSiblings(a.nextLevel, b.nextLevel); } return false; } /** * @return Do all the local indexes in the 'parent' FormIndex match the * corresponding ones in 'child'? */ public static boolean overlappingLocalIndexesMatch(FormIndex parent, FormIndex child) { if (parent.getDepth() > child.getDepth()) { return false; } while (!parent.isTerminal()) { if (parent.getLocalIndex() != child.getLocalIndex()) { return false; } parent = parent.nextLevel; child = child.nextLevel; } return parent.getLocalIndex() == child.getLocalIndex(); } public void assignRefs(FormDef f) { FormIndex cur = this; Vector<Integer> indexes = new Vector<Integer>(); Vector<Integer> multiplicities = new Vector<Integer>(); Vector<IFormElement> elements = new Vector<IFormElement>(); f.collapseIndex(this, indexes, multiplicities, elements); Vector<Integer> curMults = new Vector<Integer>(); Vector<IFormElement> curElems = new Vector<IFormElement>(); int i = 0; while (cur != null) { curMults.addElement(multiplicities.elementAt(i)); curElems.addElement(elements.elementAt(i)); TreeReference ref = f.getChildInstanceRef(curElems, curMults); cur.reference = ref; cur = cur.getNextLevel(); i++; } } }
/* * @author max */ package com.intellij.ide.impl; import com.intellij.ide.GeneralSettings; import com.intellij.ide.util.newProjectWizard.AbstractProjectWizard; import com.intellij.ide.util.projectWizard.ProjectBuilder; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.components.StorageScheme; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectBundle; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ex.ProjectManagerEx; import com.intellij.openapi.projectRoots.JavaSdk; import com.intellij.openapi.projectRoots.JavaSdkVersion; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.CompilerProjectExtension; import com.intellij.openapi.roots.LanguageLevelProjectExtension; import com.intellij.openapi.roots.ex.ProjectRootManagerEx; import com.intellij.openapi.roots.ui.configuration.ModulesConfigurator; import com.intellij.openapi.roots.ui.configuration.ModulesProvider; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.wm.*; import com.intellij.openapi.wm.ex.IdeFrameEx; import com.intellij.openapi.wm.impl.IdeFrameImpl; import com.intellij.pom.java.LanguageLevel; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; public class NewProjectUtil { private final static Logger LOG = Logger.getInstance(NewProjectUtil.class); private NewProjectUtil() { } public static void createNewProject(@Nullable Project projectToClose, @NotNull AbstractProjectWizard wizard) { String title = ProjectBundle.message("project.new.wizard.progress.title"); Runnable warmUp = () -> ProjectManager.getInstance().getDefaultProject(); // warm-up components boolean proceed = ProgressManager.getInstance().runProcessWithProgressSynchronously(warmUp, title, true, null); if (proceed && wizard.showAndGet()) { createFromWizard(wizard, projectToClose); } } public static Project createFromWizard(@NotNull AbstractProjectWizard wizard, @Nullable Project projectToClose) { try { return doCreate(wizard, projectToClose); } catch (IOException e) { UIUtil.invokeLaterIfNeeded(() -> Messages.showErrorDialog(e.getMessage(), "Project Initialization Failed")); return null; } } private static Project doCreate(AbstractProjectWizard wizard, @Nullable Project projectToClose) throws IOException { ProjectManagerEx projectManager = ProjectManagerEx.getInstanceEx(); String projectFilePath = wizard.getNewProjectFilePath(); for (Project p : ProjectManager.getInstance().getOpenProjects()) { if (ProjectUtil.isSameProject(projectFilePath, p)) { ProjectUtil.focusProjectWindow(p, false); return null; } } ProjectBuilder projectBuilder = wizard.getProjectBuilder(); LOG.debug("builder " + projectBuilder); try { File projectDir = new File(projectFilePath).getParentFile(); LOG.assertTrue(projectDir != null, "Cannot create project in '" + projectFilePath + "': no parent file exists"); FileUtil.ensureExists(projectDir); if (wizard.getStorageScheme() == StorageScheme.DIRECTORY_BASED) { FileUtil.ensureExists(new File(projectFilePath, Project.DIRECTORY_STORE_FOLDER)); } Project newProject; if (projectBuilder == null || !projectBuilder.isUpdate()) { String name = wizard.getProjectName(); newProject = projectBuilder == null ? projectManager.newProject(name, projectFilePath, true, false) : projectBuilder.createProject(name, projectFilePath); } else { newProject = projectToClose; } if (newProject == null) return projectToClose; Sdk jdk = wizard.getNewProjectJdk(); if (jdk != null) { CommandProcessor.getInstance().executeCommand(newProject, () -> ApplicationManager.getApplication().runWriteAction(() -> applyJdkToProject(newProject, jdk)), null, null); } String compileOutput = wizard.getNewCompileOutput(); CommandProcessor.getInstance().executeCommand(newProject, () -> ApplicationManager.getApplication().runWriteAction(() -> { CompilerProjectExtension extension = CompilerProjectExtension.getInstance(newProject); if (extension != null) { String canonicalPath = compileOutput; try { canonicalPath = FileUtil.resolveShortWindowsName(compileOutput); } catch (IOException ignored) { } extension.setCompilerOutputUrl(VfsUtilCore.pathToUrl(FileUtil.toSystemIndependentName(canonicalPath))); } }), null, null); if (!ApplicationManager.getApplication().isUnitTestMode()) { newProject.save(); } if (projectBuilder != null && !projectBuilder.validate(projectToClose, newProject)) { return projectToClose; } if (newProject != projectToClose && !ApplicationManager.getApplication().isUnitTestMode()) { closePreviousProject(projectToClose); } if (projectBuilder != null) { projectBuilder.commit(newProject, null, ModulesProvider.EMPTY_MODULES_PROVIDER); } boolean need2OpenProjectStructure = projectBuilder == null || projectBuilder.isOpenProjectSettingsAfter(); StartupManager.getInstance(newProject).registerPostStartupActivity(() -> { // ensure the dialog is shown after all startup activities are done ApplicationManager.getApplication().invokeLater(() -> { if (newProject.isDisposed() || ApplicationManager.getApplication().isUnitTestMode()) return; if (need2OpenProjectStructure) { ModulesConfigurator.showDialog(newProject, null, null); } ApplicationManager.getApplication().invokeLater(() -> { if (newProject.isDisposed()) return; ToolWindow toolWindow = ToolWindowManager.getInstance(newProject).getToolWindow(ToolWindowId.PROJECT_VIEW); if (toolWindow != null) { toolWindow.activate(null); } }, ModalityState.NON_MODAL); }, ModalityState.NON_MODAL); }); if (newProject != projectToClose) { ProjectUtil.updateLastProjectLocation(projectFilePath); if (WindowManager.getInstance().isFullScreenSupportedInCurrentOS()) { IdeFocusManager instance = IdeFocusManager.findInstance(); IdeFrame lastFocusedFrame = instance.getLastFocusedFrame(); if (lastFocusedFrame instanceof IdeFrameEx) { boolean fullScreen = ((IdeFrameEx)lastFocusedFrame).isInFullScreen(); if (fullScreen) { newProject.putUserData(IdeFrameImpl.SHOULD_OPEN_IN_FULL_SCREEN, Boolean.TRUE); } } } projectManager.openProject(newProject); } if (!ApplicationManager.getApplication().isUnitTestMode()) { newProject.save(); } return newProject; } finally { if (projectBuilder != null) { projectBuilder.cleanup(); } } } public static void applyJdkToProject(@NotNull Project project, @NotNull Sdk jdk) { ProjectRootManagerEx rootManager = ProjectRootManagerEx.getInstanceEx(project); rootManager.setProjectSdk(jdk); JavaSdkVersion version = JavaSdk.getInstance().getVersion(jdk); if (version != null) { LanguageLevel maxLevel = version.getMaxLanguageLevel(); LanguageLevelProjectExtension extension = LanguageLevelProjectExtension.getInstance(ProjectManager.getInstance().getDefaultProject()); LanguageLevelProjectExtension ext = LanguageLevelProjectExtension.getInstance(project); if (extension.isDefault() || maxLevel.compareTo(ext.getLanguageLevel()) < 0) { ext.setLanguageLevel(maxLevel); } } } public static void closePreviousProject(Project projectToClose) { Project[] openProjects = ProjectManager.getInstance().getOpenProjects(); if (openProjects.length > 0) { int exitCode = ProjectUtil.confirmOpenNewProject(true); if (exitCode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW) { ProjectUtil.closeAndDispose(projectToClose != null ? projectToClose : openProjects[openProjects.length - 1]); } } } }
package de.st_ddt.crazyspawner.entities; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.*; import org.bukkit.inventory.ItemStack; import org.bukkit.material.Colorable; import org.bukkit.metadata.MetadataValue; import de.st_ddt.crazyplugin.exceptions.CrazyException; import de.st_ddt.crazyspawner.CrazySpawner; import de.st_ddt.crazyspawner.entities.properties.*; import de.st_ddt.crazyutil.ChatHelper; import de.st_ddt.crazyutil.ConfigurationSaveable; import de.st_ddt.crazyutil.EntitySpawner; import de.st_ddt.crazyutil.NamedEntitySpawner; import de.st_ddt.crazyutil.VersionComparator; import de.st_ddt.crazyutil.paramitrisable.NamedEntitySpawnerParamitrisable; import de.st_ddt.crazyutil.paramitrisable.Paramitrisable; import de.st_ddt.crazyutil.paramitrisable.StringParamitrisable; import de.st_ddt.crazyutil.paramitrisable.TabbedParamitrisable; import de.st_ddt.crazyutil.source.Localized; public class CustomEntitySpawner implements NamedEntitySpawner, MetadataValue, ConfigurationSaveable { public final static String METAHEADER = "CustomEntityMeta"; protected final static boolean v146OrLater = VersionComparator.compareVersions(ChatHelper.getMinecraftVersion(), "1.4.6") >= 0; protected final static boolean v150OrLater = VersionComparator.compareVersions(ChatHelper.getMinecraftVersion(), "1.5.0") >= 0; protected final static boolean v161OrLater = VersionComparator.compareVersions(ChatHelper.getMinecraftVersion(), "1.6.1") >= 0; protected final static boolean v162OrLater = VersionComparator.compareVersions(ChatHelper.getMinecraftVersion(), "1.6.2") >= 0; protected final static EntitySpawner[] ENTITYSPAWNER = new EntitySpawner[EntityType.values().length]; @SuppressWarnings("unchecked") protected final static Set<Class<? extends EntityPropertyInterface>>[] ENTITYPROPERTIES = new Set[EntityType.values().length]; static { // Spawner - Default for (final EntityType type : EntityType.values()) if (type.isSpawnable()) registerEntitySpawner(new DefaultSpawner(type)); // Spawner - Fixes registerEntitySpawner(new CenteredSpawner(EntityType.ENDER_CRYSTAL) { @Override public Entity spawn(final Location location) { final Entity entity = super.spawn(location); location.clone().add(0, 1, 0).getBlock().setType(Material.FIRE); location.getBlock().setType(Material.BEDROCK); return entity; } }); registerEntitySpawner(new BasicSpawner(EntityType.DROPPED_ITEM) { private final ItemStack item = new ItemStack(1); @Override public Entity spawn(final Location location) { return location.getWorld().dropItem(location, item); } }); registerEntitySpawner(new ClassSpawner(EntityType.FIREWORK)); registerEntitySpawner(new FallingBlockSpawner()); registerEntitySpawner(new LightningSpawner()); // Add Spawners to NamedEntitySpawnerParamitrisable for (final EntitySpawner spawner : ENTITYSPAWNER) if (spawner != null) if (spawner instanceof NamedEntitySpawner) NamedEntitySpawnerParamitrisable.registerNamedEntitySpawner((NamedEntitySpawner) spawner, spawner.getType().name(), spawner.getType().getName()); // Properties for (final EntityType type : EntityType.values()) ENTITYPROPERTIES[type.ordinal()] = new LinkedHashSet<Class<? extends EntityPropertyInterface>>(); // Properties - VIP required to be first! registerEntityProperty(FallingBlockProperty.class, FallingBlock.class); registerEntityProperty(LightningProperty.class, LightningStrike.class); // Properties - Sorted by EntityInterfaces registerEntityProperty(AgeProperty.class, Ageable.class); registerEntityProperty(BoatProperty.class, Boat.class); registerEntityProperty(ColorableProperty.class, Colorable.class); registerEntityProperty(AlarmProperty.class, Creature.class); registerEntityProperty(DetectionProperty.class, Creature.class); registerEntityProperty(CreeperProperty.class, Creeper.class); if (v146OrLater) registerEntityProperty(HealthProperty.class, LivingEntity.class); registerEntityProperty(EndermanProperty.class, Enderman.class); registerEntityProperty(DespawnProperty.class, Entity.class, LivingEntity.class); registerEntityProperty(BurningProperty.class, Entity.class); registerEntityProperty(InvulnerableProperty.class, Entity.class); registerEntityProperty(VelocityProperty.class, Entity.class); registerEntityProperty(PassengerProperty.class, Entity.class); registerEntityProperty(PeacefulProperty.class, Entity.class); registerEntityProperty(ExperienceOrbProperty.class, ExperienceOrb.class); registerEntityProperty(ExplosiveProperty.class, Explosive.class); registerEntityProperty(FallingBlockExtendedProperty.class, FallingBlock.class); // Fireball required? registerEntityProperty(FireworkProperty.class, Firework.class); // Hanging required? if (v162OrLater) registerEntityProperty(HorseProperty.class, Horse.class); // InventoryHolder required? registerEntityProperty(IronGolemProperty.class, IronGolem.class); registerEntityProperty(AlarmProperty.class, Item.class); registerEntityProperty(DroppedItemProperty.class, Item.class); // ItemFrame required? registerEntityProperty(DamageProperty.class, LivingEntity.class); registerEntityProperty(LivingDespawnProperty.class, LivingEntity.class); registerEntityProperty(EquipmentProperties.class, LivingEntity.class); if (v150OrLater) registerEntityProperty(NameProperty.class, LivingEntity.class); registerEntityProperty(PotionProterty.class, LivingEntity.class); registerEntityProperty(XPProperty.class, LivingEntity.class); // Minecard required? registerEntityProperty(OcelotProperty.class, Ocelot.class); // Painting required? registerEntityProperty(PigProperty.class, Pig.class); registerEntityProperty(PigZombieProperty.class, PigZombie.class); // Projectile required? registerEntityProperty(SheepProperty.class, Sheep.class); registerEntityProperty(SkeletonProperty.class, Skeleton.class); registerEntityProperty(SlimeProperty.class, Slime.class); registerEntityProperty(TameableProperty.class, Tameable.class); // TNTPrimed impossible? registerEntityProperty(VillagerProperty.class, Villager.class); registerEntityProperty(WolfProperty.class, Wolf.class); registerEntityProperty(ZombieProperty.class, Zombie.class); } public static void registerEntitySpawner(final EntitySpawner spawner) { ENTITYSPAWNER[spawner.getType().ordinal()] = spawner; } public static Set<EntityType> getSpawnableEntityTypes() { final Set<EntityType> res = new HashSet<EntityType>(); for (final EntityType type : EntityType.values()) if (ENTITYSPAWNER[type.ordinal()] != null) res.add(type); return res; } public static void registerEntityProperty(final Class<? extends EntityPropertyInterface> propertyClass, final Class<?> targetClass) { for (final EntityType type : EntityType.values()) if (type.getEntityClass() != null && targetClass.isAssignableFrom(type.getEntityClass())) ENTITYPROPERTIES[type.ordinal()].add(propertyClass); } public static void registerEntityProperty(final Class<? extends EntityPropertyInterface> propertyClass, final Class<?> targetClass, final Class<?>... ignoredClasses) { for (final EntityType type : EntityType.values()) if (type.getEntityClass() != null && targetClass.isAssignableFrom(type.getEntityClass())) { for (final Class<?> ignoredClass : ignoredClasses) if (ignoredClass.isAssignableFrom(type.getEntityClass())) return; ENTITYPROPERTIES[type.ordinal()].add(propertyClass); } } protected static List<EntityPropertyInterface> getDefaultEntityProperties(final EntityType type) { final Set<Class<? extends EntityPropertyInterface>> properties = ENTITYPROPERTIES[type.ordinal()]; final List<EntityPropertyInterface> res = new ArrayList<EntityPropertyInterface>(properties.size()); for (final Class<? extends EntityPropertyInterface> property : properties) try { res.add(property.newInstance()); } catch (final Exception e) { System.err.println("WARNING: Serious Bug detected, please report this!"); System.err.println("EntityType: " + type.name() + ", Property: " + property.getSimpleName()); e.printStackTrace(); } return res; } protected static List<EntityPropertyInterface> getEntityPropertiesFromConfig(final EntityType type, final ConfigurationSection config) { final Set<Class<? extends EntityPropertyInterface>> properties = ENTITYPROPERTIES[type.ordinal()]; final List<EntityPropertyInterface> res = new ArrayList<EntityPropertyInterface>(properties.size()); for (final Class<? extends EntityPropertyInterface> property : properties) try { res.add(property.getConstructor(ConfigurationSection.class).newInstance(config)); } catch (final Exception e) { System.err.println("WARNING: Serious Bug detected, please report this!"); System.err.println("EntityType: " + type.name() + ", Property: " + property.getSimpleName()); e.printStackTrace(); } return res; } protected static List<EntityPropertyInterface> getEntityPropertiesFromParams(final EntityType type, final Map<String, ? extends Paramitrisable> params) { final Set<Class<? extends EntityPropertyInterface>> properties = ENTITYPROPERTIES[type.ordinal()]; final List<EntityPropertyInterface> res = new ArrayList<EntityPropertyInterface>(properties.size()); for (final Class<? extends EntityPropertyInterface> property : properties) try { res.add(property.getConstructor(Map.class).newInstance(params)); } catch (final Exception e) { System.err.println("WARNING: Serious Bug detected, please report this!"); System.err.println("EntityType: " + type.name() + ", Property: " + property.getSimpleName()); e.printStackTrace(); } return res; } public static StringParamitrisable getCommandParams(final EntityType type, final Map<String, ? super TabbedParamitrisable> params, final CommandSender sender) { final StringParamitrisable nameParam = new StringParamitrisable(null); params.put("n", nameParam); params.put("name", nameParam); for (final EntityPropertyInterface property : getDefaultEntityProperties(type)) property.getCommandParams(params, sender); return nameParam; } public static int getTotalSpawnableEntityTypeCount() { return getSpawnableEntityTypes().size(); } public static int getTotalPropertiesCount() { return getAllPropertyClasses().size(); } protected static Set<Class<? extends EntityPropertyInterface>> getAllPropertyClasses() { final Set<Class<? extends EntityPropertyInterface>> properties = new HashSet<Class<? extends EntityPropertyInterface>>(); for (final EntityType type : getSpawnableEntityTypes()) properties.addAll(ENTITYPROPERTIES[type.ordinal()]); return properties; } public static int getTotalCommandParamsCount() { final Map<String, Paramitrisable> params = new HashMap<String, Paramitrisable>(); final ConsoleCommandSender console = Bukkit.getConsoleSender(); for (final Class<? extends EntityPropertyInterface> property : getAllPropertyClasses()) try { property.newInstance().getCommandParams(params, console); } catch (final Exception e) { System.err.println("WARNING: Serious Bug detected, please report this!"); System.err.println("Property: " + property.getSimpleName()); e.printStackTrace(); } return new HashSet<Paramitrisable>(params.values()).size(); } protected final String name; protected final EntityType type; protected final List<EntityPropertyInterface> properties; public CustomEntitySpawner(final EntityType type) { this(type.getName() == null ? type.name() : type.getName(), type); } public CustomEntitySpawner(final String name, final EntityType type) { super(); if (name == null) throw new IllegalArgumentException("Name cannot be null!"); if (name.length() == 0) throw new IllegalArgumentException("Name cannot be empty!"); this.name = name.toUpperCase(); if (type == null) throw new IllegalArgumentException("Type cannot be null!"); this.type = type; this.properties = getDefaultEntityProperties(type); } public CustomEntitySpawner(final ConfigurationSection config) { super(); if (config == null) throw new IllegalArgumentException("Config cannot be null!"); this.name = config.getString("name", "UNNAMED").toUpperCase(); final String typeName = config.getString("type", null); if (typeName == null) throw new IllegalArgumentException("Type cannot be null!"); this.type = EntityType.valueOf(typeName.toUpperCase()); if (type == null) throw new IllegalArgumentException("Type cannot be null!"); this.properties = getEntityPropertiesFromConfig(type, config); } public CustomEntitySpawner(final EntityType type, final Map<String, ? extends Paramitrisable> params) { super(); final StringParamitrisable nameParam = (StringParamitrisable) params.get("name"); this.name = nameParam.getValue().toUpperCase(); if (type == null) throw new IllegalArgumentException("EntityType cannot be null!"); this.type = type; this.properties = getEntityPropertiesFromParams(type, params); } /** * Creates a CustomEntitySpawner from args.<br> * This is a helper method for default custom entities. * * @param name * The name of the custom entity. * @param type * The entity type of this spawner. * @param sender * The CommandSender how creates this object. * @param args * The params to create this object. */ public CustomEntitySpawner(final String name, final EntityType type, final CommandSender sender, final String... args) { super(); this.name = name; if (type == null) throw new IllegalArgumentException("Type cannot be null!"); this.type = type; final Map<String, Paramitrisable> params = new HashMap<String, Paramitrisable>(); getCommandParams(type, params, sender); for (final String arg : args) { final String[] split = arg.split(":", 2); final Paramitrisable param = params.get(split[0]); if (param != null) try { param.setParameter(split[1]); } catch (final CrazyException e) { e.printStackTrace(); } } this.properties = getEntityPropertiesFromParams(type, params); } @Override public final String getName() { return name; } @Override public final EntityType getType() { return type; } @Override public final Class<? extends Entity> getEntityClass() { return type.getEntityClass(); } protected EntitySpawner getSpawner() { if (!properties.isEmpty()) { final EntityPropertyInterface property = properties.get(0); if (property instanceof EntitySpawner) return (EntitySpawner) property; } return ENTITYSPAWNER[type.ordinal()]; } public final boolean isSpawnable() { return getSpawner() != null; } @Override public final Entity spawn(final Location location) { final EntitySpawner spawner = getSpawner(); if (spawner == null) return null; final Entity entity = spawner.spawn(location); if (entity == null) return null; apply(entity); return entity; } @Localized({ "CRAZYSPAWNER.ENTITY.PROPERTY.NAME $Name$", "CRAZYSPAWNER.ENTITY.PROPERTY.TYPE $EntityType$" }) public void show(final CommandSender target) { CrazySpawner.getPlugin().sendLocaleMessage("ENTITY.PROPERTY.NAME", target, name); CrazySpawner.getPlugin().sendLocaleMessage("ENTITY.PROPERTY.TYPE", target, type.name()); for (final EntityPropertyInterface property : properties) property.show(target); } /** * Apply all features to the given entity.<br> * EntityType of this Spawner must match the EntityType of the given entity. * * @param entity * The entity the properties should be applied to. */ public final void apply(final Entity entity) { entity.setMetadata(METAHEADER, this); for (final EntityPropertyInterface property : properties) property.apply(entity); } @Override public Collection<? extends Entity> getEntities(final World world) { // EDIT include entity properties or check meta return world.getEntitiesByClass(type.getEntityClass()); } public final StringParamitrisable getCommandParams(final Map<String, ? super TabbedParamitrisable> params, final CommandSender sender) { final StringParamitrisable nameParam = new StringParamitrisable(name); params.put("n", nameParam); params.put("name", nameParam); for (final EntityPropertyInterface property : properties) property.getCommandParams(params, sender); return nameParam; } public final void addEntityProperty(final EntityPropertyInterface property) { if (property == null) return; for (int i = 0; i < properties.size(); i++) if (properties.get(i).getClass().getName().equals(property.getClass().getName())) { properties.set(i, property); return; } properties.add(property); } @Override public void save(final ConfigurationSection config, final String path) { config.set(path + "name", name.toUpperCase()); config.set(path + "type", type.name()); for (final EntityPropertyInterface property : properties) property.save(config, path); } public void dummySave(final ConfigurationSection config, final String path) { config.set(path + "name", "String"); config.set(path + "type", "EntityType"); for (final EntityPropertyInterface property : properties) property.dummySave(config, path); } private abstract static class BasicSpawner implements NamedEntitySpawner { protected final EntityType type; public BasicSpawner(final EntityType type) { this.type = type; } @Override public final EntityType getType() { return type; } @Override public String getName() { return type.getName(); } @Override public final Class<? extends Entity> getEntityClass() { return type.getEntityClass(); } @Override public abstract Entity spawn(Location location); @Override public Collection<? extends Entity> getEntities(final World world) { return world.getEntitiesByClass(type.getEntityClass()); } } private static class DefaultSpawner extends BasicSpawner { public DefaultSpawner(final EntityType type) { super(type); } @Override public Entity spawn(final Location location) { return location.getWorld().spawnEntity(location, type); } } private static class CenteredSpawner extends DefaultSpawner { public CenteredSpawner(final EntityType type) { super(type); } @Override public Entity spawn(final Location location) { location.setX(Math.floor(location.getX()) + 0.5); location.setY(Math.floor(location.getY())); location.setZ(Math.floor(location.getZ()) + 0.5); location.setYaw(0); location.setPitch(0); return super.spawn(location); } } private static class ClassSpawner extends DefaultSpawner { public ClassSpawner(final EntityType type) { super(type); } @Override public Entity spawn(final Location location) { try { return location.getWorld().spawn(location, type.getEntityClass()); } catch (final Exception e) { e.printStackTrace(); return null; } } } public static class FallingBlockSpawner extends DefaultSpawner { protected final Material material; protected final byte data; public FallingBlockSpawner() { super(EntityType.FALLING_BLOCK); this.material = Material.STONE; this.data = 0; } public FallingBlockSpawner(final Material material, final byte data) { super(EntityType.FALLING_BLOCK); if (material == null) throw new IllegalArgumentException("Material cannot be null!"); this.material = material; this.data = data; } @Override public final FallingBlock spawn(final Location location) { try { return location.getWorld().spawnFallingBlock(location, material, data); } catch (final Exception e) { e.printStackTrace(); return null; } } @Override public final Collection<FallingBlock> getEntities(final World world) { final Collection<FallingBlock> entities = world.getEntitiesByClass(FallingBlock.class); final Iterator<FallingBlock> it = entities.iterator(); while (it.hasNext()) if (it.next().getMaterial() != material) it.remove(); return entities; } } public static class LightningSpawner extends DefaultSpawner { protected final boolean effect; public LightningSpawner() { super(EntityType.LIGHTNING); this.effect = false; } public LightningSpawner(final boolean effect) { super(EntityType.LIGHTNING); this.effect = effect; } @Override public final String getName() { return "LIGHTNINGSTRIKE"; } @Override public final LightningStrike spawn(final Location location) { if (effect) return location.getWorld().strikeLightningEffect(location); else return location.getWorld().strikeLightning(location); } @Override public final Collection<LightningStrike> getEntities(final World world) { final Collection<LightningStrike> entities = world.getEntitiesByClass(LightningStrike.class); final Iterator<LightningStrike> it = entities.iterator(); while (it.hasNext()) if (it.next().isEffect() != effect) it.remove(); return entities; } } @Override public boolean equals(final Object obj) { if (obj instanceof CustomEntitySpawner) return name.equals(((CustomEntitySpawner) obj).name); else return false; } @Override public int hashCode() { return name.hashCode(); } @Override public final CustomEntitySpawner value() { return this; } @Override public final int asInt() { return 0; } @Override public final float asFloat() { return 0; } @Override public final double asDouble() { return 0; } @Override public final long asLong() { return 0; } @Override public final short asShort() { return 0; } @Override public final byte asByte() { return 0; } @Override public final boolean asBoolean() { return false; } @Override public final String asString() { return toString(); } @Override public final CrazySpawner getOwningPlugin() { return CrazySpawner.getPlugin(); } @Override public final void invalidate() { } }
package org.javarosa.core.model; import org.javarosa.core.model.instance.TreeReference; import java.util.Vector; /** * A Form Index is an immutable index into a specific question definition that * will appear in an interaction with a user. * * An index is represented by different levels into hierarchical groups. * * Indices can represent both questions and groups. * * It is absolutely essential that there be no circularity of reference in * FormIndex's, IE, no form index's ancestor can be itself. * * Datatype Productions: * FormIndex = BOF | EOF | CompoundIndex(nextIndex:FormIndex,Location) * Location = Empty | Simple(localLevel:int) | WithMult(localLevel:int, multiplicity:int) * * @author Clayton Sims */ public class FormIndex { private boolean beginningOfForm = false; private boolean endOfForm = false; /** * The index of the questiondef in the current context */ private int localIndex; /** * The multiplicity of the current instance of a repeated question or group */ private int instanceIndex = -1; /** * The next level of this index */ private FormIndex nextLevel; private TreeReference reference; public static FormIndex createBeginningOfFormIndex() { FormIndex begin = new FormIndex(-1, null); begin.beginningOfForm = true; return begin; } public static FormIndex createEndOfFormIndex() { FormIndex end = new FormIndex(-1, null); end.endOfForm = true; return end; } /** * Constructs a simple form index that references a specific element in * a list of elements. * * @param localIndex An integer index into a flat list of elements * @param reference A reference to the instance element identified by this index; */ public FormIndex(int localIndex, TreeReference reference) { this.localIndex = localIndex; this.reference = reference; } /** * Constructs a simple form index that references a specific element in * a list of elements. * * @param localIndex An integer index into a flat list of elements * @param instanceIndex An integer index expressing the multiplicity * of the current level * @param reference A reference to the instance element identified by this index; */ public FormIndex(int localIndex, int instanceIndex, TreeReference reference) { this.localIndex = localIndex; this.instanceIndex = instanceIndex; this.reference = reference; } /** * Constructs an index which indexes an element, and provides an index * into that elements children * * @param nextLevel An index into the referenced element's index * @param localIndex An index to an element at the current level, a child * element of which will be referenced by the nextLevel index. * @param reference A reference to the instance element identified by this index; */ public FormIndex(FormIndex nextLevel, int localIndex, TreeReference reference) { this(localIndex, reference); this.nextLevel = nextLevel; } /** * Constructs an index which references an element past the level of * specificity of the current context, founded by the currentLevel * index. * (currentLevel, (nextLevel...)) */ public FormIndex(FormIndex nextLevel, FormIndex currentLevel) { if (currentLevel == null) { this.nextLevel = nextLevel.nextLevel; this.localIndex = nextLevel.localIndex; this.instanceIndex = nextLevel.instanceIndex; this.reference = nextLevel.reference; } else { this.nextLevel = nextLevel; this.localIndex = currentLevel.getLocalIndex(); this.instanceIndex = currentLevel.getInstanceIndex(); this.reference = currentLevel.reference; } } /** * Constructs an index which indexes an element, and provides an index * into that elements children, along with the current index of a * repeated instance. * * @param nextLevel An index into the referenced element's index * @param localIndex An index to an element at the current level, a child * element of which will be referenced by the nextLevel index. * @param instanceIndex How many times the element referenced has been * repeated. * @param reference A reference to the instance element identified by this index; */ public FormIndex(FormIndex nextLevel, int localIndex, int instanceIndex, TreeReference reference) { this(nextLevel, localIndex, reference); this.instanceIndex = instanceIndex; } public boolean isInForm() { return !beginningOfForm && !endOfForm; } /** * @return The index of the element in the current context */ public int getLocalIndex() { return localIndex; } /** * @return The multiplicity of the current instance of a repeated question or group */ public int getInstanceIndex() { return instanceIndex; } /** * For the fully qualified element, get the multiplicity of the element's reference * * @return The terminal element (fully qualified)'s instance index */ public int getElementMultiplicity() { return getTerminal().instanceIndex; } /** * @return An index into the next level of specificity past the current context. An * example would be an index into an element that is a child of the element referenced * by the local index. */ public FormIndex getNextLevel() { return nextLevel; } public TreeReference getLocalReference() { return reference; } /** * @return The TreeReference of the fully qualified element described by this * FormIndex. */ public TreeReference getReference() { return getTerminal().reference; } public FormIndex getTerminal() { FormIndex walker = this; while (walker.nextLevel != null) { walker = walker.nextLevel; } return walker; } /** * Identifies whether this is a terminal index, in other words whether this * index references with more specificity than the current context */ public boolean isTerminal() { return nextLevel == null; } public boolean isEndOfFormIndex() { return endOfForm; } public boolean isBeginningOfFormIndex() { return beginningOfForm; } public boolean equals(Object o) { if (!(o instanceof FormIndex)) return false; FormIndex a = this; FormIndex b = (FormIndex)o; return (a.compareTo(b) == 0); // //TODO: while(true) loops freak me out, this should probably // //get written more safely. -ctsims // //Iterate over each level of reference, and identify whether // //each object stays in sync // while(true) { // if(index.isTerminal() != local.isTerminal() || // index.getLocalIndex() != local.getLocalIndex() || // index.getInstanceIndex() != local.getInstanceIndex()) { // return false; // if(index.isTerminal()) { // return true; // local = local.getNextLevel(); // index = index.getNextLevel(); } public int compareTo(Object o) { if (!(o instanceof FormIndex)) throw new IllegalArgumentException("Attempt to compare Object of type " + o.getClass().getName() + " to a FormIndex"); FormIndex a = this; FormIndex b = (FormIndex)o; if (a.beginningOfForm) { return (b.beginningOfForm ? 0 : -1); } else if (a.endOfForm) { return (b.endOfForm ? 0 : 1); } else { //a is in form if (b.beginningOfForm) { return 1; } else if (b.endOfForm) { return -1; } } if (a.localIndex != b.localIndex) { return (a.localIndex < b.localIndex ? -1 : 1); } else if (a.instanceIndex != b.instanceIndex) { return (a.instanceIndex < b.instanceIndex ? -1 : 1); } else if ((a.getNextLevel() == null) != (b.getNextLevel() == null)) { return (a.getNextLevel() == null ? -1 : 1); } else if (a.getNextLevel() != null) { return a.getNextLevel().compareTo(b.getNextLevel()); } else { return 0; } // int comp = 0; // //TODO: while(true) loops freak me out, this should probably // //get written more safely. -ctsims // while(comp == 0) { // if(index.isTerminal() != local.isTerminal() || // index.getLocalIndex() != local.getLocalIndex() || // index.getInstanceIndex() != local.getInstanceIndex()) { // if(local.localIndex > index.localIndex) { // return 1; // } else if(local.localIndex < index.localIndex) { // return -1; // } else if (local.instanceIndex > index.instanceIndex) { // return 1; // } else if (local.instanceIndex < index.instanceIndex) { // return -1; // //This case is here as a fallback, but it shouldn't really // //ever be the case that two references have the same chain // //of indices without terminating at the same level. // else if (local.isTerminal() && !index.isTerminal()) { // return -1; // } else { // return 1; // else if(local.isTerminal()) { // break; // local = local.getNextLevel(); // index = index.getNextLevel(); // return comp; } /** * @return Only the local component of this Form Index. */ public FormIndex snip() { FormIndex retval = new FormIndex(localIndex, instanceIndex, reference); return retval; } /** * Takes in a form index which is a subset of this index, and returns the * total difference between them. This is useful for stepping up the level * of index specificty. If the subIndex is not a valid subIndex of this index, * null is returned. Since the FormIndex represented by null is always a subset, * if null is passed in as a subIndex, the full index is returned * * For example: * Indices * a = 1_0,2,1,3 * b = 1,3 * * a.diff(b) = 1_0,2 */ public FormIndex diff(FormIndex subIndex) { if (subIndex == null) { return this; } if (!isSubIndex(this, subIndex)) { return null; } if (subIndex.equals(this)) { return null; } return new FormIndex(nextLevel.diff(subIndex), this.snip()); } public String toString() { String ret = ""; FormIndex ref = this; while (ref != null) { ret += ref.getLocalIndex(); ret += ref.getInstanceIndex() == -1 ? ", " : "_" + ref.getInstanceIndex() + ", "; ref = ref.nextLevel; } return ret; } /** * @return the level of this index relative to the top level of the form */ public int getDepth() { int depth = 0; FormIndex ref = this; while (ref != null) { ref = ref.nextLevel; depth++; } return depth; } public static boolean isSubIndex(FormIndex parent, FormIndex child) { if (child.equals(parent)) { return true; } else { if (parent == null) { return false; } return isSubIndex(parent.nextLevel, child); } } public static boolean isSubElement(FormIndex parent, FormIndex child) { while (!parent.isTerminal() && !child.isTerminal()) { if (parent.getLocalIndex() != child.getLocalIndex()) { return false; } if (parent.getInstanceIndex() != child.getInstanceIndex()) { return false; } parent = parent.nextLevel; child = child.nextLevel; } //If we've gotten this far, at least one of the two is terminal if (!parent.isTerminal() && child.isTerminal()) { //can't be the parent if the child is earlier on return false; } else if (parent.getLocalIndex() != child.getLocalIndex()) { //Either they're at the same level, in which case only //identical indices should match, or they should have //the same root return false; } else if (parent.getInstanceIndex() != -1 && (parent.getInstanceIndex() != child.getInstanceIndex())) { return false; } //Barring all of these cases, it should be true. return true; } /** * @return Do all the entries of two FormIndexes match except for the last instance index? */ public static boolean areSiblings(FormIndex a, FormIndex b) { if (a.isTerminal() && b.isTerminal() && a.getLocalIndex() == b.getLocalIndex()) { return true; } if (!a.isTerminal() && !b.isTerminal()) { if (a.getLocalIndex() != b.getLocalIndex()) { return false; } return areSiblings(a.nextLevel, b.nextLevel); } return false; } /** * @return Do all the local indexes in the 'parent' FormIndex match the * corresponding ones in 'child'? */ public static boolean overlappingLocalIndexesMatch(FormIndex parent, FormIndex child) { if (parent.getDepth() > child.getDepth()) { return false; } while (!parent.isTerminal()) { if (parent.getLocalIndex() != child.getLocalIndex()) { return false; } parent = parent.nextLevel; child = child.nextLevel; } return parent.getLocalIndex() == child.getLocalIndex(); } public void assignRefs(FormDef f) { FormIndex cur = this; Vector<Integer> indexes = new Vector<Integer>(); Vector<Integer> multiplicities = new Vector<Integer>(); Vector<IFormElement> elements = new Vector<IFormElement>(); f.collapseIndex(this, indexes, multiplicities, elements); Vector<Integer> curMults = new Vector<Integer>(); Vector<IFormElement> curElems = new Vector<IFormElement>(); int i = 0; while (cur != null) { curMults.addElement(multiplicities.elementAt(i)); curElems.addElement(elements.elementAt(i)); TreeReference ref = f.getChildInstanceRef(curElems, curMults); cur.reference = ref; cur = cur.getNextLevel(); i++; } } }
package com.github.mreutegg.laszip4j.laszip; import java.io.PrintStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import static com.github.mreutegg.laszip4j.clib.Cstdio.fprintf; import static com.github.mreutegg.laszip4j.laszip.LASitem.Type.BYTE; import static com.github.mreutegg.laszip4j.laszip.LASitem.Type.GPSTIME11; import static com.github.mreutegg.laszip4j.laszip.LASitem.Type.POINT10; import static com.github.mreutegg.laszip4j.laszip.LASitem.Type.POINT14; import static com.github.mreutegg.laszip4j.laszip.LASitem.Type.RGB12; import static com.github.mreutegg.laszip4j.laszip.LASitem.Type.RGBNIR14; import static com.github.mreutegg.laszip4j.laszip.LASitem.Type.WAVEPACKET13; import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; public class LASzip { private static final PrintStream stderr = System.err; public static final int LASZIP_VERSION_MAJOR = 2; public static final int LASZIP_VERSION_MINOR = 4; public static final int LASZIP_VERSION_REVISION = 1; public static final int LASZIP_VERSION_BUILD_DATE = 150923; public static final char LASZIP_COMPRESSOR_NONE = 0; public static final char LASZIP_COMPRESSOR_POINTWISE = 1; public static final char LASZIP_COMPRESSOR_POINTWISE_CHUNKED = 2; public static final char LASZIP_COMPRESSOR_TOTAL_NUMBER_OF = 3; public static final char LASZIP_COMPRESSOR_CHUNKED = LASZIP_COMPRESSOR_POINTWISE_CHUNKED; public static final char LASZIP_COMPRESSOR_NOT_CHUNKED = LASZIP_COMPRESSOR_POINTWISE; public static final char LASZIP_COMPRESSOR_DEFAULT = LASZIP_COMPRESSOR_CHUNKED; public static final int LASZIP_CODER_ARITHMETIC = 0; public static final int LASZIP_CODER_TOTAL_NUMBER_OF = 1; public static final int LASZIP_CHUNK_SIZE_DEFAULT = 50000; // pack to and unpack from VLR byte[] bytes; // unsigned // stored in LASzip VLR data section public char compressor; public char coder; public byte version_major; // unsigned public byte version_minor; // unsigned public char version_revision; public int options; // unsigned public int chunk_size; // unsigned public long number_of_special_evlrs; /* must be -1 if unused */ public long offset_to_special_evlrs; /* must be -1 if unused */ public char num_items; public LASitem[] items; private String error_string; public LASzip() { compressor = LASZIP_COMPRESSOR_DEFAULT; coder = LASZIP_CODER_ARITHMETIC; version_major = LASZIP_VERSION_MAJOR; version_minor = LASZIP_VERSION_MINOR; version_revision = LASZIP_VERSION_REVISION; options = 0; num_items = 0; chunk_size = LASZIP_CHUNK_SIZE_DEFAULT; number_of_special_evlrs = -1; offset_to_special_evlrs = -1; error_string = null; items = null; bytes = null; } // unpack from VLR data boolean unpack(byte[] bytes, int num) { // check input if (num < 34) return return_error("too few bytes to unpack"); if (((num - 34) % 6) != 0) return return_error("wrong number bytes to unpack"); if (((num - 34) / 6) == 0) return return_error("zero items to unpack"); num_items = (char) ((num - 34) / 6); // create item list items = new LASitem[num_items]; // do the unpacking int i; int b = 0; ByteBuffer buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN); compressor = buffer.getChar(b); b += 2; coder = buffer.getChar(b); b += 2; version_major = buffer.get(b); b += 1; version_minor = buffer.get(b); b += 1; version_revision = buffer.getChar(b); b += 2; options = buffer.getInt(b); b += 4; chunk_size = buffer.getInt(b); b += 4; number_of_special_evlrs = buffer.getLong(b); b += 8; offset_to_special_evlrs = buffer.getLong(b); b += 8; num_items = buffer.getChar(b); b += 2; for (i = 0; i < num_items; i++) { items[i].type = LASitem.Type.fromOrdinal(buffer.getChar(b)); b += 2; items[i].size = buffer.getChar(b); b += 2; items[i].version = buffer.getChar(b); b += 2; } assert(num == b); // check if we support the contents for (i = 0; i < num_items; i++) { if (!check_item(items[i])) return false; } return true; } // pack to VLR data boolean pack(byte[][] bytes, int[] num) { // check if we support the contents if (!check()) return false; // prepare output num[0] = 34 + 6*num_items; this.bytes = bytes[0] = new byte[num[0]]; // pack int i; int b = 0; ByteBuffer buffer = ByteBuffer.wrap(bytes[0]).order(ByteOrder.LITTLE_ENDIAN); buffer.putChar(b, compressor); b += 2; buffer.putChar(b, coder); b += 2; buffer.put(b, version_major); b += 1; buffer.put(b, version_minor); b += 1; buffer.putChar(b, version_revision); b += 2; buffer.putInt(b, options); b += 4; buffer.putInt(b, chunk_size); b += 4; buffer.putLong(b, number_of_special_evlrs); b += 8; buffer.putLong(b, offset_to_special_evlrs); b += 8; buffer.putChar(b, num_items); b += 2; for (i = 0; i < num_items; i++) { buffer.putChar(b, (char) items[i].type.ordinal()); b += 2; buffer.putChar(b, items[i].size); b += 2; buffer.putChar(b, items[i].version); b += 2; } assert(num[0] == b); return true; } public String get_error() { return error_string; } boolean return_error(String error) { error_string = String.format("%s (LASzip v%d.%dr%d)", error, LASZIP_VERSION_MAJOR, LASZIP_VERSION_MINOR, LASZIP_VERSION_REVISION); return false; } boolean check_compressor(char compressor) { if (compressor < LASZIP_COMPRESSOR_TOTAL_NUMBER_OF) return true; String error = String.format("compressor %d not supported", (int) compressor); return return_error(error); } boolean check_coder(char coder) { if (coder < LASZIP_CODER_TOTAL_NUMBER_OF) return true; String error = String.format("coder %d not supported", (int) coder); return return_error(error); } boolean check_item(LASitem item) { switch (item.type) { case POINT10: if (item.size != 20) return return_error("POINT10 has size != 20"); if (item.version > 2) return return_error("POINT10 has version > 2"); break; case GPSTIME11: if (item.size != 8) return return_error("GPSTIME11 has size != 8"); if (item.version > 2) return return_error("GPSTIME11 has version > 2"); break; case RGB12: if (item.size != 6) return return_error("RGB12 has size != 6"); if (item.version > 2) return return_error("RGB12 has version > 2"); break; case WAVEPACKET13: if (item.size != 29) return return_error("WAVEPACKET13 has size != 29"); if (item.version > 1) return return_error("WAVEPACKET13 has version > 1"); break; case BYTE: if (item.size < 1) return return_error("BYTE has size < 1"); if (item.version > 2) return return_error("BYTE has version > 2"); break; case POINT14: if (item.size != 30) return return_error("POINT14 has size != 30"); if (item.version > 0) return return_error("POINT14 has version > 0"); break; case RGBNIR14: if (item.size != 8) return return_error("RGBNIR14 has size != 8"); if (item.version > 0) return return_error("RGBNIR14 has version > 0"); break; default: { String error = String.format("item unknown (%d,%d,%d)", item.type.ordinal(), (int) item.size, (int) item.version); return return_error(error); } } return true; } boolean check_items(char num_items, LASitem[] items) { if (num_items == 0) return return_error("number of items cannot be zero"); if (items == null) return return_error("items pointer cannot be NULL"); int i; for (i = 0; i < num_items; i++) { if (!check_item(items[i])) return false; } return true; } public boolean check() { if (!check_compressor(compressor)) return false; if (!check_coder(coder)) return false; if (!check_items(num_items, items)) return false; return true; } boolean request_compatibility_mode(char requested_compatibility_mode) { if (num_items != 0) return return_error("request compatibility mode before calling setup()"); if (requested_compatibility_mode > 1) { return return_error("compatibility mode larger than 1 not supported"); } if (requested_compatibility_mode != 0) { options = options | 0x00000001; } else { options = options & 0xFFFFFFFE; } return true; } boolean setup(byte u_point_type, char point_size, char compressor) { if (!check_compressor(compressor)) return false; this.num_items = 0; this.items = null; char[] _num_items = new char[1]; LASitem[][] _items = new LASitem[1][]; if (!setup(_num_items, _items, u_point_type, point_size, compressor)) return false; this.num_items = _num_items[0]; this.items = _items[0]; this.compressor = compressor; if (this.compressor == LASZIP_COMPRESSOR_POINTWISE_CHUNKED) { if (chunk_size == 0) chunk_size = LASZIP_CHUNK_SIZE_DEFAULT; } return true; } boolean setup(char num_items, LASitem[] items, char compressor) { // check input if (!check_compressor(compressor)) return false; if (!check_items(num_items, items)) return false; // setup compressor this.compressor = compressor; if (this.compressor == LASZIP_COMPRESSOR_POINTWISE_CHUNKED) { if (chunk_size == 0) chunk_size = LASZIP_CHUNK_SIZE_DEFAULT; } // prepare items this.num_items = 0; this.num_items = num_items; this.items = new LASitem[num_items]; // setup items int i; for (i = 0; i < this.items.length; i++) { this.items[i] = items[i]; } return true; } boolean setup(char[] num_items, LASitem[][] items, byte u_point_type, char point_size, char compressor) { boolean compatible = FALSE; boolean have_point14 = FALSE; boolean have_gps_time = FALSE; boolean have_rgb = FALSE; boolean have_nir = FALSE; boolean have_wavepacket = FALSE; int extra_bytes_number = 0; // turns on LAS 1.4 compatibility mode if ((options & 1) != 0) compatible = TRUE; // switch over the point types we know switch (u_point_type) { case 0: extra_bytes_number = (int)point_size - 20; break; case 1: have_gps_time = TRUE; extra_bytes_number = (int)point_size - 28; break; case 2: have_rgb = TRUE; extra_bytes_number = (int)point_size - 26; break; case 3: have_gps_time = TRUE; have_rgb = TRUE; extra_bytes_number = (int)point_size - 34; break; case 4: have_gps_time = TRUE; have_wavepacket = TRUE; extra_bytes_number = (int)point_size - 57; break; case 5: have_gps_time = TRUE; have_rgb = TRUE; have_wavepacket = TRUE; extra_bytes_number = (int)point_size - 63; break; case 6: have_point14 = TRUE; extra_bytes_number = (int)point_size - 30; break; case 7: have_point14 = TRUE; have_rgb = TRUE; extra_bytes_number = (int)point_size - 36; break; case 8: have_point14 = TRUE; have_rgb = TRUE; have_nir = TRUE; extra_bytes_number = (int)point_size - 38; break; case 9: have_point14 = TRUE; have_wavepacket = TRUE; extra_bytes_number = (int)point_size - 59; break; case 10: have_point14 = TRUE; have_rgb = TRUE; have_nir = TRUE; have_wavepacket = TRUE; extra_bytes_number = (int)point_size - 67; break; default: { String error = String.format("point type %d unknown", u_point_type); return return_error(error); } } if (extra_bytes_number < 0) { // char error[64]; // sprintf(error, "point size %d too small for point type %d by %d bytes", point_size, point_type, -extra_bytes_number); // return return_error(error); fprintf(stderr, "WARNING: point size %d too small by %d bytes for point type %d. assuming point_size of %d\n", point_size, -extra_bytes_number, u_point_type, point_size-extra_bytes_number); extra_bytes_number = 0; } // maybe represent new LAS 1.4 as corresponding LAS 1.3 points plus extra bytes for compatibility if (have_point14 && compatible) { // we need 4 extra bytes for the new point attributes extra_bytes_number += 5; // we store the GPS time separately have_gps_time = TRUE; // we do not use the point14 item have_point14 = FALSE; // if we have NIR ... if (have_nir) { // we need another 2 extra bytes extra_bytes_number += 2; // we do not use the NIR item have_nir = FALSE; } } // create item description num_items[0] = (char) (1 + asInt(have_gps_time) + asInt(have_rgb) + asInt(have_wavepacket) + asInt(extra_bytes_number != 0)); items[0] = new LASitem[num_items[0]]; for (int i = 0; i < items[0].length; i++) { items[0][i] = new LASitem(); } int i = 1; if (have_point14) { items[0][0].type = POINT14; items[0][0].size = 30; items[0][0].version = 0; } else { items[0][0].type = POINT10; items[0][0].size = 20; items[0][0].version = 0; } if (have_gps_time) { items[0][i].type = GPSTIME11; items[0][i].size = 8; items[0][i].version = 0; i++; } if (have_rgb) { if (have_nir) { items[0][i].type = RGBNIR14; items[0][i].size = 8; items[0][i].version = 0; } else { items[0][i].type = RGB12; items[0][i].size = 6; items[0][i].version = 0; } i++; } if (have_wavepacket) { items[0][i].type = WAVEPACKET13; items[0][i].size = 29; items[0][i].version = 0; i++; } if (extra_bytes_number != 0) { items[0][i].type = BYTE; items[0][i].size = (char) extra_bytes_number; items[0][i].version = 0; i++; } if (compressor != 0) request_version((char) 2); assert(i == num_items[0]); return true; } boolean set_chunk_size(int u_chunk_size) { if (num_items == 0) return return_error("call setup() before setting chunk size"); if (this.compressor == LASZIP_COMPRESSOR_POINTWISE_CHUNKED) { this.chunk_size = u_chunk_size; return true; } return false; } boolean request_version(char requested_version) { if (num_items == 0) return return_error("call setup() before requesting version"); if (compressor == LASZIP_COMPRESSOR_NONE) { if (requested_version > 0) return return_error("without compression version is always 0"); } else { if (requested_version < 1) return return_error("with compression version is at least 1"); if (requested_version > 2) return return_error("version larger than 2 not supported"); } char i; for (i = 0; i < num_items; i++) { switch (items[i].type) { case POINT10: case GPSTIME11: case RGB12: case BYTE: items[i].version = requested_version; break; case WAVEPACKET13: items[i].version = 1; // no version 2 break; default: return return_error("item type not supported"); } } return true; } boolean is_standard(byte[] point_type, char[] record_length) { return is_standard(num_items, items, point_type, record_length); } boolean is_standard(char num_items, LASitem[] items, byte[] point_type, char[] record_length) { if (items == null) return return_error("LASitem array is zero"); // this is always true if (point_type != null) point_type[0] = 127; if (record_length != null) { char i; record_length[0] = 0; for (i = 0; i < num_items; i++) { record_length[0] += items[i].size; } } // the minimal number of items is 1 if (num_items < 1) return return_error("less than one LASitem entries"); // the maximal number of items is 5 if (num_items > 5) return return_error("more than five LASitem entries"); if (items[0].is_type(POINT10)) { // consider all the POINT10 combinations if (num_items == 1) { if (point_type != null) point_type[0] = 0; if (record_length != null) assert(record_length[0] == 20); return true; } else { if (items[1].is_type(GPSTIME11)) { if (num_items == 2) { if (point_type != null) point_type[0] = 1; if (record_length != null) assert(record_length[0] == 28); return true; } else { if (items[2].is_type(RGB12)) { if (num_items == 3) { if (point_type != null) point_type[0] = 3; if (record_length != null) assert(record_length[0] == 34); return true; } else { if (items[3].is_type(WAVEPACKET13)) { if (num_items == 4) { if (point_type != null) point_type[0] = 5; if (record_length != null) assert(record_length[0] == 63); return true; } else { if (items[4].is_type(BYTE)) { if (num_items == 5) { if (point_type != null) point_type[0] = 5; if (record_length != null) assert(record_length[0] == (63 + items[4].size)); return true; } } } } else if (items[3].is_type(BYTE)) { if (num_items == 4) { if (point_type != null) point_type[0] = 3; if (record_length != null) assert(record_length[0] == (34 + items[3].size)); return true; } } } } else if (items[2].is_type(WAVEPACKET13)) { if (num_items == 3) { if (point_type != null) point_type[0] = 4; if (record_length != null) assert(record_length[0] == 57); return true; } else { if (items[3].is_type(BYTE)) { if (num_items == 4) { if (point_type != null) point_type[0] = 4; if (record_length != null) assert(record_length[0] == (57 + items[3].size)); return true; } } } } else if (items[2].is_type(BYTE)) { if (num_items == 3) { if (point_type != null) point_type[0] = 1; if (record_length != null) assert(record_length[0] == (28 + items[2].size)); return true; } } } } else if (items[1].is_type(RGB12)) { if (num_items == 2) { if (point_type != null) point_type[0] = 2; if (record_length != null) assert(record_length[0] == 26); return true; } else { if (items[2].is_type(BYTE)) { if (num_items == 3) { if (point_type != null) point_type[0] = 2; if (record_length != null) assert(record_length[0] == (26 + items[2].size)); return true; } } } } else if (items[1].is_type(BYTE)) { if (num_items == 2) { if (point_type != null) point_type[0] = 0; if (record_length != null) assert(record_length[0] == (20 + items[1].size)); return true; } } } } else if (items[0].is_type(POINT14)) { // consider all the POINT14 combinations if (num_items == 1) { if (point_type != null) point_type[0] = 6; if (record_length != null) assert(record_length[0] == 30); return true; } else { if (items[1].is_type(RGB12)) { if (num_items == 2) { if (point_type != null) point_type[0] = 7; if (record_length != null) assert(record_length[0] == 36); return true; } else { if (items[2].is_type(BYTE)) { if (num_items == 3) { if (point_type != null) point_type[0] = 7; if (record_length != null) assert(record_length[0] == (36 + items[2].size)); return true; } } } } else if (items[1].is_type(RGBNIR14)) { if (num_items == 2) { if (point_type != null) point_type[0] = 8; if (record_length != null) assert(record_length[0] == 38); return true; } else { if (items[2].is_type(WAVEPACKET13)) { if (num_items == 3) { if (point_type != null) point_type[0] = 10; if (record_length != null) assert(record_length[0] == 67); return true; } else { if (items[3].is_type(BYTE)) { if (num_items == 4) { if (point_type != null) point_type[0] = 10; if (record_length != null) assert(record_length[0] == (67 + items[3].size)); return true; } } } } else if (items[2].is_type(BYTE)) { if (num_items == 3) { if (point_type != null) point_type[0] = 8; if (record_length != null) assert(record_length[0] == (38 + items[2].size)); return true; } } } } else if (items[1].is_type(WAVEPACKET13)) { if (num_items == 2) { if (point_type != null) point_type[0] = 9; if (record_length != null) assert(record_length[0] == 59); return true; } else { if (items[2].is_type(BYTE)) { if (num_items == 3) { if (point_type != null) point_type[0] = 9; if (record_length != null) assert(record_length[0] == (59 + items[2].size)); return true; } } } } else if (items[1].is_type(BYTE)) { if (num_items == 2) { if (point_type != null) point_type[0] = 6; if (record_length != null) assert(record_length[0] == (30 + items[1].size)); return true; } } } } else { return_error("first LASitem is neither POINT10 nor POINT14"); } return return_error("LASitem array does not match LAS specification 1.4"); } private static int asInt(boolean b) { return b ? 1 : 0; } }
package de.hfu.studiportal.view; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import de.hfu.funfpunktnull.R; import de.hfu.studiportal.network.NoChangeException; import de.hfu.studiportal.network.RefreshTask; import de.hfu.studiportal.network.RefreshTaskStarter; public class MainActivity extends DialogHostActivity implements Refreshable { private ExamCategoryPagerAdapter pagerAdapter; private ViewPager viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Start Background Service RefreshTaskStarter.startRefreshTask(this); //Build View setContentView(R.layout.activity_main); //Set Up ViewPager viewPager = (ViewPager) findViewById(R.id.pager); this.onRefresh(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return super.onCreateOptionsMenu(menu); } @Override protected void onResume() { super.onResume(); this.cancelProgressDialog(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId() == R.id.action_refresh) { new RefreshTask(this).execute(); return true; } if(item.getItemId() == R.id.action_preferences) { Intent i = new Intent(this, PreferencesActivity.class); this.startActivity(i); return true; } if(item.getItemId() == R.id.action_open_online) { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse("https://studi-portal.hs-furtwangen.de/")); this.startActivity(i); return true; } if(item.getItemId() == R.id.action_search) { Intent i = new Intent(this, ExamSearchActivity.class); this.startActivity(i); } return super.onOptionsItemSelected(item); } @Override public void showErrorDialog(final Exception e) { if(e instanceof NoChangeException) { //No change Toast.makeText(MainActivity.this, getResources().getString(R.string.text_no_change), Toast.LENGTH_SHORT).show(); }else { super.showErrorDialog(e); } } @Override public void onRefresh() { int selectedPage = 0; if(this.viewPager != null) selectedPage = this.viewPager.getCurrentItem(); pagerAdapter = new ExamCategoryPagerAdapter(getSupportFragmentManager(), this, this); this.viewPager.setAdapter(this.pagerAdapter); viewPager.setCurrentItem(selectedPage); } }
package com.blamejared.mcbot.commands; import java.awt.Color; import java.util.List; import java.util.Random; import com.blamejared.mcbot.commands.api.Command; import com.blamejared.mcbot.commands.api.CommandBase; import com.blamejared.mcbot.commands.api.CommandException; import com.blamejared.mcbot.commands.api.CommandRegistrar; import com.blamejared.mcbot.listeners.ChannelListener; import sx.blah.discord.handle.obj.IMessage; import sx.blah.discord.util.EmbedBuilder; @Command public class CommandCommands extends CommandBase { public CommandCommands() { super("commands", false); } private final Random rand = new Random(); @Override public void process(IMessage message, List<String> flags, List<String> args) throws CommandException { final EmbedBuilder embed = new EmbedBuilder(); StringBuilder builder = new StringBuilder(); CommandRegistrar.INSTANCE.getCommands().forEach((key, val) -> { if (val.requirements().matches(message.getAuthor(), message.getGuild())) { builder.append(ChannelListener.PREFIX_CHAR).append(key).append(" ").append(val.getUsage()).append("\n"); } }); embed.withDesc(builder.toString()); rand.setSeed(builder.toString().hashCode()); embed.withColor(Color.HSBtoRGB(rand.nextFloat(), 1, 1)); embed.withTitle("Commands Available:"); message.getChannel().sendMessage(embed.build()); } public String getUsage() { return ""; } }
package org.msgpack.core.buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import static org.msgpack.core.Preconditions.*; /** * Universal MessageBuffer implementation supporting Java6 and Android. * This buffer always uses ByteBuffer-based memory access */ public class MessageBufferU extends MessageBuffer { MessageBufferU(ByteBuffer bb) { super(null, 0L, bb.remaining(), bb.order(ByteOrder.BIG_ENDIAN)); checkNotNull(reference); } MessageBufferU(byte[] arr) { this(ByteBuffer.wrap(arr)); } @Override public MessageBufferU slice(int offset, int length) { if(offset == 0 && length == size()) return this; else { checkArgument(offset + length <= size()); reference.position(offset); reference.limit(offset + length); return new MessageBufferU(reference.slice()); } } private void resetBufferPosition() { reference.position(0); reference.limit(size); } @Override public byte getByte(int index) { return reference.get(index); } @Override public boolean getBoolean(int index) { return reference.get(index) != 0; } @Override public short getShort(int index) { return reference.getShort(index); } @Override public int getInt(int index) { return reference.getInt(index); } @Override public float getFloat(int index) { return reference.getFloat(index); } @Override public long getLong(int index) { return reference.getLong(index); } @Override public double getDouble(int index) { return reference.getDouble(index); } @Override public void getBytes(int index, int len, ByteBuffer dst) { reference.position(index); reference.limit(index+len); try { dst.put(reference); } finally { resetBufferPosition(); } } @Override public void putByte(int index, byte v) { reference.put(index, v); } @Override public void putBoolean(int index, boolean v) { reference.put(index, v ? (byte) 1 : (byte) 0); } @Override public void putShort(int index, short v) { reference.putShort(index, v); } @Override public void putInt(int index, int v) { reference.putInt(index, v); } @Override public void putFloat(int index, float v) { reference.putFloat(index, v); } @Override public void putLong(int index, long l) { reference.putLong(index, l); } @Override public void putDouble(int index, double v) { reference.putDouble(index, v); } @Override public ByteBuffer toByteBuffer(int index, int length) { try { reference.position(index); reference.limit(index+length); return reference.slice(); } finally { resetBufferPosition(); } } @Override public ByteBuffer toByteBuffer() { return toByteBuffer(0, size); } @Override public void getBytes(int index, byte[] dst, int dstOffset, int length) { try { reference.position(index); reference.get(dst, dstOffset, length); } finally { resetBufferPosition(); } } @Override public void putByteBuffer(int index, ByteBuffer src, int len) { assert (len <= src.remaining()); if(src.hasArray()) { byte[] srcArray = src.array(); putBytes(index, srcArray, src.position(), len); } else { for(int i = 0; i < len; ++i) { putByte(index + i, src.get()); } } src.position(src.position() + len); } @Override public void putBytes(int index, byte[] src, int srcOffset, int length) { reference.position(index); try { reference.put(src, srcOffset, length); } finally { resetBufferPosition(); } } @Override public void copyTo(int index, MessageBuffer dst, int offset, int length) { if(dst.hasArray()) { System.arraycopy(this.base, this.offset() + index, dst.getBase(), offset, length); } else { dst.putBytes(offset, this.getArray(), this.offset(), length); } } @Override public byte[] toByteArray() { byte[] b = new byte[size()]; getBytes(0, b, 0, b.length); return b; } }
package dr.evomodel.coalescent; import jebl.math.Binomial; import dr.evolution.coalescent.TreeIntervals; import dr.evomodel.tree.TreeModel; import dr.inference.model.Likelihood; /** * Calculates the coalescent constant for a given tree(Model). * * @author Guy Baele */ public class CoalescentConstantLikelihood extends Likelihood.Abstract { public final static boolean COALESCENT_EVENTS_ONLY = false; private TreeModel treeModel; private TreeIntervals intervals; // PUBLIC STUFF public CoalescentConstantLikelihood(TreeModel treeModel) { super(treeModel); this.treeModel = treeModel; this.intervals = new TreeIntervals(treeModel); } // Likelihood IMPLEMENTATION /** * Calculates the coalescent constant given the treeModel. */ public double calculateLogLikelihood() { intervals.setIntervalsUnknown(); final int nIntervals = intervals.getIntervalCount(); //System.err.println(treeModel); //System.err.println("Interval count: " + nIntervals); double logPDF = 0.0; for (int i = 0; i < nIntervals; i++) { //System.err.println("Lineage count " + i + ": " + intervals.getLineageCount(i)); //System.err.println("Interval time " + i + ": " + intervals.getIntervalTime(i)); //System.err.println("Coalescent event " + i + ": " + intervals.getCoalescentEvents(i)); if (COALESCENT_EVENTS_ONLY) { if (intervals.getCoalescentEvents(i) > 0) { logPDF += Math.log(Binomial.choose2(intervals.getLineageCount(i))); } } else if (intervals.getLineageCount(i) > 2) { logPDF += Math.log(Binomial.choose2(intervals.getLineageCount(i))); //System.err.println("PDF: " + Binomial.choose2(intervals.getLineageCount(i))); } } //START TEST CONTEMPORANEOUS /*double test = 0.0; for (int i = 5; i > 2; --i) { test += Math.log(Binomial.choose2(i)); } if (test != logPDF) { System.err.println(test + " " + logPDF); System.exit(0); }*/ //END TEST CONTEMPORANEOUS //System.err.println("logPDF = " + (-logPDF) + "\n"); return -logPDF; } }
package wge3.game.entity.tilelayers.mapobjects; import com.badlogic.gdx.graphics.g2d.Sprite; import wge3.game.entity.Tile; public final class Door extends Wall { private boolean closed; private boolean hasLock; private boolean locked; private int destroyThreshold; private boolean horizontal; // private KeyType keytype; -> door with lock public Door(boolean horizontal, boolean closed) { sprite = new Sprite(texture, (horizontal? 7:6)*Tile.size, (closed? 3:4)*Tile.size, Tile.size, Tile.size); destroyThreshold = 50; this.closed = closed; locked = false; this.horizontal = horizontal; coversWholeTile = false; } @Override public boolean isPassable() { return !closed; } public void close() { closed = true; changeSprite(); } public void open() { if (!locked) { closed = false; changeSprite(); } } public void lock() { if (!closed) { close(); } locked = true; } public void unlock() { locked = false; } @Override public boolean blocksVision() { return closed; } @Override public void dealDamage(int amount) { if (amount >= destroyThreshold) { HP = 0; } if (closed) { open(); return; } close(); } public void changeSprite() { sprite.setRegion((horizontal? 7:6)*Tile.size, (closed? 3:4)*Tile.size, Tile.size, Tile.size); } }
package org.msgpack.core.buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import static org.msgpack.core.Preconditions.*; /** * Universal MessageBuffer implementation supporting Java6 and Android. * This buffer always uses ByteBuffer-based memory access */ public class MessageBufferU extends MessageBuffer { MessageBufferU(ByteBuffer bb) { super(null, 0L, bb.remaining(), bb.order(ByteOrder.BIG_ENDIAN)); checkNotNull(reference); } MessageBufferU(byte[] arr) { this(ByteBuffer.wrap(arr)); } @Override public MessageBufferU slice(int offset, int length) { if(offset == 0 && length == size()) return this; else { checkArgument(offset + length <= size()); reference.position(offset); reference.limit(offset + length); return new MessageBufferU(reference.slice()); } } @Override public byte getByte(int index) { return reference.get(index); } @Override public boolean getBoolean(int index) { return reference.get(index) != 0; } @Override public short getShort(int index) { return reference.getShort(index); } @Override public int getInt(int index) { return reference.getInt(index); } @Override public float getFloat(int index) { return reference.getFloat(index); } @Override public long getLong(int index) { return reference.getLong(index); } @Override public double getDouble(int index) { return reference.getDouble(index); } @Override public void getBytes(int index, int len, ByteBuffer dst) { reference.position(index); reference.limit(index+len); dst.put(reference); } @Override public void putByte(int index, byte v) { reference.put(index, v); } @Override public void putBoolean(int index, boolean v) { reference.put(index, v ? (byte) 1 : (byte) 0); } @Override public void putShort(int index, short v) { reference.putShort(index, v); } @Override public void putInt(int index, int v) { reference.putInt(index, v); } @Override public void putFloat(int index, float v) { reference.putFloat(index, v); } @Override public void putLong(int index, long l) { reference.putLong(index, l); } @Override public void putDouble(int index, double v) { reference.putDouble(index, v); } @Override public ByteBuffer toByteBuffer(int index, int length) { reference.position(index); reference.limit(index+length); return reference.slice(); } @Override public ByteBuffer toByteBuffer() { return toByteBuffer(0, size); } @Override public void getBytes(int index, byte[] dst, int dstOffset, int length) { reference.position(index); reference.get(dst, dstOffset, length); } @Override public void putByteBuffer(int index, ByteBuffer src, int len) { assert (len <= src.remaining()); if(src.hasArray()) { byte[] srcArray = src.array(); putBytes(index, srcArray, src.position(), len); } else { for(int i = 0; i < len; ++i) { putByte(index + i, src.get()); } } src.position(src.position() + len); } @Override public void putBytes(int index, byte[] src, int srcOffset, int length) { reference.position(index); reference.put(src, srcOffset, length); } @Override public void copyTo(int index, MessageBuffer dst, int offset, int length) { if(dst.hasArray()) { System.arraycopy(this.base, this.offset() + index, dst.getBase(), offset, length); } else { dst.putBytes(offset, this.getArray(), this.offset(), length); } } @Override public byte[] toByteArray() { byte[] b = new byte[size()]; getBytes(0, b, 0, b.length); return b; } }
package com.intellij.psi.formatter.java; import com.intellij.codeFormatting.general.FormatterUtil; import com.intellij.lang.ASTNode; import com.intellij.newCodeFormatting.*; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.formatter.common.AbstractBlock; import com.intellij.psi.impl.source.SourceTreeToPsiMap; import com.intellij.psi.impl.source.parsing.ChameleonTransforming; import com.intellij.psi.impl.source.tree.*; import com.intellij.psi.impl.source.tree.java.ClassElement; import com.intellij.psi.tree.IElementType; import java.util.ArrayList; import java.util.List; import java.util.Iterator; import org.jetbrains.annotations.NotNull; public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlock{ protected final CodeStyleSettings mySettings; protected Indent myIndent; private Indent myChildIndent; private Alignment myChildAlignment; private boolean myUseChildAttributes = false; private Wrap myAnnotationWrap = null; public AbstractJavaBlock(final ASTNode node, final Wrap wrap, final Alignment alignment, final Indent indent, final CodeStyleSettings settings) { super(node, wrap, alignment); mySettings = settings; myIndent = indent; } public static Block createJavaBlock(final ASTNode child, final CodeStyleSettings settings, final Indent indent, Wrap wrap, Alignment alignment) { Indent actualIndent = indent == null ? getDefaultSubtreeIndent(child) : indent; final IElementType elementType = child.getElementType(); if (child.getPsi() instanceof PsiClass) { return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings); } if (isBlockType(elementType)) { return new BlockContainingJavaBlock(child, wrap, alignment, actualIndent, settings); } if (isStatement(child, child.getTreeParent())) { return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings); } if (child instanceof LeafElement) { return new LeafBlock(child, wrap, alignment, actualIndent); } else if (isLikeExtendsList(elementType)) { return new ExtendsListBlock(child, wrap, alignment, settings); } else if (elementType == ElementType.CODE_BLOCK) { return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings); } else if (elementType == ElementType.LABELED_STATEMENT) { return new LabeledJavaBlock(child, wrap, alignment, actualIndent,settings); } else if (elementType == JavaDocElementType.DOC_COMMENT) { return new DocCommentBlock(child, wrap, alignment, actualIndent, settings); } else { return new SimpleJavaBlock(child, wrap, alignment, actualIndent,settings); } } private static boolean isLikeExtendsList(final IElementType elementType) { return elementType == ElementType.EXTENDS_LIST || elementType == ElementType.IMPLEMENTS_LIST || elementType == ElementType.THROWS_LIST; } private static boolean isBlockType(final IElementType elementType) { return elementType == ElementType.SWITCH_STATEMENT || elementType == ElementType.FOR_STATEMENT || elementType == ElementType.WHILE_STATEMENT || elementType == ElementType.DO_WHILE_STATEMENT || elementType == ElementType.TRY_STATEMENT || elementType == ElementType.CATCH_SECTION || elementType == ElementType.IF_STATEMENT || elementType == ElementType.METHOD || elementType == ElementType.ARRAY_INITIALIZER_EXPRESSION || elementType == ElementType.FOREACH_STATEMENT; } public static Block createJavaBlock(final ASTNode child, final CodeStyleSettings settings) { return createJavaBlock(child, settings, getDefaultSubtreeIndent(child), null, null); } private static Indent getDefaultSubtreeIndent(final ASTNode child) { final ASTNode parent = child.getTreeParent(); if (child.getElementType() == ElementType.ANNOTATION) return Formatter.getInstance().getNoneIndent(); final ASTNode prevElement = getPrevElement(child); if (prevElement != null && prevElement.getElementType() == ElementType.MODIFIER_LIST) { return Formatter.getInstance().getNoneIndent(); } if (child.getElementType() == ElementType.DOC_TAG) return Formatter.getInstance().getNoneIndent(); if (child.getElementType() == ElementType.DOC_COMMENT_LEADING_ASTERISKS) return Formatter.getInstance().createSpaceIndent(1); if (parent != null) { final Indent defaultChildIndent = getChildIndent(parent); if (defaultChildIndent != null) return defaultChildIndent; } return null; } private static Indent getChildIndent(final ASTNode parent) { if (parent.getElementType() == ElementType.MODIFIER_LIST) return Formatter.getInstance().getNoneIndent(); if (parent.getElementType() == ElementType.JSP_CODE_BLOCK) return Formatter.getInstance().createNormalIndent(); if (parent.getElementType() == ElementType.DUMMY_HOLDER) return Formatter.getInstance().getNoneIndent(); if (parent.getElementType() == ElementType.CLASS) return Formatter.getInstance().getNoneIndent(); if (parent.getElementType() == ElementType.IF_STATEMENT) return Formatter.getInstance().getNoneIndent(); if (parent.getElementType() == ElementType.TRY_STATEMENT) return Formatter.getInstance().getNoneIndent(); if (parent.getElementType() == ElementType.CATCH_SECTION) return Formatter.getInstance().getNoneIndent(); if (parent.getElementType() == ElementType.FOR_STATEMENT) return Formatter.getInstance().getNoneIndent(); if (parent.getElementType() == ElementType.FOREACH_STATEMENT) return Formatter.getInstance().getNoneIndent(); if (parent.getElementType() == ElementType.BLOCK_STATEMENT) return Formatter.getInstance().getNoneIndent(); if (parent.getElementType() == ElementType.DO_WHILE_STATEMENT) return Formatter.getInstance().getNoneIndent(); if (parent.getElementType() == ElementType.WHILE_STATEMENT) return Formatter.getInstance().getNoneIndent(); if (parent.getElementType() == ElementType.SWITCH_STATEMENT) return Formatter.getInstance().getNoneIndent(); if (parent.getElementType() == ElementType.METHOD) return Formatter.getInstance().getNoneIndent(); if (parent.getElementType() == JavaDocElementType.DOC_COMMENT) return Formatter.getInstance().getNoneIndent(); if (parent.getElementType() == JavaDocElementType.DOC_TAG) return Formatter.getInstance().getNoneIndent(); if (parent.getElementType() == JavaDocElementType.DOC_INLINE_TAG) return Formatter.getInstance().getNoneIndent(); if (parent.getElementType() == ElementType.IMPORT_LIST) return Formatter.getInstance().getNoneIndent(); if (SourceTreeToPsiMap.treeElementToPsi(parent) instanceof PsiFile) { return Formatter.getInstance().getNoneIndent(); } else { return null; } } public SpaceProperty getSpaceProperty(Block child1, Block child2) { return new JavaSpacePropertyProcessor(AbstractJavaBlock.getTreeNode(child2), mySettings).getResult(); } public ASTNode getFirstTreeNode() { return myNode; } public Indent getIndent() { return myIndent; } protected static boolean isStatement(final ASTNode child, final ASTNode parentNode) { if (parentNode != null) { if (parentNode.getElementType() == ElementType.CODE_BLOCK) return false; final int role = ((CompositeElement)parentNode).getChildRole(child); if (parentNode.getElementType() == ElementType.IF_STATEMENT) return role == ChildRole.THEN_BRANCH || role == ChildRole.ELSE_BRANCH; if (parentNode.getElementType() == ElementType.FOR_STATEMENT) return role == ChildRole.LOOP_BODY; if (parentNode.getElementType() == ElementType.WHILE_STATEMENT) return role == ChildRole.LOOP_BODY; if (parentNode.getElementType() == ElementType.DO_WHILE_STATEMENT) return role == ChildRole.LOOP_BODY; if (parentNode.getElementType() == ElementType.FOREACH_STATEMENT) return role == ChildRole.LOOP_BODY; } return false; } protected abstract List<Block> buildChildren(); protected Wrap createChildWrap() { if (myNode.getElementType() == ElementType.EXTENDS_LIST || myNode.getElementType() == ElementType.IMPLEMENTS_LIST) { return Formatter.getInstance().createWrap(getWrapType(mySettings.EXTENDS_LIST_WRAP), false); } else if (myNode.getElementType() == ElementType.BINARY_EXPRESSION) { Wrap actualWrap = myWrap != null ? myWrap : getReservedWrap(); if (actualWrap == null) { return Formatter.getInstance().createWrap(getWrapType(mySettings.BINARY_OPERATION_WRAP), false); } else { if (!hasTheSamePriority(myNode.getTreeParent())) { return Formatter.getInstance().createChildWrap(actualWrap, getWrapType(mySettings.BINARY_OPERATION_WRAP), false); } else { return actualWrap; } } } else if (myNode.getElementType() == ElementType.CONDITIONAL_EXPRESSION) { return Formatter.getInstance().createWrap(getWrapType(mySettings.TERNARY_OPERATION_WRAP), false); } else if (myNode.getElementType() == ElementType.ASSERT_STATEMENT) { return Formatter.getInstance().createWrap(getWrapType(mySettings.ASSERT_STATEMENT_WRAP), false); } else if (myNode.getElementType() == ElementType.FOR_STATEMENT) { return Formatter.getInstance().createWrap(getWrapType(mySettings.FOR_STATEMENT_WRAP), false); } else if (myNode.getElementType() == ElementType.METHOD) { return Formatter.getInstance().createWrap(getWrapType(mySettings.THROWS_LIST_WRAP), true); } else if (myNode.getElementType() == ElementType.CODE_BLOCK) { return Formatter.getInstance().createWrap(Wrap.NORMAL, true); } else { return null; } } protected Alignment createChildAlignment() { if (myNode.getElementType() == ElementType.ASSIGNMENT_EXPRESSION){ return createAlignment(mySettings.ALIGN_MULTILINE_ASSIGNMENT, null); } else if (myNode.getElementType() == ElementType.PARENTH_EXPRESSION){ return createAlignment(mySettings.ALIGN_MULTILINE_PARENTHESIZED_EXPRESSION, null); } else if (myNode.getElementType() == ElementType.CONDITIONAL_EXPRESSION){ return createAlignment(mySettings.ALIGN_MULTILINE_TERNARY_OPERATION, null); } else if (myNode.getElementType() == ElementType.FOR_STATEMENT){ return createAlignment(mySettings.ALIGN_MULTILINE_FOR, null); } else if (myNode.getElementType() == ElementType.EXTENDS_LIST){ return createAlignment(mySettings.ALIGN_MULTILINE_EXTENDS_LIST, null); } else if (myNode.getElementType() == ElementType.IMPLEMENTS_LIST){ return createAlignment(mySettings.ALIGN_MULTILINE_EXTENDS_LIST, null); } else if (myNode.getElementType() == ElementType.THROWS_LIST){ return createAlignment(mySettings.ALIGN_MULTILINE_THROWS_LIST, null); } else if (myNode.getElementType() == ElementType.PARAMETER_LIST){ return createAlignment(mySettings.ALIGN_MULTILINE_PARAMETERS, null); } else if (myNode.getElementType() == ElementType.BINARY_EXPRESSION){ Alignment defaultAlignment = null; if (shouldInheritAlignment()) { defaultAlignment = myAlignment; } return createAlignment(mySettings.ALIGN_MULTILINE_BINARY_OPERATION, defaultAlignment); } else if (myNode.getElementType() == ElementType.CLASS) { return Formatter.getInstance().createAlignment(); } else if (myNode.getElementType() == ElementType.METHOD) { return Formatter.getInstance().createAlignment(); } else { return null; } } private boolean shouldInheritAlignment() { if (myNode.getElementType() == ElementType.BINARY_EXPRESSION) { final ASTNode treeParent = myNode.getTreeParent(); if (treeParent != null && treeParent.getElementType() == ElementType.BINARY_EXPRESSION) { return hasTheSamePriority(treeParent); } } return false; } protected ASTNode processChild(final ArrayList<Block> result, ASTNode child, Alignment defaultAlignment, final Wrap defaultWrap, final Indent childIndent) { if (child.getElementType() == ElementType.METHOD_CALL_EXPRESSION) { result.add(createMethodCallExpressiobBlock(child, arrangeChildWrap(child, defaultWrap), arrangeChildAlignment(child, defaultAlignment))); } else if (child.getElementType() == ElementType.ARRAY_INITIALIZER_EXPRESSION) { result.addAll(new CodeBlockBlock(child, null, null, null, mySettings).buildChildren()); } else if (child.getElementType() == ElementType.LPARENTH && myNode.getElementType() == ElementType.EXPRESSION_LIST){ final Wrap wrap = Formatter.getInstance().createWrap(getWrapType(mySettings.CALL_PARAMETERS_WRAP), false); child = processParenBlock(result, child, WrappingStrategy.createDoNotWrapCommaStrategy(wrap), mySettings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS); } else if (child.getElementType() == ElementType.LPARENTH && myNode.getElementType() == ElementType.PARAMETER_LIST){ final Wrap wrap = Formatter.getInstance().createWrap(getWrapType(mySettings.METHOD_PARAMETERS_WRAP), false); child = processParenBlock(result, child, WrappingStrategy.createDoNotWrapCommaStrategy(wrap), mySettings.ALIGN_MULTILINE_PARAMETERS); } else if (child.getElementType() == ElementType.LPARENTH && myNode.getElementType() == ElementType.ANNOTATION_PARAMETER_LIST){ final Wrap wrap = Formatter.getInstance().createWrap(getWrapType(mySettings.CALL_PARAMETERS_WRAP), false); child = processParenBlock(result, child, WrappingStrategy.createDoNotWrapCommaStrategy(wrap), mySettings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS); } else if (child.getElementType() == ElementType.LPARENTH && myNode.getElementType() == ElementType.PARENTH_EXPRESSION){ child = processParenBlock(result, child, WrappingStrategy.DO_NOT_WRAP, mySettings.ALIGN_MULTILINE_PARENTHESIZED_EXPRESSION); } else if (child.getElementType() == ElementType.ENUM_CONSTANT && myNode instanceof ClassElement) { child = processEnumBlock(result, child, ((ClassElement)myNode).findEnumConstantListDelimiterPlace()); } else { final Block block = createJavaBlock(child, mySettings, childIndent, arrangeChildWrap(child, defaultWrap), arrangeChildAlignment(child, defaultAlignment)); if (child.getElementType() == ElementType.MODIFIER_LIST && containsAnnotations(child)) { myAnnotationWrap = Formatter.getInstance().createWrap(getWrapType(getAnnotationWrapType()), true); } if (block instanceof AbstractJavaBlock) { final AbstractJavaBlock javaBlock = ((AbstractJavaBlock)block); if (myNode.getElementType() == ElementType.METHOD_CALL_EXPRESSION && child.getElementType() == ElementType.REFERENCE_EXPRESSION) { javaBlock.setReservedWrap(getReservedWrap()); } else if (myNode.getElementType() == ElementType.REFERENCE_EXPRESSION && child.getElementType() == ElementType.METHOD_CALL_EXPRESSION) { javaBlock.setReservedWrap(getReservedWrap()); } else if (myNode.getElementType() == ElementType.BINARY_EXPRESSION) { javaBlock.setReservedWrap(defaultWrap); } else if (child.getElementType() == ElementType.MODIFIER_LIST) { javaBlock.setReservedWrap(myAnnotationWrap); if (!lastChildIsAnnotation(child)) { myAnnotationWrap = null; } } } result.add(block); } return child; } private Block createMethodCallExpressiobBlock(final ASTNode node, final Wrap blockWrap, final Alignment alignment) { final ArrayList<ASTNode> nodes = new ArrayList<ASTNode>(); final ArrayList<Block> subBlocks = new ArrayList<Block>(); collectNodes(nodes, node); final Wrap wrap = Formatter.getInstance().createWrap(getWrapType(mySettings.METHOD_CALL_CHAIN_WRAP), false); while (!nodes.isEmpty()) { ArrayList<ASTNode> subNodes = readToNextDot(nodes); subBlocks.add(createSynthBlock(subNodes, wrap)); } return new SynteticCodeBlock(subBlocks, alignment, mySettings, Formatter.getInstance().createContinuationWithoutFirstIndent(), blockWrap); } private Block createSynthBlock(final ArrayList<ASTNode> subNodes, final Wrap wrap) { final ArrayList<Block> subBlocks = new ArrayList<Block>(); final ASTNode firstNode = subNodes.get(0); if (firstNode.getElementType() == ElementType.DOT) { subBlocks.add(createJavaBlock(firstNode, getSettings(), Formatter.getInstance().getNoneIndent(), null, null)); subNodes.remove(0); if (!subNodes.isEmpty()) { subBlocks.add(createSynthBlock(subNodes, wrap)); } return new SynteticCodeBlock(subBlocks, null, mySettings, Formatter.getInstance().createContinuationIndent(), wrap); } else { return new SynteticCodeBlock(createJavaBlocks(subNodes), null, mySettings, Formatter.getInstance().createContinuationWithoutFirstIndent(), null); } } private List<Block> createJavaBlocks(final ArrayList<ASTNode> subNodes) { final ArrayList<Block> result = new ArrayList<Block>(); for (Iterator<ASTNode> iterator = subNodes.iterator(); iterator.hasNext();) { ASTNode node = iterator.next(); result.add(createJavaBlock(node, getSettings(), Formatter.getInstance().createContinuationWithoutFirstIndent(), null, null)); } return result; } private ArrayList<ASTNode> readToNextDot(final ArrayList<ASTNode> nodes) { final ArrayList<ASTNode> result = new ArrayList<ASTNode>(); result.add(nodes.remove(0)); for (Iterator<ASTNode> iterator = nodes.iterator(); iterator.hasNext();) { ASTNode node = iterator.next(); if (node.getElementType() == ElementType.DOT) return result; result.add(node); iterator.remove(); } return result; } private static void collectNodes(List<ASTNode> nodes, ASTNode node) { ChameleonTransforming.transformChildren(node); ASTNode child = node.getFirstChildNode(); while (child != null) { if (!containsWhiteSpacesOnly(child)) { if (child.getElementType() ==ElementType.METHOD_CALL_EXPRESSION || child.getElementType() == ElementType.REFERENCE_EXPRESSION) { collectNodes(nodes, child); } else { nodes.add(child); } } child = child.getTreeNext(); } } private boolean lastChildIsAnnotation(final ASTNode child) { ASTNode current = child.getLastChildNode(); while (current != null && current.getElementType() == ElementType.WHITE_SPACE) { current = current.getTreePrev(); } if (current == null) return false; return current.getElementType() == ElementType.ANNOTATION; } private boolean containsAnnotations(final ASTNode child) { return ((PsiModifierList)child.getPsi()).getAnnotations().length > 0; } private int getAnnotationWrapType() { if (myNode.getElementType() == ElementType.METHOD) { return mySettings.METHOD_ANNOTATION_WRAP; } if (myNode.getElementType() == ElementType.CLASS) { return mySettings.CLASS_ANNOTATION_WRAP; } if (myNode.getElementType() == ElementType.FIELD) { return mySettings.FIELD_ANNOTATION_WRAP; } if (myNode.getElementType() == ElementType.PARAMETER) { return mySettings.PARAMETER_ANNOTATION_WRAP; } if (myNode.getElementType() == ElementType.LOCAL_VARIABLE) { return mySettings.VARIABLE_ANNOTATION_WRAP; } return CodeStyleSettings.DO_NOT_WRAP; } protected Alignment arrangeChildAlignment(final ASTNode child, final Alignment defaultAlignment) { int role = ((CompositeElement)child.getTreeParent()).getChildRole(child); if (myNode.getElementType() == ElementType.FOR_STATEMENT) { if (role == ChildRole.FOR_INITIALIZATION || role == ChildRole.CONDITION || role == ChildRole.FOR_UPDATE) { return defaultAlignment; } else { return null; } } else if (myNode.getElementType() == ElementType.EXTENDS_LIST || myNode.getElementType() == ElementType.IMPLEMENTS_LIST) { if (role == ChildRole.REFERENCE_IN_LIST || role == ChildRole.IMPLEMENTS_KEYWORD) { return defaultAlignment; } else { return null; } } else if (myNode.getElementType() == ElementType.THROWS_LIST) { if (role == ChildRole.REFERENCE_IN_LIST) { return defaultAlignment; } else { return null; } } else if (myNode.getElementType() == ElementType.CLASS) { if (role == ChildRole.CLASS_OR_INTERFACE_KEYWORD) return defaultAlignment; if (isAfterClassKeyword(child)) return null; if (role == ChildRole.MODIFIER_LIST) return defaultAlignment; if (role == ChildRole.DOC_COMMENT) return defaultAlignment; return null; } else if (myNode.getElementType() == ElementType.METHOD) { if (role == ChildRole.MODIFIER_LIST) return defaultAlignment; if (role == ChildRole.TYPE) return defaultAlignment; return null; } else { return defaultAlignment; } } private boolean isAfterClassKeyword(final ASTNode child) { ASTNode treePrev = child.getTreePrev(); while (treePrev != null) { if (treePrev.getElementType() == ElementType.CLASS_KEYWORD || treePrev.getElementType() == ElementType.INTERFACE_KEYWORD) { return true; } treePrev = treePrev.getTreePrev(); } return false; } private Alignment createAlignment(final boolean alignOption, final Alignment defaultAlignment) { return alignOption ? (createAlignmentOrDefault(defaultAlignment)) : defaultAlignment; } protected Wrap arrangeChildWrap(final ASTNode child, Wrap defaultWrap) { if (myAnnotationWrap != null) { try { return myAnnotationWrap; } finally { myAnnotationWrap = null; } } final ASTNode parent = child.getTreeParent(); int role = ((CompositeElement)parent).getChildRole(child); if (myNode.getElementType() == ElementType.BINARY_EXPRESSION) { if (role == ChildRole.OPERATION_SIGN && !mySettings.BINARY_OPERATION_SIGN_ON_NEXT_LINE) return null; if (role == ChildRole.ROPERAND && mySettings.BINARY_OPERATION_SIGN_ON_NEXT_LINE) return null; return defaultWrap; } else if (child.getElementType() == ElementType.EXTENDS_LIST || child.getElementType() == ElementType.IMPLEMENTS_LIST) { return Formatter.getInstance().createWrap(getWrapType(mySettings.EXTENDS_KEYWORD_WRAP), true); } else if (child.getElementType() == ElementType.THROWS_LIST) { return Formatter.getInstance().createWrap(getWrapType(mySettings.THROWS_KEYWORD_WRAP), true); } else if (myNode.getElementType() == ElementType.EXTENDS_LIST || myNode.getElementType() == ElementType.IMPLEMENTS_LIST) { if (role == ChildRole.REFERENCE_IN_LIST) { return defaultWrap; } else { return null; } } else if (myNode.getElementType() == ElementType.CONDITIONAL_EXPRESSION) { if (role == ChildRole.COLON && !mySettings.TERNARY_OPERATION_SIGNS_ON_NEXT_LINE) return null; if (role == ChildRole.QUEST && !mySettings.TERNARY_OPERATION_SIGNS_ON_NEXT_LINE) return null; if (role == ChildRole.THEN_EXPRESSION && mySettings.TERNARY_OPERATION_SIGNS_ON_NEXT_LINE) return null; if (role == ChildRole.ELSE_EXPRESSION && mySettings.TERNARY_OPERATION_SIGNS_ON_NEXT_LINE) return null; return defaultWrap; } else if (myNode.getElementType() == ElementType.REFERENCE_EXPRESSION) { if (role == ChildRole.DOT) { return getReservedWrap(); } else { return defaultWrap; } } else if (myNode.getElementType() == ElementType.FOR_STATEMENT) { if (role == ChildRole.FOR_INITIALIZATION || role == ChildRole.CONDITION || role == ChildRole.FOR_UPDATE) { return defaultWrap; } else { return null; } } else if (myNode.getElementType() == ElementType.METHOD) { if (role == ChildRole.THROWS_LIST) { return defaultWrap; } else { return null; } } else if (myNode.getElementType() == ElementType.MODIFIER_LIST) { if (child.getElementType() == ElementType.ANNOTATION) { return getReservedWrap(); } ASTNode prevElement = getPrevElement(child); if (prevElement != null && prevElement.getElementType() == ElementType.ANNOTATION) { return getReservedWrap(); } else { return null; } } else if (myNode.getElementType() == ElementType.ASSERT_STATEMENT) { if (role == ChildRole.CONDITION) { return defaultWrap; } if (role == ChildRole.ASSERT_DESCRIPTION && !mySettings.ASSERT_STATEMENT_COLON_ON_NEXT_LINE) { return defaultWrap; } if (role == ChildRole.COLON && mySettings.ASSERT_STATEMENT_COLON_ON_NEXT_LINE) { return defaultWrap; } return null; } else if (myNode.getElementType() == ElementType.CODE_BLOCK) { if (role == ChildRole.STATEMENT_IN_BLOCK) { return defaultWrap; } else { return null; } } else { return defaultWrap; } } private static ASTNode getPrevElement(final ASTNode child) { ASTNode result = child.getTreePrev(); while (result != null && result.getElementType() == ElementType.WHITE_SPACE) { result = result.getTreePrev(); } return result; } private boolean hasTheSamePriority(final ASTNode node) { if (node == null) return false; if (node.getElementType() != ElementType.BINARY_EXPRESSION) { return false; } else { final PsiBinaryExpression expr1 = (PsiBinaryExpression)SourceTreeToPsiMap.treeElementToPsi(myNode); final PsiBinaryExpression expr2 = (PsiBinaryExpression)SourceTreeToPsiMap.treeElementToPsi(node); final PsiJavaToken op1 = expr1.getOperationSign(); final PsiJavaToken op2 = expr2.getOperationSign(); return op1.getTokenType() == op2.getTokenType(); } } protected int getWrapType(final int wrap) { switch(wrap) { case Wrap.ALWAYS: return CodeStyleSettings.WRAP_ALWAYS; case Wrap.NORMAL: return CodeStyleSettings.WRAP_AS_NEEDED; case Wrap.NONE: return CodeStyleSettings.DO_NOT_WRAP; default: return CodeStyleSettings.WRAP_ON_EVERY_ITEM; } } private ASTNode processParenBlock(List<Block> result, ASTNode child, WrappingStrategy wrappingStrategy, final boolean doAlign) { myUseChildAttributes = true; final IElementType from = ElementType.LPARENTH; final IElementType to = ElementType.RPARENTH; final Indent externalIndent = Formatter.getInstance().getNoneIndent(); final Indent internalIndent = Formatter.getInstance().createContinuationIndent(); AlignmentStrategy alignmentStrategy = AlignmentStrategy.createDoNotAlingCommaStrategy(createAlignment(doAlign, null)); setChildIndent(internalIndent); setChildAlignment(alignmentStrategy.getAlignment(null)); ASTNode prev = child; while (child != null) { if (!containsWhiteSpacesOnly(child) && child.getTextLength() > 0){ if (child.getElementType() == from) { result.add(createJavaBlock(child, mySettings, externalIndent, null, null)); } else if (child.getElementType() == to) { result.add(createJavaBlock(child, mySettings, externalIndent, null, FormatterUtil.isAfterIncompleted(child) ? alignmentStrategy.getAlignment(null) : null)); return child; } else { final IElementType elementType = child.getElementType(); result.add(createJavaBlock(child, mySettings, internalIndent, wrappingStrategy.getWrap(elementType), alignmentStrategy.getAlignment(elementType))); if (to == null) {//process only one statement return child; } } } prev = child; child = child.getTreeNext(); } return prev; } private ASTNode processEnumBlock(List<Block> result, ASTNode child, ASTNode last) { final WrappingStrategy wrappingStrategy = WrappingStrategy.createDoNotWrapCommaStrategy(Formatter.getInstance() .createWrap(getWrapType(mySettings.ENUM_CONSTANTS_WRAP), true)); while (child != null) { if (!containsWhiteSpacesOnly(child) && child.getTextLength() > 0){ result.add(createJavaBlock(child, mySettings, Formatter.getInstance().createNormalIndent(), wrappingStrategy.getWrap(child.getElementType()), null)); if (child == last) return child; } child = child.getTreeNext(); } return null; } private void setChildAlignment(final Alignment alignment) { myChildAlignment = alignment; } private void setChildIndent(final Indent internalIndent) { myChildIndent = internalIndent; } private Alignment createAlignmentOrDefault(final Alignment defaultAlignment) { return defaultAlignment == null ? Formatter.getInstance().createAlignment() :defaultAlignment; } private int getBraceStyle() { final PsiElement psiNode = SourceTreeToPsiMap.treeElementToPsi(myNode); if (psiNode instanceof PsiClass) { return mySettings.CLASS_BRACE_STYLE; } else if (psiNode instanceof PsiCodeBlock && psiNode.getParent() instanceof PsiMethod){ return mySettings.METHOD_BRACE_STYLE; } else { return mySettings.BRACE_STYLE; } } protected Indent getCodeBlockInternalIndent(final int baseChildrenIndent) { if (isTopLevelClass() && mySettings.DO_NOT_INDENT_TOP_LEVEL_CLASS_MEMBERS) { return Formatter.getInstance().getNoneIndent(); } final int braceStyle = getBraceStyle(); return braceStyle == CodeStyleSettings.NEXT_LINE_SHIFTED ? Formatter.getInstance().createNormalIndent(baseChildrenIndent - 1) : Formatter.getInstance().createNormalIndent(baseChildrenIndent); } private boolean isTopLevelClass() { if (myNode.getElementType() != ElementType.CLASS) return false; return SourceTreeToPsiMap.treeElementToPsi(myNode.getTreeParent()) instanceof PsiFile; } protected Indent getCodeBlockExternalIndent(){ final int braceStyle = getBraceStyle(); if (braceStyle == CodeStyleSettings.END_OF_LINE || braceStyle == CodeStyleSettings.NEXT_LINE || braceStyle == CodeStyleSettings.NEXT_LINE_IF_WRAPPED) { return Formatter.getInstance().getNoneIndent(); } else { return Formatter.getInstance().createNormalIndent(); } } protected abstract Wrap getReservedWrap(); protected abstract void setReservedWrap(final Wrap reservedWrap); protected static ASTNode getTreeNode(final Block child2) { if (child2 instanceof JavaBlock) { return ((JavaBlock)child2).getFirstTreeNode(); } else if (child2 instanceof LeafBlock) { return ((LeafBlock)child2).getTreeNode(); } else if (child2 instanceof SynteticCodeBlock) { return ((SynteticCodeBlock)child2).getFirstTreeNode(); } else { return null; } } @Override @NotNull public ChildAttributes getChildAttributes(final int newChildIndex) { if (myUseChildAttributes) { return new ChildAttributes(myChildIndent, myChildAlignment); } else { return super.getChildAttributes(newChildIndex); } } protected Indent getChildIndent() { return getChildIndent(myNode); } public CodeStyleSettings getSettings() { return mySettings; } }
package com.fangxuele.tool.wechat.push.ui; import java.awt.Image; import java.awt.Toolkit; /** * UI * * @author zhouy */ public class ConstantsUI { public final static String APP_NAME = "WePush"; public final static String APP_VERSION = "v_1.0.1_170626"; public final static Image IMAGE_ICON = Toolkit.getDefaultToolkit() .getImage(new MainWindow().getClass().getResource("/icon/logo-md.png")); }
/** * The single class for which all children and and parent threads are derived * <P> * There contains four constructors for the users needs. * Every constructor requires a comment, user and location. However, the user * has the option of entering an image or a title. * * @author Michael Raypold */ package ca.ualberta.team7project.models; import java.io.ByteArrayOutputStream; import java.util.Date; import java.util.LinkedList; import java.util.UUID; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.location.Location; import android.util.Base64; public class ThreadModel { private String title = null; private String comment = null; private BitmapData bitmapData = null; // bitmap stored as base64-encoded // byte array private Date timestamp = null; // time of last change of any kind private UUID uniqueID = null; // this is also the Elastic Search index private UUID parentUUID = null; private UUID topicUUID = null; private UserModel user; /** * Constructs the ThreadModel with appropriate parameters. Generic reply * with a picture * * @param comment * associated with the thread * @param image * associated with the thread (may be null) * @param user * associated with the thread * @param location * the thread was written at */ public ThreadModel(String comment, Bitmap image, UserModel user, UUID parentUUID, UUID topicUUID) { super(); this.comment = comment; this.bitmapData.encode(image); this.user = user; this.title = null; this.timestamp = new Date(); // every thread has a uniqueID, either topic or comment this.generateUniqueID(); this.parentUUID = parentUUID; this.topicUUID = parentUUID; } public UUID getParentUUID() { return parentUUID; } public void setParentUUID(UUID parentUUID) { this.parentUUID = parentUUID; } public UUID getTopicUUID() { return topicUUID; } public void setTopicUUID(UUID topicUUID) { this.topicUUID = topicUUID; } /** * Constructs the ThreadModel with appropriate parameters. Generic reply * without a picture * * @param comment * associated with the thread * @param user * associated with the thread * @param location * the thread was written at */ public ThreadModel(String comment, UserModel user) { super(); this.comment = comment; this.user = user; this.title = null; this.bitmapData = new BitmapData(); //empty bitmap will be treated as no bitmap this.timestamp = new Date(); // every thread has a uniqueID, either topic or comment this.generateUniqueID(); this.parentUUID = parentUUID; this.topicUUID = parentUUID; } /** * Constructs the ThreadModel with appropriate parameters. Top Level post * with title and picture * * @param comment * associated with the thread * @param image * associated with the thread (may be null) * @param user * associated with the thread * @param location * the thread was written at * @param title * of the thread */ public ThreadModel(String comment, Bitmap image, UserModel user, String title) { super(); this.comment = comment; this.bitmapData.encode(image); this.user = user; this.title = title; this.timestamp = new Date(); // every thread has a uniqueID, either topic or comment this.generateUniqueID(); } /** * Constructs the ThreadModel with appropriate parameters. Top Level post * without picture * * @param comment * associated with the thread * @param user * associated with the thread * @param location * the comment was written at * @param title * of the thread */ public ThreadModel(String comment, UserModel user, String title) { super(); this.comment = comment; this.user = user; this.title = title; this.bitmapData = new BitmapData(); //empty bitmap will be treated as no bitmap this.timestamp = new Date(); // every thread has a uniqueID, either topic or comment this.generateUniqueID(); } public boolean isTopic() { return (this.title != null); } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; this.timestamp = new Date(); } public Bitmap getImage() { return this.bitmapData.decode(); } public void setImage(Bitmap image) { this.bitmapData.encode(image); this.timestamp = new Date(); } public String getAuthorName() { return user.getName(); } public void setAuthorName(String authorName) { this.user.setName(authorName); this.timestamp = new Date(); } public String getAuthorUnique() { return user.getUniqueName(); } public Date getTimestamp() { return timestamp; } public void resetTimestamp() { this.timestamp = new Date(); } public Location getLocation() { return user.getLocation(); } public void setLocation(Location location) { this.user.setLocation(location); this.timestamp = new Date(); } public UUID getUniqueID() { return this.uniqueID; } public void setUniqueID(UUID uniqueID) { this.uniqueID = uniqueID; // not updating timestamp on purpose } public void generateUniqueID() { this.uniqueID = UUID.randomUUID(); // not updating timestamp on purpose } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; this.timestamp = new Date(); } protected class BitmapData { private String data = null; /** * Converts a bitmap to an array of bytes, then encodes the bytes as a * base64 string * <p> * Accepts null as the parameter, in which case the stored string is * cleared * * @param image * a bitmap to be encoded */ public void encode(Bitmap image) { if (image == null) { data = null; return; } ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.PNG, 100, byteStream); byte[] bytes = byteStream.toByteArray(); data = Base64.encodeToString(bytes, Base64.DEFAULT); } /** * Decodes the stored base64 string, then converts the bytes to a bitmap * * @return a Java Bitmap corresponding to the base64 string stored , or * null if no base64 string is stored */ public Bitmap decode() { if (data == null) return null; byte[] bytes = Base64.decode(data, Base64.DEFAULT); Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); return bitmap; } } }
package com.github.phantomthief.util; import static java.util.Optional.ofNullable; import static org.slf4j.LoggerFactory.getLogger; import java.util.Optional; import java.util.concurrent.Callable; import org.slf4j.Logger; import com.google.common.base.Throwables; /** * @author w.vela */ public final class MoreFunctions { private static final Logger logger = getLogger(MoreFunctions.class); public static <R> Optional<R> catchingOptional(Callable<R> callable) { return ofNullable(catching(callable)); } public static <R> R catching(Callable<R> callable) { return catching(callable, e -> logger.error("", e)); } public static <X extends Exception> void catching(ThrowableRunnable<X> callable) { catching(() -> { callable.run(); return null; }, e -> logger.error("", e)); } public static <R> R throwing(Callable<R> callable) { return catching(callable, Throwables::propagate); } public static <X extends Exception> void throwing(ThrowableRunnable<X> callable) { catching(() -> { callable.run(); return null; }, Throwables::propagate); } public static <R, X extends Throwable> R catching(Callable<R> callable, ThrowableConsumer<Throwable, X> exceptionHandler) throws X { try { return callable.call(); } catch (Throwable e) { exceptionHandler.accept(e); return null; } } public static <T, R> R catching(ThrowableFunction<T, R, Exception> function, T t) { return catching(function, t, e -> logger.error("", e)); } public static <T, R> R throwing(ThrowableFunction<T, R, Exception> function, T t) { return catching(function, t, Throwables::propagate); } public static <T, R, X extends Throwable> R catching( ThrowableFunction<T, R, Exception> function, T t, ThrowableConsumer<Throwable, X> exceptionHandler) throws X { try { return function.apply(t); } catch (Throwable e) { exceptionHandler.accept(e); return null; } } }
package com.fpliu.newton.ui.list; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import com.fpliu.newton.ui.base.BaseView; import com.fpliu.newton.ui.base.LazyFragment; import com.fpliu.newton.ui.pullable.PullableListView; import com.fpliu.newton.ui.pullable.PullableViewContainer; import com.fpliu.newton.ui.pullable.RefreshOrLoadMoreCallback; import com.fpliu.newton.ui.pullable.Type; import java.util.Collection; import java.util.List; /** * @author 792793182@qq.com 2016-06-06. */ public abstract class PullableListFragment<T> extends LazyFragment implements IPullableList<T, PullableListView>, AdapterView.OnItemClickListener, RefreshOrLoadMoreCallback<PullableListView> { private IPullableList<T, PullableListView> pullableList; private View headerView; private Object headerData; private boolean headerIsSelectable; private View footerView; private Object footerData; private boolean footerIsSelectable; @Override protected void onCreateViewLazy(BaseView baseView, Bundle savedInstanceState) { super.onCreateViewLazy(baseView, savedInstanceState); Activity activity = getActivity(); pullableList = new PullableListImpl<>(); addContentView(pullableList.init(activity)); setOnItemClickListener(this); if (headerView != null) { pullableList.addHeaderView(headerView, headerData, headerIsSelectable); } if (footerView != null) { pullableList.addHeaderView(footerView, footerData, footerIsSelectable); } setItemAdapter(new ItemAdapter<T>(null) { @Override public View getView(int position, View convertView, ViewGroup parent) { return PullableListFragment.this.getItemView(position, convertView, parent); } @Override public int getViewTypeCount() { return PullableListFragment.this.getItemViewTypeCount(); } @Override public int getItemViewType(int position) { return PullableListFragment.this.getItemViewType(position); } }); setRefreshOrLoadMoreCallback(this); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { } @Override public void canPullDown(boolean canPullDown) { pullableList.canPullDown(canPullDown); } @Override public void canPullUp(boolean canPullUp) { pullableList.canPullUp(canPullUp); } @Override public void finishRequestSuccess(Type type, List<T> items) { pullableList.finishRequestSuccess(type, items); } @Override public void finishRequestSuccess(Type type, List<T> items, String itemsEmptyMessageWhenRefresh) { pullableList.finishRequestSuccess(type, items, itemsEmptyMessageWhenRefresh); } @Override public void setRefreshOrLoadMoreCallback(RefreshOrLoadMoreCallback callback) { pullableList.setRefreshOrLoadMoreCallback(callback); } @Override public View init(Context context) { return pullableList.init(context); } @Override public PullableViewContainer<PullableListView> getPullableViewContainer() { return pullableList.getPullableViewContainer(); } @Override public void setItemAdapter(ItemAdapter<T> itemAdapter) { pullableList.setItemAdapter(itemAdapter); } @Override public ItemAdapter<T> getItemAdapter() { return pullableList.getItemAdapter(); } @Override public void setItems(List<T> items) { pullableList.setItems(items); } @Override public List<T> getItems() { return pullableList.getItems(); } @Override public boolean addAll(Collection<? extends T> collection) { return pullableList.addAll(collection); } @Override public boolean add(T item) { return pullableList.add(item); } @Override public T set(int location, T item) { return pullableList.set(location, item); } @Override public boolean remove(T item) { return pullableList.remove(item); } @Override public T getItem(int position) { return pullableList.getItem(position); } @Override public int getCount() { return pullableList.getCount(); } @Override public void clear() { pullableList.clear(); } @Override public int getItemViewTypeCount() { return pullableList.getItemViewTypeCount(); } @Override public int getItemViewType(int position) { return pullableList.getItemViewType(position); } @Override public void notifyDataSetChanged() { pullableList.notifyDataSetChanged(); } @Override public void setDividerHeight(int height) { pullableList.setDividerHeight(height); } @Override public void setViewBeforeBody(int layoutId) { pullableList.setViewBeforeBody(layoutId); } @Override public void setViewBeforeBody(View view) { pullableList.setViewBeforeBody(view); } @Override public void setViewAfterBody(int layoutId) { pullableList.setViewAfterBody(layoutId); } @Override public void setViewAfterBody(View view) { pullableList.setViewAfterBody(view); } //super.onCreate() @Override public void addHeaderView(View view, Object data, boolean isSelectable) { this.headerView = view; this.headerData = data; this.headerIsSelectable = isSelectable; } //super.onCreate() @Override public void addFooterView(View view, Object data, boolean isSelectable) { this.footerView = view; this.footerData = data; this.footerIsSelectable = isSelectable; } @Override public void setOnItemClickListener(AdapterView.OnItemClickListener listener) { pullableList.setOnItemClickListener(listener); } @Override public void refresh() { pullableList.refresh(); } }
package lpn.parser; import java.util.ArrayList; import java.util.HashMap; import java.util.Set; import java.lang.Math; public class ExprTree { String op; char isit; // b=Boolean, i=Integer, c=Continuous, n=Number, t=Truth value, // w=bitWise, a=Arithmetic, r=Relational, l=Logical double lvalue, uvalue; String variable; double real; boolean logical; ExprTree r1, r2; private String tokvalue = ""; private int position = 0; public int token = 0; private ExprTree newresult; private ArrayList<String> booleanSignals, integerSignals, continuousSignals; private LhpnFile lhpn; public String expression; public ExprTree() { } /** * This constructor is used in PlatuGrammar.g to convert LPNs from USF to LhpnFile. * All LPNs from USF use integer variables only. So only integer signals are dealt with here. * @param expression */ public ExprTree(String expression) { this.expression = expression; booleanSignals = new ArrayList<String>(); integerSignals = new ArrayList<String>(); continuousSignals = new ArrayList<String>(); // intexpr_gettok(expression); // intexpr_L(expression); } public ExprTree(LhpnFile lhpn) { this.lhpn = lhpn; String[] bools = lhpn.getBooleanVars(); String[] conts = lhpn.getContVars(); String[] ints = lhpn.getIntVars(); booleanSignals = new ArrayList<String>(); integerSignals = new ArrayList<String>(); continuousSignals = new ArrayList<String>(); for (int j = 0; j < bools.length; j++) { booleanSignals.add(bools[j]); } for (int j = 0; j < conts.length; j++) { continuousSignals.add(conts[j]); } for (int j = 0; j < ints.length; j++) { integerSignals.add(ints[j]); } } public ExprTree(Abstraction abstraction) { this.lhpn = abstraction; String[] bools = abstraction.getBooleanVars(); String[] conts = abstraction.getContVars(); String[] ints = abstraction.getIntVars(); booleanSignals = new ArrayList<String>(); integerSignals = new ArrayList<String>(); continuousSignals = new ArrayList<String>(); for (int j = 0; j < bools.length; j++) { booleanSignals.add(bools[j]); } for (int j = 0; j < conts.length; j++) { continuousSignals.add(conts[j]); } for (int j = 0; j < ints.length; j++) { integerSignals.add(ints[j]); } } public ExprTree(Transition transition) { } ExprTree(char willbe, int lNV, int uNV, String var) { op = ""; r1 = null; r2 = null; isit = willbe; if ((isit == 'b') || (isit == 't')) logical = true; else logical = false; uvalue = uNV; lvalue = lNV; variable = var; real = 0; } public ExprTree(ExprTree nr1, ExprTree nr2, String nop, char willbe) { op = nop; r1 = nr1; r2 = nr2; isit = willbe; if ((isit == 'r') || (isit == 'l')) { logical = true; uvalue = 1; lvalue = 0; } else { logical = false; uvalue = INFIN; lvalue = -INFIN; } variable = null; } public ExprTree(ExprTree source) { if (source.op != null) { op = source.op; } isit = source.isit; lvalue = source.lvalue; uvalue = source.uvalue; if (source.variable != null) { variable = source.variable; } real = source.real; logical = source.logical; if (source.r1 != null) { r1 = source.r1; } if (source.r2 != null) { r2 = source.r2; } if (source.tokvalue != null) { tokvalue = source.tokvalue; } position = source.position; token = source.token; if (source.newresult != null) { newresult = source.newresult; } if (source.booleanSignals != null) { booleanSignals = source.booleanSignals; } if (source.integerSignals != null) { integerSignals = source.integerSignals; } if (source.continuousSignals != null) { continuousSignals = source.continuousSignals; } if (source.lhpn != null) { lhpn = source.lhpn; } } public int intexpr_gettok(String expr) { char c; boolean readword; boolean readnum; boolean readsci; boolean readsign; readword = false; readnum = false; readsci = false; readsign = false; tokvalue = ""; while (position < expr.length()) { c = expr.charAt(position); position++; switch (c) { case '(': case ')': case '[': case ']': case ',': case '~': case '|': case '&': case '*': case '^': case '/': case '%': case '=': case '<': case '>': if ((!readword) && (!readnum) && (!readsci)) { return (c); } else { position return (WORD); } case '+': case '-': if ((readsci) && (!readnum) && (readsign)) { tokvalue += c; readsign = false; break; } if ((readsci) && (!readnum) && (!readsign)) { return -1; } else if ((!readword) && (!readnum) && (!readsci)) { return (c); } else { position return (WORD); } case ' ': if (readword) { return (WORD); } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (!readword) { readnum = true; } tokvalue += c; break; case '.': if (readsci) { return -1; } else if (!readword) { readnum = true; } tokvalue += c; break; case 'E': case 'e': if (readsci) { return -1; } else if (readnum) { readsci = true; readnum = false; readsign = true; tokvalue += c; break; } default: if ((readnum) || (readsci)) { return -1; } readword = true; tokvalue += c; break; } } if ((!readword) && (!readnum)) { return (END_OF_STRING); } else if (readword || readnum) { return (WORD); } return -1; } public boolean intexpr_U(String expr) { double temp; switch (token) { case WORD: if (tokvalue.toLowerCase().equals("and")) { token = intexpr_gettok(expr); if ((token) != '(') { System.out.print("ERROR: Expected a (\n"); return false; } token = intexpr_gettok(expr); if (!intexpr_R(expr)) { return false; } (token) = intexpr_gettok(expr); newresult.token = token; newresult.tokvalue = tokvalue; newresult.position = position; if (!newresult.intexpr_R(expr)) return false; token = newresult.token; position = newresult.position; if ((token) != ')') { System.out.printf("ERROR: Expected a )\n"); return false; } // simplify if operands are static if (((newresult.isit == 'n') || (newresult.isit == 't')) && (((this).isit == 'n') || ((this).isit == 't')) && ((this).lvalue == (this).uvalue) && (newresult.lvalue == newresult.uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN) && (newresult.lvalue != INFIN) && (newresult.lvalue != -INFIN)) { (this).isit = 'n'; (this).lvalue = ((int) (this).lvalue) & ((int) newresult.lvalue); (this).uvalue = (this).lvalue; } else { setNodeValues((this), newresult, "&", 'w'); } (token) = intexpr_gettok(expr); } else if (tokvalue.toLowerCase().equals("or")) { (token) = intexpr_gettok(expr); if ((token) != '(') { System.out.printf("ERROR: Expected a (\n"); return false; } (token) = intexpr_gettok(expr); if (!intexpr_R(expr)) return false; if ((token) != ',') { System.out.printf("ERROR: Expected a ,\n"); return false; } (token) = intexpr_gettok(expr); newresult.token = token; newresult.tokvalue = tokvalue; newresult.position = position; if (!newresult.intexpr_R(expr)) return false; token = newresult.token; position = newresult.position; if ((token) != ')') { System.out.printf("ERROR: Expected a )\n"); return false; } // simplify if operands are static if (((newresult.isit == 'n') || (newresult.isit == 't')) && (((this).isit == 'n') || ((this).isit == 't')) && ((this).lvalue == (this).uvalue) && (newresult.lvalue == newresult.uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN) && (newresult.lvalue != INFIN) && (newresult.lvalue != -INFIN)) { (this).isit = 'n'; (this).lvalue = (int) (this).lvalue | (int) newresult.lvalue; (this).uvalue = (this).lvalue; } else { setNodeValues((this), newresult, "|", 'w'); } (token) = intexpr_gettok(expr); } else if (tokvalue.toLowerCase().equals("xor")) { (token) = intexpr_gettok(expr); if ((token) != '(') { System.out.printf("ERROR: Expected a (\n"); return false; } (token) = intexpr_gettok(expr); if (!intexpr_R(expr)) return false; if ((token) != ',') { System.out.printf("ERROR: Expected a ,\n"); return false; } (token) = intexpr_gettok(expr); newresult.token = token; newresult.tokvalue = tokvalue; newresult.position = position; if (!newresult.intexpr_R(expr)) return false; token = newresult.token; position = newresult.position; if ((token) != ')') { System.out.printf("ERROR: Expected a )\n"); return false; } // simplify if operands are static if (((newresult.isit == 'n') || (newresult.isit == 't')) && (((this).isit == 'n') || ((this).isit == 't')) && ((this).lvalue == (this).uvalue) && (newresult.lvalue == newresult.uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN) && (newresult.lvalue != INFIN) && (newresult.lvalue != -INFIN)) { (this).isit = 'n'; (this).lvalue = (int) (this).lvalue ^ (int) newresult.lvalue; (this).uvalue = (this).lvalue; } else { setNodeValues((this), newresult, "X", 'w'); } (token) = intexpr_gettok(expr); } else if (tokvalue.toLowerCase().equals("min")) { (token) = intexpr_gettok(expr); if ((token) != '(') { System.out.printf("ERROR: Expected a (\n"); return false; } (token) = intexpr_gettok(expr); if (!intexpr_R(expr)) return false; if ((token) != ',') { System.out.printf("ERROR: Expected a ,\n"); return false; } (token) = intexpr_gettok(expr); newresult.token = token; newresult.tokvalue = tokvalue; newresult.position = position; if (!newresult.intexpr_R(expr)) return false; token = newresult.token; position = newresult.position; if ((token) != ')') { System.out.printf("ERROR: Expected a )\n"); return false; } // simplify if operands are static if (((newresult.isit == 'n') || (newresult.isit == 't')) && (((this).isit == 'n') || ((this).isit == 't')) && ((this).lvalue == (this).uvalue) && (newresult.lvalue == newresult.uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN) && (newresult.lvalue != INFIN) && (newresult.lvalue != -INFIN)) { (this).isit = 'n'; (this).lvalue = Math.min((this).lvalue, newresult.lvalue); (this).uvalue = (this).lvalue; } else { setNodeValues((this), newresult, "m", 'a'); } (token) = intexpr_gettok(expr); } else if (tokvalue.toLowerCase().equals("max")) { (token) = intexpr_gettok(expr); if ((token) != '(') { System.out.printf("ERROR: Expected a (\n"); return false; } (token) = intexpr_gettok(expr); if (!intexpr_R(expr)) return false; if ((token) != ',') { System.out.printf("ERROR: Expected a ,\n"); return false; } (token) = intexpr_gettok(expr); newresult.token = token; newresult.tokvalue = tokvalue; newresult.position = position; if (!newresult.intexpr_R(expr)) return false; token = newresult.token; position = newresult.position; if ((token) != ')') { System.out.printf("ERROR: Expected a )\n"); return false; } // simplify if operands are static if (((newresult.isit == 'n') || (newresult.isit == 't')) && (((this).isit == 'n') || ((this).isit == 't')) && ((this).lvalue == (this).uvalue) && (newresult.lvalue == newresult.uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN) && (newresult.lvalue != INFIN) && (newresult.lvalue != -INFIN)) { (this).isit = 'n'; (this).lvalue = Math.max((this).lvalue, newresult.lvalue); (this).uvalue = (this).lvalue; } else { setNodeValues((this), newresult, "M", 'a'); } (token) = intexpr_gettok(expr); } else if (tokvalue.toLowerCase().equals("idiv")) { (token) = intexpr_gettok(expr); if ((token) != '(') { System.out.printf("ERROR: Expected a (\n"); return false; } (token) = intexpr_gettok(expr); if (!intexpr_R(expr)) return false; if ((token) != ',') { System.out.printf("ERROR: Expected a ,\n"); return false; } (token) = intexpr_gettok(expr); newresult.token = token; newresult.tokvalue = tokvalue; newresult.position = position; if (!newresult.intexpr_R(expr)) return false; token = newresult.token; position = newresult.position; if ((token) != ')') { System.out.printf("ERROR: Expected a )\n"); return false; } // simplify if operands are static if (((newresult.isit == 'n') || (newresult.isit == 't')) && (((this).isit == 'n') || ((this).isit == 't')) && ((this).lvalue == (this).uvalue) && (newresult.lvalue == newresult.uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN) && (newresult.lvalue != INFIN) && (newresult.lvalue != -INFIN)) { (this).isit = 'n'; (this).lvalue = Math .floor((this).lvalue / newresult.lvalue); (this).uvalue = (this).lvalue; } else { setNodeValues((this), newresult, "i", 'a'); } (token) = intexpr_gettok(expr); } else if (tokvalue.toLowerCase().equals("bit")) { (token) = intexpr_gettok(expr); if ((token) != '(') { System.out.printf("ERROR: Expected a (\n"); return false; } (token) = intexpr_gettok(expr); if (!intexpr_R(expr)) return false; if ((token) != ',') { System.out.printf("ERROR: Expected a ,\n"); return false; } (token) = intexpr_gettok(expr); newresult.token = token; newresult.tokvalue = tokvalue; newresult.position = position; if (!newresult.intexpr_R(expr)) return false; token = newresult.token; position = newresult.position; if ((token) != ')') { System.out.printf("ERROR: Expected a )\n"); return false; } // simplify if operands are static if (((newresult.isit == 'n') || (newresult.isit == 't')) && (((this).isit == 'n') || ((this).isit == 't')) && ((this).lvalue == (this).uvalue) && (newresult.lvalue == newresult.uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN) && (newresult.lvalue != INFIN) && (newresult.lvalue != -INFIN)) { (this).isit = 't'; (this).lvalue = ((int) (this).lvalue >> (int) newresult.lvalue) & 1; (this).uvalue = (this).lvalue; } else { setNodeValues((this), newresult, "[]", 'l'); } (token) = intexpr_gettok(expr); } else if (tokvalue.toLowerCase().equals("floor")) { (token) = intexpr_gettok(expr); if ((token) != '(') { System.out.printf("ERROR: Expected a (\n"); return false; } (token) = intexpr_gettok(expr); if (!intexpr_R(expr)) return false; if ((token) != ')') { System.out.printf("ERROR: Expected a )\n"); return false; } // simplify if operands are static if (((this).isit == 'n') || ((this).isit == 't') && ((this).lvalue == (this).uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)) { (this).isit = 'n'; (this).lvalue = Math.floor((this).lvalue); (this).uvalue = (this).lvalue; } else { setNodeValues((this), null, "f", 'a'); } (token) = intexpr_gettok(expr); } else if (tokvalue.toLowerCase().equals("ceil")) { (token) = intexpr_gettok(expr); if ((token) != '(') { System.out.printf("ERROR: Expected a (\n"); return false; } (token) = intexpr_gettok(expr); if (!intexpr_R(expr)) return false; if ((token) != ')') { System.out.printf("ERROR: Expected a )\n"); return false; } // simplify if operands are static if (((this).isit == 'n') || ((this).isit == 't') && ((this).lvalue == (this).uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)) { (this).isit = 'n'; (this).lvalue = Math.ceil((this).lvalue); (this).uvalue = (this).lvalue; } else { setNodeValues((this), null, "c", 'a'); } (token) = intexpr_gettok(expr); } else if (tokvalue.toLowerCase().equals("not")) { (token) = intexpr_gettok(expr); if ((token) != '(') { System.out.printf("ERROR: Expected a (\n"); return false; } (token) = intexpr_gettok(expr); if (!intexpr_R(expr)) return false; if ((token) != ')') { System.out.printf("ERROR: Expected a )\n"); return false; } // simplify if operands are static if (((this).isit == 'n') || ((this).isit == 't') && ((this).lvalue == (this).uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)) { (this).isit = 'n'; (this).lvalue = ~(int) (this).lvalue; (this).uvalue = (this).lvalue; } else { setNodeValues((this), null, "~", 'w'); } (token) = intexpr_gettok(expr); } else if (tokvalue.toLowerCase().equals("int")) { (token) = intexpr_gettok(expr); if ((token) != '(') { System.out.printf("ERROR: Expected a (\n"); return false; } (token) = intexpr_gettok(expr); if (!intexpr_L(expr)) return false; if ((token) != ')') { System.out.printf("ERROR: Expected a )\n"); return false; } // simplify if operands are static if (((this).isit == 'n') || ((this).isit == 't')) { // DO NOTHING } else { setNodeValues((this), null, "INT", 'l'); } (token) = intexpr_gettok(expr); } else if (tokvalue.equals("uniform")) { (token) = intexpr_gettok(expr); if ((token) != '(') { System.out.printf("ERROR: Expected a (\n"); return false; } (token) = intexpr_gettok(expr); if (!intexpr_R(expr)) return false; if ((token) != ',') { System.out.printf("ERROR: Expected a ,\n"); return false; } (token) = intexpr_gettok(expr); newresult.token = token; newresult.tokvalue = tokvalue; newresult.position = position; if (!newresult.intexpr_R(expr)) return false; token = newresult.token; position = newresult.position; if ((token) != ')') { System.out.printf("ERROR: Expected a )\n"); return false; } setNodeValues((this), newresult, "uniform", 'a'); (token) = intexpr_gettok(expr); } else if (tokvalue.equals("normal")) { (token) = intexpr_gettok(expr); if ((token) != '(') { System.out.printf("ERROR: Expected a (\n"); return false; } (token) = intexpr_gettok(expr); if (!intexpr_R(expr)) return false; if ((token) != ',') { System.out.printf("ERROR: Expected a ,\n"); return false; } (token) = intexpr_gettok(expr); newresult.token = token; newresult.tokvalue = tokvalue; newresult.position = position; if (!newresult.intexpr_R(expr)) return false; token = newresult.token; position = newresult.position; if ((token) != ')') { System.out.printf("ERROR: Expected a )\n"); return false; } setNodeValues((this), newresult, "normal", 'a'); (token) = intexpr_gettok(expr); } else if (tokvalue.equals("gamma")) { (token) = intexpr_gettok(expr); if ((token) != '(') { System.out.printf("ERROR: Expected a (\n"); return false; } (token) = intexpr_gettok(expr); if (!intexpr_R(expr)) return false; if ((token) != ',') { System.out.printf("ERROR: Expected a ,\n"); return false; } (token) = intexpr_gettok(expr); newresult.token = token; newresult.tokvalue = tokvalue; newresult.position = position; if (!newresult.intexpr_R(expr)) return false; token = newresult.token; position = newresult.position; if ((token) != ')') { System.out.printf("ERROR: Expected a )\n"); return false; } setNodeValues((this), newresult, "gamma", 'a'); (token) = intexpr_gettok(expr); } else if (tokvalue.equals("lognormal")) { (token) = intexpr_gettok(expr); if ((token) != '(') { System.out.printf("ERROR: Expected a (\n"); return false; } (token) = intexpr_gettok(expr); if (!intexpr_R(expr)) return false; if ((token) != ',') { System.out.printf("ERROR: Expected a ,\n"); return false; } (token) = intexpr_gettok(expr); newresult.token = token; newresult.tokvalue = tokvalue; newresult.position = position; if (!newresult.intexpr_R(expr)) return false; token = newresult.token; position = newresult.position; if ((token) != ')') { System.out.printf("ERROR: Expected a )\n"); return false; } setNodeValues((this), newresult, "lognormal", 'a'); (token) = intexpr_gettok(expr); } else if (tokvalue.equals("binomial")) { (token) = intexpr_gettok(expr); if ((token) != '(') { System.out.printf("ERROR: Expected a (\n"); return false; } (token) = intexpr_gettok(expr); if (!intexpr_R(expr)) return false; if ((token) != ',') { System.out.printf("ERROR: Expected a ,\n"); return false; } (token) = intexpr_gettok(expr); newresult.token = token; newresult.tokvalue = tokvalue; newresult.position = position; if (!newresult.intexpr_R(expr)) return false; token = newresult.token; position = newresult.position; if ((token) != ')') { System.out.printf("ERROR: Expected a )\n"); return false; } setNodeValues((this), newresult, "binomial", 'a'); (token) = intexpr_gettok(expr); } else if (tokvalue.equals("exponential")) { (token) = intexpr_gettok(expr); if ((token) != '(') { System.out.printf("ERROR: Expected a (\n"); return false; } (token) = intexpr_gettok(expr); if (!intexpr_R(expr)) return false; if ((token) != ')') { System.out.printf("ERROR: Expected a )\n"); return false; } setNodeValues((this), null, "exponential", 'a'); (token) = intexpr_gettok(expr); } else if (tokvalue.equals("chisq")) { (token) = intexpr_gettok(expr); if ((token) != '(') { System.out.printf("ERROR: Expected a (\n"); return false; } (token) = intexpr_gettok(expr); if (!intexpr_R(expr)) return false; if ((token) != ')') { System.out.printf("ERROR: Expected a )\n"); return false; } setNodeValues((this), null, "chisq", 'a'); (token) = intexpr_gettok(expr); } else if (tokvalue.equals("laplace")) { (token) = intexpr_gettok(expr); if ((token) != '(') { System.out.printf("ERROR: Expected a (\n"); return false; } (token) = intexpr_gettok(expr); if (!intexpr_R(expr)) return false; if ((token) != ')') { System.out.printf("ERROR: Expected a )\n"); return false; } setNodeValues((this), null, "laplace", 'a'); (token) = intexpr_gettok(expr); } else if (tokvalue.equals("cauchy")) { (token) = intexpr_gettok(expr); if ((token) != '(') { System.out.printf("ERROR: Expected a (\n"); return false; } (token) = intexpr_gettok(expr); if (!intexpr_R(expr)) return false; if ((token) != ')') { System.out.printf("ERROR: Expected a )\n"); return false; } setNodeValues((this), null, "cauchy", 'a'); (token) = intexpr_gettok(expr); } else if (tokvalue.equals("rayleigh")) { (token) = intexpr_gettok(expr); if ((token) != '(') { System.out.printf("ERROR: Expected a (\n"); return false; } (token) = intexpr_gettok(expr); if (!intexpr_R(expr)) return false; if ((token) != ')') { System.out.printf("ERROR: Expected a )\n"); return false; } setNodeValues((this), null, "rayleigh", 'a'); (token) = intexpr_gettok(expr); } else if (tokvalue.equals("poisson")) { (token) = intexpr_gettok(expr); if ((token) != '(') { System.out.printf("ERROR: Expected a (\n"); return false; } (token) = intexpr_gettok(expr); if (!intexpr_R(expr)) return false; if ((token) != ')') { System.out.printf("ERROR: Expected a )\n"); return false; } setNodeValues((this), null, "poisson", 'a'); (token) = intexpr_gettok(expr); } else if (tokvalue.equals("bernoulli")) { (token) = intexpr_gettok(expr); if ((token) != '(') { System.out.printf("ERROR: Expected a (\n"); return false; } (token) = intexpr_gettok(expr); if (!intexpr_R(expr)) return false; if ((token) != ')') { System.out.printf("ERROR: Expected a )\n"); return false; } setNodeValues((this), null, "bernoulli", 'a'); (token) = intexpr_gettok(expr); } else if (tokvalue.equals("rate")) { (token) = intexpr_gettok(expr); if ((token) != '(') { System.out.printf("ERROR: Expected a (\n"); return false; } (token) = intexpr_gettok(expr); if (!intexpr_R(expr)) return false; if ((token) != ')') { System.out.printf("ERROR: Expected a )\n"); return false; } setNodeValues((this), null, "rate", 'a'); (token) = intexpr_gettok(expr); } else if ((tokvalue.equals("true")) || tokvalue.equals("TRUE")) { setVarValues('t', 1, 1, null); (token) = intexpr_gettok(expr); } else if (tokvalue.equals("t") && !booleanSignals.contains(tokvalue) && !integerSignals.contains(tokvalue) && !continuousSignals.contains(tokvalue)) { setVarValues('t', 1, 1, null); (token) = intexpr_gettok(expr); } else if (tokvalue.equals("T") && !booleanSignals.contains(tokvalue) && !integerSignals.contains(tokvalue) && !continuousSignals.contains(tokvalue)) { setVarValues('t', 1, 1, null); (token) = intexpr_gettok(expr); } else if ((tokvalue.equals("false")) || tokvalue.equals("FALSE")) { setVarValues('t', 0, 0, null); (token) = intexpr_gettok(expr); } else if (tokvalue.equals("f") && !booleanSignals.contains(tokvalue) && !integerSignals.contains(tokvalue) && !continuousSignals.contains(tokvalue)) { setVarValues('t', 0, 0, null); (token) = intexpr_gettok(expr); } else if (tokvalue.equals("F") && !booleanSignals.contains(tokvalue) && !integerSignals.contains(tokvalue) && !continuousSignals.contains(tokvalue)) { setVarValues('t', 0, 0, null); (token) = intexpr_gettok(expr); } else if ((tokvalue.toLowerCase().equals("unknown"))) { setVarValues('t', 0, 1, null); (token) = intexpr_gettok(expr); } else if (tokvalue.toLowerCase().equals("inf")) { setVarValues('n', INFIN, INFIN, null); token = intexpr_gettok(expr); } else { // do boolean lookup here!!! if (booleanSignals.contains(tokvalue)) { setVarValues('b', 0, 1, tokvalue); (token) = intexpr_gettok(expr); return true; } else if (integerSignals.contains(tokvalue)) { setVarValues('i', -INFIN, INFIN, tokvalue); (token) = intexpr_gettok(expr); return true; } else if (continuousSignals.contains(tokvalue)) { setVarValues('c', -INFIN, INFIN, tokvalue); (token) = intexpr_gettok(expr); return true; } if (tokvalue.equals("")) { System.out.printf( "U1:ERROR(%s): Expected a ID, Number, or a (\n", tokvalue); return false; } else if ((int) (tokvalue.charAt(0)) > ('9') || ((int) (tokvalue.charAt(0)) < '0')) { System.out.printf( "U1:ERROR(%s): Expected a ID, Number, or a (\n", tokvalue); return false; } temp = Double.parseDouble(tokvalue); setVarValues('n', temp, temp, null); token = intexpr_gettok(expr); } break; case '(': (token) = intexpr_gettok(expr); if (!intexpr_L(expr)) return false; if ((token) != ')') { System.out.printf("ERROR: Expected a )\n"); return false; } (token) = intexpr_gettok(expr); break; default: System.out.printf("U2:ERROR: Expected a ID, Number, or a (\n"); return false; } return true; } public boolean intexpr_T(String expr) { switch (token) { case WORD: case '(': if (!intexpr_U(expr)) return false; break; case '-': (token) = intexpr_gettok(expr); if (!intexpr_U(expr)) return false; // simplify if operands are static if ((((this).isit == 'n') || ((this).isit == 't')) && ((this).lvalue == (this).uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)) { (this).isit = 'n'; (this).lvalue = -((this).lvalue); (this).uvalue = (this).lvalue; } else { setNodeValues((this), null, "U-", 'a'); } break; default: System.out.printf("T:ERROR: Expected a ID, Number, (, or -\n"); return false; } return true; } public boolean intexpr_C(String expr) { newresult = new ExprTree(this); switch (token) { case '*': (token) = intexpr_gettok(expr); newresult.token = token; newresult.tokvalue = tokvalue; newresult.position = position; if (!newresult.intexpr_T(expr)) return false; token = newresult.token; position = newresult.position; // simplify if operands are static if (((newresult.isit == 'n') || (newresult.isit == 't')) && (((this).isit == 'n') || ((this).isit == 't')) && ((this).lvalue == (this).uvalue) && (newresult.lvalue == newresult.uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN) && (newresult.lvalue != INFIN) && (newresult.lvalue != -INFIN)) { (this).isit = 'n'; (this).lvalue = (this).lvalue * newresult.lvalue; (this).uvalue = (this).lvalue; } else { setNodeValues((this), newresult, "*", 'a'); } if (!intexpr_C(expr)) return false; break; case '^': (token) = intexpr_gettok(expr); newresult.token = token; newresult.tokvalue = tokvalue; newresult.position = position; if (!newresult.intexpr_T(expr)) return false; token = newresult.token; position = newresult.position; // simplify if operands are static if (((newresult.isit == 'n') || (newresult.isit == 't')) && (((this).isit == 'n') || ((this).isit == 't')) && ((this).lvalue == (this).uvalue) && (newresult.lvalue == newresult.uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN) && (newresult.lvalue != INFIN) && (newresult.lvalue != -INFIN)) { (this).isit = 'n'; (this).lvalue = Math.pow(lvalue, newresult.lvalue); (this).uvalue = (this).lvalue; } else { setNodeValues((this), newresult, "^", 'a'); } if (!intexpr_C(expr)) return false; break; case '/': (token) = intexpr_gettok(expr); newresult.token = token; newresult.tokvalue = tokvalue; newresult.position = position; if (!newresult.intexpr_T(expr)) return false; token = newresult.token; position = newresult.position; // simplify if operands are static if (((newresult.isit == 'n') || (newresult.isit == 't')) && (((this).isit == 'n') || ((this).isit == 't')) && ((this).lvalue == (this).uvalue) && (newresult.lvalue == newresult.uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN) && (newresult.lvalue != INFIN) && (newresult.lvalue != -INFIN)) { (this).isit = 'n'; (this).lvalue = (this).lvalue / newresult.lvalue; (this).uvalue = (this).lvalue; } else { setNodeValues((this), newresult, "/", 'a'); } if (!intexpr_C(expr)) return false; break; case '%': (token) = intexpr_gettok(expr); newresult.token = token; newresult.tokvalue = tokvalue; newresult.position = position; if (!newresult.intexpr_T(expr)) return false; token = newresult.token; position = newresult.position; // simplify if operands are static if (((newresult.isit == 'n') || (newresult.isit == 't')) && (((this).isit == 'n') || ((this).isit == 't')) && ((this).lvalue == (this).uvalue) && (newresult.lvalue == newresult.uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN) && (newresult.lvalue != INFIN) && (newresult.lvalue != -INFIN)) { (this).isit = 'n'; (this).lvalue = (this).lvalue % newresult.lvalue; (this).uvalue = (this).lvalue; } else { setNodeValues((this), newresult, "%", 'a'); } if (!intexpr_C(expr)) return false; break; case '+': case '-': case ')': case '[': case ']': case '|': case '&': case '=': case '<': case '>': case ',': case IMPLIES: case END_OF_STRING: break; case '(': case WORD: if (!newresult.intexpr_T(expr)) return false; token = newresult.token; position = newresult.position; // simplify if operands are static if (((newresult.isit == 'n') || (newresult.isit == 't')) && (((this).isit == 'n') || ((this).isit == 't')) && ((this).lvalue == (this).uvalue) && (newresult.lvalue == newresult.uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN) && (newresult.lvalue != INFIN) && (newresult.lvalue != -INFIN)) { (this).isit = 'n'; (this).lvalue = (this).lvalue * newresult.lvalue; (this).uvalue = (this).lvalue; } else { setNodeValues((this), newresult, "*", 'a'); } if (!intexpr_C(expr)) return false; break; default: System.out.printf("ERROR: Expected a * or /\n"); return false; } return true; } public boolean intexpr_B(String expr) { newresult = new ExprTree(this); switch (token) { case '+': (token) = intexpr_gettok(expr); newresult.token = token; newresult.tokvalue = tokvalue; newresult.position = position; if (!newresult.intexpr_S(expr)) return false; token = newresult.token; position = newresult.position; // simplify if operands are static if (((newresult.isit == 'n') || (newresult.isit == 't')) && (((this).isit == 'n') || ((this).isit == 't')) && ((this).lvalue == (this).uvalue) && (newresult.lvalue == newresult.uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN) && (newresult.lvalue != INFIN) && (newresult.lvalue != -INFIN)) { (this).isit = 'n'; (this).lvalue = (this).lvalue + newresult.lvalue; (this).uvalue = (this).lvalue; } else { setNodeValues((this), newresult, "+", 'a'); } if (!intexpr_B(expr)) return false; break; case '-': (token) = intexpr_gettok(expr); newresult.token = token; newresult.tokvalue = tokvalue; newresult.position = position; if (!newresult.intexpr_S(expr)) return false; token = newresult.token; position = newresult.position; // simplify if operands are static if (((newresult.isit == 'n') || (newresult.isit == 't')) && (((this).isit == 'n') || ((this).isit == 't')) && ((this).lvalue == (this).uvalue) && (newresult.lvalue == newresult.uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN) && (newresult.lvalue != INFIN) && (newresult.lvalue != -INFIN)) { (this).isit = 'n'; (this).lvalue = (this).lvalue - newresult.lvalue; (this).uvalue = (this).lvalue; } else { setNodeValues((this), newresult, "-", 'a'); } if (!intexpr_B(expr)) return false; break; case ')': case '[': case ']': case '|': case '&': case '=': case '<': case '>': case ',': case IMPLIES: case END_OF_STRING: break; default: System.out.printf("ERROR: Expected a + or -\n"); return false; } return true; } public boolean intexpr_S(String expr) { switch (token) { case WORD: case '(': case '-': if (!intexpr_T(expr)) return false; if (!intexpr_C(expr)) return false; break; default: System.out.printf("S:ERROR: Expected a ID, Number, (, or -\n"); return false; } return true; } public boolean intexpr_R(String expr) { switch (token) { case WORD: case '(': case '-': if (!intexpr_S(expr)) return false; if (!intexpr_B(expr)) return false; break; default: System.out.printf("R:ERROR: Expected a ID, Number, (, or -\n"); return false; } return true; } public boolean intexpr_P(String expr) { newresult = new ExprTree(this); int spos, i; String ineq = ""; String comp; switch (token) { case '=': spos = position; (token) = intexpr_gettok(expr); newresult.token = token; newresult.tokvalue = tokvalue; newresult.position = position; if (!newresult.intexpr_R(expr)) return false; token = newresult.token; tokvalue = newresult.tokvalue; position = newresult.position; // simplify if operands are static if (((newresult.isit == 'n') || (newresult.isit == 't')) && (((this).isit == 'n') || ((this).isit == 't')) && ((this).lvalue == (this).uvalue) && (newresult.lvalue == newresult.uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN) && (newresult.lvalue != INFIN) && (newresult.lvalue != -INFIN)) { (this).isit = 't'; if (this.lvalue == newresult.lvalue) { this.lvalue = 1; } else { this.lvalue = 0; } (this).uvalue = (this).lvalue; } else { if ((this).isit == 'c') { comp = variable; comp += "="; // int paren = 0; // for (i = spos; i < position; i++) { // if (expr.charAt(i) == '(') // paren++; // if (expr.charAt(i) == ')') // paren--; // ineq = ineq + expr.charAt(i); comp += ineq; if (booleanSignals.contains(comp)) { this.isit = 'b'; this.variable = comp; this.lvalue = 0; this.uvalue = 1; return true; } else { booleanSignals.add(comp); this.isit = 'b'; this.variable = comp; this.lvalue = 0; this.uvalue = 1; return true; } } else { setNodeValues((this), newresult, "==", 'r'); } } break; case '>': spos = position; (token) = intexpr_gettok(expr); newresult.token = token; if ((token) == '=') { spos = position; (token) = intexpr_gettok(expr); newresult.token = token; newresult.tokvalue = tokvalue; newresult.position = position; if (!newresult.intexpr_R(expr)) return false; token = newresult.token; tokvalue = newresult.tokvalue; position = newresult.position; // simplify if operands are static if (((newresult.isit == 'n') || (newresult.isit == 't')) && (((this).isit == 'n') || ((this).isit == 't')) && ((this).lvalue == (this).uvalue) && (newresult.lvalue == newresult.uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN) && (newresult.lvalue != INFIN) && (newresult.lvalue != -INFIN)) { (this).isit = 't'; if ((this).lvalue >= newresult.lvalue) { this.lvalue = 1; } else { this.lvalue = 0; } (this).uvalue = (this).lvalue; } else { setNodeValues((this), newresult, ">=", 'r'); } } else { newresult.token = token; newresult.tokvalue = tokvalue; newresult.position = position; if (!newresult.intexpr_R(expr)) return false; token = newresult.token; tokvalue = newresult.tokvalue; position = newresult.position; // simplify if operands are static if (((newresult.isit == 'n') || (newresult.isit == 't')) && (((this).isit == 'n') || ((this).isit == 't')) && ((this).lvalue == (this).uvalue) && (newresult.lvalue == newresult.uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN) && (newresult.lvalue != INFIN) && (newresult.lvalue != -INFIN)) { (this).isit = 't'; if ((this).lvalue > newresult.lvalue) { this.lvalue = 1; } else { this.lvalue = 0; } (this).uvalue = (this).lvalue; } else { setNodeValues((this), newresult, ">", 'r'); } } break; case '<': spos = position; (token) = intexpr_gettok(expr); if ((token) == '=') { spos = position; (token) = intexpr_gettok(expr); newresult.token = token; newresult.tokvalue = tokvalue; newresult.position = position; if (!newresult.intexpr_R(expr)) return false; token = newresult.token; tokvalue = newresult.tokvalue; position = newresult.position; // simplify if operands are static if (((newresult.isit == 'n') || (newresult.isit == 't')) && (((this).isit == 'n') || ((this).isit == 't')) && ((this).lvalue == (this).uvalue) && (newresult.lvalue == newresult.uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN) && (newresult.lvalue != INFIN) && (newresult.lvalue != -INFIN)) { (this).isit = 't'; if ((this).lvalue <= newresult.lvalue) { this.lvalue = 1; } else { this.lvalue = 0; } (this).uvalue = (this).lvalue; } else { setNodeValues((this), newresult, "<=", 'r'); } } else { newresult.token = token; newresult.tokvalue = tokvalue; newresult.position = position; if (!newresult.intexpr_R(expr)) return false; token = newresult.token; tokvalue = newresult.tokvalue; position = newresult.position; // simplify if operands are static if (((newresult.isit == 'n') || (newresult.isit == 't')) && (((this).isit == 'n') || ((this).isit == 't')) && ((this).lvalue == (this).uvalue) && (newresult.lvalue == newresult.uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN) && (newresult.lvalue != INFIN) && (newresult.lvalue != -INFIN)) { (this).isit = 't'; if ((this).lvalue < newresult.lvalue) { this.lvalue = 1; } else { this.lvalue = 0; } (this).uvalue = (this).lvalue; } else { setNodeValues((this), newresult, "<", 'r'); } } break; case '[': (token) = intexpr_gettok(expr); newresult.token = token; newresult.tokvalue = tokvalue; newresult.position = position; if (!newresult.intexpr_R(expr)) return false; token = newresult.token; tokvalue = newresult.tokvalue; position = newresult.position; if ((token) != ']') { System.out.printf("ERROR: Expected a ]\n"); return false; } // simplify if operands are static if (((newresult.isit == 'n') || (newresult.isit == 't')) && (((this).isit == 'n') || ((this).isit == 't')) && ((this).lvalue == (this).uvalue) && (newresult.lvalue == newresult.uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN) && (newresult.lvalue != INFIN) && (newresult.lvalue != -INFIN)) { (this).isit = 't'; (this).lvalue = (((int) (this).lvalue) >> ((int) newresult.lvalue)) & 1; (this).uvalue = (this).lvalue; } else { setNodeValues((this), newresult, "[]", 'l'); } (token) = intexpr_gettok(expr); break; case '&': case '|': case ')': case IMPLIES: case END_OF_STRING: break; default: System.out.printf("ERROR: Expected a [, =, <, or >\n"); return false; } return true; } public boolean intexpr_O(String expr) { switch (token) { case WORD: case '(': case '-': if (!intexpr_R(expr)) return false; if (!intexpr_P(expr)) return false; break; default: System.out.printf("O:ERROR: Expected a ID, Number, or a (\n"); return false; } return true; } public boolean intexpr_N(String expr) { switch (token) { case WORD: case '-': case '(': if (!intexpr_O(expr)) return false; break; case '~': (token) = intexpr_gettok(expr); if (!intexpr_O(expr)) return false; // simplify if operands are static if ((((this).isit == 'n') || ((this).isit == 't')) && ((this).lvalue == (this).uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)) { (this).isit = 't'; if (this.lvalue == 1) { this.lvalue = 0; } else { this.lvalue = 1; } (this).uvalue = (this).lvalue; } else { setNodeValues((this), null, "!", 'l'); } break; default: System.out.printf("N:ERROR: Expected a ID, Number, (, or -\n"); return false; } return true; } public boolean intexpr_E(String expr) { newresult = new ExprTree(this); switch (token) { case '&': token = intexpr_gettok(expr); newresult.token = token; newresult.tokvalue = tokvalue; newresult.position = position; if (!newresult.intexpr_N(expr)) return false; token = newresult.token; position = newresult.position; // simplify if operands are static if (((newresult.isit == 'n') || (newresult.isit == 't')) && (((this).isit == 'n') || ((this).isit == 't')) && ((this).lvalue == (this).uvalue) && (newresult.lvalue == newresult.uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN) && (newresult.lvalue != INFIN) && (newresult.lvalue != -INFIN)) { (this).isit = 't'; if ((this.lvalue == 0) || (newresult.lvalue == 0)) { this.lvalue = 0; } else { this.lvalue = 1; } (this).uvalue = (this).lvalue; } else { setNodeValues((this), newresult, "&&", 'l'); } if (!intexpr_E(expr)) return false; break; case '|': case ')': case IMPLIES: case END_OF_STRING: break; default: System.out.printf("ERROR(%c): Expected an &\n", (token)); return false; } return true; } public boolean intexpr_D(String expr) { newresult = new ExprTree(this); switch (token) { case '|': (token) = intexpr_gettok(expr); newresult.token = token; newresult.tokvalue = tokvalue; newresult.position = position; if (!newresult.intexpr_M(expr)) return false; token = newresult.token; position = newresult.position; // simplify if operands are static if (((newresult.isit == 'n') || (newresult.isit == 't')) && (((this).isit == 'n') || ((this).isit == 't')) && ((this).lvalue == (this).uvalue) && (newresult.lvalue == newresult.uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN) && (newresult.lvalue != INFIN) && (newresult.lvalue != -INFIN)) { (this).isit = 't'; if (this.lvalue != 0 || newresult.lvalue != 0) { this.lvalue = 1; } else { this.lvalue = 0; } (this).uvalue = (this).lvalue; } else { setNodeValues((this), newresult, "||", 'l'); } if (!intexpr_D(expr)) return false; break; case ')': case END_OF_STRING: break; case IMPLIES: (token) = intexpr_gettok(expr); if (!intexpr_M(expr)) return false; // simplify if operands are static if (((newresult.isit == 'n') || (newresult.isit == 't')) && (((this).isit == 'n') || ((this).isit == 't')) && ((this).lvalue == (this).uvalue) && (newresult.lvalue == newresult.uvalue) && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN) && (newresult.lvalue != INFIN) && (newresult.lvalue != -INFIN)) { (this).isit = 't'; if (this.lvalue != 0 || newresult.lvalue == 0) { this.lvalue = 1; } else { this.lvalue = 0; } (this).uvalue = (this).lvalue; } else { setNodeValues(this, newresult, "->", 'l'); } if (!intexpr_D(expr)) return false; break; default: System.out.printf("ERROR: Expected an | or ->\n"); return false; } return true; } public boolean intexpr_M(String expr) { switch (token) { case WORD: case '(': case '~': case '-': if (!intexpr_N(expr)) return false; if (!intexpr_E(expr)) return false; break; default: System.out.printf("M: ERROR: Expected a ID, Number, (, or -\n"); return false; } return true; } public boolean intexpr_L(String expr) { switch (token) { case WORD: case '(': case '~': case '-': if (!intexpr_M(expr)) return false; if (!intexpr_D(expr)) return false; break; default: System.out.printf("L:ERROR: Expected a ID, Number, (, or -\n"); return false; } return true; } public String toString() { String result = ""; result = getElement("LHPN"); return result; } public String toString(String type) { String result = ""; result = getElement(type); return result; } public String toString(String type, String lhpnSbml) { String result = ""; result = getElement(lhpnSbml); if (type.equals("continuous") || type.equals("integer")) { if (isit == 't') { if (uvalue == 0) { result = "0"; } else { result = "1"; } } } else { if (isit == 'n') { if (uvalue == 0) { result = "FALSE"; } else { result = "TRUE"; } } } return result; } public boolean implies(ExprTree expr) { if (isEqual(expr)) { return true; } if (expr.isit == 'l' && expr.op.equals("||")) { if (implies(expr.r1) || implies(expr.r2)) { return true; } } else if (expr.isit == 'l' && expr.op.equals("&&")) { if (implies(expr.r1) && implies(expr.r2)) { return true; } } switch (isit) { case 't': // Truth value if (uvalue == 1 && lvalue == 1) { return false; } else if (uvalue == 0 && lvalue == 0) { return true; } else { return false; } case 'r': // Relational if (op.contains(">")) { if (expr.isit == 'r' && expr.op.contains(">")) { if (r2.lvalue > expr.r2.uvalue) { return true; } else if (r2.lvalue == expr.r2.uvalue && op.length() >= expr.op.length()) { return true; } } } else if (op.contains("<")) { if (expr.isit == 'r' && expr.op.contains("<")) { if (r2.lvalue < expr.r2.uvalue) { return true; } else if (r2.lvalue == expr.r2.uvalue && op.length() >= expr.op.length()) { return true; } } } return false; case 'l': // Logical if (op.equals("&&")) { if (expr.isit == 'b') { if (r1.implies(expr) || r2.implies(expr)) { return true; } } } else if (op.equals("||")) { if (expr.isit == 'b') { if (r1.implies(expr) && r2.implies(expr)) { return true; } } } return false; case 'b': // Boolean case 'i': // Integer case 'c': // Continuous case 'n': // Number case 'w': // bitWise case 'a': // Arithmetic default: return false; } } public boolean containsVar(String var) { switch (isit) { case 'b': // Boolean case 'i': // Integer case 'c': // Continuous if (variable.equals(var)) return true; return false; case 'r': // Relational case 'l': // Logical case 'a': // Arithmetic case 'w': // bitWise if (r1 != null) { if (r1.containsVar(var)) { return true; } } if (r2 != null) { if (r2.containsVar(var)) { return true; } } return false; case 'n': // Number case 't': // Truth value default: return false; } } public ArrayList<String> getVars() { ArrayList<String> vars = new ArrayList<String>(); switch (isit) { case 'b': // Boolean case 'i': // Integer case 'c': // Continuous if (!vars.contains(variable)) vars.add(variable); break; case 'r': // Relational case 'l': // Logical case 'a': // Arithmetic case 'w': // bitWise if (r1 != null) vars.addAll(r1.getVars()); if (r2 != null) vars.addAll(r2.getVars()); break; case 'n': // Number case 't': // Truth value default: break; } return vars; } public void scaleVals(Double scaleFactor) { switch (isit) { case 'b': // Boolean case 'i': // Integer case 'c': // Continuous break; case 'r': // Relational case 'l': // Logical case 'a': // Arithmetic case 'w': // bitWise if (r1 != null) r1.scaleVals(scaleFactor); if (r2 != null) r2.scaleVals(scaleFactor); break; case 'n': // Number variable = String .valueOf((int) (Double.parseDouble(variable) * scaleFactor)); break; case 't': // Truth value default: break; } } public boolean containsCont() { switch (isit) { case 'b': // Boolean case 't': // Truth value return false; case 'i': // Integer case 'c': // Continuous case 'r': // Relational case 'a': // Arithmetic case 'n': // Number return true; case 'l': // Logical case 'w': // bitWise boolean r1cont = false, r2cont = false; if (r1 != null) r1cont = r1.containsCont(); if (r2 != null) r2cont = r2.containsCont(); return (r1cont || r2cont); } return false; } public void replace(String var, String type, ExprTree e) { if (this == e) { return; } boolean simplify = false; switch (isit) { case 'b': // Boolean case 'i': // Integer case 'c': // Continuous if (variable.equals(var)) { if (e.isit == 'a' || e.isit == 'r' || e.isit == 'l' || e.isit == 'w') { setNodeValues(e.r1, e.r2, e.op, e.isit); } else { setVarValues(e.isit, e.lvalue, e.uvalue, e.variable); } } return; case 'w': // bitWise case 'l': // Logical case 'r': // Relational case 'a': // Arithmetic if (r1 != null || r2 != null) { if (r1 != null) r1.replace(var, type, e); if (r2 != null) r2.replace(var, type, e); break; } // simplify if operands are static if (op.equals("&&")) { if ((r1.isit == 'n') || (r1.isit == 't')) { if (r1.lvalue == 0) { setVarValues('t', 0.0, 0.0, null); simplify = true; } else { if (r2.isit == 'l' || r2.isit == 'a' || r2.isit == 'w' || r2.isit == 'r') { setNodeValues(r2.r1, r2.r2, r2.op, r2.isit); } else { setVarValues(r2.isit, r2.lvalue, r2.uvalue, r2.variable); } } } else if (((r2).isit == 'n') || ((r2).isit == 't')) { if (r2.lvalue == 0) { setVarValues('t', 0.0, 0.0, null); simplify = true; } else { if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w' || r1.isit == 'r') { setNodeValues(r1.r1, r1.r2, r1.op, r1.isit); } else { setVarValues(r1.isit, r1.lvalue, r1.uvalue, r1.variable); } } } } else if (op.equals("||")) { if ((r1.isit == 'n') || (r1.isit == 't')) { if (r1.lvalue == 1) { setVarValues('t', 1.0, 1.0, null); simplify = true; } else { if (r2.isit == 'l' || r2.isit == 'a' || r2.isit == 'w' || r2.isit == 'r') { setNodeValues(r2.r1, r2.r2, r2.op, r2.isit); } else { setVarValues(r2.isit, r2.lvalue, r2.uvalue, r2.variable); } } } else if (((r2).isit == 'n') || ((r2).isit == 't')) { if (r2.lvalue == 1) { setVarValues('t', 1.0, 1.0, null); simplify = true; } else { if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w' || r1.isit == 'r') { setNodeValues(r1.r1, r1.r2, r1.op, r1.isit); } else { setVarValues(r1.isit, r1.lvalue, r1.uvalue, r1.variable); } } } else if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 't'; if (r1.lvalue != 0 || r2.lvalue != 0) { this.lvalue = 1; } else { this.lvalue = 0; } (this).uvalue = (this).lvalue; simplify = true; } } else if (op.equals("->")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 't'; if (r1.lvalue != 0 || r2.lvalue == 0) { this.lvalue = 1; } else { this.lvalue = 0; } (this).uvalue = (this).lvalue; simplify = true; } } else if (op.equals("!")) { if (((r1).isit == 'n') || ((r1).isit == 't')) { (this).isit = 't'; if (r1.lvalue == 1) { this.lvalue = 0; } else { this.lvalue = 1; } (this).uvalue = (this).lvalue; simplify = true; } } else if (op.equals("==")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 't'; if (r1.lvalue == r2.lvalue) { this.lvalue = 1; } else { this.lvalue = 0; } (this).uvalue = (this).lvalue; simplify = true; } } else if (op.equals(">=")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 't'; if ((r1).lvalue >= r2.lvalue) { this.lvalue = 1; } else { this.lvalue = 0; } (this).uvalue = (this).lvalue; simplify = true; } } else if (op.equals(">")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 't'; if ((r1).lvalue > r2.lvalue) { this.lvalue = 1; } else { this.lvalue = 0; } (this).uvalue = (this).lvalue; simplify = true; } } else if (op.equals("<=")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 't'; if ((r1).lvalue <= r2.lvalue) { this.lvalue = 1; } else { this.lvalue = 0; } (this).uvalue = (this).lvalue; simplify = true; } } else if (op.equals("<")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 't'; if ((r1).lvalue < r2.lvalue) { this.lvalue = 1; } else { this.lvalue = 0; } (this).uvalue = (this).lvalue; simplify = true; } } else if (op.equals("&")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 'n'; (this).lvalue = ((int) (r1).lvalue) & ((int) r2.lvalue); (this).uvalue = (this).lvalue; simplify = true; } } else if (op.equals("|")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 'n'; (this).lvalue = (int) (r1).lvalue | (int) r2.lvalue; (this).uvalue = (this).lvalue; simplify = true; } } else if (op.equals("X")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 'n'; (this).lvalue = (int) (r1).lvalue ^ (int) r2.lvalue; (this).uvalue = (this).lvalue; simplify = true; } } else if (op.equals("m")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 'n'; (this).lvalue = Math.min((r1).lvalue, r2.lvalue); (this).uvalue = (this).lvalue; simplify = true; } } else if (op.equals("M")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 'n'; (this).lvalue = Math.max((r1).lvalue, r2.lvalue); (this).uvalue = (this).lvalue; simplify = true; } } else if (op.equals("i")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 'n'; (this).lvalue = Math.floor((r1).lvalue / (r2).lvalue); (this).uvalue = (this).lvalue; simplify = true; } } else if (op.equals("f")) { if (((r1).isit == 'n') || ((r1).isit == 't')) { (this).isit = 'n'; (this).lvalue = Math.floor((r1).lvalue); (this).uvalue = (this).lvalue; simplify = true; } } else if (op.equals("c")) { if (((r1).isit == 'n') || ((r1).isit == 't')) { (this).isit = 'n'; (this).lvalue = Math.ceil((r1).lvalue); (this).uvalue = (this).lvalue; simplify = true; } } else if (op.equals("~")) { if (((r1).isit == 'n') || ((r1).isit == 't')) { (this).isit = 'n'; (this).lvalue = ~(int) (r1).lvalue; (this).uvalue = (this).lvalue; simplify = true; } } else if (op.equals("[]")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 't'; (this).lvalue = (((int) (r1).lvalue) >> ((int) r2.lvalue)) & 1; (this).uvalue = (this).lvalue; simplify = true; } } else if (op.equals("U-")) { if (((r1).isit == 'n') || ((r1).isit == 't')) { (this).isit = 'n'; (this).lvalue = -((r1).lvalue); (this).uvalue = (this).lvalue; simplify = true; } } else if (op.equals("*")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 'n'; (this).lvalue = (r1).lvalue * r2.lvalue; (this).uvalue = (this).lvalue; } } else if (op.equals("/")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 'n'; (this).lvalue = (r1).lvalue / r2.lvalue; (this).uvalue = (this).lvalue; simplify = true; } } else if (op.equals("%")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 'n'; (this).lvalue = (r1).lvalue % r2.lvalue; (this).uvalue = (this).lvalue; simplify = true; } } else if (op.equals("+")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 'n'; (this).lvalue = (r1).lvalue + r2.lvalue; (this).uvalue = (this).lvalue; } else if ((r1.isit == 'n') || (r1.isit == 't')) { if (r1.lvalue == 0 && r1.uvalue == 0) { setNodeValues(r2.r1, r2.r2, r2.op, r2.isit); } } else if (((r2).isit == 'n') || ((r2).isit == 't')) { if (r2.lvalue == 0 && r2.uvalue == 0) { setNodeValues(r1.r1, r1.r2, r1.op, r1.isit); } } } else if (op.equals("-")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 'n'; (this).lvalue = (r1).lvalue - r2.lvalue; (this).uvalue = (this).lvalue; simplify = true; } } break; case 't': // Truth value if (lvalue != 0 && uvalue != 0) { lvalue = 1; uvalue = 1; } else if (lvalue != 0 || uvalue != 0) { lvalue = 0; uvalue = 1; } return; case 'n': // Number break; } if (simplify) { if (type.equals("integer") || type.equals("continuous")) { isit = 'n'; } else { isit = 't'; if (lvalue != 0 && uvalue != 0) { lvalue = 1; uvalue = 1; } else if (lvalue != 0 || uvalue != 0) { lvalue = 0; uvalue = 1; } } } } public void replaceVar(String var1, String var2) { switch (isit) { case 'b': // Boolean case 'i': // Integer case 'c': // Continuous if (variable.equals(var1)) { variable = var2; } return; case 'w': // bitWise case 'l': // Logical case 'r': // Relational case 'a': // Arithmetic if (r1 != null) r1.replaceVar(var1, var2); if (r2 != null) r2.replaceVar(var1, var2); case 't': // Truth value case 'n': // Number break; } } public char getChange(HashMap<String, String> variables) { switch (isit) { case 'b': // Boolean if (variables.containsKey(variable)) { if (variables.get(variable).toString().toLowerCase().equals( "false")) return 'F'; if (variables.get(variable).toString().toLowerCase().equals( "true")) return 'T'; else { return 'X'; } } else { return 'U'; } case 't': // Truth value if (uvalue == 0) return 'T'; else if (lvalue == 1) return 'F'; return 'U'; case 'l': // Logical if (op.equals("||")) { if (r1.getChange(variables) == 'T' || r2.getChange(variables) == 'T') { return 'T'; } else if (r1.getChange(variables) == 'X' || r2.getChange(variables) == 'X') { return 'X'; } else if (r1.getChange(variables) == 't') { if (r2.getChange(variables) == 'f') { return 'X'; } else { return 't'; } } else if (r2.getChange(variables) == 't') { if (r1.getChange(variables) == 'f') { return 'X'; } else { return 't'; } } else if (r1.getChange(variables) == 'f' || r2.getChange(variables) == 'f') { return 'f'; } else if (r1.getChange(variables) == 'F') { if (r2.getChange(variables) == 'F') { return 'F'; } else { return 'f'; } } else if (r2.getChange(variables) == 'F') { return 'f'; } return 'U'; } else if (op.equals("&&")) { if (r1.getChange(variables) == 'F' || r2.getChange(variables) == 'F') { return 'F'; } else if (r1.getChange(variables) == 'X' || r2.getChange(variables) == 'X') { return 'X'; } else if (r1.getChange(variables) == 'f') { if (r2.getChange(variables) == 't') { return 'X'; } else { return 'f'; } } else if (r2.getChange(variables) == 'f') { if (r1.getChange(variables) == 't') { return 'X'; } else { return 'f'; } } else if (r1.getChange(variables) == 't' || r2.getChange(variables) == 't') { return 't'; } else if (r1.getChange(variables) == 'T') { if (r2.getChange(variables) == 'T') { return 'T'; } else { return 't'; } } else if (r2.getChange(variables) == 'T') { return 't'; } return 'U'; } else if (op.equals("!")) { if (r1.getChange(variables) == 'T') { return 'F'; } else if (r1.getChange(variables) == 'F') { return 'T'; } else if (r1.getChange(variables) == 't') { return 'f'; } else if (r1.getChange(variables) == 'f') { return 't'; } return r1.getChange(variables); } else if (op.equals("->")) { if (r1.getChange(variables) == 'T' || r2.getChange(variables) == 'F') { return 'T'; } else if (r1.getChange(variables) == 'X' || r2.getChange(variables) == 'X') { return 'X'; } else if (r1.getChange(variables) == 't') { if (r2.getChange(variables) == 't') { return 'X'; } else { return 't'; } } else if (r2.getChange(variables) == 'f') { if (r1.getChange(variables) == 'f') { return 'X'; } else { return 't'; } } else if (r1.getChange(variables) == 'f') { return 'f'; } else if (r2.getChange(variables) == 't') { return 'f'; } else if (r1.getChange(variables) == 'F') { if (r2.getChange(variables) == 'T') { return 'F'; } else { return 'f'; } } else if (r2.getChange(variables) == 'T') { return 'f'; } return 'U'; } case 'r': // Relational boolean flag = false; for (String var : getVars()) { if (variables.containsKey(var)) { flag = true; break; } } if (!flag) { return 'U'; } if (op.equals("==")) { if (r1.evaluateExpr(variables) == r2.evaluateExpr(variables)) { return 'T'; } else if (new Double(r1.evaluateExpr(variables)) .equals(Double.NaN) || new Double(r2.evaluateExpr(variables)) .equals(Double.NaN)) { return 'X'; } return 'F'; } else if (op.equals(">=")) { if (r1.evaluateExpr(variables) >= r2.evaluateExpr(variables)) { return 'T'; } else if (new Double(r2.evaluateExpr(variables)) .equals(Double.NaN) || new Double(r1.evaluateExpr(variables)) .equals(Double.NaN)) { return 'X'; } return 'F'; } else if (op.equals("<=")) { if (r1.evaluateExpr(variables) <= r2.evaluateExpr(variables)) { return 'T'; } else if (new Double(r1.evaluateExpr(variables)) .equals(Double.NaN) || new Double(r2.evaluateExpr(variables)) .equals(Double.NaN)) { return 'X'; } return 'F'; } else if (op.equals(">")) { if (r1.evaluateExpr(variables) > r2.evaluateExpr(variables)) { return 'T'; } else if (new Double(r1.evaluateExpr(variables)) .equals(Double.NaN) || new Double(r2.evaluateExpr(variables)) .equals(Double.NaN)) { return 'X'; } return 'F'; } else if (op.equals("<")) { if (r1.evaluateExpr(variables) < r2.evaluateExpr(variables)) { return 'T'; } else if (new Double(r1.evaluateExpr(variables)) .equals(Double.NaN) || new Double(r2.evaluateExpr(variables)) .equals(Double.NaN)) { return 'X'; } return 'F'; } return 'X'; case 'i': // Integer if (variables.containsKey(variable)) { if (Integer.parseInt(variables.get(variable)) == 0.0) { return 'F'; } else { return 'T'; } } else { return 'U'; } case 'c': // Continuous return 'X'; case 'n': // Number if (uvalue == 0.0 && lvalue == 0.0) { return 'F'; } else { return 'T'; } } return 'X'; } public boolean becomesFalse(HashMap<String, String> variables) { switch (isit) { case 'b': // Boolean if (variables.containsKey(variable)) if (variables.get(variable).toString().toLowerCase().equals( "false")) return true; return false; case 't': // Truth value if (lvalue == 0) return true; return false; case 'l': // Logical if (op.equals("||")) { if (r1.becomesFalse(variables) && r2.becomesFalse(variables)) { return true; } return false; } else if (op.equals("&&")) { if ((r1.becomesFalse(variables) && !r2.becomesTrue(variables)) || (!r1.becomesTrue(variables) && r2 .becomesFalse(variables))) return true; return false; } else if (op.equals("==")) { if (!(r1.isEqual(r2) || r1.evaluateExpr(variables) == r2 .evaluateExpr(variables))) return true; return false; } else if (op.equals("!")) { if (r1.becomesTrue(variables)) return true; return false; } else if (op.equals("->")) { if (r1.becomesFalse(variables) || r2.becomesTrue(variables)) { return true; } return false; } else if (op.equals("[]")) { if (!(evaluateExpr(variables) == 0.0)) { return true; } return false; } case 'w': // bitWise if (op.equals("&")) { if (!(evaluateExpr(variables) == 0.0)) { return true; } return false; } else if (op.equals("|")) { if (!(evaluateExpr(variables) == 0.0)) { return true; } return false; } else if (op.equals("X")) { if (!(evaluateExpr(variables) == 0.0)) { return true; } return false; } else if (op.equals("~")) { if (!(evaluateExpr(variables) == 0.0)) { return true; } return false; } case 'r': // Relational if (r1.isit == 'i') { if (!variables.containsKey(r1.variable)) { return false; } if (op.equals("==")) { if (r1.evaluateExpr(variables) == r2 .evaluateExpr(variables)) { return false; } return true; } else if (op.equals(">=")) { if (r1.evaluateExpr(variables) >= r2 .evaluateExpr(variables)) { return false; } return true; } else if (op.equals("<=")) { if (r1.evaluateExpr(variables) <= r2 .evaluateExpr(variables)) { return false; } return true; } else if (op.equals(">")) { if (r1.evaluateExpr(variables) > r2.evaluateExpr(variables)) { return false; } return true; } else if (op.equals("<")) { if (r1.evaluateExpr(variables) < r2.evaluateExpr(variables)) { return false; } return true; } return true; } else { return true; } case 'i': // Integer if (variables.containsKey(variable)) { if (Integer.parseInt(variables.get(variable)) == 0.0) { return true; } else { return false; } } else { return false; } case 'c': // Continuous return true; case 'a': // Arithmetic boolean contains = false; for (String s : getVars()) { if (variables.containsKey(s)) { contains = true; break; } } if (!contains) { return false; } if (!(evaluateExpr(variables) == 0.0)) { return false; } else { return true; } case 'n': // Number if (uvalue == 0.0 && lvalue == 0.0) { return true; } else { return false; } } return false; } public boolean becomesTrue(HashMap<String, String> variables) { switch (isit) { case 'b': // Boolean if (variables.containsKey(variable)) { if (variables.get(variable).toString().matches("[\\d[\\.]]+")) { if (Double.parseDouble(variables.get(variable).toString()) != 0) { return true; } } if (variables.get(variable).toString().toLowerCase().equals( "true")) return true; } return false; case 'i': // Integer if (variables.containsKey(variable)) { if (!variables.get(variable).equals("0.0")) { return true; } } return false; case 'c': // Continuous return true; case 'n': // Number case 't': // Truth value if (uvalue != 0) return true; return false; case 'l': // Logical if (op.equals("||")) { if (r1.becomesTrue(variables) || r2.becomesTrue(variables)) return true; return false; } else if (op.equals("&&")) { if ((r1.becomesTrue(variables) && !r2.becomesFalse(variables)) || (!r1.becomesFalse(variables) && r2 .becomesTrue(variables))) return true; return false; } else if (op.equals("==")) { if (r1.isEqual(r2, variables) || r1.evaluateExpr(variables) == r2 .evaluateExpr(variables)) return true; return false; } else if (op.equals("!")) { if (r1.becomesFalse(variables)) return true; return false; } else if (op.equals("->")) { if (r1.becomesTrue(variables) || r2.becomesFalse(variables)) { return true; } else { return false; } } case 'w': // bitWise if (op.equals("&")) { if (evaluateExpr(variables) == 0.0) { return false; } return true; } else if (op.equals("|")) { if (evaluateExpr(variables) == 0.0) { return false; } return true; } else if (op.equals("X")) { if (evaluateExpr(variables) == 0.0) { return false; } return true; } else if (op.equals("~")) { if (evaluateExpr(variables) == 0.0) { return false; } return true; } else if (op.equals("[]")) { if (evaluateExpr(variables) == 0.0) { return false; } return true; } case 'r': // Relational if (r1.isit == 'i') { if (!variables.containsKey(r1.variable)) { return false; } if (op.equals("==")) { if (!(r1.evaluateExpr(variables) == r2 .evaluateExpr(variables))) { return false; } return true; } else if (op.equals(">=")) { if (!(r1.evaluateExpr(variables) >= r2 .evaluateExpr(variables))) { return false; } return true; } else if (op.equals("<=")) { if (!(r1.evaluateExpr(variables) <= r2 .evaluateExpr(variables))) { return false; } return true; } else if (op.equals(">")) { if (!(r1.evaluateExpr(variables) > r2 .evaluateExpr(variables))) { return false; } return true; } else if (op.equals("<")) { if (!(r1.evaluateExpr(variables) < r2 .evaluateExpr(variables))) { return false; } return true; } return true; } else { return true; } case 'a': // Arithmetic boolean contains = false; for (String s : getVars()) { if (variables.containsKey(s)) { contains = true; break; } } if (!contains) { return false; } if (!(evaluateExpr(variables) != 0.0)) { return false; } else { return true; } } return true; } public String getElement(String type) { boolean sbmlFlag; sbmlFlag = type.equals("SBML"); Boolean verilog = type.equalsIgnoreCase("Verilog"); String result = ""; switch (isit) { case 'b': // Boolean case 'i': // Integer case 'c': // Continuous if (!sbmlFlag) { result = variable; } else { if (isit == 'b') { result = "eq(" + variable + ",1)"; } else { result = variable; } } break; case 'n': // Number // long term solution: create initial assignment // short term solution: initialize all inf, -inf, [-inf, inf] to 0 // initialize [l,u] to (l+u)/2 Double tempuval = uvalue; Double templval = lvalue; if ((uvalue == lvalue) || tempuval.toString().equals("")) { if (lvalue == INFIN) { result = "inf"; } else if (lvalue == -INFIN) { result = "-inf"; } else { if (tempuval % 1 == 0) { int tempval = (int) (tempuval / 1); result = new Integer(tempval).toString(); } else { result = tempuval.toString(); } } } else { String lval; if (lvalue == INFIN) { lval = "inf"; } else if (lvalue == -INFIN) { lval = "-inf"; } else { if (tempuval % 1 == 0) { int tempval = (int) (templval / 1); lval = new Integer(tempval).toString(); } else { lval = templval.toString(); } } String uval; if (uvalue == INFIN) { uval = "inf"; } else if (uvalue == -INFIN) { uval = "-inf"; } else { if (tempuval % 1 == 0) { int tempval = (int) (tempuval / 1); uval = new Integer(tempval).toString(); } else { uval = tempuval.toString(); } } if (verilog) { result = "uniform(" + lval + "," + uval + ")"; } else { result = "uniform(" + lval + "," + uval + ")"; } } break; case 't': // Truth value if (uvalue == 0 && lvalue == 0) { if (verilog) result = "0"; else result = "FALSE"; } else if (uvalue == 1 && lvalue == 1) { if (verilog) result = "1"; else result = "TRUE"; } else { if (sbmlFlag | verilog) { result = "0"; } result = "UNKNOWN"; } break; case 'w': // bitWise if (op.equals("&")) { if (r1 != null && r2 != null) { if (sbmlFlag) { result = "BITAND(" + r1.getElement(type) + "," + r2.getElement(type) + ")"; } else if (verilog) { result = r1.getElement(type) + "&" + r2.getElement(type); } else { result = "and(" + r1.getElement(type) + "," + r2.getElement(type) + ")"; } } } else if (op.equals("|")) { if (r1 != null && r2 != null) { if (sbmlFlag) { result = "BITOR(" + r1.getElement(type) + "," + r2.getElement(type) + ")"; } else if (verilog) { result = r1.getElement(type) + "|" + r2.getElement(type); } else { result = "or(" + r1.getElement(type) + "," + r2.getElement(type) + ")"; } } } else if (op.equals("!")) { if (r1 != null && r2 != null) { if (sbmlFlag) { result = "BITNOT(" + r1.getElement(type) + ")"; } else if (verilog) { result = "~" + r1.getElement(type); } else { result = "not(" + r1.getElement(type) + ")"; } } } else if (op.equals("X")) { if (r1 != null && r2 != null) { if (sbmlFlag) { result = "XOR(" + r1.getElement(type) + "," + r2.getElement(type) + ")"; } else if (verilog) { result = r1.getElement(type) + "^" + r2.getElement(type); } else { result = "exor(" + r1.getElement(type) + "," + r2.getElement(type) + ")"; } } } break; case 'a': // Arithmetic case 'r': // Relational case 'l': // Logical if (op.equals("!")) { if (r1 != null) { if (r1.isit == 'b' || r1.isit == 'i' || r1.isit == 'c' || r1.isit == 'n' || r1.isit == 't') { if (sbmlFlag) { result = "not(" + r1.getElement(type) + ")"; } else if (verilog) { result = "!" + r1.getElement(type); } else { result = "~" + r1.getElement(type); } } else { if (sbmlFlag) { result = "not(" + r1.getElement(type) + ")"; } else if (verilog) { result = "!" + "(" + r1.getElement(type) + ")"; } else { result = "~" + "(" + r1.getElement(type) + ")"; } } } break; } else { if (op.equals("&&")) { if (r1.isit == 'r' || (r1.isit == 'l' && r1.op.equals("||"))) { if (r1 != null) { if (sbmlFlag) { result = "and(" + r1.getElement(type) + ","; } else if (verilog) { result = "(" + r1.getElement(type) + ")&&"; } else { result = "(" + r1.getElement(type) + ")"; } } } else { if (r1 != null) { if (sbmlFlag) { result = "and(" + r1.getElement(type) + ","; } else if (verilog) { result = r1.getElement(type) + "&&"; } else { result = r1.getElement(type); } } } if (!sbmlFlag && !verilog) { result = result + "&"; } if (r2.isit == 'r' || (r2.isit == 'l' && r2.op.equals("||"))) { if (r2 != null) { if (sbmlFlag) { result = result + r2.getElement(type) + ")"; } else { result = result + "(" + r2.getElement(type) + ")"; } } } else { if (r2 != null) { if (sbmlFlag) { result = result + r2.getElement(type) + ")"; } else { result = result + r2.getElement(type); } } } } else if (op.equals("||")) { if (r1.isit == 'r') { if (r1 != null) { if (sbmlFlag) { result = "or(" + r1.getElement(type) + ","; } else if (verilog) { result = "(" + r1.getElement(type) + ")||"; } else { result = "(" + r1.getElement(type) + ")"; } } } else { if (r1 != null) { if (sbmlFlag) { result = "or(" + r1.getElement(type) + ","; } else if (verilog) { result = r1.getElement(type) + "||"; } else { result = r1.getElement(type); } } } if (!sbmlFlag && !verilog) { result = result + "|"; } if (r2.isit == 'r') { if (r2 != null) { if (sbmlFlag) { result = result + r2.getElement(type) + ")"; } else { result = result + "(" + r2.getElement(type) + ")"; } } } else { if (r2 != null) { if (sbmlFlag) { result = result + r2.getElement(type) + ")"; } else { result = result + r2.getElement(type); } } } } else if (op.equals("f")) { if (r1 != null) { if (r1.isit == 'n') { result = new Integer((int) Math.floor(r1.lvalue)) .toString(); } else { if (sbmlFlag) { result = "floor(" + r1.getElement(type) + ")"; } else if (verilog) { result = "$floor(" + r1.getElement(type) + ")"; } else { result = "floor(" + r1.getElement(type) + ")"; } } } } else if (op.equals("c")) { if (r1 != null) { if (r1.isit == 'n') { result = new Integer((int) Math.ceil(r1.lvalue)) .toString(); } else { if (sbmlFlag) { result = "ceil(" + r1.getElement(type) + ")"; } else if (verilog) { result = "$ceil(" + r1.getElement(type) + ")"; } else { result = "ceil(" + r1.getElement(type) + ")"; } } } } else if (op.equals("m")) { if (r1 != null && r2 != null) { if (r1.isit == 'n' && r2.isit == 'n') { if (r1.lvalue < r2.lvalue) { result = r1.getElement(type); } else { result = r2.getElement(type); } } else { if (sbmlFlag) { result = "piecewise(" + r1.getElement(type) + ",leq(" + r1.getElement(type) + "," + r2.getElement(type) + ")," + r2.getElement(type) + ")"; //} else if (verilog) { //result = "min(" + r1.getElement(type) + "," // + r2.getElement(type) + ")"; } else if (verilog) { result = "("+r1.getElement(type) +"<"+r2.getElement(type) +"?"+r1.getElement(type) +":"+r2.getElement(type) +")"; } else { result = "min(" + r1.getElement(type) + "," + r2.getElement(type) + ")"; } } } } else if (op.equals("M")) { if (r1 != null && r2 != null) { if (r1.isit == 'n' && r2.isit == 'n') { if (r1.lvalue > r2.lvalue) { result = r1.getElement(type); } else { result = r2.getElement(type); } } else { if (sbmlFlag) { result = "piecewise(" + r1.getElement(type) + ",geq(" + r1.getElement(type) + "," + r2.getElement(type) + ")," + r2.getElement(type) + ")"; //} else if (verilog) { //result = "max(" + r1.getElement(type) + "," //+ r2.getElement(type) + ")"; } else if (verilog) { result = "("+r1.getElement(type) +">"+r2.getElement(type) +"?"+r1.getElement(type) +":"+r2.getElement(type) +")"; } else { result = "max(" + r1.getElement(type) + "," + r2.getElement(type) + ")"; } } } } else if (op.equals("i")) { if (r1 != null && r2 != null) { if (sbmlFlag) { result = "floor(" + r1.getElement(type) + "/" + r2.getElement(type) + ")"; } else if (verilog) { result = "floor(" + r1.getElement(type) + "/" + r2.getElement(type) + ")"; } else { result = "idiv(" + r1.getElement(type) + "," + r2.getElement(type) + ")"; } } } else if (op.equals("uniform")) { if (r1 != null && r2 != null) { if (verilog) { result = "uniform(" + r1.getElement(type) + "," + r2.getElement(type) + ")"; } else { result = "uniform(" + r1.getElement(type) + "," + r2.getElement(type) + ")"; } } } // TODO: Add verilog functions for other distributions else if (op.equals("[]")) { if (r1 != null && r2 != null) { result = "BIT(" + r1.getElement(type) + "," + r2.getElement(type) + ")"; } } else if (op.equals("normal")) { if (r1 != null && r2 != null) { result = "normal(" + r1.getElement(type) + "," + r2.getElement(type) + ")"; } } else if (op.equals("gamma")) { if (r1 != null && r2 != null) { result = "gamma(" + r1.getElement(type) + "," + r2.getElement(type) + ")"; } } else if (op.equals("lognormal")) { if (r1 != null && r2 != null) { result = "lognormal(" + r1.getElement(type) + "," + r2.getElement(type) + ")"; } } else if (op.equals("binomial")) { if (r1 != null && r2 != null) { result = "binomial(" + r1.getElement(type) + "," + r2.getElement(type) + ")"; } } else if (op.equals("exponential")) { if (r1 != null) { result = "exponential(" + r1.getElement(type) + ")"; } } else if (op.equals("chisq")) { if (r1 != null) { result = "chisq(" + r1.getElement(type) + ")"; } } else if (op.equals("laplace")) { if (r1 != null) { result = "laplace(" + r1.getElement(type) + ")"; } } else if (op.equals("cauchy")) { if (r1 != null) { result = "cauchy(" + r1.getElement(type) + ")"; } } else if (op.equals("rayleigh")) { if (r1 != null) { result = "rayleigh(" + r1.getElement(type) + ")"; } } else if (op.equals("poisson")) { if (r1 != null) { result = "poisson(" + r1.getElement(type) + ")"; } } else if (op.equals("bernoulli")) { if (r1 != null) { result = "bernoulli(" + r1.getElement(type) + ")"; } } else if (op.equals("rate")) { if (r1 != null) { result = "rate(" + r1.getElement(type) + ")"; } } else if (op.equals("INT")) { if (r1 != null) { if (sbmlFlag) { result = "piecewise(1," + r1.getElement(type) + ",0 )"; } else { result = "INT(" + r1.getElement(type) + ")"; } } } else if (op.equals("==")) { if (r1 != null) { if (sbmlFlag) { result = "eq(" + r1.getElement(type) + ","; } else if (verilog) { result = r1.getElement(type) + "=="; } else { result = r1.getElement(type); } } if (!sbmlFlag && !verilog) { result = result + "="; } if (r2 != null) { if (sbmlFlag) { result = result + r2.getElement(type) + ")"; } else { result = result + r2.getElement(type); } } } else if (op.equals("+")) { if (r1.isit == 'n' && r1.lvalue >= 0 && r2.isit == 'a' && r2.op.equals("uniform")) { ExprTree tempUniform = new ExprTree(r2); r1.setNodeValues(r1, tempUniform.r1, "+", 'a'); r2.setNodeValues(r1, tempUniform.r2, "+", 'a'); isit = 'a'; op = "uniform"; } else if (r1.isit == 'a' && r1.op.equals("uniform") && r2.isit == 'n' && r2.lvalue >= 0) { ExprTree tempUniform = new ExprTree(r1); r1.setNodeValues(r2, tempUniform.r1, "+", 'a'); r2.setNodeValues(r2, tempUniform.r2, "+", 'a'); isit = 'a'; op = "uniform"; } else { try { String r1String = r1.getElement(type); String r2String = r2.getElement(type); result = new Float(Float.parseFloat(r1String) + Float.parseFloat(r2String)).toString(); } catch (NumberFormatException e) { if (r1.isit == 'b' || r1.isit == 'i' || r1.isit == 'c' || r1.isit == 'n' || r1.isit == 't' || (r1.isit == 'a' && (r1.op.equals("+") || r1.op.equals("-") || r1.op.equals("*") || r1.op.equals("/") || r1.op .equals("^")))) { if (r1 != null) { result = r1.getElement(type); } } else { if (r1 != null) { result = "(" + r1.getElement(type) + ")"; } } result = result + "+"; if (r2.isit == 'b' || r2.isit == 'i' || r2.isit == 'c' || r2.isit == 'n' || r2.isit == 't' || (r2.isit == 'a' && (r2.op.equals("+") || r2.op.equals("-") || r2.op.equals("*") || r2.op.equals("/") || r2.op .equals("^")))) { if (r2 != null) { result = result + r2.getElement(type); } } else { if (r2 != null) { result = result + "(" + r2.getElement(type) + ")"; } } } } } else if (op.equals("-")) { if (r1.isit == 'a' && r1.op.equals("uniform") && r2.isit == 'n' && r2.lvalue >= 0) { ExprTree tempUniform = new ExprTree(r1); r1.setNodeValues(tempUniform.r1, r2, "-", 'a'); r2.setNodeValues(tempUniform.r2, r2, "-", 'a'); isit = 'a'; op = "uniform"; } else { try { String r1String = r1.getElement(type); String r2String = r2.getElement(type); result = new Float(Float.parseFloat(r1String) - Float.parseFloat(r2String)).toString(); } catch (NumberFormatException e) { if (r1.isit == 'b' || r1.isit == 'i' || r1.isit == 'c' || r1.isit == 'n' || r1.isit == 't' || (r1.isit == 'a' && (r1.op.equals("+") || r1.op.equals("-") || r1.op.equals("*") || r1.op.equals("/") || r1.op .equals("^")))) { if (r1 != null) { result = r1.getElement(type); } } else { if (r1 != null) { result = "(" + r1.getElement(type) + ")"; } } result = result + "-"; if (r2.isit == 'b' || r2.isit == 'i' || r2.isit == 'c' || r2.isit == 'n' || r2.isit == 't' || (r2.isit == 'a' && (r2.op.equals("-") || r2.op.equals("*") || r2.op.equals("/") || r2.op .equals("^")))) { if (r2 != null) { result = result + r2.getElement(type); } } else { if (r2 != null) { result = result + "(" + r2.getElement(type) + ")"; } } } } } else if (op.equals("*")) { if (r1.isit == 'n' && r1.lvalue >= 0 && r2.isit == 'a' && r2.op.equals("uniform")) { ExprTree tempUniform = new ExprTree(r2); r1.setNodeValues(r1, tempUniform.r1, "*", 'a'); r2.setNodeValues(r1, tempUniform.r2, "*", 'a'); isit = 'a'; op = "uniform"; } else if (r1.isit == 'a' && r1.op.equals("uniform") && r2.isit == 'n' && r2.lvalue >= 0) { ExprTree tempUniform = new ExprTree(r1); r1.setNodeValues(r2, tempUniform.r1, "*", 'a'); r2.setNodeValues(r2, tempUniform.r2, "*", 'a'); isit = 'a'; op = "uniform"; } else { try { String r1String = r1.getElement(type); String r2String = r2.getElement(type); result = new Float(Float.parseFloat(r1String) * Float.parseFloat(r2String)).toString(); } catch (NumberFormatException e) { if (r1.isit == 'b' || r1.isit == 'i' || r1.isit == 'c' || r1.isit == 'n' || r1.isit == 't' || (r1.isit == 'a' && (r1.op.equals("*") || r1.op.equals("/") || r1.op .equals("^")))) { if (r1 != null) { result = r1.getElement(type); } } else { if (r1 != null) { result = "(" + r1.getElement(type) + ")"; } } result = result + "*"; if (r2.isit == 'b' || r2.isit == 'i' || r2.isit == 'c' || r2.isit == 'n' || r2.isit == 't' || (r2.isit == 'a' && (r2.op.equals("*") || r2.op.equals("/") || r2.op .equals("^")))) { if (r2 != null) { result = result + r2.getElement(type); } } else { if (r2 != null) { result = result + "(" + r2.getElement(type) + ")"; } } } } } else if (op.equals("/")) { if (r1.isit == 'a' && r1.op.equals("uniform") && r2.isit == 'n' && r2.lvalue >= 0) { ExprTree tempUniform = new ExprTree(r1); r1.setNodeValues(tempUniform.r1, r2, "/", 'a'); r2.setNodeValues(tempUniform.r2, r2, "/", 'a'); isit = 'a'; op = "uniform"; } else { try { String r1String = r1.getElement(type); String r2String = r2.getElement(type); result = new Float(Float.parseFloat(r1String) / Float.parseFloat(r2String)).toString(); } catch (NumberFormatException e) { if (r1.isit == 'b' || r1.isit == 'i' || r1.isit == 'c' || r1.isit == 'n' || r1.isit == 't' || (r1.isit == 'a' && (r1.op.equals("*") || r1.op.equals("/") || r1.op .equals("^")))) { if (r1 != null) { result = r1.getElement(type); } } else { if (r1 != null) { result = "(" + r1.getElement(type) + ")"; } } result = result + "/"; if (r2.isit == 'b' || r2.isit == 'i' || r2.isit == 'c' || r2.isit == 'n' || r2.isit == 't' || (r2.isit == 'a' && (r2.op.equals("/") || r2.op .equals("^")))) { if (r2 != null) { result = result + r2.getElement(type); } } else { if (r2 != null) { result = result + "(" + r2.getElement(type) + ")"; } } } } } else if (op.equals("^")) { try { String r1String = r1.getElement(type); String r2String = r2.getElement(type); result = new Integer(Integer.parseInt(r1String) ^ Integer.parseInt(r2String)).toString(); } catch (NumberFormatException e) { if (r1.isit == 'b' || r1.isit == 'i' || r1.isit == 'c' || r1.isit == 'n' || r1.isit == 't' || (r1.isit == 'a' && (r1.op.equals("*") || r1.op.equals("/") || r1.op .equals("^")))) { if (r1 != null) { result = "(" + r1.getElement(type) + ")"; } } else { if (r1 != null) { result = "(" + r1.getElement(type) + ")"; } } result = result + "^"; if (r2.isit == 'b' || r2.isit == 'i' || r2.isit == 'c' || r2.isit == 'n' || r2.isit == 't' || (r2.isit == 'a' && (r2.op.equals("/") || r2.op .equals("^")))) { if (r2 != null) { result = result + "(" + r2.getElement(type) + ")"; } } else { if (r2 != null) { result = result + "(" + r2.getElement(type) + ")"; } } } } // relational ops: geq, leq, gt, lt // mod else { if (!sbmlFlag) { if (r1 != null) { if (r1.isit == 'b' || r1.isit == 'i' || r1.isit == 'c' || r1.isit == 'n' || r1.isit == 't') { result = r1.getElement(type); } else { result = "(" + r1.getElement(type) + ")"; } } result = result + op; if (r2 != null) { if (r2.isit == 'b' || r2.isit == 'i' || r2.isit == 'c' || r2.isit == 'n' || r2.isit == 't') { result = result + r2.getElement(type); } else { result = result + "(" + r2.getElement(type) + ")"; } } } if (sbmlFlag) { if (op.equals("<=")) { if (r1 != null && r2 != null) { result = "leq(" + r1.getElement(type) + "," + r2.getElement(type) + ")"; } } if (op.equals(">=")) { if (r1 != null && r2 != null) { result = "geq(" + r1.getElement(type) + "," + r2.getElement(type) + ")"; } } if (op.equals(">")) { if (r1 != null && r2 != null) { result = "gt(" + r1.getElement(type) + "," + r2.getElement(type) + ")"; } } if (op.equals("<")) { if (r1 != null && r2 != null) { result = "lt(" + r1.getElement(type) + "," + r2.getElement(type) + ")"; } } if (op.equals("%")) { if (r1 != null && r2 != null) { result = "mod(" + r1.getElement(type) + "," + r2.getElement(type) + ")"; } } } } } } return result; } public ExprTree minimizeUniforms() { if (r1 != null) { r1.minimizeUniforms(); } if (r2 != null) { r2.minimizeUniforms(); } if (isit == 'a' && op.equals("m")) { if (r1.isit == 'n' && r2.isit == 'n') { isit = 'n'; if (r1.lvalue < r2.lvalue) { lvalue = r1.lvalue; } else { lvalue = r2.lvalue; } r1 = null; r2 = null; } else if (r1.isit == 'a' && r1.op.equals("uniform") && r2.isit == 'a' && r2.op.equals("uniform")) { ExprTree l1 = r1.r1; ExprTree l2 = r2.r1; ExprTree u1 = r1.r2; ExprTree u2 = r2.r2; op = "uniform"; r1.op = "m"; r2.op = "m"; r1.r1 = l1; r1.r2 = l2; r2.r1 = u1; r2.r2 = u2; } } if (isit == 'a' && op.equals("M")) { if (r1.isit == 'n' && r2.isit == 'n') { isit = 'n'; if (r1.lvalue < r2.lvalue) { lvalue = r2.lvalue; } else { lvalue = r1.lvalue; } r1 = null; r2 = null; } else if (r1.isit == 'a' && r1.op.equals("uniform") && r2.isit == 'a' && r2.op.equals("uniform")) { ExprTree l1 = r1.r1; ExprTree l2 = r2.r1; ExprTree u1 = r1.r2; ExprTree u2 = r2.r2; op = "uniform"; r1.op = "M"; r2.op = "M"; r1.r1 = l1; r1.r2 = l2; r2.r1 = u1; r2.r2 = u2; } } if (isit == 'a' && op.equals("+")) { if (r1.isit == 'a' && r1.op.equals("uniform") && r2.isit == 'a' && r2.op.equals("uniform")) { ExprTree l1 = r1.r1; ExprTree l2 = r2.r1; ExprTree u1 = r1.r2; ExprTree u2 = r2.r2; op = "uniform"; r1.op = "+"; r2.op = "+"; r1.r1 = l1; r1.r2 = l2; r2.r1 = u1; r2.r2 = u2; } } if (isit == 'a' && op.equals("-")) { if (r1.isit == 'a' && r1.op.equals("uniform") && r2.isit == 'a' && r2.op.equals("uniform")) { ExprTree l1 = r1.r1; ExprTree l2 = r2.r1; ExprTree u1 = r1.r2; ExprTree u2 = r2.r2; op = "uniform"; r1.op = "+"; r2.op = "+"; r1.r1 = l1; r1.r2 = u2; r2.r1 = u1; r2.r2 = l2; } } if (isit == 'a' && op.equals("c")) { if (r1.isit == 'a' && r1.op.equals("uniform")) { ExprTree l1 = r1.r1; ExprTree u1 = r1.r2; op = "uniform"; r1 = new ExprTree(l1, null, "c", 'a'); r2 = new ExprTree(u1, null, "c", 'a'); } } if (isit == 'a' && op.equals("f")) { if (r1.isit == 'a' && r1.op.equals("uniform")) { ExprTree l1 = r1.r1; ExprTree u1 = r1.r2; op = "uniform"; r1 = new ExprTree(l1, null, "f", 'a'); r2 = new ExprTree(u1, null, "f", 'a'); } } if (isit == 'a' && op.equals("uniform")) { if (r1.isit == 'a' && r1.op.equals("uniform")) { r1 = r1.r1; } if (r2.isit == 'a' && r2.op.equals("uniform")) { r2 = r2.r2; } } return this; } public boolean isEqual(ExprTree expr) { if (isit == expr.isit) { boolean same = false; switch (isit) { case 'b': // Boolean case 'i': // Integer case 'c': // Continuous if (variable.equals(expr.variable)) { same = true; } break; case 'n': // Number case 't': // Truth value if (uvalue == expr.uvalue && lvalue == expr.lvalue) { same = true; } break; case 'w': // bitWise case 'a': // Arithmetic case 'r': // Relational case 'l': // Logical if (op.equals(expr.op)) { same = true; } } if (same) { boolean r1Same = false, r2Same = false; if (r1 == null) { if (expr.r1 == null) { r1Same = true; } } else if (r1.isEqual(expr.r1)) { r1Same = true; } if (r2 == null) { if (expr.r2 == null) { r2Same = true; } } else if (r2.isEqual(expr.r2)) { r2Same = true; } if (r1Same && r2Same) { return true; } } } return false; } private boolean isEqual(ExprTree expr, HashMap<String, String> variables) { if (isit == expr.isit) { boolean same = false; switch (isit) { case 'b': // Boolean case 'i': // Integer case 'c': // Continuous if (variables.containsKey(variable)) { if (variables.containsKey(expr.variable)) { if (variables.get(variable).equals( variables.get(expr.variable))) same = true; } } else if (variable.equals(expr.variable)) { same = true; } break; case 'n': // Number case 't': // Truth value if (uvalue == expr.uvalue && lvalue == expr.lvalue) { same = true; } else if (variables.containsKey(expr.variable)) { if (uvalue == lvalue) { if (uvalue == 1.0 && variables.get(expr.variable).toLowerCase() .equals("true")) same = true; else if (uvalue == 0.0 && variables.get(expr.variable).toLowerCase() .equals("false")) same = true; } } break; case 'w': // bitWise case 'a': // Arithmetic case 'r': // Relational case 'l': // Logical if (op.equals(expr.op)) { same = true; } } if (same) { boolean r1Same = false, r2Same = false; if (r1 == null) { if (expr.r1 == null) { r1Same = true; } } else if (r1.isEqual(expr.r1)) { r1Same = true; } if (r2 == null) { if (expr.r2 == null) { r2Same = true; } } else if (r2.isEqual(expr.r2)) { r2Same = true; } if (r1Same && r2Same) { return true; } } } return false; } private void setVarValues(char willbe, double lNV, double uNV, String var) { op = ""; r1 = null; r2 = null; isit = willbe; if ((isit == 'b') || (isit == 't')) logical = true; else logical = false; uvalue = uNV; lvalue = lNV; variable = var; real = 0; } public void setNodeValues(ExprTree nr1, ExprTree nr2, String nop, char willbe) { ExprTree r1temp = null, r2temp = null; if (nr1 != null) { r1temp = new ExprTree(nr1); } if (nr2 != null) { r2temp = new ExprTree(nr2); } r1 = r1temp; r2 = r2temp; op = nop; isit = willbe; if ((isit == 'r') || (isit == 'l')) { logical = true; uvalue = 1; lvalue = 0; } else { logical = false; uvalue = INFIN; lvalue = -INFIN; } variable = null; // simplify if operands are static if (isit == 'a' || isit == 'r' || isit == 'l' || isit == 'w') { if (op.equals("&&")) { if ((r1.isit == 'n') || (r1.isit == 't')) { if (r1.lvalue == 0) { setVarValues('t', 0.0, 0.0, null); } else { if (r2.isit == 'l' || r2.isit == 'a' || r2.isit == 'w' || r2.isit == 'r') { setNodeValues(r2.r1, r2.r2, r2.op, r2.isit); } else { setVarValues(r2.isit, r2.lvalue, r2.uvalue, r2.variable); } } } else if (((r2).isit == 'n') || ((r2).isit == 't')) { if (r2.lvalue == 0) { setVarValues('t', 0.0, 0.0, null); } else { if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w' || r1.isit == 'r') { setNodeValues(r1.r1, r1.r2, r1.op, r1.isit); } else { setVarValues(r1.isit, r1.lvalue, r1.uvalue, r1.variable); } } } else if (r1.equals(r2)) { if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w' || r1.isit == 'r') { setNodeValues(r1.r1, r1.r2, r1.op, r1.isit); } else { setVarValues(r1.isit, r1.lvalue, r1.uvalue, r1.variable); } } else { ExprTree notE = new ExprTree(this); notE.setNodeValues((this), null, "!", 'l'); if (r1.equals(notE) || notE.equals(r1)) { setVarValues('t', 0.0, 0.0, null); } } } else if (op.equals("||")) { if ((r1.isit == 'n') || (r1.isit == 't')) { if (r1.lvalue != 0) { setVarValues('t', 1.0, 1.0, null); } else { if (r2.isit == 'l' || r2.isit == 'a' || r2.isit == 'w' || r2.isit == 'r') { setNodeValues(r2.r1, r2.r2, r2.op, r2.isit); } else { setVarValues(r2.isit, r2.lvalue, r2.uvalue, r2.variable); } } } else if (((r2).isit == 'n') || ((r2).isit == 't')) { if (r2.lvalue != 0) { setVarValues('t', 1.0, 1.0, null); } else { if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w' || r1.isit == 'r') { setNodeValues(r1.r1, r1.r2, r1.op, r1.isit); } else { setVarValues(r1.isit, r1.lvalue, r1.uvalue, r1.variable); } } } else if (r1.equals(r2)) { if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w' || r1.isit == 'r') { setNodeValues(r1.r1, r1.r2, r1.op, r1.isit); } else { setVarValues(r1.isit, r1.lvalue, r1.uvalue, r1.variable); } } else { ExprTree notE = new ExprTree(this); notE.setNodeValues((this), null, "!", 'l'); if (r1.equals(notE) || notE.equals(r1)) { setVarValues('t', 1.0, 1.0, null); } } } else if (op.equals("->")) { if (r1.isit == 'n' || r1.isit == 't') { if (r1.lvalue != 0) { if (r2.isit == 'l' || r2.isit == 'a' || r2.isit == 'w' || r2.isit == 'r') { setNodeValues(r2.r1, r2.r2, r2.op, r2.isit); } else { setVarValues(r2.isit, r2.lvalue, r2.uvalue, r2.variable); } } else if (r1.uvalue == 0) { setVarValues('t', 1.0, 1.0, null); } } else if (r2.isit == 't' || r2.isit == 'n') { if (r2.lvalue != 0) { setVarValues('t', 1.0, 1.0, null); } else if (r2.uvalue == 0) { ExprTree notE = new ExprTree(r2); notE.setNodeValues((this), null, "!", 'l'); setNodeValues(notE.r1, notE.r2, notE.op, notE.isit); } } } else if (op.equals("!")) { if (((r1).isit == 'n') || ((r1).isit == 't')) { (this).isit = 't'; if (r1.lvalue == 1) { this.lvalue = 0; } else { this.lvalue = 1; } (this).uvalue = (this).lvalue; } } else if (op.equals("==")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 't'; if (r1.lvalue == r2.lvalue) { this.lvalue = 1; } else { this.lvalue = 0; } (this).uvalue = (this).lvalue; } } else if (op.equals(">=")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 't'; if ((r1).lvalue >= r2.lvalue) { this.lvalue = 1; } else { this.lvalue = 0; } (this).uvalue = (this).lvalue; } } else if (op.equals(">")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 't'; if ((r1).lvalue > r2.lvalue) { this.lvalue = 1; } else { this.lvalue = 0; } (this).uvalue = (this).lvalue; } } else if (op.equals("<=")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 't'; if ((r1).lvalue <= r2.lvalue) { this.lvalue = 1; } else { this.lvalue = 0; } (this).uvalue = (this).lvalue; } } else if (op.equals("<")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 't'; if ((r1).lvalue < r2.lvalue) { this.lvalue = 1; } else { this.lvalue = 0; } (this).uvalue = (this).lvalue; } } else if (op.equals("&")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 'n'; (this).lvalue = ((int) (r1).lvalue) & ((int) r2.lvalue); (this).uvalue = (this).lvalue; } } else if (op.equals("|")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 'n'; (this).lvalue = (int) (r1).lvalue | (int) r2.lvalue; (this).uvalue = (this).lvalue; } } else if (isit == 'w' && op.equals("X")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 'n'; (this).lvalue = (int) (r1).lvalue ^ (int) r2.lvalue; (this).uvalue = (this).lvalue; } } else if (op.equals("m")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 'n'; (this).lvalue = Math.min((r1).lvalue, r2.lvalue); (this).uvalue = (this).lvalue; } } else if (op.equals("M")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 'n'; (this).lvalue = Math.max((r1).lvalue, r2.lvalue); (this).uvalue = (this).lvalue; } } else if (op.equals("i")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 'n'; (this).lvalue = Math.floor((r1).lvalue / r2.lvalue); (this).uvalue = (this).lvalue; } } else if (op.equals("f")) { if (((r1).isit == 'n') || ((r1).isit == 't')) { (this).isit = 'n'; (this).lvalue = Math.floor((r1).lvalue); (this).uvalue = (this).lvalue; } } else if (op.equals("c")) { if (((r1).isit == 'n') || ((r1).isit == 't')) { (this).isit = 'n'; (this).lvalue = Math.ceil((r1).lvalue); (this).uvalue = (this).lvalue; } } else if (op.equals("~")) { if (((r1).isit == 'n') || ((r1).isit == 't')) { (this).isit = 'n'; (this).lvalue = ~(int) (r1).lvalue; (this).uvalue = (this).lvalue; } } else if (op.equals("[]")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 't'; (this).lvalue = (((int) (r1).lvalue) >> ((int) r2.lvalue)) & 1; (this).uvalue = (this).lvalue; } } else if (op.equals("U-")) { if (((r1).isit == 'n') || ((r1).isit == 't')) { (this).isit = 'n'; (this).lvalue = -((r1).lvalue); (this).uvalue = (this).lvalue; } } else if (op.equals("*")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 'n'; (this).lvalue = (r1).lvalue * r2.lvalue; (this).uvalue = (this).lvalue; } else if (r1.isit == 'n' || r1.isit == 't') { if (r1.lvalue == 0 && r1.uvalue == 0) { setVarValues('t', 0.0, 0.0, null); } else if (r1.lvalue == 1 && r1.uvalue == 1) { if (r2.isit == 'l' || r2.isit == 'a' || r2.isit == 'w' || r2.isit == 'r') { setNodeValues(r2.r1, r2.r2, r2.op, r2.isit); } else { setVarValues(r2.isit, r2.lvalue, r2.uvalue, r2.variable); } } } else if (r2.isit == 'n' || r2.isit == 't') { if (r2.lvalue == 0 && r2.uvalue == 0) { setVarValues('t', 0.0, 0.0, null); } else if (r2.lvalue == 1 && r2.uvalue == 1) { if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w' || r1.isit == 'r') { setNodeValues(r1.r1, r1.r2, r1.op, r1.isit); } else { setVarValues(r1.isit, r1.lvalue, r1.uvalue, r1.variable); } } } } else if (op.equals("/")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 'n'; (this).lvalue = (r1).lvalue / r2.lvalue; (this).uvalue = (this).lvalue; } else if ((r1.isit == 'n' || r1.isit == 't') && r1.uvalue == 0 && r1.lvalue == 0) { setVarValues('n', 0.0, 0.0, null); } else if ((r2.isit == 'n' || r2.isit == 't') && r2.lvalue == 1 && r2.uvalue == 1) { if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w' || r1.isit == 'r') { setNodeValues(r1.r1, r1.r2, r1.op, r1.isit); } else { setVarValues(r1.isit, r1.lvalue, r1.uvalue, r1.variable); } } } else if (op.equals("%")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 'n'; (this).lvalue = (r1).lvalue % r2.lvalue; (this).uvalue = (this).lvalue; } else if ((r2.isit == 'n' || r2.isit == 't') && r2.lvalue == 1.0 && r2.uvalue == 1.0) { setVarValues('n', 0.0, 0.0, null); } else if ((r1.isit == 'n' || r1.isit == 't') && r1.lvalue == 1.0 && r1.uvalue == 1.0) { setVarValues('n', 1.0, 1.0, null); } } else if (op.equals("+")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 'n'; (this).lvalue = (r1).lvalue + r2.lvalue; (this).uvalue = (this).lvalue; } else if ((r1.isit == 'n' || r1.isit == 't') && r1.lvalue == 0 && r1.uvalue == 0) { if (r2.isit == 'l' || r2.isit == 'a' || r2.isit == 'w' || r2.isit == 'r') { setNodeValues(r2.r1, r2.r2, r2.op, r2.isit); } else { setVarValues(r2.isit, r2.lvalue, r2.uvalue, r2.variable); } } else if ((r2.isit == 'n' || r2.isit == 't') && r2.lvalue == 0 && r2.uvalue == 0) { if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w' || r1.isit == 'r') { setNodeValues(r1.r1, r1.r2, r1.op, r1.isit); } else { setVarValues(r1.isit, r1.lvalue, r1.uvalue, r1.variable); } } } else if (op.equals("-")) { if (((r1.isit == 'n') || (r1.isit == 't')) && (((r2).isit == 'n') || ((r2).isit == 't'))) { (this).isit = 'n'; (this).lvalue = (r1).lvalue - r2.lvalue; (this).uvalue = (this).lvalue; } else if ((r1.isit == 'n' || r1.isit == 't') && r1.lvalue == 0 && r1.uvalue == 0) { setNodeValues(r2, null, "U-", 'a'); } else if ((r2.isit == 'n' || r2.isit == 't') && r2.lvalue == 0 && r2.uvalue == 0) { if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w' || r1.isit == 'r') { setNodeValues(r1.r1, r1.r2, r1.op, r1.isit); } else { setVarValues(r1.isit, r1.lvalue, r1.uvalue, r1.variable); } } } } } public double evaluateExpr(HashMap<String, String> variables) { double left; double right; switch (isit) { case 'b': // Boolean if (variables != null) { if (!variables.containsKey(variable) || variables.get(variable).toLowerCase().equals( "unknown")) return Double.NaN; if (variables.get(variable).toLowerCase().equals("true") || variables.get(variable).equals("1")) { return 1.0; } else { return 0.0; } } else { return Double.NaN; } case 'c': // Continuous return Double.NaN; case 'i': // Integer if (variables != null) { try { return Double.parseDouble(variables.get(variable)); } catch (Exception e) { return Double.NaN; } } else { return Double.NaN; } case 'n': // Number if (uvalue == lvalue) { return uvalue; } else { return ((uvalue - lvalue) * new java.util.Random().nextDouble()) + lvalue; } case 't': // Truth value if (uvalue == 1 && lvalue == 1) { return 1.0; } else if (uvalue == 0 && lvalue == 0) { return 0.0; } else { return Double.NaN; } case 'w': // bitWise if (r1 != null) { left = r1.evaluateExpr(variables); } else { left = Double.NaN; } if (r2 != null) { right = r2.evaluateExpr(variables); } else { right = Double.NaN; } if (op.equals("&")) { return ((int) left) & ((int) right); } else if (op.equals("|")) { return ((int) left) | ((int) right); } else if (op.equals("!")) { return ~((int) left); } else if (op.equals("X")) { return ((int) left) ^ ((int) right); } case 'a': // Arithmetic case 'r': // Relational case 'l': // Logical if (op.equals("!")) { if (r1 != null) { if (r1.evaluateExpr(variables) == 1.0) { return 0.0; } else if (r1.evaluateExpr(variables) == 0.0) { return 1.0; } else { return Double.NaN; } } else if (r2 != null) { if (r2.evaluateExpr(variables) == 1.0) { return 0.0; } else if (r2.evaluateExpr(variables) == 0.0) { return 1.0; } else { return Double.NaN; } } else { return Double.NaN; } } else { if (r1 != null) { left = r1.evaluateExpr(variables); } else { left = Double.NaN; } if (r2 != null) { right = r2.evaluateExpr(variables); } else { right = Double.NaN; } if (op.equals("&&")) { if (left == 1.0 && right == 1.0) { return 1.0; } else if (left == 0.0 || right == 0.0) { return 0.0; } else return Double.NaN; } else if (op.equals("||")) { if (left == 1.0 || right == 1.0) { return 1.0; } else if (left == 0.0 && right == 0.0) { return 0.0; } else return Double.NaN; } else if (op.equals("==")) { if (left == Double.NaN || right == Double.NaN) { return Double.NaN; } else if (left == right) { return 1.0; } else if (left != right) { return 0.0; } else { return Double.NaN; } } else if (op.equals("->")) { if (left == 0.0 && (right == 1.0 || right == 0.0)) { return 1.0; } else if (left == 1.0 && right == 1.0) { return 1.0; } else if (left == 1.0 && right == 0.0) { return 0.0; } else { return Double.NaN; } } else if (op.equals("+")) { return left + right; } else if (op.equals("*")) { return left * right; } else if (op.equals("/")) { return left / right; } else if (op.equals("%")) { return left % right; } else if (op.equals("^")) { return Math.pow(left, right); } else if (op.equals("[]")) { return (((int) left) >> ((int) right)) & 1; } else if (op.equals("f")) { return Math.floor(left); } else if (op.equals("c")) { return Math.ceil(left); } else if (op.equals("m")) { return Math.min(left, right); } else if (op.equals("M")) { return Math.max(left, right); } else if (op.equals("i")) { return ((int) left) / ((int) right); } else if (op.equals("uniform")) { return Double.NaN; } else if (op.equals("normal")) { return Double.NaN; } else if (op.equals("gamma")) { return Double.NaN; } else if (op.equals("lognormal")) { return Double.NaN; } else if (op.equals("binomial")) { return Double.NaN; } else if (op.equals("exponential")) { return Double.NaN; } else if (op.equals("chisq")) { return Double.NaN; } else if (op.equals("laplace")) { return Double.NaN; } else if (op.equals("cauchy")) { return Double.NaN; } else if (op.equals("rayleigh")) { return Double.NaN; } else if (op.equals("poisson")) { return Double.NaN; } else if (op.equals("bernoulli")) { return Double.NaN; } else if (op.equals("rate")) { return Double.NaN; } else if (op.equals("INT")) { return ((int) left); } else if (op.equals("<")) { if (left < right) { return 1.0; } else if (left >= right) { return 0.0; } else { return Double.NaN; } } else if (op.equals(">")) { if (left > right) { return 1.0; } else if (left <= right) { return 0.0; } else { return Double.NaN; } } else if (op.equals("<=")) { if (left <= right) { return 1.0; } else if (left > right) { return 0.0; } else { return Double.NaN; } } else if (op.equals(">=")) { if (left >= right) { return 1.0; } else if (left < right) { return 0.0; } else { return Double.NaN; } } else { return Double.NaN; } } } return Double.NaN; } private static final int WORD = 1; private static final int IMPLIES = 7; private static final int END_OF_STRING = 2; private static final int INFIN = 2147483647; public String getOp() { return op; } public ExprTree getLeftChild() { return r1; } public ExprTree getRightChild() { return r2; } public ExprTree getExprTree() { token = this.intexpr_gettok(expression); this.intexpr_L(expression); return this; } public void setIntegerSignals(Set<String> signalSet) { for (String s : signalSet) { integerSignals.add(s); } } }
package group5.trackerexpress; import java.io.File; import java.util.UUID; import android.app.Activity; import android.content.Intent; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Spinner; public class EditExpenseActivity extends Activity { private Spinner category, currency; private ImageButton imgButton; private Button createExpenseButton; private CheckBox flagCheckBox; private EditText description, amount; private Uri receiptUri; final Intent intent = this.getIntent(); UUID serialisedId = (UUID) intent.getSerializableExtra("claimUUID"); final Claim claim = ClaimController.getInstance(EditExpenseActivity.this).getClaimList().getClaim(serialisedId); @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_expense); OnClickListener picListener = new OnClickListener() { public void onClick(View v) { takeAPhoto(); } }; imgButton.setOnClickListener(picListener); } private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100; public void takeAPhoto() { // TODO: Create an intent with the action // MediaStore.ACTION_IMAGE_CAPTURE // ComponentName cn = new ComponentName("es.softwareprocess.bogopicgen", // "es.softwareprocess.bogopicgen.BogoPicGenActivity"); // ComponentName cn = new ComponentName("com.android.camera", // "com.android.camera.Camera"); // intent.setComponent(cn); // Create a folder to store pictures String folder = Environment.getExternalStorageDirectory().getAbsolutePath() + "/tmp"; File folderF = new File(folder); if (!folderF.exists()) { folderF.mkdir(); ImageButton button = (ImageButton) findViewById(R.id.TakeAPhoto); Drawable photo = Drawable.createFromPath(receiptUri.getPath()); button.setImageDrawable(photo); } // Create an URI for the picture file String imageFilePath = folder + "/" + String.valueOf(System.currentTimeMillis()) + ".jpg"; File imageFile = new File(imageFilePath); receiptUri = Uri.fromFile(imageFile); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, receiptUri); startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE); // TODO: Put in the intent in the tag MediaStore.EXTRA_OUTPUT the URI // TODO: Start the activity (expecting a result), with the code // CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE } private void initializeVars() { // TODO Auto-generated method stub description = (EditText) findViewById(R.id.editDescription); amount = (EditText) findViewById(R.id.editAmount); imgButton = (ImageButton) findViewById(R.id.TakeAPhoto); category = (Spinner) findViewById(R.id.categorySpinner); ArrayAdapter<CharSequence> categoryAdapter = ArrayAdapter.createFromResource (this, R.array.category_array, android.R.layout.simple_spinner_item); //create array adapter using string array and default spinner layout categoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); //specify layout to use when list of choices appears category.setAdapter(categoryAdapter); currency = (Spinner) findViewById(R.id.currencySpinner); ArrayAdapter<CharSequence> currencyAdapter = ArrayAdapter.createFromResource (this, R.array.currency_array, android.R.layout.simple_spinner_item); //create array adapter using string array and default spinner layout currencyAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); //specify layout to use when list of choices appears category.setAdapter(currencyAdapter); createExpenseButton = (Button) findViewById(R.id.createExpenseButton); flagCheckBox = (CheckBox) findViewById(R.id.incompleteCheckBox); } public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // An item was selected. You can retrieve the selected item using // parent.getItemAtPosition(pos) parent.getItemAtPosition(position); } public void onNothingSelected(AdapterView<?> parent) { // Another interface callback } }
package com.mycompany.codekata.kata02; public class Day2 { /** * Binary search for value in array. Recursive version. * * @param val value to search for * @param arr array to search in * @return position of val in arr or -1 if not found */ public static int chop(int val, int[] arr, int start, int length) { int cut; if (arr.length == 0) { return -1; } if (length == 1) { return arr[start] == val ? start : -1; } cut = length / 2; if (arr[start + cut] <= val) { // right return chop(val, arr, start + cut, length - cut); } else { // left return chop(val, arr, start, cut); } } public static int chop(int val, int[] arr) { return chop(val, arr, 0, arr.length); } }
package com.github.phantomthief.util; import java.util.concurrent.Callable; import com.google.common.base.Throwables; /** * @author w.vela */ public class MoreFunctions { public interface FunctionWithThrowable<T, R, X extends Throwable> { R apply(T t) throws X; } public static final <R> R catching(Callable<R> callable) { return catching(callable, (Class<Throwable>) null); } @SafeVarargs public static final <R> R catching(Callable<R> callable, Class<? extends Throwable>... catchThrowables) { try { return callable.call(); } catch (Throwable e) { if (catchThrowables != null) { for (Class<? extends Throwable> throwable : catchThrowables) { if (throwable != null) { if (throwable.isInstance(e)) { continue; } else { throw Throwables.propagate(e); } } } } return null; } } public static final <T, R> R catching(FunctionWithThrowable<T, R, Throwable> function, T t) { return catching(function, t, (Class<Throwable>) null); } @SafeVarargs public static final <T, R> R catching(FunctionWithThrowable<T, R, Throwable> function, T t, Class<? extends Throwable>... catchThrowables) { try { return function.apply(t); } catch (Throwable e) { if (catchThrowables != null) { for (Class<? extends Throwable> throwable : catchThrowables) { if (throwable != null) { if (throwable.isInstance(e)) { continue; } else { throw Throwables.propagate(e); } } } } return null; } } }
package com.github.davidmoten.util; import java.io.File; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.HashMap; import java.util.Map; import rx.Observable; public final class DelegatorGenerator { public static void generate(Map<Class<?>, String> map, File directory) { for (Class<?> cls : map.keySet()) { String className = cls.getCanonicalName(); String newClassName = map.get(cls); for (Method method : cls.getDeclaredMethods()) { System.out.println(method.toGenericString()); String mods = Modifier.toString(method.getModifiers()); String g = method.getGenericReturnType().toString(); for (Class<?> c : map.keySet()) { g = g.replaceAll("\\b" + c.getCanonicalName() + "\\b", map.get(c)); } String typeParams = typeParameters(method); System.out.format("%s %s %s %s(\n", mods, typeParams, g, method.getName()); } } } String sharedToGenericString(Method m, int modifierMask, boolean isDefault) { try { StringBuilder sb = new StringBuilder(); printModifiersIfNonzero(m, sb, modifierMask, isDefault); TypeVariable<?>[] typeparms = m.getTypeParameters(); if (typeparms.length > 0) { boolean first = true; sb.append('<'); for (TypeVariable<?> typeparm : typeparms) { if (!first) sb.append(','); // Class objects can't occur here; no need to test // and call Class.getName(). sb.append(typeparm.toString()); first = false; } sb.append("> "); } specificToGenericStringHeader(m, sb); sb.append('('); Type[] params = m.getGenericParameterTypes(); for (int j = 0; j < params.length; j++) { String param = params[j].getTypeName(); if (m.isVarArgs() && (j == params.length - 1)) // replace T[] // with param = param.replaceFirst("\\[\\]$", "..."); sb.append(param); if (j < (params.length - 1)) sb.append(','); } sb.append(')'); Type[] exceptions = m.getGenericExceptionTypes(); if (exceptions.length > 0) { sb.append(" throws "); for (int k = 0; k < exceptions.length; k++) { sb.append((exceptions[k] instanceof Class) ? ((Class) exceptions[k]).getName() : exceptions[k].toString()); if (k < (exceptions.length - 1)) sb.append(','); } } return sb.toString(); } catch (Exception e) { return "<" + e + ">"; } } void specificToGenericStringHeader(Method m, StringBuilder sb) { Type genRetType = m.getGenericReturnType(); sb.append(genRetType.getTypeName()).append(' '); sb.append(m.getDeclaringClass().getTypeName()).append('.'); sb.append(m.getName()); } void printModifiersIfNonzero(Method m, StringBuilder sb, int mask, boolean isDefault) { int mod = m.getModifiers() & mask; if (mod != 0 && !isDefault) { sb.append(Modifier.toString(mod)).append(' '); } else { int access_mod = mod & (Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE); if (access_mod != 0) sb.append(Modifier.toString(access_mod)).append(' '); if (isDefault) sb.append("default "); mod = (mod & ~(Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE)); if (mod != 0) sb.append(Modifier.toString(mod)).append(' '); } } private static String typeParameters(Method method) { String typeParams; StringBuilder sb = new StringBuilder(); TypeVariable<?>[] typeparms = method.getTypeParameters(); if (typeparms.length > 0) { boolean first = true; sb.append('<'); for (TypeVariable<?> typeparm : typeparms) { if (!first) sb.append(','); // Class objects can't occur here; no need to test // and call Class.getName(). sb.append(typeparm.toString()); first = false; } sb.append("> "); } typeParams = sb.toString(); return typeParams; } public static void main(String[] args) { Map<Class<?>, String> map = new HashMap<Class<?>, String>(); map.put(Observable.class, "rx.Ob"); generate(map, new File("target")); } }
// Triple Play - utilities for use in PlayN-based games package tripleplay.platform; import java.awt.Dimension; import java.awt.Canvas; import javax.swing.JFrame; import org.lwjgl.opengl.Display; import playn.core.PlayN; import playn.java.JavaPlatform; /** * Implements Java-specific TriplePlay services. */ public class JavaTPPlatform extends TPPlatform { /** Registers the IOS TriplePlay platform. */ public static JavaTPPlatform register (JavaPlatform platform, JavaPlatform.Config config) { JavaTPPlatform instance = new JavaTPPlatform(platform, config); TPPlatform.register(instance); return instance; } protected JavaTPPlatform (JavaPlatform platform, JavaPlatform.Config config) { _platform = platform; _frame = new JFrame("Game"); _frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Canvas canvas = new Canvas(); canvas.setPreferredSize(new Dimension(config.width, config.height)); _frame.getContentPane().add(canvas); _frame.pack(); _frame.setResizable(false); _frame.setVisible(true); try { Display.setParent(canvas); } catch (Exception e) { e.printStackTrace(); } } @Override public boolean hasNativeTextFields () { return true; } @Override public NativeTextField createNativeTextField () { return new JavaNativeTextField(_frame.getLayeredPane()); } /** The Java platform with which this TPPlatform was registered. */ protected JavaPlatform _platform; protected JFrame _frame; }
package io.spine.reflect; import com.google.common.reflect.TypeToken; import javax.annotation.CheckReturnValue; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import static com.google.common.base.Preconditions.checkNotNull; /** * Base interface for enumerations on generic parameters of types. * * <p>Example of implementing an enumeration for generic parameters: * <pre> {@code * public abstract class Tuple<K, V> { * ... * public enum GenericParameter extends GenericTypeIndex<Tuple> { * * // <K> param has index 0 * KEY(0), * * // <V> param has index 1 * VALUE(1); * * private final int index; * * GenericParameter(int index) { this.index = index; } * * {@literal @}Override * public int getIndex() { return index; } * * {@literal @}Override * public Class<?> getArgumentIn(Class<? extends Tuple> derivedClass) { * return Default.getArgument(this, derivedClass); * } * } * } * }</pre> * @param <C> the type in which class the generic index is declared * @author Alexander Yevsyukov */ public interface GenericTypeIndex<C> { /** * Obtains a zero-based index of a generic parameter of a type. */ int getIndex(); /** * Obtains the class of the generic type argument. * * @param cls the class to inspect * @return the argument class */ Class<?> getArgumentIn(Class<? extends C> cls); /** * Allows to obtain argument value of the {@code <C>} generic parameter for * {@code GenericTypeIndex} implementations. */ class Default { // Replace this class with the default interface method when migrating to Java 8. private Default() { // Prevent instantiation of this utility class. } /** * Obtains a generic argument of the passed class. * * @param index the index of the generic argument * @param cls the class in which inheritance chain the argument is specified * @param <C> the type of the class * @return the value of the generic argument */ public static <C> Class<?> getArgument(GenericTypeIndex<C> index, Class<? extends C> cls) { checkNotNull(index); checkNotNull(cls); @SuppressWarnings("unchecked") /* The type is ensured by the declaration of the GenericTypeIndex interface. */ final Class<C> superclass = (Class<C>) getArgument(index.getClass(), GenericTypeIndex.class, 0); final Class<?> result = getArgument(cls, superclass, index.getIndex()); return result; } /** * Obtains the class of a generic type argument which is specified in the inheritance chain * of the passed class. * * @param cls the end class for which we find the generic argument * @param genericSuperclass the superclass of the passed which has generic parameters * @param argNumber the index of the generic parameter in the superclass * @param <T> the type of superclass * @return the class of the generic type argument */ @CheckReturnValue static <T> Class<?> getArgument(Class<? extends T> cls, Class<T> genericSuperclass, int argNumber) { checkNotNull(cls); checkNotNull(genericSuperclass); final TypeToken<?> supertypeToken = TypeToken.of(cls) .getSupertype(genericSuperclass); final ParameterizedType genericSupertype = (ParameterizedType) supertypeToken.getType(); final Type[] typeArguments = genericSupertype.getActualTypeArguments(); final Type typeArgument = typeArguments[argNumber]; @SuppressWarnings("unchecked") // The type is ensured by the calling code. final Class<?> result = (Class<?>) typeArgument; return result; } } }
// Triple Play - utilities for use in PlayN-based games package tripleplay.platform; import java.awt.Dimension; import java.awt.Canvas; import javax.swing.JFrame; import org.lwjgl.opengl.Display; import playn.core.PlayN; import playn.java.JavaPlatform; /** * Implements Java-specific TriplePlay services. */ public class JavaTPPlatform extends TPPlatform { /** Registers the IOS TriplePlay platform. */ public static JavaTPPlatform register (JavaPlatform platform, JavaPlatform.Config config) { JavaTPPlatform instance = new JavaTPPlatform(platform, config); TPPlatform.register(instance); return instance; } protected JavaTPPlatform (JavaPlatform platform, JavaPlatform.Config config) { _platform = platform; _frame = new JFrame("Game"); Canvas canvas = new Canvas(); canvas.setPreferredSize(new Dimension(config.width, config.height)); _frame.getContentPane().add(canvas); _frame.pack(); _frame.setResizable(false); _frame.setVisible(true); try { Display.setParent(canvas); } catch (Exception e) { e.printStackTrace(); } } @Override public boolean hasNativeTextFields () { return true; } @Override public NativeTextField createNativeTextField () { return new JavaNativeTextField(_frame.getLayeredPane()); } /** The Java platform with which this TPPlatform was registered. */ protected JavaPlatform _platform; protected JFrame _frame; }
package soot.jimple.toolkits.annotation.logic; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Stack; import soot.Body; import soot.BodyTransformer; import soot.Unit; import soot.jimple.Stmt; import soot.toolkits.graph.ExceptionalUnitGraph; import soot.toolkits.graph.MHGDominatorsFinder; import soot.toolkits.graph.UnitGraph; public class LoopFinder extends BodyTransformer { private UnitGraph g; private HashMap<Stmt, List<Stmt>> loops; public Collection<Loop> loops(){ Collection<Loop> result = new HashSet<Loop>(); for (Map.Entry<Stmt,List<Stmt>> entry : loops.entrySet()) { result.add(new Loop(entry.getKey(),entry.getValue(),g)); } return result; } protected void internalTransform (Body b, String phaseName, Map options){ g = new ExceptionalUnitGraph(b); MHGDominatorsFinder a = new MHGDominatorsFinder(g); loops = new HashMap<Stmt, List<Stmt>>(); Iterator<Unit> stmtsIt = b.getUnits().iterator(); while (stmtsIt.hasNext()){ Stmt s = (Stmt)stmtsIt.next(); List<Unit> succs = g.getSuccsOf(s); Collection<Unit> dominaters = (Collection<Unit>)a.getDominators(s); ArrayList<Stmt> headers = new ArrayList<Stmt>(); Iterator<Unit> succsIt = succs.iterator(); while (succsIt.hasNext()){ Stmt succ = (Stmt)succsIt.next(); if (dominaters.contains(succ)){ //header succeeds and dominates s, we have a loop headers.add(succ); } } Iterator<Stmt> headersIt = headers.iterator(); while (headersIt.hasNext()){ Stmt header = headersIt.next(); List<Stmt> loopBody = getLoopBodyFor(header, s); // for now just print out loops as sets of stmts //System.out.println("FOUND LOOP: Header: "+header+" Body: "+loopBody); if (loops.containsKey(header)){ // merge bodies List<Stmt> lb1 = loops.get(header); loops.put(header, union(lb1, loopBody)); } else { loops.put(header, loopBody); } } } } private List<Stmt> getLoopBodyFor(Stmt header, Stmt node){ ArrayList<Stmt> loopBody = new ArrayList<Stmt>(); Stack<Unit> stack = new Stack<Unit>(); loopBody.add(header); stack.push(node); while (!stack.isEmpty()){ Stmt next = (Stmt)stack.pop(); if (!loopBody.contains(next)){ // add next to loop body loopBody.add(0, next); // put all preds of next on stack Iterator<Unit> it = g.getPredsOf(next).iterator(); while (it.hasNext()){ stack.push(it.next()); } } } assert (node==header && loopBody.size()==1) || loopBody.get(loopBody.size()-2)==node; assert loopBody.get(loopBody.size()-1)==header; return loopBody; } private List<Stmt> union(List<Stmt> l1, List<Stmt> l2){ Iterator<Stmt> it = l2.iterator(); while (it.hasNext()){ Stmt next = it.next(); if (!l1.contains(next)){ l1.add(next); } } return l1; } }
package org.spine3.time; import com.google.protobuf.Duration; import com.google.protobuf.Timestamp; import com.google.protobuf.util.Timestamps; import org.junit.Test; import java.text.ParseException; import java.util.TimeZone; import static org.junit.Assert.assertEquals; import static org.spine3.test.Tests.assertHasPrivateParameterlessCtor; import static org.spine3.time.Durations2.hours; import static org.spine3.time.Durations2.hoursAndMinutes; import static org.spine3.time.Time.MILLIS_PER_SECOND; import static org.spine3.time.Time.getCurrentTime; import static org.spine3.time.ZoneOffsets.MAX_HOURS_OFFSET; import static org.spine3.time.ZoneOffsets.MAX_MINUTES_OFFSET; import static org.spine3.time.ZoneOffsets.MIN_HOURS_OFFSET; import static org.spine3.time.ZoneOffsets.MIN_MINUTES_OFFSET; import static org.spine3.time.ZoneOffsets.getDefault; import static org.spine3.time.ZoneOffsets.ofHours; import static org.spine3.time.ZoneOffsets.ofHoursMinutes; import static org.spine3.time.ZoneOffsets.parse; public class ZoneOffsetsShould { @Test public void has_private_constructor() { assertHasPrivateParameterlessCtor(ZoneOffsets.class); } @Test public void get_current_zone_offset() { final TimeZone timeZone = TimeZone.getDefault(); final ZoneOffset zoneOffset = getDefault(); final Timestamp now = getCurrentTime(); final long date = Timestamps.toMillis(now); final int offsetSeconds = timeZone.getOffset(date) / MILLIS_PER_SECOND; final String zoneId = timeZone.getID(); assertEquals(zoneId, zoneOffset.getId()); assertEquals(offsetSeconds, zoneOffset.getAmountSeconds()); } @Test public void create_instance_by_hours_offset() { final Duration twoHours = hours(2); assertEquals(twoHours.getSeconds(), ofHours(2).getAmountSeconds()); } @Test public void create_instance_by_hours_and_minutes_offset() { assertEquals(hoursAndMinutes(8, 45).getSeconds(), ofHoursMinutes(8, 45).getAmountSeconds()); assertEquals(hoursAndMinutes(-4, -50).getSeconds(), ofHoursMinutes(-4, -50).getAmountSeconds()); } @Test(expected = IllegalArgumentException.class) public void require_same_sign_for_hours_and_minutes_negative_hours() { ofHoursMinutes(-1, 10); } @Test(expected = IllegalArgumentException.class) public void require_same_sign_for_hours_and_minutes_positive_hours() { ofHoursMinutes(1, -10); } @Test(expected = IllegalArgumentException.class) public void do_not_accept_more_than_14_hours() { ofHours(MAX_HOURS_OFFSET + 1); } @Test(expected = IllegalArgumentException.class) public void do_not_accept_more_than_11_hours_by_abs() { ofHours(MIN_HOURS_OFFSET - 1); } @Test(expected = IllegalArgumentException.class) public void do_not_accept_more_than_60_minutes() { ofHoursMinutes(10, MAX_MINUTES_OFFSET + 1); } @Test(expected = IllegalArgumentException.class) public void do_not_accept_more_than_17_hours_and_60_minutes() { ofHoursMinutes(3, MIN_MINUTES_OFFSET - 1); } @Test public void convert_to_string() throws ParseException { final ZoneOffset positive = ofHoursMinutes(5, 48); final ZoneOffset negative = ofHoursMinutes(-3, -36); assertEquals(positive, parse(ZoneOffsets.toString(positive))); assertEquals(negative, parse(ZoneOffsets.toString(negative))); } @Test public void parse_string() throws ParseException { assertEquals(ofHoursMinutes(4, 30), parse("+4:30")); assertEquals(ofHoursMinutes(4, 30), parse("+04:30")); assertEquals(ofHoursMinutes(-2, -45), parse("-2:45")); assertEquals(ofHoursMinutes(-2, -45), parse("-02:45")); } @Test(expected = ParseException.class) public void fail_when_sign_char_missing() throws ParseException { ZoneOffsets.parse("x03:00"); } }
package org.micro.neural.config.store; import com.google.common.util.concurrent.ThreadFactoryBuilder; import lombok.extern.slf4j.Slf4j; import org.micro.neural.Neural; import org.micro.neural.common.Constants; import org.micro.neural.common.URL; import org.micro.neural.common.collection.ConcurrentHashSet; import static org.micro.neural.common.Constants.*; import org.micro.neural.common.utils.SerializeUtils; import org.micro.neural.config.*; import org.micro.neural.config.GlobalConfig.*; import org.micro.neural.extension.ExtensionLoader; import java.util.*; import java.util.concurrent.*; /** * Store Pool * <p> * space=neural * module=limiter/degrade * <p> * 1.GlobalConfig-Hash: [space]:GLOBAL-->[module]-->[json] * 2.NeuralConfig-Hash: [space]:RULE-->[module]:[application]:[group]:[resource]-->[json] * 2.GlobalStatistics-Hash: [space]:STATISTICS-->[module]:[application]:[group]:[resource]-->[json] * <p> * 3.GlobalConfig-Channel: [space]:GLOBAL:CHANNEL:[module]-->[json] * 4.NeuralConfig-Channel: [space]:RULE:CHANNEL:[module]:[application]:[group]:[resource]-->[json] * <p> * identity=[module] * identity=[module]:[application]:[group]:[resource] * * @author lry */ @Slf4j public class StorePool implements IStoreListener { private static final String SPACE_DEFAULT = "neural"; private static final String PULL_CONFIG_CYCLE_KEY = "pullConfigCycle"; private static final String STATISTIC_REPORT_CYCLE_KEY = "statisticReportCycle"; private String space; private long pullConfigCycle; private long statisticReportCycle; private IStore store; private ScheduledExecutorService pullConfigExecutor = null; private ScheduledExecutorService pushStatisticsExecutor = null; private volatile Set<String> channels = new ConcurrentHashSet<>(); /** * Map<[module], Neural> */ private volatile Map<String, Neural> modules = new ConcurrentHashMap<>(); /** * Map<[module], Map<[identity], [JSON]>> */ private volatile Map<String, Map<String, String>> ruleConfigs = new ConcurrentHashMap<>(); private static StorePool INSTANCE = new StorePool(); private StorePool() { } public static StorePool getInstance() { return INSTANCE; } public void registerGlobal(String module, Neural neural) { modules.put(module, neural); } public void registerRule(String module, String identity, String ruleConfig) { Map<String, String> moduleMap = ruleConfigs.computeIfAbsent(module, k -> new HashMap<>()); moduleMap.put(identity, ruleConfig); } public IStore getStore() { return store; } public void initialize(URL url) { this.pullConfigCycle = url.getParameter(PULL_CONFIG_CYCLE_KEY, 5L); this.statisticReportCycle = url.getParameter(STATISTIC_REPORT_CYCLE_KEY, 1000L); this.space = url.getParameter(URL.GROUP_KEY, SPACE_DEFAULT); if (space.contains(Constants.DELIMITER)) { throw new IllegalArgumentException("The space can't include ':'"); } space = space.toUpperCase(); this.store = ExtensionLoader.getLoader(IStore.class).getExtension(url.getProtocol()); store.initialize(url); // start cycle pull configs scheduled scheduledPullConfigs(); // start subscribe configs listener subscribeNotifyConfigs(); // start cycle push statistics scheduled scheduledPushStatistics(); // add shutdown Hook Runtime.getRuntime().addShutdownHook(new Thread(this::destroy)); } /** * The subscribe * * @param module module * @param object {@link RuleConfig} */ public void publish(String module, Object object) { String channel; if (object instanceof GlobalConfig) { channel = space + DELIMITER + Category.GLOBAL.name() + DELIMITER + module; } else if (object instanceof RuleConfig) { RuleConfig ruleConfig = (RuleConfig) object; channel = space + DELIMITER + Category.RULE.name() + DELIMITER + module + DELIMITER + ruleConfig.identity(); } else { throw new IllegalArgumentException("Illegal object type"); } store.publish(channel, object); } /** * The cycle pull configs scheduled */ private void scheduledPullConfigs() { if (null != pullConfigExecutor) { log.warn("The {} cyclePullConfigs is executed", space); return; } // initialize pull all configs pullConfigs(); // start pull config data executor log.debug("The {} executing pull config data executor", space); // build Task Name ThreadFactoryBuilder pullBuilder = new ThreadFactoryBuilder(); pullBuilder.setDaemon(true); pullBuilder.setNameFormat("neural-scheduled-pull-config"); ThreadFactory pullThreadFactory = pullBuilder.build(); this.pullConfigExecutor = Executors.newScheduledThreadPool(1, pullThreadFactory); // execute schedule pull config by fixed rate this.pullConfigExecutor.scheduleAtFixedRate(this::pullConfigs, pullConfigCycle, pullConfigCycle, TimeUnit.MILLISECONDS); } /** * The pull all configs */ private void pullConfigs() { List<String> remoteChannels = new ArrayList<>(); // pull remote global configs String remoteGlobalConfigKey = String.join(DELIMITER, space, Category.GLOBAL.name()); Map<String, String> remoteGlobalConfigs = store.pull(remoteGlobalConfigKey); log.debug("The global config pull changed: {}", remoteGlobalConfigs); if (remoteGlobalConfigs == null || remoteGlobalConfigs.isEmpty()) { if (!modules.isEmpty()) { remoteGlobalConfigs = new HashMap<>(modules.size()); for (Map.Entry<String, Neural> entry : modules.entrySet()) { remoteGlobalConfigs.put(entry.getKey(), SerializeUtils.serialize(entry.getValue().getGlobalConfig())); } store.batchAdd(remoteGlobalConfigKey, remoteGlobalConfigs); } } if (remoteGlobalConfigs != null && !remoteGlobalConfigs.isEmpty()) { for (Map.Entry<String, String> entry : remoteGlobalConfigs.entrySet()) { String remoteGlobalChannel = String.join(DELIMITER, remoteGlobalConfigKey, CHANNEL, entry.getKey()); remoteChannels.add(remoteGlobalChannel); String module = entry.getKey(); Neural neural = modules.get(module); if (neural != null) { neural.notify(Category.GLOBAL, Category.GLOBAL.name(), entry.getValue()); } } } // pull remote rule configs String remoteRuleConfigKey = String.join(DELIMITER, space, Category.RULE.name()); Map<String, String> remoteRuleConfigs = store.pull(remoteRuleConfigKey); log.debug("The rule config pull changed: {}", remoteRuleConfigs); if (remoteRuleConfigs == null || remoteRuleConfigs.isEmpty()) { if (!ruleConfigs.isEmpty()) { remoteRuleConfigs = new HashMap<>(ruleConfigs.size()); for (Map.Entry<String, Map<String, String>> entry : ruleConfigs.entrySet()) { remoteRuleConfigs.putAll(entry.getValue()); } store.batchAdd(remoteRuleConfigKey, remoteRuleConfigs); } } if (remoteRuleConfigs != null && !remoteRuleConfigs.isEmpty()) { for (Map.Entry<String, String> entry : remoteRuleConfigs.entrySet()) { String remoteRuleChannel = String.join(DELIMITER, remoteRuleConfigKey, CHANNEL, entry.getKey()); remoteChannels.add(remoteRuleChannel); int index = entry.getKey().indexOf(DELIMITER); String module = entry.getKey().substring(0, index); Neural neural = modules.get(module); if (neural != null) { String identity = entry.getKey().substring(index + 1); neural.notify(Category.RULE, identity, entry.getValue()); } } } // update channel list channels.clear(); if (!remoteChannels.isEmpty()) { channels.addAll(remoteChannels); } } /** * The subscribe configs */ private void subscribeNotifyConfigs() { // start subscribe config data executor log.debug("The {} executing subscribe config data executor", space); if (channels.isEmpty()) { return; } // the execute subscribe store.subscribe(channels, this); } @Override public void notify(String channel, String data) { log.debug("The {} config subscribed changed: {}, {}", space, channel, data); if (null == channel || channel.length() == 0 || null == data || data.length() == 0) { return; } Category remoteCategory = Category.valueOf(channel.split(DELIMITER)[0]); String remoteChannel = channel.substring(channel.indexOf(CHANNEL) + 8); String module = remoteChannel.split(DELIMITER)[0]; Neural neural = modules.get(module); if (neural != null) { String identity = null; if (Category.RULE == remoteCategory) { identity = remoteChannel.substring(remoteChannel.indexOf(DELIMITER) + 1); } neural.notify(remoteCategory, identity, data); } } /** * The cycle push statistics scheduled */ @SuppressWarnings("unchecked") private void scheduledPushStatistics() { if (null != pushStatisticsExecutor) { log.warn("The {} cyclePushStatistics is executed", space); return; } // start push statistics data executor log.debug("The {} executing push statistics data executor", space); ThreadFactoryBuilder pushBuilder = new ThreadFactoryBuilder(); ThreadFactory pushTreadFactory = pushBuilder.setDaemon(true).setNameFormat(space + "-push-statistics").build(); this.pushStatisticsExecutor = Executors.newScheduledThreadPool(1, pushTreadFactory); // execute schedule push statistics by fixed rate this.pushStatisticsExecutor.scheduleAtFixedRate(() -> { for (Map.Entry<String, Neural> entry : modules.entrySet()) { try { Neural neural = entry.getValue(); // query memory statistics data Map<String, Map<String, Long>> statisticsData = neural.collect(); log.debug("The {} cycle push statistics: {}", space, statisticsData); if (null == statisticsData || statisticsData.isEmpty()) { return; } Map<String, Long> sendData = new HashMap<>(); for (Map.Entry<String, Map<String, Long>> identityEntry : statisticsData.entrySet()) { for (Map.Entry<String, Long> tempEntry : identityEntry.getValue().entrySet()) { sendData.put(String.join(DELIMITER, space, tempEntry.getKey()), tempEntry.getValue()); } } // push statistics data to remote store.batchIncrBy(neural.getGlobalConfig().getStatisticExpire(), sendData); } catch (Exception e) { log.error(e.getMessage(), e); } } }, statisticReportCycle, statisticReportCycle, TimeUnit.MILLISECONDS); } /** * The destroy store config */ public void destroy() { log.debug("The {} is executing destroy", space); if (null != pullConfigExecutor) { pullConfigExecutor.shutdown(); } if (null != pushStatisticsExecutor) { pushStatisticsExecutor.shutdown(); } store.unSubscribe(this); if (null != store) { store.destroy(); } } }
package com.github.msemys.esjc; import com.github.msemys.esjc.subscription.PersistentSubscriptionChannel; import com.github.msemys.esjc.subscription.PersistentSubscriptionNakEventAction; import com.github.msemys.esjc.util.Subscriptions.DropData; import com.github.msemys.esjc.util.concurrent.ResettableLatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.UUID; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import static com.github.msemys.esjc.util.Preconditions.checkArgument; import static com.github.msemys.esjc.util.Subscriptions.DROP_SUBSCRIPTION_EVENT; import static com.github.msemys.esjc.util.Subscriptions.UNKNOWN_DROP_DATA; import static com.github.msemys.esjc.util.Threads.sleepUninterruptibly; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toCollection; /** * Persistent subscription. */ public abstract class PersistentSubscription implements AutoCloseable { private static final Logger logger = LoggerFactory.getLogger(PersistentSubscription.class); private static final int MAX_EVENTS = 2000; private final String subscriptionId; private final String streamId; private final PersistentSubscriptionListener listener; private final UserCredentials userCredentials; private final boolean autoAck; private PersistentSubscriptionChannel subscription; private final Queue<ResolvedEvent> queue = new ConcurrentLinkedQueue<>(); private final AtomicBoolean isProcessing = new AtomicBoolean(); private final AtomicReference<DropData> dropData = new AtomicReference<>(); private final AtomicBoolean isDropped = new AtomicBoolean(); private final ResettableLatch stopped = new ResettableLatch(true); private final int bufferSize; private final Executor executor; protected PersistentSubscription(String subscriptionId, String streamId, PersistentSubscriptionListener listener, UserCredentials userCredentials, int bufferSize, boolean autoAck, Executor executor) { this.subscriptionId = subscriptionId; this.streamId = streamId; this.listener = listener; this.userCredentials = userCredentials; this.bufferSize = bufferSize; this.autoAck = autoAck; this.executor = executor; } protected CompletableFuture<PersistentSubscription> start() { stopped.reset(); SubscriptionListener<PersistentSubscriptionChannel> subscriptionListener = new SubscriptionListener<PersistentSubscriptionChannel>() { @Override public void onEvent(PersistentSubscriptionChannel subscription, ResolvedEvent event) { enqueue(event); } @Override public void onClose(PersistentSubscriptionChannel subscription, SubscriptionDropReason reason, Exception exception) { enqueueSubscriptionDropNotification(reason, exception); } }; return startSubscription(subscriptionId, streamId, bufferSize, subscriptionListener, userCredentials).thenApply(s -> { subscription = (PersistentSubscriptionChannel) s; return PersistentSubscription.this; }); } protected abstract CompletableFuture<Subscription> startSubscription(String subscriptionId, String streamId, int bufferSize, SubscriptionListener<PersistentSubscriptionChannel> listener, UserCredentials userCredentials); /** * Acknowledge that the specified {@code eventIds} of the messages have completed processing (this will tell the server it has been processed). * <p><b>Note:</b> there is no need to ack a message if you have Auto Ack enabled.</p> * * @param eventIds the event ids to acknowledge. */ public void acknowledge(UUID... eventIds) { checkArgument(eventIds.length <= MAX_EVENTS, "events is limited to %d to ack at a time", MAX_EVENTS); subscription.notifyEventsProcessed(asList(eventIds)); } /** * Acknowledge that the specified message have completed processing (this will tell the server it has been processed). * <p><b>Note:</b> there is no need to ack a message if you have Auto Ack enabled.</p> * * @param event the event to acknowledge. */ public void acknowledge(ResolvedEvent event) { acknowledge(event.originalEvent().eventId); } /** * Acknowledge that the specified messages have completed processing (this will tell the server it has been processed). * <p><b>Note:</b> there is no need to ack a message if you have Auto Ack enabled.</p> * * @param events the events to acknowledge. */ public void acknowledge(List<ResolvedEvent> events) { acknowledge(events.stream().map(e -> e.originalEvent().eventId).toArray(UUID[]::new)); } /** * Marks that the specified message failed processing. The server will be take action based upon the action parameter. * * @param event the event to mark as failed. * @param action the action to take. * @param reason an error message as to why the failure is occurring. */ public void fail(ResolvedEvent event, PersistentSubscriptionNakEventAction action, String reason) { subscription.notifyEventsFailed(singletonList(event.originalEvent().eventId), action, reason); } /** * Marks that the specified messages have failed processing. The server will take action based upon the action parameter. * * @param events the events to mark as failed. * @param action the action to take. * @param reason an error message as to why the failure is occurring. */ public void fail(List<ResolvedEvent> events, PersistentSubscriptionNakEventAction action, String reason) { checkArgument(events.size() <= MAX_EVENTS, "events is limited to %d to ack at a time", MAX_EVENTS); subscription.notifyEventsFailed(events.stream() .map(e -> e.originalEvent().eventId) .collect(toCollection(() -> new ArrayList<>(events.size()))), action, reason); } /** * Unsubscribes from the persistent subscription. * * @param timeout the maximum wait time before it should timeout. * @throws TimeoutException when timeouts */ public void stop(Duration timeout) throws TimeoutException { logger.trace("Persistent subscription to {}: requesting stop...", streamId); enqueueSubscriptionDropNotification(SubscriptionDropReason.UserInitiated, null); if (!stopped.await(timeout.toMillis(), TimeUnit.MILLISECONDS)) { throw new TimeoutException(String.format("Could not stop %s in time.", getClass().getSimpleName())); } } /** * Unsubscribes from the persistent subscription (using 2 seconds wait time before it should timeout). * * @throws TimeoutException when timeouts * @see #stop(Duration) */ @Override public void close() throws TimeoutException { stop(Duration.ofSeconds(2)); } private void enqueueSubscriptionDropNotification(SubscriptionDropReason reason, Exception exception) { // if drop data was already set -- no need to enqueue drop again, somebody did that already if (dropData.compareAndSet(null, new DropData(reason, exception))) { enqueue(DROP_SUBSCRIPTION_EVENT); } } private void enqueue(ResolvedEvent event) { queue.offer(event); if (isProcessing.compareAndSet(false, true)) { executor.execute(this::processQueue); } } private void processQueue() { do { if (subscription == null) { sleepUninterruptibly(1); } else { ResolvedEvent event; while ((event = queue.poll()) != null) { // drop subscription artificial ResolvedEvent if (event.equals(DROP_SUBSCRIPTION_EVENT)) { DropData previousDropData = dropData.getAndAccumulate(UNKNOWN_DROP_DATA, (current, update) -> (current == null) ? update : current); if (previousDropData == null) { previousDropData = UNKNOWN_DROP_DATA; } dropSubscription(previousDropData.reason, previousDropData.exception); return; } DropData currentDropData = dropData.get(); if (currentDropData != null) { dropSubscription(currentDropData.reason, currentDropData.exception); return; } try { listener.onEvent(this, event); if (autoAck) { subscription.notifyEventsProcessed(singletonList(event.originalEvent().eventId)); } logger.trace("Persistent subscription to {}: processed event ({}, {}, {} @ {}).", streamId, event.originalEvent().eventStreamId, event.originalEvent().eventNumber, event.originalEvent().eventType, event.originalEventNumber()); } catch (Exception e) { dropSubscription(SubscriptionDropReason.EventHandlerException, e); return; } } } isProcessing.compareAndSet(true, false); } while (!queue.isEmpty() && isProcessing.compareAndSet(false, true)); } private void dropSubscription(SubscriptionDropReason reason, Exception exception) { if (isDropped.compareAndSet(false, true)) { logger.trace("Persistent subscription to {}: dropping subscription, reason: {}", streamId, reason, exception); if (subscription != null) { subscription.unsubscribe(); } listener.onClose(this, reason, exception); stopped.release(); } } }
package com.semmle.js.extractor; import com.semmle.js.extractor.ExtractorConfig.HTMLHandling; import com.semmle.js.extractor.ExtractorConfig.Platform; import com.semmle.js.extractor.ExtractorConfig.SourceType; import com.semmle.js.extractor.FileExtractor.FileType; import com.semmle.js.extractor.trapcache.DefaultTrapCache; import com.semmle.js.extractor.trapcache.DummyTrapCache; import com.semmle.js.extractor.trapcache.ITrapCache; import com.semmle.js.parser.ParsedProject; import com.semmle.js.parser.TypeScriptParser; import com.semmle.ts.extractor.TypeExtractor; import com.semmle.ts.extractor.TypeTable; import com.semmle.util.data.StringUtil; import com.semmle.util.data.UnitParser; import com.semmle.util.exception.ResourceError; import com.semmle.util.exception.UserError; import com.semmle.util.extraction.ExtractorOutputConfig; import com.semmle.util.files.FileUtil; import com.semmle.util.files.PathMatcher; import com.semmle.util.io.WholeIO; import com.semmle.util.language.LegacyLanguage; import com.semmle.util.process.ArgsParser; import com.semmle.util.process.ArgsParser.FileMode; import com.semmle.util.trap.TrapWriter; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.regex.Pattern; /** The main entry point of the JavaScript extractor. */ public class Main { /** * A version identifier that should be updated every time the extractor changes in such a way that * it may produce different tuples for the same file under the same {@link ExtractorConfig}. */ public static final String EXTRACTOR_VERSION = "2019-10-08"; public static final Pattern NEWLINE = Pattern.compile("\n"); // symbolic constants for command line parameter names private static final String P_ABORT_ON_PARSE_ERRORS = "--abort-on-parse-errors"; private static final String P_DEBUG_EXCLUSIONS = "--debug-exclusions"; private static final String P_DEFAULT_ENCODING = "--default-encoding"; private static final String P_EXCLUDE = "--exclude"; private static final String P_EXPERIMENTAL = "--experimental"; private static final String P_EXTERNS = "--externs"; private static final String P_EXTRACT_PROGRAM_TEXT = "--extract-program-text"; private static final String P_FILE_TYPE = "--file-type"; private static final String P_HTML = "--html"; private static final String P_INCLUDE = "--include"; private static final String P_PLATFORM = "--platform"; private static final String P_QUIET = "--quiet"; private static final String P_SOURCE_TYPE = "--source-type"; private static final String P_TRAP_CACHE = "--trap-cache"; private static final String P_TRAP_CACHE_BOUND = "--trap-cache-bound"; private static final String P_TYPESCRIPT = "--typescript"; private static final String P_TYPESCRIPT_FULL = "--typescript-full"; private static final String P_TYPESCRIPT_RAM = "--typescript-ram"; // symbolic constants for deprecated command line parameter names private static final String P_EXCLUDE_PATH = "--exclude-path"; private static final String P_TOLERATE_PARSE_ERRORS = "--tolerate-parse-errors"; private static final String P_NODEJS = "--nodejs"; private static final String P_MOZ_EXTENSIONS = "--mozExtensions"; private static final String P_JSCRIPT = "--jscript"; private static final String P_HELP = "--help"; private static final String P_ECMA_VERSION = "--ecmaVersion"; private final ExtractorOutputConfig extractorOutputConfig; private ExtractorConfig extractorConfig; private PathMatcher includeMatcher, excludeMatcher; private FileExtractor fileExtractor; private ExtractorState extractorState; private final Set<File> projectFiles = new LinkedHashSet<>(); private final Set<File> files = new LinkedHashSet<>(); private final Set<File> extractedFiles = new LinkedHashSet<>(); /* used to detect cyclic directory hierarchies */ private final Set<String> seenDirectories = new LinkedHashSet<>(); /** * If true, the extractor state is shared with other extraction jobs. * * <p>This is used by the test runner. */ private boolean hasSharedExtractorState = false; public Main(ExtractorOutputConfig extractorOutputConfig) { this.extractorOutputConfig = extractorOutputConfig; this.extractorState = new ExtractorState(); } public Main(ExtractorOutputConfig extractorOutputConfig, ExtractorState extractorState) { this.extractorOutputConfig = extractorOutputConfig; this.extractorState = extractorState; this.hasSharedExtractorState = true; } public void run(String[] args) { ArgsParser ap = addArgs(new ArgsParser(args)); ap.parse(); extractorConfig = parseJSOptions(ap); ITrapCache trapCache; if (ap.has(P_TRAP_CACHE)) { Long sizeBound = null; if (ap.has(P_TRAP_CACHE_BOUND)) { String tcb = ap.getString(P_TRAP_CACHE_BOUND); sizeBound = DefaultTrapCache.asFileSize(tcb); if (sizeBound == null) ap.error("Invalid TRAP cache size bound: " + tcb); } trapCache = new DefaultTrapCache(ap.getString(P_TRAP_CACHE), sizeBound, EXTRACTOR_VERSION); } else { if (ap.has(P_TRAP_CACHE_BOUND)) ap.error( P_TRAP_CACHE_BOUND + " should only be specified together with " + P_TRAP_CACHE + "."); trapCache = new DummyTrapCache(); } fileExtractor = new FileExtractor(extractorConfig, extractorOutputConfig, trapCache); setupMatchers(ap); collectFiles(ap); if (files.isEmpty()) { verboseLog(ap, "Nothing to extract."); return; } TypeScriptParser tsParser = extractorState.getTypeScriptParser(); tsParser.setTypescriptRam(extractorConfig.getTypeScriptRam()); if (containsTypeScriptFiles()) { tsParser.verifyInstallation(!ap.has(P_QUIET)); } for (File projectFile : projectFiles) { long start = verboseLogStartTimer(ap, "Opening project " + projectFile); ParsedProject project = tsParser.openProject(projectFile); verboseLogEndTimer(ap, start); // Extract all files belonging to this project which are also matched // by our include/exclude filters. List<File> filesToExtract = new ArrayList<>(); for (File sourceFile : project.getSourceFiles()) { if (files.contains(normalizeFile(sourceFile)) && !extractedFiles.contains(sourceFile.getAbsoluteFile())) { filesToExtract.add(sourceFile); } } tsParser.prepareFiles(filesToExtract); for (int i = 0; i < filesToExtract.size(); ++i) { ensureFileIsExtracted(filesToExtract.get(i), ap); } // Close the project to free memory. This does not need to be in a `finally` as // the project is not a system resource. tsParser.closeProject(projectFile); } if (!projectFiles.isEmpty()) { // Extract all the types discovered when extracting the ASTs. TypeTable typeTable = tsParser.getTypeTable(); extractTypeTable(projectFiles.iterator().next(), typeTable); } List<File> remainingTypescriptFiles = new ArrayList<>(); for (File f : files) { if (!extractedFiles.contains(f.getAbsoluteFile()) && FileType.forFileExtension(f) == FileType.TYPESCRIPT) { remainingTypescriptFiles.add(f); } } if (!remainingTypescriptFiles.isEmpty()) { tsParser.prepareFiles(remainingTypescriptFiles); for (File f : remainingTypescriptFiles) { ensureFileIsExtracted(f, ap); } } // The TypeScript compiler instance is no longer needed - free up some memory. if (hasSharedExtractorState) { tsParser.reset(); // This is called from a test runner, so keep the process alive. } else { tsParser.killProcess(); } // Extract files that were not part of a project. for (File f : files) { ensureFileIsExtracted(f, ap); } } private void extractTypeTable(File fileHandle, TypeTable table) { TrapWriter trapWriter = extractorOutputConfig.getTrapWriterFactory().mkTrapWriter(fileHandle); try { new TypeExtractor(trapWriter, table).extract(); } finally { FileUtil.close(trapWriter); } } private void ensureFileIsExtracted(File f, ArgsParser ap) { if (!extractedFiles.add(f.getAbsoluteFile())) { // The file has already been extracted as part of a project. return; } long start = verboseLogStartTimer(ap, "Extracting " + f); try { fileExtractor.extract(f.getAbsoluteFile(), extractorState); verboseLogEndTimer(ap, start); } catch (IOException e) { throw new ResourceError("Extraction of " + f + " failed.", e); } } private void verboseLog(ArgsParser ap, String message) { if (!ap.has(P_QUIET)) { System.out.println(message); } } private long verboseLogStartTimer(ArgsParser ap, String message) { if (!ap.has(P_QUIET)) { System.out.print(message + "..."); System.out.flush(); } return System.currentTimeMillis(); } private void verboseLogEndTimer(ArgsParser ap, long start) { long end = System.currentTimeMillis(); if (!ap.has(P_QUIET)) { System.out.println(" done (" + (end - start) / 1000 + " seconds)."); } } /** Returns true if the project contains a TypeScript file to be extracted. */ private boolean containsTypeScriptFiles() { for (File file : files) { // The file headers have already been checked, so don't use I/O. if (FileType.forFileExtension(file) == FileType.TYPESCRIPT) { return true; } } return false; } public void collectFiles(ArgsParser ap) { for (File f : ap.getOneOrMoreFiles("files", FileMode.FILE_OR_DIRECTORY_MUST_EXIST)) collectFiles(f, true); } public void setupMatchers(ArgsParser ap) { Set<String> includes = new LinkedHashSet<>(); // only extract HTML and JS by default addIncludesFor(includes, FileType.HTML); addIncludesFor(includes, FileType.JS); // extract TypeScript if `--typescript` or `--typescript-full` was specified if (getTypeScriptMode(ap) != TypeScriptMode.NONE) addIncludesFor(includes, FileType.TYPESCRIPT); // add explicit include patterns for (String pattern : ap.getZeroOrMore(P_INCLUDE)) addPathPattern(includes, System.getProperty("user.dir"), pattern); this.includeMatcher = new PathMatcher(includes); // if we are extracting (potential) Node.js code, we also want to // include package.json files, and files without extension if (getPlatform(ap) != Platform.WEB) { PathMatcher innerIncludeMatcher = this.includeMatcher; this.includeMatcher = new PathMatcher("**/package.json") { @Override public boolean matches(String path) { // match files without extension String basename = path.substring(path.lastIndexOf(File.separatorChar) + 1); if (FileUtil.extension(basename).isEmpty()) return true; // match package.json and anything matched by the inner matcher return super.matches(path) || innerIncludeMatcher.matches(path); } }; } Set<String> excludes = new LinkedHashSet<>(); for (String pattern : ap.getZeroOrMore(P_EXCLUDE)) addPathPattern(excludes, System.getProperty("user.dir"), pattern); for (String excl : ap.getZeroOrMore(P_EXCLUDE_PATH)) { File exclFile = new File(excl).getAbsoluteFile(); String base = exclFile.getParent(); for (String pattern : NEWLINE.split(new WholeIO().strictread(exclFile))) addPathPattern(excludes, base, pattern); } this.excludeMatcher = new PathMatcher(excludes); if (ap.has(P_DEBUG_EXCLUSIONS)) { System.out.println("Inclusion patterns: " + this.includeMatcher); System.out.println("Exclusion patterns: " + this.excludeMatcher); } } private void addIncludesFor(Set<String> includes, FileType filetype) { for (String extension : filetype.getExtensions()) includes.add("**/*" + extension); } private void addPathPattern(Set<String> patterns, String base, String pattern) { pattern = pattern.trim(); if (pattern.isEmpty()) return; if (!FileUtil.isAbsolute(pattern) && base != null) { pattern = base + "/" + pattern; } if (pattern.endsWith("/")) pattern = pattern.substring(0, pattern.length() - 1); patterns.add(pattern); } private ArgsParser addArgs(ArgsParser argsParser) { argsParser.addDeprecatedFlag( P_ECMA_VERSION, 1, "Files are now always extracted as ECMAScript 2017."); argsParser.addFlag( P_EXCLUDE, 1, "Do not extract files matching the given filename pattern.", true); argsParser.addToleratedFlag(P_EXCLUDE_PATH, 1, true); argsParser.addFlag( P_EXPERIMENTAL, 0, "Enable experimental support for pending ECMAScript proposals " + "(public class fields, function.sent, decorators, export extensions, function bind, " + "parameter-less catch, dynamic import, numeric separators, bigints, top-level await), " + "as well as other language extensions (E4X, JScript, Mozilla and v8-specific extensions) and full HTML extraction."); argsParser.addFlag( P_EXTERNS, 0, "Extract the given JavaScript files as Closure-style externs."); argsParser.addFlag( P_EXTRACT_PROGRAM_TEXT, 0, "Extract a representation of the textual content of the program " + "(in addition to its syntactic structure)."); argsParser.addFlag( P_FILE_TYPE, 1, "Assume all files to be of the given type, regardless of extension; " + "the type must be one of " + StringUtil.glue(", ", FileExtractor.FileType.allNames) + "."); argsParser.addFlag(P_HELP, 0, "Display this help."); argsParser.addFlag( P_HTML, 1, "Control extraction of HTML files: " + "'scripts' extracts JavaScript code embedded inside HTML, but not the HTML itself; " + "'elements' additionally extracts HTML elements and their attributes, as well as HTML comments, but not textual content (default); " + "'all' extracts elements, embedded scripts, comments and text."); argsParser.addFlag( P_INCLUDE, 1, "Extract files matching the given filename pattern (in addition to HTML and JavaScript files).", true); argsParser.addDeprecatedFlag(P_JSCRIPT, 0, "Use '" + P_EXPERIMENTAL + "' instead."); argsParser.addDeprecatedFlag(P_MOZ_EXTENSIONS, 0, "Use '" + P_EXPERIMENTAL + "' instead."); argsParser.addDeprecatedFlag(P_NODEJS, 0, "Use '" + P_PLATFORM + " node' instead."); argsParser.addFlag( P_PLATFORM, 1, "Extract the given JavaScript files as code for the given platform: " + "'node' extracts them as Node.js modules; " + "'web' as plain JavaScript files; " + "'auto' uses heuristics to automatically detect " + "Node.js modules and extracts everything else as plain JavaScript files. " + "The default is 'auto'."); argsParser.addFlag(P_QUIET, 0, "Produce less output."); argsParser.addFlag( P_SOURCE_TYPE, 1, "The source type to use; must be one of 'script', 'module' or 'auto'. " + "The default is 'auto'."); argsParser.addToleratedFlag(P_TOLERATE_PARSE_ERRORS, 0); argsParser.addFlag( P_ABORT_ON_PARSE_ERRORS, 0, "Abort extraction if a parse error is encountered."); argsParser.addFlag(P_TRAP_CACHE, 1, "Use the given directory as the TRAP cache."); argsParser.addFlag( P_TRAP_CACHE_BOUND, 1, "A (soft) upper limit on the size of the TRAP cache, " + "in standard size units (e.g., 'g' for gigabytes)."); argsParser.addFlag(P_DEFAULT_ENCODING, 1, "The encoding to use; default is UTF-8."); argsParser.addFlag(P_TYPESCRIPT, 0, "Enable basic TypesScript support."); argsParser.addFlag( P_TYPESCRIPT_FULL, 0, "Enable full TypeScript support with static type information."); argsParser.addFlag( P_TYPESCRIPT_RAM, 1, "Amount of memory allocated to the TypeScript compiler process. The default is 1G."); argsParser.addToleratedFlag(P_DEBUG_EXCLUSIONS, 0); argsParser.addTrailingParam("files", "Files and directories to extract."); return argsParser; } private boolean enableExperimental(ArgsParser ap) { return ap.has(P_EXPERIMENTAL) || ap.has(P_JSCRIPT) || ap.has(P_MOZ_EXTENSIONS); } private static TypeScriptMode getTypeScriptMode(ArgsParser ap) { if (ap.has(P_TYPESCRIPT_FULL)) return TypeScriptMode.FULL; if (ap.has(P_TYPESCRIPT)) return TypeScriptMode.BASIC; return TypeScriptMode.NONE; } private ExtractorConfig parseJSOptions(ArgsParser ap) { ExtractorConfig cfg = new ExtractorConfig(enableExperimental(ap)) .withExterns(ap.has(P_EXTERNS)) .withPlatform(getPlatform(ap)) .withTolerateParseErrors( ap.has(P_TOLERATE_PARSE_ERRORS) || !ap.has(P_ABORT_ON_PARSE_ERRORS)) .withHtmlHandling( ap.getEnum( P_HTML, HTMLHandling.class, ap.has(P_EXPERIMENTAL) ? HTMLHandling.ALL : HTMLHandling.ELEMENTS)) .withFileType(getFileType(ap)) .withSourceType(ap.getEnum(P_SOURCE_TYPE, SourceType.class, SourceType.AUTO)) .withExtractLines(ap.has(P_EXTRACT_PROGRAM_TEXT)) .withTypeScriptMode(getTypeScriptMode(ap)) .withTypeScriptRam( ap.has(P_TYPESCRIPT_RAM) ? UnitParser.parseOpt(ap.getString(P_TYPESCRIPT_RAM), UnitParser.MEGABYTES) : 0); if (ap.has(P_DEFAULT_ENCODING)) cfg = cfg.withDefaultEncoding(ap.getString(P_DEFAULT_ENCODING)); return cfg; } private String getFileType(ArgsParser ap) { String fileType = null; if (ap.has(P_FILE_TYPE)) { fileType = StringUtil.uc(ap.getString(P_FILE_TYPE)); if (!FileExtractor.FileType.allNames.contains(fileType)) ap.error("Invalid file type " + ap.getString(P_FILE_TYPE)); } return fileType; } private Platform getPlatform(ArgsParser ap) { if (ap.has(P_NODEJS)) return Platform.NODE; return ap.getEnum(P_PLATFORM, Platform.class, Platform.AUTO); } /** * Collect files to extract under a given root, which may be either a file or a directory. The * {@code explicit} flag indicates whether {@code root} was explicitly passed to the extractor as * a command line argument, or whether it is examined as part of a recursive traversal. */ private void collectFiles(File root, boolean explicit) { if (!root.exists()) { System.err.println("Skipping " + root + ", which does not exist."); return; } if (root.isDirectory()) { // exclude directories we've seen before if (seenDirectories.add(FileUtil.tryMakeCanonical(root).getPath())) // apply exclusion filters for directories if (!excludeMatcher.matches(root.getAbsolutePath())) { File[] gs = root.listFiles(); if (gs == null) System.err.println("Skipping " + root + ", which cannot be listed."); else for (File g : gs) collectFiles(g, false); } } else { String path = root.getAbsolutePath(); // extract files that are supported, match the layout (if any), pass the includeMatcher, // and do not pass the excludeMatcher if (fileExtractor.supports(root) && extractorOutputConfig.shouldExtract(root) && (explicit || includeMatcher.matches(path) && !excludeMatcher.matches(path))) { files.add(normalizeFile(root)); } if (extractorConfig.getTypeScriptMode() == TypeScriptMode.FULL && root.getName().equals("tsconfig.json") && !excludeMatcher.matches(path)) { projectFiles.add(root); } } } private File normalizeFile(File root) { return root.getAbsoluteFile().toPath().normalize().toFile(); } public static void main(String[] args) { try { new Main(new ExtractorOutputConfig(LegacyLanguage.JAVASCRIPT)).run(args); } catch (UserError e) { System.err.println(e.getMessage()); if (!e.reportAsInfoMessage()) System.exit(1); } } }
package com.github.otbproject.otbproject.util; import com.github.otbproject.otbproject.App; import com.github.otbproject.otbproject.bot.Bot; import com.github.otbproject.otbproject.gui.GuiApplication; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Watcher { private static final int EXCEPTION_LIMIT = 5; private static final int DUPLICATE_LIMIT = 3; private static final ExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadExecutor( new ThreadFactoryBuilder() .setNameFormat("watcher") .setUncaughtExceptionHandler(((t, e) -> { App.logger.error("Watcher thread crashed"); App.logger.error("Please report watcher crash to the developers"); App.logger.catching(e); if (Bot.Graphics.present()) { GuiApplication.errorAlert("Watcher Error", "OTB watcher has encountered an error"); } })) .build() ); private static int numExceptions = 0; public static void logException() { StackTraceElement[] stackTrace = new Throwable().getStackTrace(); final String stackTraceElement = (stackTrace.length > 1) ? stackTrace[1].toString() : "unknown location"; EXECUTOR_SERVICE.execute(() -> { numExceptions++; App.logger.error("Unexpected exception number " + numExceptions + " at " + stackTraceElement); if ((numExceptions >= EXCEPTION_LIMIT) && (numExceptions < EXCEPTION_LIMIT + DUPLICATE_LIMIT)) { App.logger.error("OTB has experienced multiple internal errors"); App.logger.error("Please report this problem to the developers"); if (Bot.Graphics.present()) { GuiApplication.errorAlert("Internal Error", "OTB has experienced multiple internal errors"); } } }); } }
package com.google.sps.servlets; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceConfig; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthException; import com.google.firebase.auth.FirebaseToken; import com.google.sps.firebase.FirebaseAppManager; import java.io.IOException; import java.util.ArrayList; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/check-student") public class CheckStudentStatus extends HttpServlet { FirebaseAuth authInstance; DatastoreService datastore; @Override public void init(ServletConfig config) throws ServletException { try { authInstance = FirebaseAuth.getInstance(FirebaseAppManager.getApp()); } catch (IOException e) { throw new ServletException(e); } } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { datastore = DatastoreServiceFactory.getDatastoreService(); System.setProperty( DatastoreServiceConfig.DATASTORE_EMPTY_LIST_SUPPORT, Boolean.TRUE.toString()); try { // Find user ID String idToken = request.getParameter("userToken"); FirebaseToken decodedToken = authInstance.verifyIdToken(idToken); String uID = decodedToken.getUid(); // Retrive entity String classCode = request.getParameter("classCode").trim(); Key classKey = KeyFactory.stringToKey(classCode); Entity classEntity = datastore.get(classKey); // Find position in queue ArrayList<String> queue = (ArrayList) classEntity.getProperty("studentQueue"); String pos = Integer.toString(queue.indexOf(uID) + 1); response.setContentType("application/json;"); response.getWriter().print(pos); } catch (EntityNotFoundException e) { response.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (IllegalArgumentException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); } catch (FirebaseAuthException e) { response.sendError(HttpServletResponse.SC_FORBIDDEN); } } }
package com.opensymphony.workflow; import junit.framework.TestCase; import java.net.URL; import java.util.HashMap; public class ExceptionTestCase extends TestCase { //~ Constructors /////////////////////////////////////////////////////////// public ExceptionTestCase(String s) { super(s); } //~ Methods //////////////////////////////////////////////////////////////// public void testFactoryException() { TestWorkflow.configFile = "/osworkflow-badfactory.xml"; //we expect an InternalWorkflowException (can't throw a checked exception in constructor, otherwise the ejb provider //will break spec by having a constructor try { TestWorkflow workflow = new TestWorkflow("testuser"); fail("bad factory did not throw an error"); } catch (InternalWorkflowException ex) { assertTrue("Expected FactoryException, but instead got " + ex.getRootCause(), ex.getRootCause() instanceof FactoryException); } } public void testInitializeInvalidActionException() throws Exception { TestWorkflow.configFile = "/osworkflow.xml"; TestWorkflow workflow = new TestWorkflow("testuser"); URL url = getClass().getResource("/samples/auto1.xml"); assertNotNull("Unable to find resource /samples/auto1.xml", url); try { workflow.initialize(url.toString(), 2, new HashMap()); } catch (InvalidActionException e) { return; } fail("Expected InvalidActionException but did not get one for a bad action in initialize"); } public void testInvalidActionException() throws Exception { TestWorkflow.configFile = "/osworkflow.xml"; TestWorkflow workflow = new TestWorkflow("testuser"); URL url = getClass().getResource("/samples/auto1.xml"); assertNotNull("Unable to find resource /samples/auto1.xml", url); long id = workflow.initialize(url.toString(), 1, new HashMap()); try { workflow.doAction(id, 10, null); } catch (InvalidActionException e) { return; } fail("Expected InvalidActionException but did not get one for a bad action"); } public void testStoreException() throws Exception { TestWorkflow.configFile = "/osworkflow-jdbc.xml"; TestWorkflow workflow = new TestWorkflow("testuser"); //correct behaviour is to get a store exception since we can't look up the DS URL url = getClass().getResource("/samples/auto1.xml"); assertNotNull("Unable to find resource /samples/auto1.xml", url); try { workflow.initialize(url.toString(), 1, new HashMap()); } catch (StoreException e) { return; } fail("Expected StoreException but did not get one for a bad JDBC datasource"); } }
package com.github.sabomichal.immutablexjc; import java.beans.Introspector; import java.io.StringWriter; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.ResourceBundle; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.logging.Level; import java.util.stream.Stream; import com.sun.codemodel.JAnnotationUse; import com.sun.codemodel.JAnnotationValue; import com.sun.codemodel.JBlock; import com.sun.codemodel.JClass; import com.sun.codemodel.JClassAlreadyExistsException; import com.sun.codemodel.JCodeModel; import com.sun.codemodel.JConditional; import com.sun.codemodel.JDefinedClass; import com.sun.codemodel.JExpr; import com.sun.codemodel.JExpression; import com.sun.codemodel.JFieldVar; import com.sun.codemodel.JFormatter; import com.sun.codemodel.JInvocation; import com.sun.codemodel.JMethod; import com.sun.codemodel.JMod; import com.sun.codemodel.JType; import com.sun.codemodel.JVar; import com.sun.tools.xjc.Options; import com.sun.tools.xjc.Plugin; import com.sun.tools.xjc.outline.ClassOutline; import com.sun.tools.xjc.outline.Outline; import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlElement; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.reflect.FieldUtils; import org.xml.sax.ErrorHandler; /** * IMMUTABLE-XJC plugin implementation. * * @author <a href="mailto:sabo.michal@gmail.com">Michal Sabo</a> */ public final class PluginImpl extends Plugin { private static final String BUILDER_OPTION_NAME = "-imm-builder"; private static final String SIMPLEBUILDERNAME_OPTION_NAME = "-imm-simplebuildername"; private static final String INHERIT_BUILDER_OPTION_NAME = "-imm-inheritbuilder"; private static final String CCONSTRUCTOR_OPTION_NAME = "-imm-cc"; private static final String WITHIFNOTNULL_OPTION_NAME = "-imm-ifnotnull"; private static final String NOPUBLICCONSTRUCTOR_OPTION_NAME = "-imm-nopubconstructor"; private static final String PUBLICCONSTRUCTOR_MAXARGS_OPTION_NAME = "-imm-pubconstructormaxargs"; private static final String SKIPCOLLECTIONS_OPTION_NAME = "-imm-skipcollections"; private static final String CONSTRUCTORDEFAULTS_OPTION_NAME = "-imm-constructordefaults"; private static final String OPTIONAL_GETTER_OPTION_NAME = "-imm-optionalgetter"; private static final String UNSET_PREFIX = "unset"; private static final String SET_PREFIX = "set"; private static final String MESSAGE_PREFIX = "IMMUTABLE-XJC"; private static final String OPTION_NAME = "immutable"; private static final JType[] NO_ARGS = new JType[0]; private ResourceBundle resourceBundle = ResourceBundle.getBundle(PluginImpl.class.getCanonicalName()); private boolean createBuilder; private boolean builderInheritance; private boolean createCConstructor; private boolean createWithIfNotNullMethod; private boolean createBuilderWithoutPublicConstructor; private int publicConstructorMaxArgs = Integer.MAX_VALUE; private boolean leaveCollectionsMutable; private boolean setDefaultValuesInConstructor; private boolean useSimpleBuilderName; private boolean optionalGetter; private Options options; @Override public boolean run(final Outline model, final Options options, final ErrorHandler errorHandler) { boolean success = true; this.options = options; this.log(Level.INFO, "title"); List<? extends ClassOutline> classes = new ArrayList<ClassOutline>(model.getClasses()); if (builderInheritance) { classes.sort(new Comparator<ClassOutline>() { @Override public int compare(ClassOutline o1, ClassOutline o2) { return Integer.compare(getDepth(o1), getDepth(o2)); } private int getDepth(ClassOutline outline) { int depth = 0; while ((outline = outline.getSuperClass()) != null) { ++depth; } return depth; } }); } for (ClassOutline clazz : classes) { JDefinedClass implClass = clazz.implClass; JFieldVar[] declaredFields = getDeclaredFields(implClass); ClassField[] superclassFieldsWithOwners = getSuperclassFields(implClass); JFieldVar[] superclassFields = Arrays.stream(superclassFieldsWithOwners).map(ClassField::getField).toArray(JFieldVar[]::new); makePropertiesPrivate(implClass); makePropertiesFinal(implClass, declaredFields); int declaredFieldsLength = declaredFields.length; int superclassFieldsLength = superclassFields.length; JMethod propertyContructor = null; if (declaredFieldsLength + superclassFieldsLength > 0) { int mod; if (createBuilderWithoutPublicConstructor || (createBuilder && declaredFieldsLength + superclassFieldsLength > publicConstructorMaxArgs)) { mod = JMod.NONE; } else { mod = JMod.PUBLIC; } propertyContructor = addPropertyContructor(implClass, declaredFields, superclassFields, mod); if (propertyContructor == null) { log(Level.WARNING, "couldNotAddPropertyCtor", implClass.binaryName()); } } if (propertyContructor == null || !propertyContructor.params().isEmpty()) { addStandardConstructor(implClass, declaredFields, superclassFields); } makeClassFinal(implClass); removeSetters(implClass); replaceCollectionGetters(implClass, declaredFields); if (optionalGetter) { replaceOptionalGetters(implClass, declaredFields); } if (createBuilder) { if (!clazz.implClass.isAbstract()) { JFieldVar[] unhandledSuperclassFields = getUnhandledSuperclassFields(superclassFieldsWithOwners); JDefinedClass builderClass; if ((builderClass = addBuilderClass(clazz, declaredFields, unhandledSuperclassFields, superclassFields)) == null) { log(Level.WARNING, "couldNotAddClassBuilder", implClass.binaryName()); } if (createCConstructor && builderClass != null) { addCopyConstructor(clazz.implClass, builderClass, declaredFields, unhandledSuperclassFields); } } } } // if superclass is a JAXB bound class or an abstract class, revert setting it final for (ClassOutline clazz : model.getClasses()) { if (clazz.getSuperClass() != null) { clazz.getSuperClass().implClass.mods().setFinal(false); } else if (clazz.implClass.isAbstract()) { clazz.implClass.mods().setFinal(false); } } this.options = null; return success; } @Override public String getOptionName() { return OPTION_NAME; } @Override public String getUsage() { final String n = System.getProperty("line.separator", "\n"); final int maxOptionLength = PUBLICCONSTRUCTOR_MAXARGS_OPTION_NAME.length(); StringBuilder retval = new StringBuilder(); appendOption(retval, "-" + OPTION_NAME, getMessage("usage"), n, maxOptionLength); appendOption(retval, BUILDER_OPTION_NAME, getMessage("builderUsage"), n, maxOptionLength); appendOption(retval, SIMPLEBUILDERNAME_OPTION_NAME, getMessage("simpleBuilderNameUsage"), n, maxOptionLength); appendOption(retval, INHERIT_BUILDER_OPTION_NAME, getMessage("inheritBuilderUsage"), n, maxOptionLength); appendOption(retval, CCONSTRUCTOR_OPTION_NAME, getMessage("cConstructorUsage"), n, maxOptionLength); appendOption(retval, WITHIFNOTNULL_OPTION_NAME, getMessage("withIfNotNullUsage"), n, maxOptionLength); appendOption(retval, NOPUBLICCONSTRUCTOR_OPTION_NAME, getMessage("builderWithoutPublicConstructor"), n, maxOptionLength); appendOption(retval, SKIPCOLLECTIONS_OPTION_NAME, getMessage("leaveCollectionsMutable"), n, maxOptionLength); appendOption(retval, PUBLICCONSTRUCTOR_MAXARGS_OPTION_NAME, getMessage("publicConstructorMaxArgs"), n, maxOptionLength); appendOption(retval, CONSTRUCTORDEFAULTS_OPTION_NAME, getMessage("setDefaultValuesInConstructor"), n, maxOptionLength); appendOption(retval, OPTIONAL_GETTER_OPTION_NAME, getMessage("optionalGetterUsage"), n, maxOptionLength); return retval.toString(); } private void appendOption(StringBuilder retval, String option, String description, String n, int optionColumnWidth) { retval.append(" "); retval.append(option); for (int i = option.length(); i < optionColumnWidth; i++) { retval.append(' '); } retval.append(" : "); retval.append(description); retval.append(n); } @Override public int parseArgument(final Options opt, final String[] args, final int i) { if (args[i].startsWith(BUILDER_OPTION_NAME)) { this.createBuilder = true; return 1; } if (args[i].startsWith(SIMPLEBUILDERNAME_OPTION_NAME)) { this.useSimpleBuilderName = true; return 1; } if (args[i].startsWith(INHERIT_BUILDER_OPTION_NAME)) { this.createBuilder = true; this.builderInheritance = true; return 1; } if (args[i].startsWith(CCONSTRUCTOR_OPTION_NAME)) { this.createCConstructor = true; return 1; } if (args[i].startsWith(WITHIFNOTNULL_OPTION_NAME)) { this.createWithIfNotNullMethod = true; return 1; } if (args[i].startsWith(NOPUBLICCONSTRUCTOR_OPTION_NAME)) { this.createBuilderWithoutPublicConstructor = true; return 1; } if (args[i].startsWith(SKIPCOLLECTIONS_OPTION_NAME)) { this.leaveCollectionsMutable = true; return 1; } if (args[i].startsWith(PUBLICCONSTRUCTOR_MAXARGS_OPTION_NAME)) { this.publicConstructorMaxArgs = Integer.parseInt(args[i].substring(PUBLICCONSTRUCTOR_MAXARGS_OPTION_NAME.length() + 1)); return 1; } if (args[i].startsWith(CONSTRUCTORDEFAULTS_OPTION_NAME)) { this.setDefaultValuesInConstructor = true; return 1; } if (args[i].startsWith(OPTIONAL_GETTER_OPTION_NAME)) { this.optionalGetter = true; return 1; } return 0; } private String getMessage(final String key, final Object... args) { return MessageFormat.format(resourceBundle.getString(key), args); } private JDefinedClass addBuilderClass(ClassOutline clazz, JFieldVar[] declaredFields, JFieldVar[] unhandledSuperclassFields, JFieldVar[] allSuperclassFields) { JDefinedClass builderClass = generateBuilderClass(clazz.implClass); if (builderClass == null) { return null; } addBuilderMethodsForFields(builderClass, declaredFields); // handle all superclass fields not handled by any superclass builder addBuilderMethodsForFields(builderClass, unhandledSuperclassFields); if (builderInheritance) { // re-type inherited builder methods for (int i = 0; i < allSuperclassFields.length - unhandledSuperclassFields.length; i++) { JFieldVar inheritedField = allSuperclassFields[i]; JMethod unconditionalWithMethod = addWithMethod(builderClass, inheritedField, true); if (createWithIfNotNullMethod) { addWithIfNotNullMethod(builderClass, inheritedField, unconditionalWithMethod, true); } if (isCollection(inheritedField)) { addAddMethod(builderClass, inheritedField, true); } } } addNewBuilder(clazz, builderClass); if (createCConstructor) { addNewBuilderCc(clazz, builderClass); } addBuildMethod(clazz.implClass, builderClass, declaredFields, allSuperclassFields); return builderClass; } private void addBuilderMethodsForFields(JDefinedClass builderClass, JFieldVar[] declaredFields) { for (JFieldVar field : declaredFields) { addProperty(builderClass, field); JMethod unconditionalWithMethod = addWithMethod(builderClass, field, false); if (createWithIfNotNullMethod) { addWithIfNotNullMethod(builderClass, field, unconditionalWithMethod, false); } if (isCollection(field)) { addAddMethod(builderClass, field, false); } } } private JVar addProperty(JDefinedClass clazz, JFieldVar field) { JType jType = getJavaType(field); int builderFieldVisibility = builderInheritance ? JMod.PROTECTED : JMod.PRIVATE; if (isCollection(field)) { return clazz.field(builderFieldVisibility, jType, field.name(), getNewCollectionExpression(field.type().owner(), jType)); } else { return clazz.field(builderFieldVisibility, jType, field.name()); } } private JMethod addBuildMethod(JDefinedClass clazz, JDefinedClass builderClass, JFieldVar[] declaredFields, JFieldVar[] superclassFields) { JMethod method = builderClass.method(JMod.PUBLIC, clazz, "build"); if (hasSuperClass(builderClass)) { method.annotate(Override.class); } JInvocation constructorInvocation = JExpr._new(clazz); for (JFieldVar field : superclassFields) { if (mustAssign(field)) { constructorInvocation.arg(JExpr.ref(field.name())); } } for (JFieldVar field : declaredFields) { if (mustAssign(field)) { constructorInvocation.arg(JExpr.ref(field.name())); } } method.body()._return(constructorInvocation); return method; } private void addNewBuilder(ClassOutline clazz, JDefinedClass builderClass) { if (builderInheritance || !hasSuperClassWithSameName(clazz)) { String builderMethodName = generateBuilderMethodName(clazz); JMethod method = clazz.implClass.method(JMod.PUBLIC | JMod.STATIC, builderClass, builderMethodName); method.body()._return(JExpr._new(builderClass)); } } private void addNewBuilderCc(ClassOutline clazz, JDefinedClass builderClass) { if (builderInheritance || !hasSuperClassWithSameName(clazz)) { String builderMethodName = generateBuilderMethodName(clazz); JMethod method = clazz.implClass.method(JMod.PUBLIC | JMod.STATIC, builderClass, builderMethodName); JVar param = method.param(JMod.FINAL, clazz.implClass, "o"); method.body()._return(JExpr._new(builderClass).arg(param)); } } private String generateBuilderMethodName(ClassOutline clazz) { if (isUseSimpleBuilderName()) { return "builder"; } return Introspector.decapitalize(clazz.implClass.name()) + "Builder"; } private boolean isUseSimpleBuilderName() { return useSimpleBuilderName; } private boolean hasSuperClassWithSameName(ClassOutline clazz) { ClassOutline superclass = clazz.getSuperClass(); while (superclass != null) { if (superclass.implClass.name().equals(clazz.implClass.name())) { return true; } superclass = superclass.getSuperClass(); } return false; } private JMethod addPropertyContructor(JDefinedClass clazz, JFieldVar[] declaredFields, JFieldVar[] superclassFields, int constAccess) { JMethod ctor = clazz.getConstructor(getFieldTypes(declaredFields, superclassFields)); if (ctor == null) { ctor = this.generatePropertyConstructor(clazz, declaredFields, superclassFields, constAccess); } else { this.log(Level.WARNING, "standardCtorExists"); } return ctor; } private JMethod addStandardConstructor(final JDefinedClass clazz, JFieldVar[] declaredFields, JFieldVar[] superclassFields) { JMethod ctor = clazz.getConstructor(NO_ARGS); if (ctor == null) { ctor = this.generateStandardConstructor(clazz, declaredFields, superclassFields); } else { this.log(Level.WARNING, "standardCtorExists"); } return ctor; } private JMethod addCopyConstructor(final JDefinedClass clazz, final JDefinedClass builderClass, JFieldVar[] declaredFields, JFieldVar[] superclassFields) { JMethod ctor = generateCopyConstructor(clazz, builderClass, declaredFields, superclassFields); createConstructor(builderClass, JMod.PUBLIC); return ctor; } private JMethod addWithMethod(JDefinedClass builderClass, JFieldVar field, boolean inherit) { String fieldName = StringUtils.capitalize(field.name()); JMethod method = builderClass.method(JMod.PUBLIC, builderClass, "with" + fieldName); if (inherit) { generateMethodParameter(method, field); generateSuperCall(method); } else { generatePropertyAssignment(method, field); } method.body()._return(JExpr._this()); return method; } private JMethod addWithIfNotNullMethod(JDefinedClass builderClass, JFieldVar field, JMethod unconditionalWithMethod, boolean inherit) { if (field.type().isPrimitive()) return null; String fieldName = StringUtils.capitalize(field.name()); JMethod method = builderClass.method(JMod.PUBLIC, builderClass, "with" + fieldName + "IfNotNull"); JVar param = generateMethodParameter(method, field); JBlock block = method.body(); if (inherit) { generateSuperCall(method); method.body()._return(JExpr._this()); } else { JConditional conditional = block._if(param.eq(JExpr._null())); conditional._then()._return(JExpr._this()); conditional._else()._return(JExpr.invoke(unconditionalWithMethod).arg(param)); } return method; } private JMethod addAddMethod(JDefinedClass builderClass, JFieldVar field, boolean inherit) { List<JClass> typeParams = ((JClass) getJavaType(field)).getTypeParameters(); if (!typeParams.iterator().hasNext()) { return null; } JMethod method = builderClass.method(JMod.PUBLIC, builderClass, "add" + StringUtils.capitalize(field.name())); JBlock block = method.body(); String fieldName = field.name(); JVar param = method.param(JMod.FINAL, typeParams.iterator().next(), fieldName); if (inherit) { generateSuperCall(method); } else { JInvocation invocation = JExpr.refthis(fieldName).invoke("add").arg(param); block.add(invocation); } block._return(JExpr._this()); return method; } private void generateSuperCall(JMethod method) { method.annotate(Override.class); JBlock block = method.body(); JInvocation superInvocation = block.invoke(JExpr._super(), method); for (JVar param : method.params()) { superInvocation.arg(param); } } private JDefinedClass generateBuilderClass(JDefinedClass clazz) { JDefinedClass builderClass = null; String builderClassName = getBuilderClassName(clazz); try { builderClass = clazz._class(JMod.PUBLIC | JMod.STATIC, builderClassName); if (builderInheritance) { for (JClass superClass = clazz._extends(); superClass != null; superClass = superClass._extends()) { JClass superClassBuilderClass = getBuilderClass(superClass); if (superClassBuilderClass != null) { builderClass._extends(superClassBuilderClass); break; } } } } catch (JClassAlreadyExistsException e) { this.log(Level.WARNING, "builderClassExists", builderClassName); } return builderClass; } private String getBuilderClassName(JClass clazz) { if (isUseSimpleBuilderName()) { return "Builder"; } return clazz.name() + "Builder"; } private JClass getBuilderClass(JClass clazz) { //Current limitation: this only works for classes from this model / outline, i.e. that are part of this generator run if (!createBuilder || clazz.isAbstract()) { return null; } String builderClassName = getBuilderClassName(clazz); if (clazz instanceof JDefinedClass) { JDefinedClass definedClass = (JDefinedClass) clazz; for (Iterator<JDefinedClass> i = definedClass.classes(); i.hasNext(); ) { JDefinedClass innerClass = i.next(); if (builderClassName.equals(innerClass.name())) { return innerClass; } } } return null; } private void replaceOptionalGetters(JDefinedClass implClass, JFieldVar[] declaredFields) { for (JFieldVar field : declaredFields) { if (isCollection(field)) { continue; } if (!isRequired(field)) { JMethod getterMethod = getGetterProperty(field, implClass); if (getterMethod != null) { replaceOptionalGetter(implClass, field, getterMethod); } } } } private void replaceOptionalGetter(JDefinedClass ownerClass, JFieldVar field, final JMethod getter) { // remove the old getter ownerClass.methods().remove(getter); JCodeModel codeModel = field.type().owner(); final JClass optionalWrappedReturnType = codeModel.ref(Optional.class).narrow(field.type()); // and create a new one JMethod newGetter = ownerClass.method(getter.mods().getValue(), optionalWrappedReturnType, getter.name()); JBlock block = newGetter.body(); JVar param = generateMethodParameter(getter, field); block._return(getOptionalWrappedExpression(codeModel, param)); getter.javadoc().append("Returns optional attribute/element."); } private void replaceCollectionGetters(JDefinedClass implClass, JFieldVar[] declaredFields) { for (JFieldVar field : declaredFields) { if (isCollection(field) && !leaveCollectionsMutable) { JMethod getterMethod = getGetterProperty(field, implClass); if (getterMethod != null) { replaceCollectionGetter(implClass, field, getterMethod); } } } } private void replaceCollectionGetter(JDefinedClass ownerClass, JFieldVar field, final JMethod getter) { // remove the old getter ownerClass.methods().remove(getter); // and create a new one JMethod newGetter = ownerClass.method(getter.mods().getValue(), getter.type(), getter.name()); JBlock block = newGetter.body(); JVar ret = block.decl(getJavaType(field), "ret"); JCodeModel codeModel = field.type().owner(); JVar param = generateMethodParameter(getter, field); JConditional conditional = block._if(param.eq(JExpr._null())); conditional._then().assign(ret, getEmptyCollectionExpression(codeModel, param)); conditional._else().assign(ret, getUnmodifiableWrappedExpression(codeModel, param)); block._return(ret); getter.javadoc().append("Returns unmodifiable collection."); } private void generatePropertyAssignment(final JMethod method, JFieldVar field) { generatePropertyAssignment(method, field, false); } private void generatePropertyAssignment(final JMethod method, JFieldVar field, boolean wrapUnmodifiable) { JBlock block = method.body(); JCodeModel codeModel = field.type().owner(); String fieldName = field.name(); JVar param = generateMethodParameter(method, field); if (isCollection(field) && !leaveCollectionsMutable && wrapUnmodifiable) { JConditional conditional = block._if(param.eq(JExpr._null())); conditional._then().assign(JExpr.refthis(fieldName), JExpr._null()); conditional._else().assign(JExpr.refthis(fieldName), getDefensiveCopyExpression(codeModel, getJavaType(field), param)); } else { block.assign(JExpr.refthis(fieldName), JExpr.ref(fieldName)); } } private JVar generateMethodParameter(final JMethod method, JFieldVar field) { String fieldName = field.name(); JType javaType = getJavaType(field); return method.param(JMod.FINAL, javaType, fieldName); } private JExpression getDefensiveCopyExpression(JCodeModel codeModel, JType jType, JVar param) { List<JClass> typeParams = ((JClass) jType).getTypeParameters(); JClass newClass = null; if (param.type().erasure().equals(codeModel.ref(Collection.class))) { newClass = codeModel.ref(ArrayList.class); } else if (param.type().erasure().equals(codeModel.ref(List.class))) { newClass = codeModel.ref(ArrayList.class); } else if (param.type().erasure().equals(codeModel.ref(Map.class))) { newClass = codeModel.ref(HashMap.class); } else if (param.type().erasure().equals(codeModel.ref(Set.class))) { newClass = codeModel.ref(HashSet.class); } else if (param.type().erasure().equals(codeModel.ref(SortedMap.class))) { newClass = codeModel.ref(TreeMap.class); } else if (param.type().erasure().equals(codeModel.ref(SortedSet.class))) { newClass = codeModel.ref(TreeSet.class); } if (newClass != null && !typeParams.isEmpty()) { newClass = newClass.narrow(typeParams); } return newClass == null ? JExpr._null() : JExpr._new(newClass).arg(param); } private JExpression getUnmodifiableWrappedExpression(JCodeModel codeModel, JVar param) { if (param.type().erasure().equals(codeModel.ref(Collection.class))) { return codeModel.ref(Collections.class).staticInvoke("unmodifiableCollection").arg(param); } else if (param.type().erasure().equals(codeModel.ref(List.class))) { return codeModel.ref(Collections.class).staticInvoke("unmodifiableList").arg(param); } else if (param.type().erasure().equals(codeModel.ref(Map.class))) { return codeModel.ref(Collections.class).staticInvoke("unmodifiableMap").arg(param); } else if (param.type().erasure().equals(codeModel.ref(Set.class))) { return codeModel.ref(Collections.class).staticInvoke("unmodifiableSet").arg(param); } else if (param.type().erasure().equals(codeModel.ref(SortedMap.class))) { return codeModel.ref(Collections.class).staticInvoke("unmodifiableSortedMap").arg(param); } else if (param.type().erasure().equals(codeModel.ref(SortedSet.class))) { return codeModel.ref(Collections.class).staticInvoke("unmodifiableSortedSet").arg(param); } return param; } private JExpression getEmptyCollectionExpression(JCodeModel codeModel, JVar param) { if (param.type().erasure().equals(codeModel.ref(Collection.class))) { return codeModel.ref(Collections.class).staticInvoke("emptyList"); } else if (param.type().erasure().equals(codeModel.ref(List.class))) { return codeModel.ref(Collections.class).staticInvoke("emptyList"); } else if (param.type().erasure().equals(codeModel.ref(Map.class))) { return codeModel.ref(Collections.class).staticInvoke("emptyMap"); } else if (param.type().erasure().equals(codeModel.ref(Set.class))) { return codeModel.ref(Collections.class).staticInvoke("emptySet"); } else if (param.type().erasure().equals(codeModel.ref(SortedMap.class))) { return JExpr._new(codeModel.ref(TreeMap.class)); } else if (param.type().erasure().equals(codeModel.ref(SortedSet.class))) { return JExpr._new(codeModel.ref(TreeSet.class)); } return param; } private JExpression getNewCollectionExpression(JCodeModel codeModel, JType jType) { List<JClass> typeParams = ((JClass) jType).getTypeParameters(); JClass newClass = null; if (jType.erasure().equals(codeModel.ref(Collection.class))) { newClass = codeModel.ref(ArrayList.class); } else if (jType.erasure().equals(codeModel.ref(List.class))) { newClass = codeModel.ref(ArrayList.class); } else if (jType.erasure().equals(codeModel.ref(Map.class))) { newClass = codeModel.ref(HashMap.class); } else if (jType.erasure().equals(codeModel.ref(Set.class))) { newClass = codeModel.ref(HashSet.class); } else if (jType.erasure().equals(codeModel.ref(SortedMap.class))) { newClass = codeModel.ref(TreeMap.class); } else if (jType.erasure().equals(codeModel.ref(SortedSet.class))) { newClass = codeModel.ref(TreeSet.class); } if (newClass != null && !typeParams.isEmpty()) { newClass = newClass.narrow(typeParams); } return newClass == null ? JExpr._null() : JExpr._new(newClass); } private JExpression getOptionalWrappedExpression(JCodeModel codeModel, JVar param) { return codeModel.ref(Optional.class).staticInvoke("ofNullable").arg(param); } private void generateDefaultPropertyAssignment(JMethod method, JFieldVar field) { JBlock block = method.body(); String propertyName = field.name(); block.assign(JExpr.refthis(propertyName), defaultValue(field)); } private JExpression defaultValue(JFieldVar field) { JType javaType = field.type(); if (setDefaultValuesInConstructor) { Optional<JAnnotationUse> xmlElementAnnotation = getAnnotation(field.annotations(), XmlElement.class.getCanonicalName()); if (xmlElementAnnotation.isPresent()) { JAnnotationValue annotationValue = xmlElementAnnotation.get().getAnnotationMembers().get("defaultValue"); if (annotationValue != null) { StringWriter sw = new StringWriter(); JFormatter f = new JFormatter(sw); annotationValue.generate(f); return JExpr.lit(sw.toString().replaceAll("\"", "")); } } } if (javaType.isPrimitive()) { if (field.type().owner().BOOLEAN.equals(javaType)) { return JExpr.lit(false); } else if (javaType.owner().SHORT.equals(javaType)) { return JExpr.cast(javaType.owner().SHORT, JExpr.lit(0)); } else { return JExpr.lit(0); } } return JExpr._null(); } private Optional<JAnnotationUse> getAnnotation(Collection<JAnnotationUse> annotations, String clazz) { return annotations.stream().filter(ann -> ann.getAnnotationClass().fullName().equals(clazz)).findFirst(); } private JMethod generatePropertyConstructor(JDefinedClass clazz, JFieldVar[] declaredFields, JFieldVar[] superclassFields, int constAccess) { final JMethod ctor = createConstructor(clazz, constAccess); if (superclassFields.length > 0) { JInvocation superInvocation = ctor.body().invoke("super"); for (JFieldVar field : superclassFields) { if (mustAssign(field)) { superInvocation.arg(JExpr.ref(field.name())); generateMethodParameter(ctor, field); } } } for (JFieldVar field : declaredFields) { if (mustAssign(field)) { generatePropertyAssignment(ctor, field, true); } } return ctor; } private boolean mustAssign(JFieldVar field) { // we have to assign final field, except filled collection fields, since we might loose the collection type upon marshal return !isFinal(field) || !isCollection(field) || getInitJExpression(field) == null; } private boolean shouldAssign(JFieldVar field) { // we don't want to clear filled collection fields in default constructor, since we might loose the collection type upon marshal return !isCollection(field) || getInitJExpression(field) == null; } private JMethod generateStandardConstructor(final JDefinedClass clazz, JFieldVar[] declaredFields, JFieldVar[] superclassFields) { final JMethod ctor = createConstructor(clazz, JMod.PROTECTED); ctor.javadoc().add("Used by JAX-B"); if (superclassFields.length > 0) { JInvocation superInvocation = ctor.body().invoke("super"); for (JFieldVar field : superclassFields) { if (mustAssign(field)) { superInvocation.arg(defaultValue(field)); } } } for (JFieldVar field : declaredFields) { if (shouldAssign(field)) { generateDefaultPropertyAssignment(ctor, field); } } return ctor; } private JMethod generateCopyConstructor(final JDefinedClass clazz, final JDefinedClass builderClass, JFieldVar[] declaredFields, JFieldVar[] superclassFields) { final JMethod ctor = createConstructor(builderClass, JMod.PUBLIC); final JVar o = ctor.param(JMod.FINAL, clazz, "o"); if (hasSuperClass(builderClass)) { ctor.body().invoke("super").arg(o); } else { String builderName = isUseSimpleBuilderName() ? String.format("%s.%s", clazz.name(), builderClass.name()) : builderClass.name(); ctor.body()._if(o.eq(JExpr._null()))._then() ._throw(JExpr._new(builderClass.owner().ref(NullPointerException.class)) .arg("Cannot create a copy of '" + builderName + "' from 'null'.")); } JCodeModel codeModel = clazz.owner(); for (JFieldVar field : superclassFields) { String propertyName = field.name(); JType type = field.type(); if (type instanceof JDefinedClass) { JMethod getter = getGetterProperty(field, clazz); if (isCollection(field)) { JVar tmpVar = ctor.body().decl(0, getJavaType(field), "_" + propertyName, JExpr.invoke(o, getter)); JConditional conditional = ctor.body()._if(tmpVar.eq(JExpr._null())); conditional._then().assign(JExpr.refthis(propertyName), getNewCollectionExpression(codeModel, getJavaType(field))); conditional._else().assign(JExpr.refthis(propertyName), getDefensiveCopyExpression(codeModel, getJavaType(field), tmpVar)); } else { ctor.body().assign(JExpr.refthis(propertyName), JExpr.invoke(o, getter)); } } } for (JFieldVar field : declaredFields) { String propertyName = field.name(); if (isCollection(field)) { JVar tmpVar = ctor.body().decl(0, getJavaType(field), "_" + propertyName, JExpr.ref(o, propertyName)); JConditional conditional = ctor.body()._if(tmpVar.eq(JExpr._null())); conditional._then().assign(JExpr.refthis(propertyName), getNewCollectionExpression(codeModel, getJavaType(field))); conditional._else().assign(JExpr.refthis(propertyName), getDefensiveCopyExpression(codeModel, getJavaType(field), tmpVar)); } else { ctor.body().assign(JExpr.refthis(propertyName), JExpr.ref(o, propertyName)); } } return ctor; } private boolean hasSuperClass(final JDefinedClass builderClass) { // we have to account for java.lang.Object, which we don't care about... return builderClass._extends() != null && builderClass._extends()._extends() != null; } private JMethod createConstructor(final JDefinedClass clazz, final int visibility) { return clazz.constructor(visibility); } private JType getJavaType(JFieldVar field) { return field.type(); } private JType[] getFieldTypes(JFieldVar[] declaredFields, JFieldVar[] superclassFields) { JType[] fieldTypes = new JType[declaredFields.length + superclassFields.length]; int i = 0; for (JFieldVar field : superclassFields) { fieldTypes[i++] = field.type(); } for (JFieldVar field : declaredFields) { fieldTypes[i++] = field.type(); } return fieldTypes; } private JMethod getGetterProperty(final JFieldVar field, final JDefinedClass clazz) { JMethod getter = clazz.getMethod("get" + StringUtils.capitalize(field.name()), NO_ARGS); if (getter == null) { getter = clazz.getMethod("is" + StringUtils.capitalize(field.name()), NO_ARGS); } if (getter == null) { List<JDefinedClass> superClasses = getSuperClasses(clazz); for (JDefinedClass definedClass : superClasses) { getter = getGetterProperty(field, definedClass); if (getter != null) { break; } } } if (getter == null) { //XJC does not work conform Introspector.decapitalize when multiple upper-case letter are in field name Optional<JAnnotationUse> xmlElementAnnotation = getAnnotation(field.annotations(), XmlElement.class.getCanonicalName()); if (xmlElementAnnotation.isPresent()) { JAnnotationValue annotationValue = xmlElementAnnotation.get().getAnnotationMembers().get("name"); if (annotationValue != null) { StringWriter sw = new StringWriter(); JFormatter f = new JFormatter(sw); annotationValue.generate(f); getter = clazz.getMethod("get" + sw.toString().replaceAll("\"", ""), NO_ARGS); } } } return getter; } private void makeClassFinal(JDefinedClass clazz) { clazz.mods().setFinal(true); } private void makePropertiesPrivate(JDefinedClass clazz) { for (JFieldVar field : clazz.fields().values()) { field.mods().setPrivate(); } } private void makePropertiesFinal(JDefinedClass clazz, JFieldVar[] declaredFields) { for (JFieldVar field : declaredFields) { String fieldName = field.name(); clazz.fields().get(fieldName).mods().setFinal(!(leaveCollectionsMutable && isCollection(field))); clazz.fields().get(fieldName).init(null); // remove field assignment } } private boolean isCollection(JFieldVar field) { if (field.type() instanceof JClass) { return isCollection((JClass) field.type()); } return false; } private boolean isCollection(JClass clazz) { return clazz.owner().ref(Collection.class).isAssignableFrom(clazz) || isMap(clazz); } private boolean isMap(JFieldVar field) { if (field.type() instanceof JClass) { return isMap((JClass) field.type()); } return false; } private boolean isMap(JClass clazz) { return clazz.equals(clazz.owner().ref(Map.class).narrow(clazz.getTypeParameters())); } private boolean isRequired(JFieldVar field) { return Stream.of(XmlElement.class, XmlAttribute.class) .map(annotationType -> getAnnotation(field.annotations(), annotationType.getCanonicalName()) .map(JAnnotationUse::getAnnotationMembers) .map(annotationValues -> annotationValues.get("required")) .filter(annotationValue -> { StringWriter sw = new StringWriter(); JFormatter f = new JFormatter(sw); annotationValue.generate(f); return sw.toString().equals("true"); }) ).anyMatch(Optional::isPresent); } private void removeSetters(JDefinedClass clazz) { Collection<JMethod> methods = clazz.methods(); Iterator<JMethod> it = methods.iterator(); while (it.hasNext()) { JMethod method = it.next(); String methodName = method.name(); if (methodName.startsWith(SET_PREFIX) || methodName.startsWith(UNSET_PREFIX)) { it.remove(); } } } private JFieldVar[] getDeclaredFields(JDefinedClass clazz) { return clazz.fields().values().stream().filter(f -> !(isFinal(f) && isStatic(f))).toArray(JFieldVar[]::new); } private ClassField[] getSuperclassFields(JDefinedClass clazz) { List<JDefinedClass> superclasses = getSuperClasses(clazz); // get all fields in class reverse order List<ClassField> superclassFields = new ArrayList<>(); Collections.reverse(superclasses); for (JDefinedClass classOutline : superclasses) { Map<String, JFieldVar> fields = classOutline.fields(); for (JFieldVar jFieldVar : fields.values()) { if (!(isStatic(jFieldVar) && isFinal(jFieldVar))) { superclassFields.add(new ClassField(classOutline, jFieldVar)); } } } return superclassFields.toArray(new ClassField[0]); } private List<JDefinedClass> getSuperClasses(JClass clazz) { // first get all superclasses List<JDefinedClass> superclasses = new ArrayList<>(); JClass superclass = clazz._extends(); while (superclass != null) { if (superclass instanceof JDefinedClass) { superclasses.add((JDefinedClass) superclass); } superclass = superclass._extends(); } return superclasses; } public boolean isStatic(JFieldVar var) { return (var.mods().getValue() & JMod.STATIC) != 0; } public boolean isFinal(JFieldVar var) { return (var.mods().getValue() & JMod.FINAL) != 0; } private JFieldVar[] getUnhandledSuperclassFields(ClassField[] superclassFieldsWithOwners) { JFieldVar[] superclassFields = Arrays.stream(superclassFieldsWithOwners).map(ClassField::getField).toArray(JFieldVar[]::new); if (!builderInheritance) { //we want to handle all inherited field return superclassFields; } // we only need fields whose classes don't have a builder themselves... // superclassFields are in class reverse order, i.e. root class first, direct superclass last, cf. #getSuperclassFields(ClassOutline) for (int i = superclassFields.length - 1; i >= 0; i JDefinedClass type = superclassFieldsWithOwners[i].getClazz(); if (type != null && getBuilderClass(type) != null) { // this class has its own builder, so we can stop here... if (i == superclassFields.length - 1) { return new JFieldVar[0]; } JFieldVar[] handledSuperclassFields = new JFieldVar[superclassFields.length - i - 1]; System.arraycopy(superclassFields, i + 1, handledSuperclassFields, 0, handledSuperclassFields.length); return handledSuperclassFields; } } // no superclass with a builder, so we actually need them all... return superclassFields; } // init field is private :-( , we really need this private JExpression getInitJExpression(JFieldVar jFieldVar) { try { return (JExpression) FieldUtils.readField(jFieldVar, "init", true); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } } private void log(final Level level, final String key, final Object... args) { final String message = "[" + MESSAGE_PREFIX + "] [" + level.getLocalizedName() + "] " + getMessage(key, args); int logLevel = Level.WARNING.intValue(); if (this.options != null && !this.options.quiet) { if (this.options.verbose) { logLevel = Level.INFO.intValue(); } if (this.options.debugMode) { logLevel = Level.ALL.intValue(); } } if (level.intValue() >= logLevel) { if (level.intValue() <= Level.INFO.intValue()) { System.out.println(message); } else { System.err.println(message); } } } private static class ClassField { private JDefinedClass clazz; private JFieldVar field; public ClassField(JDefinedClass clazz, JFieldVar field) { this.clazz = clazz; this.field = field; } public JDefinedClass getClazz() { return clazz; } public JFieldVar getField() { return field; } } }
package net.yeah.zhouyou.mickey.address.v2; import static net.yeah.zhouyou.mickey.address.v2.DFAInstance.*; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Pattern; public class AddressScanner { private static final Set<String> dCity; static { dCity = new HashSet<String>(); dCity.add(""); dCity.add(""); dCity.add(""); dCity.add(""); } private static Pattern p = Pattern.compile("[\\s]"); public static Address scan(String txt) { return scan(txt, true); } public static Address scan(String txt, boolean exactMatch4Level) { txt = p.matcher(txt).replaceAll(""); List<String> addrList = dfa.scan(txt); if (addrList.size() == 0) return new Address(txt); Address res = matchAddress(txt, addrList); if (exactMatch4Level && res.getTown() == null && res.getCity() != null) { // DFA DFA cityDFA = DFAInstance.getDFA(res.getCity().getId()); addrList = cityDFA.scan(txt); // addrListDFAInstance.dfadfa res = matchAddress(txt, addrList); } if (res.getCityAddress() == null && res.getProvinceAddress() != null && dCity.contains(res.getProvinceAddress())) { List<CityToken> ctl = DataCache.nameMap.get(res.getProvinceAddress() + ""); for (int i = 0; i < ctl.size(); ++i) { CityToken ct = ctl.get(0); if (ct.getParentId() != null && ct.getParentId().equals(res.getProvince().getId())) { res.setAddr(ct.getId(), null); break; } } } return res; } private static Address matchAddress(String txt, List<String> addrList) { Address res = new Address(txt); CityToken top = null; CityToken bottom = null; while (!addrList.isEmpty()) { String name = addrList.remove(0); CityToken firstct = findTopCT(name); if (firstct.getLevel() > 3) { continue; } res.setAddr(firstct.getId(), name); top = firstct; bottom = firstct; break; } while (!addrList.isEmpty()) { String name = addrList.remove(0); List<CityToken> ccl = getccl(top, bottom, name); if (ccl.size() == 1) { CityToken ct = ccl.get(0); if (ct.getLevel() < top.getLevel()) { top = ct; res.setAddr(ct.getId(), name); } else { if (ct.getLevel() <= 2 || bottom.getLevel() >= 3 // bottomct || ct.getLevel() - bottom.getLevel() <= 2 // bottombottom || name.length() >= 3 || DataCache.idMap.get(ct.getId()).get(0).getName().endsWith(name) ) { bottom = ct; res.setAddr(ct.getId(), name); } else { bottom = getNextBottom(addrList, res, top, bottom, name, ccl); } } } else if (ccl.size() > 1) { bottom = getNextBottom(addrList, res, top, bottom, name, ccl); } } CityToken ct = bottom; while (ct.getLevel() > 0) { CityToken pct = ct.getParent(); if (pct == null) break; if (res.getAddr(pct.getLevel()) == null) { res.setAddr(pct.getId(), null); } ct = pct; } return res; } private static CityToken getNextBottom(List<String> addrList, Address res, CityToken top, CityToken bottom, String name, List<CityToken> ccl) { if (!addrList.isEmpty()) { String name2 = addrList.remove(0); for (int i = 0; i < ccl.size(); ++i) { CityToken cct = ccl.get(i); List<CityToken> ccl2 = getccl(top, cct, name2); if (!ccl2.isEmpty()) { CityToken ct2 = ccl2.get(0); if (ct2.getLevel() > cct.getLevel()) { bottom = ct2; res.setAddr(cct.getId(), name); res.setAddr(ct2.getId(), name2); } } } } return bottom; } /** * name */ private static List<CityToken> getccl(CityToken top, CityToken bottom, String name) { List<CityToken> ccl = new ArrayList<CityToken>(); List<CityToken> nctl = DataCache.nameMap.get(name); for (int i = 0; i < nctl.size(); ++i) { CityToken ct = nctl.get(i); if (ct.getLevel() < top.getLevel()) { if (hasRelationship(ct, top)) { ccl.clear(); ccl.add(ct); break; } } else if (ct.getLevel() > bottom.getLevel()) { if (hasRelationship(bottom, ct)) { if (!ccl.isEmpty()) { if (ccl.get(0).getLevel() > ct.getLevel()) { ccl.clear(); ccl.add(ct); } else if (ccl.get(0).getLevel() == ct.getLevel()) { ccl.add(ct); } } else ccl.add(ct); } } } return ccl; } private static CityToken findTopCT(String name) { CityToken top = null; List<CityToken> nctl = DataCache.nameMap.get(name); for (int i = 0; i < nctl.size(); ++i) { CityToken ct = nctl.get(i); if (top == null || ct.getLevel() < top.getLevel()) { top = ct; } } return top; } private static boolean hasRelationship(CityToken pct, CityToken ct) { if (ct.getParentId() == null || ct.getLevel() <= pct.getLevel() || ct.getLevel() - pct.getLevel() > 2) return false; boolean res = ct.getParentId().equals(pct.getId()); if (!res) { CityToken parentCt = ct.getParent(); if (parentCt != null) { // ctparentct return hasRelationship(pct, parentCt); } } return res; } }
package at.archistar.crypto; import at.archistar.crypto.data.Share; import at.archistar.crypto.exceptions.ReconstructionException; import at.archistar.crypto.exceptions.WeakSecurityException; import at.archistar.crypto.random.FakeRandomSource; import at.archistar.crypto.random.RandomSource; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Collections; import static org.fest.assertions.api.Assertions.assertThat; import static org.junit.Assert.fail; import org.junit.Test; /** * Tests for {@link CevallosEngine} */ public class TestCevallosEngine { private static final byte data[] = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; private static final RandomSource rng = new FakeRandomSource(); /** A simple working share/reconstruct round over data. * * @throws ReconstructionException reconstruction did not work * @throws WeakSecurityException should not happen due to fixed parameters * @throws NoSuchAlgorithmException should not happen due to fixed algorithms */ @Test public void simpleShareReconstructRound() throws ReconstructionException, WeakSecurityException, NoSuchAlgorithmException { CryptoEngine algorithm = new CevallosEngine(8, 4, rng); Share shares[] = algorithm.share(data); byte reconstructedData[] = algorithm.reconstruct(shares); assertThat(reconstructedData).isEqualTo(data); } /** Create a new CryptoEngine if t >= n/3 (lower) and upper bound * * @throws WeakSecurityException should not happen due to fixed parameters * @throws NoSuchAlgorithmException should not happen due to fixed algorithms */ @Test public void withinLowerBounds() throws WeakSecurityException, NoSuchAlgorithmException{ /* TODO: loop over n to test more cases (: */ int n = 12; int t = n/3; CryptoEngine engine = new CevallosEngine(n, t+1, rng); assertThat(engine).isNotNull(); } /** Fail if lower than bound n/3 * * @throws WeakSecurityException happen as the lower bound is reached * @throws NoSuchAlgorithmException should not happen due to fixed algorithms */ @Test(expected=WeakSecurityException.class) public void failOutsideofLowerBound() throws WeakSecurityException, NoSuchAlgorithmException{ int n = 11; int t = 3; CryptoEngine engine = new CevallosEngine(n, t+1, rng); fail(); } /** Create a new CryptoEngine if t >= n/3 (lower) and upper bound * * @throws WeakSecurityException should not happen due to fixed parameters * @throws NoSuchAlgorithmException should not happen due to fixed algorithms */ @Test public void withinUpperBound() throws WeakSecurityException, NoSuchAlgorithmException{ int n = 11; int t = 5; CryptoEngine engine = new CevallosEngine(n, t, rng); assertThat(engine).isNotNull(); } /** Fail if t is higher than the upper bound * * TODO: do we really want to fail when this happens? * * @throws WeakSecurityException happen as the upper bound was reached * @throws NoSuchAlgorithmException should not happen due to fixed algorithms */ @Test(expected=WeakSecurityException.class) public void tGoodRangeUpperBoundLimitFailTest() throws WeakSecurityException, NoSuchAlgorithmException{ int n = 10; int t = 5; CryptoEngine engine = new CevallosEngine(n, t + 1, rng); fail(); } /** it should reconstruct if the number of shares > k * * @throws ReconstructionException if this is thrown the test really fails * @throws WeakSecurityException happen as the upper bound was reached * @throws NoSuchAlgorithmException should not happen due to fixed algorithms */ @Test public void reconstructPartialShares() throws ReconstructionException, WeakSecurityException, NoSuchAlgorithmException { int n = 8; int k = 4; CryptoEngine algorithm = new CevallosEngine(n, k, rng); Share shares[] = algorithm.share(data); for(int i = k; i < n; i++) { Share[] shares1 = Arrays.copyOfRange(shares, 0, i); byte reconstructedData[] = algorithm.reconstruct(shares1); assertThat(reconstructedData).isEqualTo(data); } } /** it should reconstruct if shares were shuffled * * @throws ReconstructionException if this is thrown the test really fails * @throws WeakSecurityException happen as the upper bound was reached * @throws NoSuchAlgorithmException should not happen due to fixed algorithms */ @Test public void shuffleSharesBeforeReconstruct() throws ReconstructionException, WeakSecurityException, NoSuchAlgorithmException { CryptoEngine algorithm = new CevallosEngine(8, 4, rng); Share shares[] = algorithm.share(data); Collections.shuffle(Arrays.asList(shares)); byte reconstructedData[] = algorithm.reconstruct(shares); assertThat(reconstructedData).isEqualTo(data); } /** it should fail if the number of shares <= k * * @throws WeakSecurityException happen as the upper bound was reached * @throws NoSuchAlgorithmException should not happen due to fixed algorithms */ public void failIfThereAintEnoughShares() throws WeakSecurityException, NoSuchAlgorithmException { int n=8; int k=4; CryptoEngine algorithm = new CevallosEngine(n, k, rng); Share shares[] = algorithm.share(data); for (int i = 0; i < k; i++) { Share[] shares1 = Arrays.copyOfRange(shares, 0, k); try { algorithm.reconstruct(shares1); fail("could reconstruct even if there were too few shares! (k=" + k + ")"); } catch(ReconstructionException ex) { // actually the good case! } } } }
package org.akvo.flow.xml; import java.util.ArrayList; import java.util.List; import org.waterforpeople.mapping.app.gwt.client.survey.OptionContainerDto; import org.waterforpeople.mapping.app.gwt.client.survey.QuestionOptionDto; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.gallatinsystems.survey.domain.Question; import com.gallatinsystems.survey.domain.QuestionOption; @JsonInclude(JsonInclude.Include.NON_NULL) public class XmlOptions { @JacksonXmlElementWrapper(localName = "option", useWrapping = false) private List<XmlOption> option; @JacksonXmlProperty(localName = "allowOther", isAttribute = true) private boolean allowOther; @JacksonXmlProperty(localName = "allowMultiple", isAttribute = true) private boolean allowMultiple; @JacksonXmlProperty(localName = "renderType", isAttribute = true) private String renderType; //Ignore for now public XmlOptions() { } public XmlOptions(Question q) { allowOther = Boolean.TRUE.equals(q.getAllowOtherFlag()); allowMultiple = Boolean.TRUE.equals(q.getAllowMultipleFlag()); if (q.getQuestionOptionMap() != null) { option = new ArrayList<XmlOption>(); for (QuestionOption o: q.getQuestionOptionMap().values()) { //In key order option.add(new XmlOption(o)); } } } /** * @return a DTO with relevant fields copied */ public OptionContainerDto toDto() { OptionContainerDto dto = new OptionContainerDto(); dto.setAllowOtherFlag(allowOther); dto.setAllowMultipleFlag(allowMultiple); if (option != null) { ArrayList<QuestionOptionDto> oList = new ArrayList<>(); for (XmlOption o : option) { oList.add(o.toDto()); } dto.setOptionsList(oList); } return dto; } @Override public String toString() { return "options{" + "allowOther='" + allowOther + "',allowMultiple='" + allowMultiple + "',options=" + option==null?"(null)":option.toString() + "}"; } public List<XmlOption> getOption() { return option; } public void setOption(List<XmlOption> option) { this.option = option; } public boolean getAllowOther() { return allowOther; } public void setAllowOther(boolean allowOther) { this.allowOther = allowOther; } public boolean getAllowMultiple() { return allowMultiple; } public void setAllowMultiple(boolean allowMultiple) { this.allowMultiple = allowMultiple; } public String getRenderType() { return renderType; } public void setRenderType(String renderType) { this.renderType = renderType; } }
package com.hubspot.jinjava.objects.collections; import com.google.common.collect.ForwardingMap; import com.hubspot.jinjava.objects.PyWrapper; import java.util.Map; import java.util.Set; public class PyMap extends ForwardingMap<String, Object> implements PyWrapper { private Map<String, Object> map; public PyMap(Map<String, Object> map) { this.map = map; } @Override protected Map<String, Object> delegate() { return map; } @Override public String toString() { return delegate().toString(); } public Map<String, Object> toMap() { return map; } public Set<java.util.Map.Entry<String, Object>> items() { return entrySet(); } public void update(Map<? extends String, ? extends Object> m) { putAll(m); } }