answer
stringlengths
17
10.2M
package com.mebigfatguy.fbcontrib.detect; import java.util.ArrayDeque; import java.util.BitSet; import java.util.Deque; import java.util.Iterator; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.CodeException; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.Type; import com.mebigfatguy.fbcontrib.utils.BugType; import com.mebigfatguy.fbcontrib.utils.CollectionUtils; import com.mebigfatguy.fbcontrib.utils.OpcodeUtils; import com.mebigfatguy.fbcontrib.utils.StopOpcodeParsingException; import com.mebigfatguy.fbcontrib.utils.ToString; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.BytecodeScanningDetector; import edu.umd.cs.findbugs.OpcodeStack; import edu.umd.cs.findbugs.ba.ClassContext; /** * looks for relatively large if blocks of code, where you unconditionally return from them, and then follow that with an unconditional return of a small block. * This places the bulk of the logic to the right indentation-wise, making it more difficult to read than needed. It would be better to invert the logic of the * if block, and immediately return, allowing the bulk of the logic to be move to the left, for easier reading. */ public class BuryingLogic extends BytecodeScanningDetector { private static final String BURY_LOGIC_LOW_RATIO_PROPERTY = "fb-contrib.bl.low_ratio"; private static final String BURY_LOGIC_NORMAL_RATIO_PROPERTY = "fb-contrib.bl.normal_ratio"; private static final double LOW_BUG_RATIO_LIMIT = 16.0; private static final double NORMAL_BUG_RATIO_LIMIT = 30.0; private final static BitSet resetOps = new BitSet(); static { resetOps.set(PUTFIELD); resetOps.set(PUTSTATIC); resetOps.set(POP); resetOps.set(POP2); resetOps.set(TABLESWITCH); resetOps.set(LOOKUPSWITCH); resetOps.set(MONITORENTER); resetOps.set(MONITOREXIT); } private BugReporter bugReporter; private OpcodeStack stack; private Deque<IfBlock> ifBlocks; /** * if an previous if block has been closed off with a return, hold onto it. */ private IfBlock activeUnconditional; private BitSet casePositions; private double lowBugRatioLimit; private double normalBugRatioLimit; private BitSet catchPCs; private BitSet gotoBranchPCs; /** * if we've processed an if block, we want to avoid else ifs, so don't start looking for a new if branch, until some instruction that can't be part of a * conditional is found */ private boolean lookingForResetOp; public BuryingLogic(BugReporter bugReporter) { this.bugReporter = bugReporter; String lowRatio = System.getProperty(BURY_LOGIC_LOW_RATIO_PROPERTY); try { if (lowRatio == null) { lowBugRatioLimit = LOW_BUG_RATIO_LIMIT; } else { lowBugRatioLimit = Double.parseDouble(lowRatio); if (lowBugRatioLimit <= 0) { lowBugRatioLimit = LOW_BUG_RATIO_LIMIT; } } } catch (NumberFormatException e) { lowBugRatioLimit = LOW_BUG_RATIO_LIMIT; } String normalRatio = System.getProperty(BURY_LOGIC_NORMAL_RATIO_PROPERTY); try { if (normalRatio == null) { normalBugRatioLimit = NORMAL_BUG_RATIO_LIMIT; } else { normalBugRatioLimit = Double.parseDouble(normalRatio); if (normalBugRatioLimit <= 0) { normalBugRatioLimit = NORMAL_BUG_RATIO_LIMIT; } } } catch (NumberFormatException e) { normalBugRatioLimit = NORMAL_BUG_RATIO_LIMIT; } } @Override public void visitClassContext(ClassContext classContext) { try { stack = new OpcodeStack(); ifBlocks = new ArrayDeque<>(); gotoBranchPCs = new BitSet(); casePositions = new BitSet(); super.visitClassContext(classContext); } finally { stack = null; ifBlocks = null; catchPCs = null; gotoBranchPCs = null; casePositions = null; } } @Override public void visitCode(Code obj) { Method m = getMethod(); if (m.getReturnType() == Type.VOID) { return; } stack.resetForMethodEntry(this); ifBlocks.clear(); activeUnconditional = null; CodeException[] ces = obj.getExceptionTable(); if (CollectionUtils.isEmpty(ces)) { catchPCs = null; } else { catchPCs = new BitSet(); for (CodeException ce : ces) { catchPCs.set(ce.getHandlerPC()); } } gotoBranchPCs.clear(); casePositions.clear(); lookingForResetOp = false; try { super.visitCode(obj); } catch (StopOpcodeParsingException e) { // reported an issue, so get out } } /** * the difficult problem is to figure out when you are at the bottom of an if/else chain when all the above if/else blocks leave via returns. then there is * only one branch target to the statement after the last else, which is indistinquishable from a simple if/else. */ @Override public void sawOpcode(int seen) { try { int removed = 0; if (!ifBlocks.isEmpty()) { Iterator<IfBlock> it = ifBlocks.iterator(); while (it.hasNext()) { IfBlock block = it.next(); if ((getPC() >= block.getEnd())) { it.remove(); removed++; } } } if (removed > 1) { activeUnconditional = null; } else if (removed == 1) { } if (!casePositions.isEmpty()) { int firstCasePos = casePositions.nextSetBit(0); if (firstCasePos == getPC()) { casePositions.clear(firstCasePos); activeUnconditional = null; lookingForResetOp = false; } } if (lookingForResetOp) { if (isResetOp(seen)) { lookingForResetOp = false; } else { return; } } if (isBranch(seen)) { if (activeUnconditional != null) { activeUnconditional = null; if (!ifBlocks.isEmpty()) { ifBlocks.removeLast(); } lookingForResetOp = true; } int target = getBranchTarget(); if (getBranchOffset() > 0) { if ((seen == GOTO) || (seen == GOTO_W)) { gotoBranchPCs.set(target); } else if ((catchPCs == null) || !catchPCs.get(getNextPC())) { ifBlocks.addLast(new IfBlock(getNextPC(), target)); } } else { removeLoopBlocks(target); } } else if (isReturn(seen)) { if ((activeUnconditional != null) && !gotoBranchPCs.get(activeUnconditional.getEnd())) { int ifSize = activeUnconditional.getEnd() - activeUnconditional.getStart(); int elseSize = getPC() - activeUnconditional.getEnd(); double ratio = (double) ifSize / (double) elseSize; if (ratio > lowBugRatioLimit) { bugReporter .reportBug(new BugInstance(this, BugType.BL_BURYING_LOGIC.name(), ratio > normalBugRatioLimit ? NORMAL_PRIORITY : LOW_PRIORITY) .addClass(this).addMethod(this).addSourceLineRange(this, activeUnconditional.getStart(), activeUnconditional.getEnd())); throw new StopOpcodeParsingException(); } } else if (!ifBlocks.isEmpty() && (getNextPC() == ifBlocks.getFirst().getEnd()) && !gotoAcrossPC(getNextPC())) { activeUnconditional = ifBlocks.getFirst(); } lookingForResetOp = true; } else if ((seen == TABLESWITCH) || (seen == LOOKUPSWITCH)) { int[] offsets = getSwitchOffsets(); int pc = getPC(); for (int offset : offsets) { casePositions.set(pc + offset); } } } finally { stack.sawOpcode(this, seen); } } /** * returns whether the last downward branching jump seen crosses over the current location * * @param pc * the current location * @return if the last if statement branched over here */ private boolean gotoAcrossPC(int pc) { int target = gotoBranchPCs.previousSetBit(Integer.MAX_VALUE); return (target > pc); } /** * determines if this opcode couldn't be part of a conditional expression or at least is very unlikely to be so. * * @param seen * the currently parse opcode * @return if this operation resets the looking for conditionals */ private boolean isResetOp(int seen) { return resetOps.get(seen) || OpcodeUtils.isStore(seen) || OpcodeUtils.isReturn(seen) || ((OpcodeUtils.isInvoke(seen) && getSigConstantOperand().endsWith(")V")) || (isBranch(seen) && (getBranchOffset() < 0))); } /** * remove all if blocks that are contained within a loop, once that loop has ended * * @param target * the start of the loop block */ private void removeLoopBlocks(int target) { Iterator<IfBlock> it = ifBlocks.descendingIterator(); while (it.hasNext()) { if (it.next().getStart() >= target) { it.remove(); } else { return; } } } /** * represents the byte offset code range of code that is executed inside an if block */ static class IfBlock { private int start; private int end; public IfBlock(int s, int e) { start = s; end = e; } public int getStart() { return start; } public int getEnd() { return end; } @Override public String toString() { return ToString.build(this); } } }
package com.codeaffine.extras.ide.test; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.part.EditorPart; public class TestEditorPart extends EditorPart { public static final String ID = "com.codeaffine.extras.platform.test.internal.TestEditorPart"; @Override public void init( IEditorSite site, IEditorInput input ) { setSite( site ); setInput( input ); } @Override public void createPartControl( Composite parent ) { } @Override public void setFocus() { } @Override public void doSave( IProgressMonitor monitor ) { } @Override public void doSaveAs() { } @Override public boolean isDirty() { return false; } @Override public boolean isSaveAsAllowed() { return false; } }
package net.sf.taverna.t2.workbench.run; import java.text.DateFormat; import java.util.Date; import java.util.Map; import java.util.Map.Entry; import net.sf.taverna.t2.facade.ResultListener; import net.sf.taverna.t2.facade.WorkflowInstanceFacade; import net.sf.taverna.t2.invocation.TokenOrderException; import net.sf.taverna.t2.invocation.WorkflowDataToken; import net.sf.taverna.t2.lang.observer.Observer; import net.sf.taverna.t2.monitor.MonitorManager; import net.sf.taverna.t2.monitor.MonitorManager.MonitorMessage; import net.sf.taverna.t2.provenance.ProvenanceConnectorFactory; import net.sf.taverna.t2.provenance.ProvenanceConnectorFactoryRegistry; import net.sf.taverna.t2.provenance.connector.ProvenanceConnector; import net.sf.taverna.t2.reference.ReferenceService; import net.sf.taverna.t2.reference.T2Reference; import net.sf.taverna.t2.workbench.reference.config.DataManagementConfiguration; import net.sf.taverna.t2.workbench.views.monitor.MonitorViewComponent; import net.sf.taverna.t2.workbench.views.monitor.PreviousRunsComponent; import net.sf.taverna.t2.workbench.views.results.ResultViewComponent; import net.sf.taverna.t2.workflowmodel.Dataflow; import net.sf.taverna.t2.workflowmodel.EditException; import org.apache.log4j.Logger; public class DataflowRun { private static Logger logger = Logger .getLogger(DataflowRun.class); private WorkflowInstanceFacade facade; private Map<String, T2Reference> inputs; private Date date; private MonitorViewComponent monitorViewComponent; private ResultViewComponent resultsComponent; private Observer<MonitorMessage> monitorObserver; private int results = 0; private Dataflow dataflow; // Unique identifier of the workflow run private String runId; private ProvenanceConnector connector; private boolean isProvenanceEnabledForRun = true; private boolean isDataSavedInDatabase = true; private ReferenceService referenceService; public DataflowRun(Dataflow dataflow, Date date, String sessionID, ReferenceService referenceService) { this.dataflow = dataflow; this.date = date; this.runId = sessionID; this.referenceService = referenceService; String connectorType = DataManagementConfiguration.getInstance() .getConnectorType(); for (ProvenanceConnectorFactory factory : ProvenanceConnectorFactoryRegistry .getInstance().getInstances()) { if (connectorType.equalsIgnoreCase(factory.getConnectorType())) { connector = factory.getProvenanceConnector(); } } try { if (connector != null) { connector.init(); connector.setSessionID(sessionID); connector.setReferenceService(referenceService); // set the ref. service specific to this run } } catch (Exception except) { } } public DataflowRun(WorkflowInstanceFacade facade, Map<String, T2Reference> inputs, Date date, ReferenceService referenceService) { this.date = date; monitorViewComponent = new MonitorViewComponent(); this.facade = facade; this.inputs = inputs; this.referenceService = referenceService; this.dataflow = facade.getDataflow(); connector = (ProvenanceConnector) (facade .getContext().getProvenanceReporter()); monitorViewComponent .setProvenanceConnector(connector); monitorViewComponent.setReferenceService(referenceService); this.runId = facade.getWorkflowRunId(); resultsComponent = new ResultViewComponent(); } public void run() { monitorObserver = monitorViewComponent.setDataflow(dataflow); // resultsComponent.setContext(context); MonitorManager.getInstance().addObserver(monitorObserver); // Use the empty context by default to root this facade on the monitor // tree // Only if this workflow has at least one output port there will be some // results to observe. // Otherwise, we have to find another way of detecting when a workflow // without output ports // has finished running - we do that by observing when all processors // have finished. if (dataflow.getOutputPorts().size() > 0) { facade.addResultListener(new ResultListener() { public void resultTokenProduced(WorkflowDataToken token, String portName) { if (token.getIndex().length == 0) { results++; if (results == dataflow.getOutputPorts().size()) { facade.removeResultListener(this); MonitorManager.getInstance().removeObserver( monitorObserver); monitorObserver = null; results = 0; } } } }); } try { resultsComponent.register(facade, isProvenanceEnabledForRun); } catch (EditException e1) { logger.error("Unable to register facade", e1); } facade.fire(); if (inputs != null) { for (Entry<String, T2Reference> entry : inputs.entrySet()) { String portName = entry.getKey(); T2Reference identifier = entry.getValue(); int[] index = new int[] {}; try { WorkflowDataToken token = new WorkflowDataToken("", index, identifier, facade.getContext()); facade.pushData(token, portName); resultsComponent.pushInputData(token, portName); } catch (TokenOrderException e) { logger.error("Unable to push data", e); } } } } @Override public String toString() { return dataflow.getLocalName() + " " + DateFormat.getDateTimeInstance().format(date); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((dataflow == null) ? 0 : dataflow.getInternalIdentier() .hashCode()); result = prime * result + ((date == null) ? 0 : date.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final DataflowRun other = (DataflowRun) obj; if (dataflow == null) { if (other.dataflow != null) return false; } else if (!dataflow.getInternalIdentier().equals( other.dataflow.getInternalIdentier())) return false; if (date == null) { if (other.date != null) return false; } else if (!date.equals(other.date)) return false; return true; } public Dataflow getDataflow() { return dataflow; } public void setDataflow(Dataflow dataflow) { this.dataflow = dataflow; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } /** * Returns the monitorViewComponent. * * @return the monitorViewComponent */ public MonitorViewComponent getOrCreateMonitorViewComponent() { if (monitorViewComponent == null) { monitorViewComponent = new PreviousRunsComponent(); monitorViewComponent.setProvenanceConnector(connector); monitorViewComponent.setReferenceService(referenceService); monitorObserver = monitorViewComponent.setDataflow(dataflow); resultsComponent = new ResultViewComponent(); resultsComponent.repopulate(getDataflow(), getRunId(), getDate(), getReferenceService(), isProvenanceEnabledForRun); monitorViewComponent.setStatus(MonitorViewComponent.Status.COMPLETE); // monitorViewComponent.revalidate(); } return monitorViewComponent; } public MonitorViewComponent getMonitorViewComponent() { return monitorViewComponent; } /** * Returns the resultsComponent. * * @return the resultsComponent */ public ResultViewComponent getResultsComponent() { return resultsComponent; } public void setRunId(String runId) { this.runId = runId; } public String getRunId() { return runId; } public void setProvenanceEnabledForRun(boolean isProvenanceEnabledForRun) { this.isProvenanceEnabledForRun = isProvenanceEnabledForRun; } public boolean isProvenanceEnabledForRun() { return isProvenanceEnabledForRun; } public void setDataSavedInDatabase(boolean dataSavedInDatabase) { this.isDataSavedInDatabase = dataSavedInDatabase; } public boolean isDataSavedInDatabase() { return isDataSavedInDatabase; } public void setReferenceService(ReferenceService referenceService) { this.referenceService = referenceService; } public ReferenceService getReferenceService() { return referenceService; } }
package org.unitime.timetable.webutil; import java.awt.Color; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Collections; import java.util.Enumeration; import java.util.Hashtable; import java.util.StringTokenizer; import org.unitime.commons.web.WebTable; import org.unitime.timetable.util.PdfEventHandler; import com.lowagie.text.Chunk; import com.lowagie.text.Document; import com.lowagie.text.Element; import com.lowagie.text.Font; import com.lowagie.text.FontFactory; import com.lowagie.text.Image; import com.lowagie.text.PageSize; import com.lowagie.text.Paragraph; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.PdfPCell; import com.lowagie.text.pdf.PdfPTable; import com.lowagie.text.pdf.PdfWriter; /** * @author Tomas Muller */ public class PdfWebTable extends WebTable { private Hashtable iImages = new Hashtable(); public void addImage(String name, java.awt.Image image) { iImages.put(name, image); } public PdfWebTable(int columns, String name, String[] headers, String[] align, boolean[] asc) { this(columns, name, null, headers, align, asc); } public PdfWebTable(int columns, String name, String ref, String[] headers, String[] align, boolean[] asc) { super(columns, name, ref, headers, align, asc); } private PdfPCell createCell() { PdfPCell cell = new PdfPCell(); cell.setBorderColor(Color.BLACK); cell.setPadding(3); cell.setBorderWidth(0); cell.setVerticalAlignment(Element.ALIGN_TOP); cell.setHorizontalAlignment(Element.ALIGN_CENTER); return cell; } private float addImage(PdfPCell cell, String name) { try { java.awt.Image awtImage = (java.awt.Image)iImages.get(name); if (awtImage==null) return 0; Image img = Image.getInstance(awtImage, Color.WHITE); Chunk ck = new Chunk(img, 0, 0); if (cell.getPhrase()==null) { cell.setPhrase(new Paragraph(ck)); cell.setVerticalAlignment(Element.ALIGN_TOP); cell.setHorizontalAlignment(Element.ALIGN_CENTER); } else { cell.getPhrase().add(ck); } return awtImage.getWidth(null); } catch (Exception e) { return 0; } } public static float getWidth(String text, boolean bold, boolean italic) { Font font = FontFactory.getFont(FontFactory.HELVETICA, 12, (italic&&bold?Font.BOLDITALIC:italic?Font.ITALIC:bold?Font.BOLD:Font.NORMAL)); float width = 0; if (text.indexOf('\n')>=0) { for (StringTokenizer s = new StringTokenizer(text,"\n"); s.hasMoreTokens();) width = Math.max(width,font.getBaseFont().getWidthPoint(s.nextToken(), font.size())); } else width = Math.max(width,font.getBaseFont().getWidthPoint(text, font.size())); return width; } public static float getWidthOfLastLine(String text, boolean bold, boolean italic) { Font font = FontFactory.getFont(FontFactory.HELVETICA, 12, (italic&&bold?Font.BOLDITALIC:italic?Font.ITALIC:bold?Font.BOLD:Font.NORMAL)); float width = 0; if (text.indexOf('\n')>=0) { for (StringTokenizer s = new StringTokenizer(text,"\n"); s.hasMoreTokens();) width = font.getBaseFont().getWidthPoint(s.nextToken(), font.size()); } else width = Math.max(width,font.getBaseFont().getWidthPoint(text, font.size())); return width; } private float addText(PdfPCell cell, String text, boolean bold, boolean italic, boolean underline, Color color, Color bgColor) { Font font = FontFactory.getFont(FontFactory.HELVETICA, 12, (underline?Font.UNDERLINE:0)+(italic&&bold?Font.BOLDITALIC:italic?Font.ITALIC:bold?Font.BOLD:Font.NORMAL), color); Chunk chunk = new Chunk(text,font); if (bgColor!=null) chunk.setBackground(bgColor); if (cell.getPhrase()==null) { cell.setPhrase(new Paragraph(chunk)); cell.setVerticalAlignment(Element.ALIGN_TOP); cell.setHorizontalAlignment(Element.ALIGN_CENTER); } else { cell.getPhrase().add(chunk); } float width = 0; if (text.indexOf('\n')>=0) { for (StringTokenizer s = new StringTokenizer(text,"\n"); s.hasMoreTokens();) width = Math.max(width,font.getBaseFont().getWidthPoint(s.nextToken(), font.size())); } else width = Math.max(width,font.getBaseFont().getWidthPoint(text, font.size())); return width; } private float addText(PdfPCell cell, String text, boolean bold, boolean italic, boolean underline, Color color, boolean borderTop, boolean borderBottom, boolean borderLeft, boolean borderRight, Color borderColor, Color bgColor ) { cell.setBorderWidth(1); if (borderTop) { cell.setBorder(PdfPCell.TOP); if (borderColor==null) cell.setBorderColorTop(Color.BLACK); else cell.setBorderColorTop(borderColor); } if (borderBottom) { cell.setBorder(PdfPCell.BOTTOM); if (borderColor==null) cell.setBorderColorBottom(Color.BLACK); else cell.setBorderColorBottom(borderColor); } if (borderLeft) { cell.setBorder(PdfPCell.LEFT); if (borderColor==null) cell.setBorderColorLeft(Color.BLACK); else cell.setBorderColorLeft(borderColor); } if (borderRight) { cell.setBorder(PdfPCell.RIGHT); if (borderColor==null) cell.setBorderColorRight(Color.BLACK); else cell.setBorderColorRight(borderColor); } return addText(cell, text, bold, italic, underline, color, bgColor); } private float addText(PdfPCell cell, String text, boolean bold, boolean italic, boolean underline, Color color, boolean border, Color borderColor, Color bgColor) { if (border) { cell.setBorderWidth(1); cell.setBorder(PdfPCell.RIGHT | PdfPCell.LEFT | PdfPCell.TOP | PdfPCell.BOTTOM ); if (borderColor==null) cell.setBorderColor(Color.BLACK); else cell.setBorderColor(borderColor); } return addText(cell, text, bold, italic, underline, color, bgColor); } private float addText(PdfPCell cell, String text, boolean bold) { if (text==null) return addText(cell, "", bold, false, false, Color.BLACK, null); if (text.indexOf("@@")<0) return addText(cell, text, bold, false, false, Color.BLACK, null); Color color = Color.BLACK; Color bcolor = Color.BLACK; Color bgColor = null; boolean bd=bold, it=false, un=false; boolean ba=false, bt=false, bb=false, bl=false, br=false; float maxWidth = 0; boolean first = true; for (StringTokenizer s = new StringTokenizer(text,"\n"); s.hasMoreTokens();) { String line = s.nextToken(); float width = 0; int pos = 0; while (true) { int idx = line.indexOf("@@", pos); if (idx<0) { if (ba) { width += addText(cell, (!first && pos==0?"\n":"")+line.substring(pos), bd, it, un, color, true, bcolor, bgColor); } else { if (bt || bb || bl || br) { width += addText(cell, (!first && pos==0?"\n":"")+line.substring(pos), bd, it, un, color, bt, bb, bl, br, bcolor, bgColor); } else width += addText(cell, (!first && pos==0?"\n":"")+line.substring(pos), bd, it, un, color, bgColor); } break; } else { if (ba) { width += addText(cell, (!first && pos==0?"\n":"")+line.substring(pos, idx), bd, it, un, color, true, bcolor, bgColor); } else { if (bt || bb || bl || br) { width += addText(cell, (!first && pos==0?"\n":"")+line.substring(pos, idx), bd, it, un, color, bt, bb, bl, br, bcolor, bgColor); } else width += addText(cell, (!first && pos==0?"\n":"")+line.substring(pos, idx), bd, it, un, color, bgColor); } pos = idx; } pos+=2; //for @@ String cmd = line.substring(pos, line.indexOf(' ',pos)); pos+=cmd.length()+1; if ("BOLD".equals(cmd)) bd=true; if ("END_BOLD".equals(cmd)) bd=false; if ("ITALIC".equals(cmd)) it=true; if ("END_ITALIC".equals(cmd)) it=false; if ("UNDERLINE".equals(cmd)) un=true; if ("END_UNDERLINE".equals(cmd)) un=false; if ("COLOR".equals(cmd)) { String hex = line.substring(pos, line.indexOf(' ',pos)); pos+=hex.length()+1; color = new Color(Integer.parseInt(hex,16)); } if ("END_COLOR".equals(cmd)) { color = Color.BLACK; } if ("BGCOLOR".equals(cmd)) { String hex = line.substring(pos, line.indexOf(' ',pos)); pos+=hex.length()+1; bgColor = new Color(Integer.parseInt(hex,16)); } if ("END_BGCOLOR".equals(cmd)) { bgColor = null; } if ("IMAGE".equals(cmd)) { String name = line.substring(pos, line.indexOf(' ',pos)); pos+=name.length()+1; width += addImage(cell, name); } if ("BORDER_ALL".equals(cmd) || "BORDER_TOP".equals(cmd) || "BORDER_BOTTOM".equals(cmd) || "BORDER_LEFT".equals(cmd) || "BORDER_RIGHT".equals(cmd) ) { String hex = line.substring(pos, line.indexOf(' ',pos)); pos+=hex.length()+1; bcolor = new Color(Integer.parseInt(hex,16)); if ("BORDER_ALL".equals(cmd)) { ba = true; } else { if ("BORDER_TOP".equals(cmd)) { bt = true; } if ("BORDER_BOTTOM".equals(cmd)) { bb = true; } if ("BORDER_LEFT".equals(cmd)) { bl = true; } if ("BORDER_RIGHT".equals(cmd)) { br = true; } } } if ("NO_WRAP".equals(cmd)) { cell.setNoWrap(true); } } maxWidth = Math.max(maxWidth, width); first=false; } return maxWidth; } private float[] widths = null; /** * Prints pdf table. By default does not split table across * page boundaries * @param ordCol * @return */ public PdfPTable printPdfTable(int ordCol) { return printPdfTable(ordCol, false); } /** * Prints pdf table. By default does not split table across * page boundaries * @param ordCol * @param keepTogether true does not split table across pages * @return */ public PdfPTable printPdfTable(int ordCol, boolean keepTogether) { PdfPTable table = new PdfPTable(getNrColumns()); table.setWidthPercentage(100); table.getDefaultCell().setPadding(3); table.getDefaultCell().setBorderWidth(0); table.setSplitRows(false); table.setKeepTogether(keepTogether); boolean asc = (ordCol == 0 || iAsc == null || iAsc.length <= Math.abs(ordCol) - 1 ? true : iAsc[Math.abs(ordCol) - 1]); if (ordCol < 0) asc = !asc; widths = new float[iColumns]; for (int i=0;i<iColumns;i++) widths[i] = 0f; String lastLine[] = new String[Math.max(iColumns,(iHeaders==null?0:iHeaders.length))]; if (iHeaders != null) { for (int i = 0; i < iColumns; i++) { if (isFiltered(i)) continue; PdfPCell c = createCell(); c.setBorderWidthBottom(1); float width = addText(c,iHeaders[i]==null?"":iHeaders[i],true); widths[i] = Math.max(widths[i],width); String align = (iAlign != null ? iAlign[i] : "left"); if ("left".equals(align)) c.setHorizontalAlignment(Element.ALIGN_LEFT); if ("right".equals(align)) c.setHorizontalAlignment(Element.ALIGN_RIGHT); if ("center".equals(align)) c.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(c); } table.setHeaderRows(1); } if (ordCol != 0) { Collections.sort(iLines, new WebTableComparator(Math.abs(ordCol) - 1, asc)); } for (Enumeration el = iLines.elements(); el.hasMoreElements();) { WebTableLine wtline = (WebTableLine) el.nextElement(); String[] line = wtline.getLine(); boolean blank = iBlankWhenSame; for (int i = 0; i < iColumns; i++) { if (isFiltered(i)) continue; if (blank && line[i]!=null && !line[i].equals(lastLine[i])) blank=false; PdfPCell c = createCell(); float width = addText(c,blank || line[i]==null?"":line[i],false); widths[i] = Math.max(widths[i],width); String align = (iAlign != null ? iAlign[i] : "left"); if ("left".equals(align)) c.setHorizontalAlignment(Element.ALIGN_LEFT); if ("right".equals(align)) c.setHorizontalAlignment(Element.ALIGN_RIGHT); if ("center".equals(align)) c.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(c); lastLine[i] = line[i]; } } try { if (getNrFilteredColumns()<0) { table.setWidths(widths); } else { float[] x = new float[getNrColumns()]; int idx = 0; for (int i=0;i<iColumns;i++) { if (isFiltered(i)) continue; x[idx++] = widths[i]; } table.setWidths(x); } } catch (Exception e) { e.printStackTrace(); } return table; } public float getWidth() { float totalWidth = 0f; for (int i=0;i<widths.length;i++) totalWidth += 25f+widths[i]; totalWidth = Math.max(PageSize.LETTER.height(), totalWidth); return totalWidth; } public String getName() { return iName; } public void exportPdf(File file, int ordCol) throws Exception { FileOutputStream out = null; try { PdfPTable table = printPdfTable(ordCol); float width = getWidth(); Document doc = new Document(new Rectangle(60f + width, 60f + 0.75f * width),30,30,30,30); out = new FileOutputStream(file); PdfWriter iWriter = PdfWriter.getInstance(doc, out); iWriter.setPageEvent(new PdfEventHandler()); doc.open(); if (iName!=null) doc.add(new Paragraph(iName, FontFactory.getFont(FontFactory.HELVETICA_BOLD, 16))); doc.add(table); doc.close(); } finally { try { if (out!=null) out.close(); } catch (IOException e) {} } } }
package beast.app.beastapp; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.net.URLDecoder; import javax.swing.JOptionPane; import beast.app.BEASTVersion; import beast.app.util.Utils6; /** * Loads beast.jar and launches BEAST through the BEASTMain class * * This class should be compiled against 1.6 and packaged by itself. The * remainder of BEAST can be compiled against Java 1.8 * **/ public class BeastLauncher { public static void main(String[] args) throws NoSuchMethodException, SecurityException, ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException { if (javaVersionCheck("BEAST")) { loadBEASTJars(); BeastMain.main(args); } } /** * Load jars. The path is relative to the parent directory of the jar * containing this class, taking the lib directory. This is meant only to * load beast.jar and perhaps some other libraries, not all packages. **/ static protected void loadBEASTJars() throws IOException, NoSuchMethodException, SecurityException, ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { BeastLauncher clu = new BeastLauncher(); // first try beast from the package_user_dir/lib/beast.jar String beastUserDir = getPackageUserDir(); String pathDelimiter = isWindows() ? "\\\\" : "/"; beastUserDir += pathDelimiter + "BEAST" + pathDelimiter; String beastJar = beastUserDir + "lib"; boolean foundOne = checkForBEAST(new File(beastJar), clu); String launcherJar = clu.getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); // deal with special characters and spaces in path launcherJar = URLDecoder.decode(launcherJar, "UTF-8"); System.err.println("jardir = " + launcherJar); File jarDir0 = new File(launcherJar).getParentFile(); while ((!foundOne) && (jarDir0 != null)) { // && jarDir0.exists() && // jarDir0.isDirectory()) { foundOne = checkForBEAST(jarDir0, clu); foundOne = foundOne || checkForBEAST((isWindows() ? new File(jarDir0.getAbsolutePath() + "\\lib") : new File(jarDir0.getAbsolutePath() + "/lib")), clu); if (foundOne) { createBeastPackage(jarDir0, pathDelimiter); } jarDir0 = jarDir0.getParentFile(); } if (!foundOne) { System.err.println("WARNING: could not find beast.jar"); // if beast.jar or its classes are not already in the class path (as is when launched e.g. as developer) // the next line will fail } // initialise beast.jar Method method = Class.forName("beast.evolution.alignment.Alignment").getMethod("findDataTypes"); method.invoke(null); } private static void createBeastPackage(File jarDir0, String pathDelimiter) { try { // create package user dir, if it not already exists File dir = new File(getPackageUserDir() + pathDelimiter + "BEAST" + pathDelimiter + "lib"); if (!dir.exists()) { if (!dir.mkdirs()) { // cannot create dir, let alone create a beast package return; } } File beastJar = new File(jarDir0 + pathDelimiter + "lib" + pathDelimiter + "beast.jar"); File target = new File(dir + pathDelimiter + "beast.jar"); copyFileUsingStream(beastJar, target); String version = "<addon name='BEAST' version='" + (new BEASTVersion()).getVersion() + "'>\n" + "</addon>"; FileWriter outfile = new FileWriter(getPackageUserDir() + pathDelimiter + "beast" + pathDelimiter + "version.xml"); outfile.write(version); outfile.close(); File beastSrcJar = new File(jarDir0 + pathDelimiter + "beast.src.jar"); File srcTarget = new File(dir + pathDelimiter + "beast.src.jar"); copyFileUsingStream(beastSrcJar, srcTarget); // TODO: include templates? // if so, how to prevent clashes with templates in package and in installation dir? // TODO: what about examples? } catch (Exception e) { // do net let exceptions hold up launch of beast & friends e.printStackTrace(); } } // copy files using Java 6 code private static void copyFileUsingStream(File source, File dest) throws IOException { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(source); os = new FileOutputStream(dest); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } } finally { is.close(); os.close(); } } private static boolean checkForBEAST(File jarDir, Object clu) throws IOException { System.err.println("Checking out " + jarDir.getAbsolutePath()); boolean foundOne = false; if (jarDir.exists()) { URL url = new URL("file://" + (isWindows() ? "/" : "") + jarDir.getAbsolutePath() + "/beast.jar"); if (new File(jarDir.getAbsoluteFile()+File.separator+"beast.jar").exists()) { URLClassLoader sysLoader = (URLClassLoader) clu.getClass().getClassLoader(); Class<?> sysclass = URLClassLoader.class; try { // Parameters Class<?>[] parameters = new Class[] { URL.class }; Method method = sysclass.getDeclaredMethod("addURL", parameters); method.setAccessible(true); method.invoke(sysLoader, new Object[] { url }); System.err.println("Loaded URL " + url); foundOne = true; } catch (Throwable t) { t.printStackTrace(); throw new IOException("Error, could not add URL to system classloader"); } String classpath = System.getProperty("java.class.path"); String jar = url + ""; classpath += System.getProperty("path.separator") + jar.substring(5); System.setProperty("java.class.path", classpath); } } return foundOne; } static boolean isMac() { return System.getProperty("os.name").toLowerCase().startsWith("mac"); } static boolean isWindows() { return System.getProperty("os.name").toLowerCase().startsWith("windows"); } static boolean isLinux() { return System.getProperty("os.name").toLowerCase().startsWith("linux"); } /** make sure we run Java version 8 or better **/ static protected boolean javaVersionCheck(String app) { String javaVersion = System.getProperty("java.version"); // javaVersion should be something like "1.7.0_25" String[] version = javaVersion.split("\\."); if (version.length > 2) { try { int majorVersion = Integer.parseInt(version[1]); if (majorVersion <= 7) { String JAVA_VERSION_MSG = "<html>" + app + " requires Java version 8,<br>" + "but the current version is " + majorVersion + ".<br><br>" + "You can get Java from <a href='https: + "Continuing, but expect the unexpected.</html>"; if (!java.awt.GraphicsEnvironment.isHeadless()) { JOptionPane.showMessageDialog(null, JAVA_VERSION_MSG); } else { JAVA_VERSION_MSG = JAVA_VERSION_MSG.replaceAll("<br>", "\n"); JAVA_VERSION_MSG = JAVA_VERSION_MSG.replaceAll("<[^<]*>", ""); System.err.println(JAVA_VERSION_MSG); } return true; } } catch (NumberFormatException e) { // We only get here if the JVM does not return the expected // string format when asked for java.version. // hope for the best } return true; } // We only get here if the JVM does not return the expected // string format when asked for java.version. // hope for the best return true; } public static String getPackageUserDir() { if (System.getProperty("beast.user.package.dir") != null) return System.getProperty("beast.user.package.dir"); if (Utils6.isWindows()) { return System.getProperty("user.home") + "\\BEAST\\" + (new BEASTVersion()).getMajorVersion(); } if (Utils6.isMac()) { return System.getProperty("user.home") + "/Library/Application Support/BEAST/" + (new BEASTVersion()).getMajorVersion(); } // Linux and unices return System.getProperty("user.home") + "/.beast/" + (new BEASTVersion()).getMajorVersion(); } }
package com.uvg.expo.login; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.uvg.expo.Global; import com.uvg.expo.R; import com.uvg.expo.map.RenderCreation; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import cz.msebera.android.httpclient.Header; import cz.msebera.android.httpclient.entity.StringEntity; public class Registrar extends AppCompatActivity implements View.OnClickListener{ EditText email,pass; EditText nomcom,genero; Button btn_reg; //se llama a la base de datos para registrar al usuario private FirebaseAuth auth; private FirebaseAuth.AuthStateListener authListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registrar); btn_reg = (Button)findViewById(R.id.btn_reg); //edit texts email = (EditText)findViewById(R.id.email); pass = (EditText)findViewById(R.id.pass); nomcom = (EditText)findViewById(R.id.nomcom); genero = (EditText)findViewById(R.id.genero); btn_reg.setOnClickListener(this); //se llama a una instancia de firebase auth = FirebaseAuth.getInstance(); authListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); } }; } //Cuando pulse el boton se registrara el usuario @Override public void onClick(View view) { if(view.getId() == R.id.btn_reg){ String emails = email.getText().toString().trim(); String password = pass.getText().toString().trim(); if (TextUtils.isEmpty(emails)) { Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show(); return; } if (TextUtils.isEmpty(password)) { Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show(); return; } if (password.length() < 6) { Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters!", Toast.LENGTH_SHORT).show(); return; } auth.createUserWithEmailAndPassword(emails, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { // If sign in fails, display a message to the user. If sign in succeeds // the auth state listener will be notified and logic to handle the // signed in user can be handled in the listener. if (!task.isSuccessful()) { Toast.makeText(Registrar.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(Registrar.this, "Se ha registrado!", Toast.LENGTH_SHORT).show(); JSONObject jsonParams = new JSONObject(); AsyncHttpClient client2 = new AsyncHttpClient(); try { jsonParams.put("UserName", nomcom.getText().toString()); jsonParams.put("Email", email.getText().toString()); jsonParams.put("Password", ""); } catch (JSONException e) { e.printStackTrace(); } StringEntity entity = null; try { entity = new StringEntity(jsonParams.toString()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String restApiUrl = "https://experiencia-uvg.azurewebsites.net:443/api/GameUsersApi"; client2.post(getApplicationContext(), restApiUrl, entity, "application/json", new JsonHttpResponseHandler(){ @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { // Root JSON in response is an dictionary i.e { "data : [ ... ] } // Handle resulting parsed JSON response here JSONObject respuesta = response; Log.d("Json",respuesta.toString()); try { String id = respuesta.getString("ID"); Global.setUserId(id); String name = respuesta.getString("username"); Global.setUserName(name); startActivity(new Intent(Registrar.this,RenderCreation.class)); } catch (JSONException e) { //onFailure(statusCode, headers, e, (JSONObject)null); e.printStackTrace(); } } }); } } }); } } @Override public void onStart() { super.onStart(); auth.addAuthStateListener(authListener); } @Override public void onStop() { super.onStop(); if (authListener != null) { auth.removeAuthStateListener(authListener); } } }
package ar.com.ada3d.controller; import java.util.ArrayList; import java.util.Calendar; import java.math.*; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.io.Serializable; import javax.faces.model.SelectItem; import org.openntf.domino.Document; import org.openntf.domino.Session; import ar.com.ada3d.model.Edificio; import ar.com.ada3d.model.Porcentual; import ar.com.ada3d.model.Prorrateo; import ar.com.ada3d.utilidades.*; import lotus.domino.NotesException; import ar.com.ada3d.connect.QueryAS400; import ar.com.ada3d.utilidades.DocUsr; import java.math.BigDecimal; import java.util.*; /* * Cuando hablo de edificios son todos los de la administracion. * Cuando hablo de MyEdificios son los edificios que puede ver el usuario. * Cuando hablo de MyEdificiosTrabajo son para trabajar el usuario es decir que no estan bloqueados * Tomo la scope de usuario para los edificios autorizados por usuario * */ public class EdificioBean implements Serializable { public EdificioBean() { //System.out.println("FPR - Constr. Edificios y llamada AS400"); AddEdificiosAs400(); } private Edificio edificio; private static final long serialVersionUID = 1L; HashMap<String, Edificio> hmEdificios = new HashMap<String, Edificio>(); private static List<Edificio> listaEdificios; private static List<Edificio> listaEdificiosTrabajo; private boolean isMasivoActualizado = false; /** * Esto devuelve para cada usuario el ComboBox de Edificios autorizados para * trabajar * @return: etiqueta y valor para xp:comboBox * @usedIn: Combo principal en ccLayoutBootstrap, est asociado a una * sessionScope(edificioSelected) */ public List<SelectItem> getComboboxMyEdificios() { DocUsr docUsuario = (DocUsr) JSFUtil.resolveVariable("DocUsr"); List<SelectItem> options = new ArrayList<SelectItem>(); for (Edificio miEdificio : listaEdificios) { if (!docUsuario.getEdificiosNoAccessLista().contains( miEdificio.getEdf_codigo())) { // Solo edificios autorizados SelectItem option = new SelectItem(); option .setLabel(miEdificio.getEdf_codigoVisual().equals("") ? miEdificio .getEdf_codigo() : miEdificio.getEdf_codigoVisual() + " " + miEdificio.getEdf_direccion() + " " + ar.com.ada3d.utilidades.Conversores.DateToString(miEdificio.getEdf_fechaUltimaLiquidacion(), "dd/MM/yyyy" )); option.setValue(miEdificio.getEdf_codigo()); options.add(option); } } return options; } /** * Esto devuelve para cada usuario el ComboBox de Edificios autorizados para * trabajar y en estadoProceso=1 * @return etiqueta y valor para xp:comboBox * @usedIn layout tiene una propiedad para mostrar o no en cada XPage */ public static List<SelectItem> getComboboxMyEdificiosTrabajo() { DocUsr docUsuario = (DocUsr) JSFUtil.resolveVariable("DocUsr"); List<SelectItem> options = new ArrayList<SelectItem>(); for (Edificio miEdificio : listaEdificios) { if (miEdificio.getEdf_estadoProceso().equals("1")) { // solo // estado=1 if (!docUsuario.getEdificiosNoAccessLista().contains( miEdificio.getEdf_codigo())) { // Solo edificios // autorizados SelectItem option = new SelectItem(); option.setLabel(miEdificio.getEdf_direccion()); option.setValue(miEdificio.getEdf_codigo()); options.add(option); } } } return options; } /** * Devuelve un string con la lista de edificios * @param verdadero devuelve solo los que trabaja el usuario, sino todos * @return un string con la lista de edificios * @usedin frmConfigUsr para traer la lista de edificios autorizados para el usuario * @usedin typeAhead de edificios * */ public ArrayList<String> getArraySrtringListaEdificios(boolean prm_isDeTrabajo) { ArrayList<String> result = new ArrayList<String>(); List<Edificio> lista = prm_isDeTrabajo ? listaEdificiosTrabajo : listaEdificios; for (Edificio miEdificio : lista) { result.add(miEdificio.getEdf_direccion() + "|" + miEdificio.getEdf_codigo()); } return result; } /** * Agrego edificios de a uno al hashMap * @param objeto Edificio */ private void AddEdificioMap(Edificio prmEdificio) { hmEdificios.put(prmEdificio.getEdf_codigo(), prmEdificio); } /** * Obtengo un edificio por el codigo SASA * @param texto con el codigo de edificio * @return un objeto Edificio o nulo */ public Edificio getEdificioMap(String prmCodigoEdificio) { if (hmEdificios.containsKey(prmCodigoEdificio)) { return hmEdificios.get(prmCodigoEdificio); } return null; } /** * Agrego Edificios consultando As400, cada linea separa el dato por un pipe */ private void AddEdificiosAs400() { DocUsr docUsuario = (DocUsr) JSFUtil.resolveVariable("DocUsr"); if (!(listaEdificios == null)){ listaEdificios.clear(); listaEdificiosTrabajo.clear(); hmEdificios.clear(); } QueryAS400 query = new ar.com.ada3d.connect.QueryAS400(); ArrayList<String> nl = null; Edificio myEdificio = null; try { nl = query.getSelectAS("controllerEdificios", null, false); } catch (NotesException e) { e.printStackTrace(); } for (String strLinea : nl) { if (listaEdificios == null) { listaEdificios = new ArrayList<Edificio>(); } if (listaEdificiosTrabajo == null) { listaEdificiosTrabajo = new ArrayList<Edificio>(); } myEdificio = actualizoUnEdificioAs400( myEdificio, strLinea); listaEdificios.add(myEdificio); if(!docUsuario.getEdificiosNoAccessLista().contains(strLinea.split("\\|")[0].trim())){ listaEdificiosTrabajo.add(myEdificio); } AddEdificioMap(myEdificio); // Lo agrego al mapa por cdigo } } private List<SelectItem> opcionesDiaCuotaFija(Calendar cal){ List<SelectItem> options = new ArrayList<SelectItem>(); SelectItem optionMesLiquedacion = new SelectItem(); optionMesLiquedacion.setLabel(ar.com.ada3d.utilidades.Conversores.DateToString(cal.getTime(), "dd/MM/yyyy")); optionMesLiquedacion.setValue("N"); options.add(optionMesLiquedacion); cal.add(Calendar.DATE, 1); SelectItem optionMesSiguiente = new SelectItem(); optionMesSiguiente.setLabel(ar.com.ada3d.utilidades.Conversores.DateToString(cal.getTime(), "dd/MM/yyyy")); optionMesSiguiente.setValue("B"); options.add(optionMesSiguiente); return options; } /** * Al cargar un edificio en la misma consulta al AS400 tambien cargo los datos de prorrateo * @param strLinea de AS400 que estoy procesando * @param tipo de prorrateo del edificio * @return la lista de prorrateos */ private List<Prorrateo> cargaProrrateoEdificio(String strLinea, String strTipo){ Prorrateo myProrrateo; List<Prorrateo> listaProrrateosEdificio = new ArrayList<Prorrateo>(); int posicionPorcentaje = 5; int posicionCuotaFija = 9; int tempPorcentaje = 0; int tempPosicionEnGrilla = 0; String strValorCuotaFija; for(int i=1; i<5; i++){ //Son 4 porcentuales por ahora //variables que recorren 4 valores a prorratear posicionPorcentaje = posicionPorcentaje + 1; posicionCuotaFija = posicionCuotaFija + 1; //Define si se crea o no el objeto Prorrateo tempPorcentaje = Integer.parseInt(strLinea.split("\\|")[posicionPorcentaje].trim()); if(tempPorcentaje != 0){ myProrrateo = new Prorrateo(); myProrrateo.setPrt_posicion(i); myProrrateo.setPrt_posicionEnGrilla(tempPosicionEnGrilla); tempPosicionEnGrilla = tempPosicionEnGrilla + 1; myProrrateo.setPrt_titulo("Porcentual myProrrateo.setPrt_porcentaje(tempPorcentaje); //valor que va a tener la cuota fija o el presupuesto strValorCuotaFija = strLinea.split("\\|")[posicionCuotaFija].trim(); //Defino el tipo individual de prorrateo, pero si el valor es 0 es gasto if (strValorCuotaFija.equals("0")){ myProrrateo.setPrt_tipo("G"); }else if (strTipo.equals("P")){ myProrrateo.setPrt_tipo("P"); myProrrateo.setPrt_importe(new BigDecimal(ar.com.ada3d.utilidades.Conversores.stringToStringDecimal(strValorCuotaFija, Locale.UK, 2))); }else if(strTipo.equals("C")){ myProrrateo.setPrt_tipo("C"); myProrrateo.setPrt_importe(new BigDecimal(ar.com.ada3d.utilidades.Conversores.stringToStringDecimal(strValorCuotaFija, Locale.UK, 2))); }else{ myProrrateo.setPrt_tipo("G"); } listaProrrateosEdificio.add(myProrrateo); } } return listaProrrateosEdificio; } /** * Al cargar un edificio en la misma consulta al AS400 tambien cargo los datos de porcentuales * @param strLinea de AS400 que estoy procesando * @return lista con porcentuales */ private List<Porcentual> cargaPorcentualEdificio(String strLinea){ Porcentual myPorcentual; List<Porcentual> listaPorcentualesEdificio = new ArrayList<Porcentual>(); int posicionPorcentaje = 6; int posicionHonorarios = 22; int posicionEnGrilla = 0; for(int i=1; i<5; i++){ //Son 4 porcentuales por ahora myPorcentual = new Porcentual(); myPorcentual.setPorc_posicion(i); myPorcentual.setPorc_titulo("Honorarios % " + i); myPorcentual.setPorc_porcentaje(Integer.parseInt(strLinea.split("\\|")[posicionPorcentaje].trim())); myPorcentual.setPorc_importeHonorarios(new BigDecimal(ar.com.ada3d.utilidades.Conversores.stringToStringDecimal(strLinea.split("\\|")[posicionHonorarios].trim(), Locale.UK, 2))); posicionPorcentaje = posicionPorcentaje + 1; posicionHonorarios = posicionHonorarios + 1; posicionEnGrilla = posicionEnGrilla + 1; listaPorcentualesEdificio.add(myPorcentual); } return listaPorcentualesEdificio; } /** * Prorrateo: Oculta o visualiza otros campos al cambiar la opcin * @param El edificio que estoy modificando * @param La posicin que estoy modificando en la XPage (es un repeat) * @usedIn: en el combo de valores a prorratear */ public String onChangeProrrateos(Edificio prm_edificio, Integer prm_idxRptProrrateoTipo){ BigDecimal tempSumatoriaImportes = new BigDecimal(0); ArrayList<String> tempArrayCuotaFijaDia = new ArrayList<String>(); String tempCuotaFijaDia = ""; for(Prorrateo myProrrateo : prm_edificio.getListaProrrateos()){ tempArrayCuotaFijaDia.add(myProrrateo.getPrt_tipo()); if (prm_idxRptProrrateoTipo.equals(myProrrateo.getPrt_posicionEnGrilla())){ //Solo modifico la linea del repeat que ha cambiado if (myProrrateo.getPrt_tipo().equals("G")){ myProrrateo.setPrt_importe(null); }else{//CUOTA FIJA o Presupuesto if(myProrrateo.getPrt_importe() == null){ myProrrateo.setPrt_importe(new BigDecimal(1)); } if (myProrrateo.getPrt_tipo().equals("C")){ //CF cargo el combo prm_edificio.setEdf_cuotaFijaDiaOpcionesCombo(opcionesDiaCuotaFija(ar.com.ada3d.utilidades.Conversores.dateToCalendar(prm_edificio.getEdf_fechaProximaLiquidacion()))); tempCuotaFijaDia = "B"; }else{ tempCuotaFijaDia = "P"; } } } //Hago una sumatoria si da cero tengo que enviar un * if(myProrrateo.getPrt_tipo().equals("G")){ tempSumatoriaImportes = tempSumatoriaImportes.add(new BigDecimal(0)); }else{ tempSumatoriaImportes = tempSumatoriaImportes.add(myProrrateo.getPrt_importe()); } } //Al final chequeo todo antes de confirmar la cuotaFijaDia if(tempSumatoriaImportes.equals(new BigDecimal(0))){ //Son todos gastos prm_edificio.setEdf_cuotaFijaDia("*"); }else{ if(tempCuotaFijaDia.equals("P")){//Chequeo si cambio realmente a P if(tempArrayCuotaFijaDia.contains("C") || tempArrayCuotaFijaDia.contains("B")){ return "prt_tipo~No puede seleccionar PRESUPUESTO si existe una CUOTA FIJA."; }else{ prm_edificio.setEdf_cuotaFijaDia("P"); } }else if(tempCuotaFijaDia.equals("C") || tempCuotaFijaDia.equals("B")){//Chequeo si cambio realmente a C if(tempArrayCuotaFijaDia.contains("P")){ return "prt_tipo~No puede seleccionar CUOTA FIJA si existe un PRESUPUESTO ."; }else{ prm_edificio.setEdf_cuotaFijaDia(tempCuotaFijaDia); } }else if(tempCuotaFijaDia.equals("*")){//Chequeo si cambio realmente a * if(tempArrayCuotaFijaDia.contains("P") || tempArrayCuotaFijaDia.contains("C") || tempArrayCuotaFijaDia.contains("B")){ prm_edificio.setEdf_cuotaFijaDia(tempCuotaFijaDia); } } } return ""; } /** * Modifica los siguientes datos: * -Fecha prxima liquidacion * -Mes de prorrateo y recibos (solo si es cuota fija) * -Fecha 1er vto en recibos * -Fecha 2do vto en recibos * @param El edificio que estoy modificando * @usedIn Slider de frecuencia */ @SuppressWarnings("static-access") public void onClickFrecuencia(Edificio prm_edificio){ Calendar cal = Calendar.getInstance(); cal.setTime(prm_edificio.getEdf_fechaUltimaLiquidacion()); cal.add(Calendar.MONTH, prm_edificio.getEdf_frecuenciaLiquidacion()); cal.set(cal.DATE, cal.getActualMaximum(cal.DAY_OF_MONTH)); prm_edificio.setEdf_fechaProximaLiquidacion(cal.getTime()); if(prm_edificio.getEdf_cuotaFijaDia().equals("N") || prm_edificio.getEdf_cuotaFijaDia().equals("B")){ prm_edificio.setEdf_cuotaFijaDiaOpcionesCombo(opcionesDiaCuotaFija(ar.com.ada3d.utilidades.Conversores.dateToCalendar(prm_edificio.getEdf_fechaProximaLiquidacion()))); } /* cal.setTime(sessionScope.edfObj.edf_fechaPrimerVencimientoRecibos) cal.add(java.util.Calendar.MONTH, frecuencia); sessionScope.edfObj.edf_fechaPrimerVencimientoRecibos = cal.getTime(); */ } /** * Actualizo solo el edificio recibido * @usedIn: Es una clase privada solo se usa aca * @Param objeto Edificio por actualizar * @Param strLinea leida del AS, solo con datos si es un nuevo el objeto. (blanco si es una actualizacin) * @return objeto Edificio */ @SuppressWarnings("static-access") private Edificio actualizoUnEdificioAs400(Edificio myEdificio, String strLinea) { DocLock lockeos = (DocLock) JSFUtil.resolveVariable("DocLock"); if(!strLinea.equals("")){ myEdificio = new Edificio(); myEdificio.setEdf_codigo(strLinea.split("\\|")[0].trim()); }else{ //Es una actualizacion Document docDummy = JSFUtil.getDocDummy(); docDummy.appendItemValue("Codigo", myEdificio.getEdf_codigo()); QueryAS400 query = new ar.com.ada3d.connect.QueryAS400(); ArrayList<String> nl = null; try { nl = query.getSelectAS("controllerUnEdificio", docDummy, false); } catch (NotesException e) { e.printStackTrace(); } strLinea = nl.get(0); } //Agrego el usuario si el edificio est lockeado if(lockeos.isLocked("edf_" + myEdificio.getEdf_codigo())) myEdificio.setEdf_lockedBy(lockeos.getLock("edf_" + myEdificio.getEdf_codigo())); myEdificio.setEdf_codigoVisual(strLinea.split("\\|")[1].trim()); String tempDireccionLocalidad = strLinea.split("\\|")[2].trim(); if(!tempDireccionLocalidad.contains("-")){ throw new java.lang.Error("La direccion del edificio " + myEdificio.getEdf_codigo() + " no tiene un guin."); //throw new java.lang.RuntimeException("La direccion del edificio " + myEdificio.getEdf_codigo() + " no tiene un guin."); } myEdificio.setEdf_direccion(strLinea.split("\\|")[2].trim().split("-")[0]); myEdificio.setEdf_localidad(strLinea.split("\\|")[2].trim().split("-")[1]); myEdificio.setEdf_estadoProceso(strLinea.split("\\|")[3].trim()); myEdificio.setEdf_fechaUltimaLiquidacion(ar.com.ada3d.utilidades.Conversores.StringToDate("ddMMyy", strLinea.split("\\|")[4].trim())); myEdificio.setEdf_frecuenciaLiquidacion (Integer.parseInt(strLinea.split("\\|")[5].trim())); Calendar cal = Calendar.getInstance(); cal.setTime(myEdificio.getEdf_fechaUltimaLiquidacion()); cal.add(Calendar.MONTH, myEdificio.getEdf_frecuenciaLiquidacion()); cal.set(cal.DATE, cal.getActualMaximum(cal.DAY_OF_MONTH)); myEdificio.setEdf_fechaProximaLiquidacion(cal.getTime()); //Defino el tipo de prorrateo String strTipo = strLinea.split("\\|")[14].trim(); String strTempTipo; if(strTipo.equals("") || strTipo.equals("N")){ strTempTipo = "C"; }else if (strTipo.equals("P")){//Presupuesto strTempTipo = "P"; }else{ strTempTipo = "G"; } myEdificio.setListaProrrateos(cargaProrrateoEdificio(strLinea, strTempTipo)); //Creo el combo de fecha prorrateo si es cuota fija if(strTipo.equals("") || strTipo.equals("N")){ //blanco puede ser por gastos for(Prorrateo myProrrateo : myEdificio.getListaProrrateos()){ if(myProrrateo.getPrt_tipo().equals("C")){ List<SelectItem> options = new ArrayList<SelectItem>(); SelectItem optionMesLiquedacion = new SelectItem(); optionMesLiquedacion.setLabel(ar.com.ada3d.utilidades.Conversores.DateToString(cal.getTime(), "dd/MM/yyyy")); optionMesLiquedacion.setValue("N"); options.add(optionMesLiquedacion); if(strTipo.equals("")){//CF y fecha prorrateo le agrego 1 dia para que sea el dia 1 del mes siguiente cal.add(Calendar.DATE, 1); myEdificio.setEdf_cuotaFijaDia("B"); }else{//CF y fecha prorrateo dem liquidacin myEdificio.setEdf_cuotaFijaDia("N"); cal.add(Calendar.DATE, 1); } SelectItem optionMesSiguiente = new SelectItem(); optionMesSiguiente.setLabel(ar.com.ada3d.utilidades.Conversores.DateToString(cal.getTime(), "dd/MM/yyyy")); optionMesSiguiente.setValue("B"); options.add(optionMesSiguiente); myEdificio.setEdf_cuotaFijaDiaOpcionesCombo(options); break; } } } myEdificio.setEdf_importeInteresPunitorioDeudores( new BigDecimal(ar.com.ada3d.utilidades.Conversores.stringToStringDecimal(strLinea.split("\\|")[15].trim(), Locale.US, 1))); myEdificio.setEdf_importeRecargoSegundoVencimiento( new BigDecimal(ar.com.ada3d.utilidades.Conversores.stringToStringDecimal(strLinea.split("\\|")[16].trim(), Locale.UK, 1))); myEdificio.setEdf_fechaPrimerVencimientoRecibos(ar.com.ada3d.utilidades.Conversores.StringToDate("ddMMyy", strLinea.split("\\|")[17].trim())); myEdificio.setEdf_fechaSegundoVencimientoRecibos(ar.com.ada3d.utilidades.Conversores.StringToDate("ddMMyy", strLinea.split("\\|")[18].trim())); myEdificio.setEdf_modalidadInteresesPunitorios(strLinea.split("\\|")[19].trim()); myEdificio.setEdf_cuit(strLinea.split("\\|")[20].trim()); myEdificio.setEdf_imprimeTitulosEnLiquidacion(strLinea.split("\\|")[21].trim().equals("1") ? "1":"0"); //Voy a cargar todos los porcentuales, los utilizados y los no utilizados myEdificio.setListaPorcentuales(cargaPorcentualEdificio(strLinea)); //TODO: falta saber que campo tomar del AS400 myEdificio.setEdf_importeFranqueo( new BigDecimal(ar.com.ada3d.utilidades.Conversores.stringToStringDecimal(strLinea.split("\\|")[15].trim(), Locale.US, 2))); myEdificio.setEdf_importeMultaDeudores( new BigDecimal(ar.com.ada3d.utilidades.Conversores.stringToStringDecimal(strLinea.split("\\|")[15].trim(), Locale.US, 2))); myEdificio.setEdf_isReadMode(true); return myEdificio; } /** * Funcion en el boton editar * Actualizo solo el edificio que voy a modificar y lockea el edificio * @usedIn: Boton edit edificio */ public void editEdificio(Edificio prm_edificio) { actualizoUnEdificioAs400(prm_edificio, ""); Session session = JSFUtil.getSession(); DocLock lock = (DocLock) JSFUtil.resolveVariable("DocLock"); if (lock.isLocked("edf_" + prm_edificio.getEdf_codigo())){ if (!lock.getLock("edf_" + prm_edificio.getEdf_codigo()).equals(session.getEffectiveUserName())) return; } lock.addLock("edf_" + prm_edificio.getEdf_codigo(), session.getEffectiveUserName()); prm_edificio.setEdf_isReadMode(false); prm_edificio.setEdf_lockedBy(session.getEffectiveUserName()); } /** * Update de tablas AS400 con los datos del edificio */ public void saveEdificio(Edificio prm_edificio) { Document docDummy = JSFUtil.getDocDummy(); docDummy.appendItemValue("Codigo", prm_edificio.getEdf_codigo()); docDummy.appendItemValue("DIRECC", prm_edificio.getEdf_direccion() + "-" + prm_edificio.getEdf_localidad()); docDummy.appendItemValue("CodigoVisual", prm_edificio.getEdf_codigoVisual()); docDummy.appendItemValue("frecuencia", prm_edificio.getEdf_frecuenciaLiquidacion()); docDummy.appendItemValue("imprimirTitulos", prm_edificio.getEdf_imprimeTitulosEnLiquidacion()); docDummy.appendItemValue("CTFJ1", "0"); docDummy.appendItemValue("CTFJ2", "0"); docDummy.appendItemValue("CTFJ3", "0"); docDummy.appendItemValue("CTFJ4", "0"); docDummy.appendItemValue("E12", ar.com.ada3d.utilidades.Conversores.bigDecimalToAS400(prm_edificio.getEdf_importeInteresPunitorioDeudores(),1)); docDummy.appendItemValue("E08A", ar.com.ada3d.utilidades.Conversores.bigDecimalToAS400(prm_edificio.getEdf_importeRecargoSegundoVencimiento(),1)); docDummy.appendItemValue("VTOEX1", ar.com.ada3d.utilidades.Conversores.DateToString(prm_edificio.getEdf_fechaPrimerVencimientoRecibos(), "ddMMyy")); docDummy.appendItemValue("VTOEX2", ar.com.ada3d.utilidades.Conversores.DateToString(prm_edificio.getEdf_fechaSegundoVencimientoRecibos(), "ddMMyy")); //Recorro los prorrateos para cargar Cuota Fija o Presupuesto for(Prorrateo myProrrateo: prm_edificio.getListaProrrateos()){ if (myProrrateo.getPrt_importe() != null){ docDummy.replaceItemValue("CTFJ" + myProrrateo.getPrt_posicion(), ar.com.ada3d.utilidades.Conversores.bigDecimalToAS400(myProrrateo.getPrt_importe(), 2)); } } //Estado blanco de AS400 yo lo tengo como B. Se reemplaza docDummy.appendItemValue("ESTADO2", prm_edificio.getEdf_cuotaFijaDia().equals("B")? "" : prm_edificio.getEdf_cuotaFijaDia()); docDummy.appendItemValue("E13A", prm_edificio.getEdf_modalidadInteresesPunitorios()); for (Porcentual myPorcentual : prm_edificio.getListaPorcentuales()){ switch (myPorcentual.getPorc_posicion()){ case 1: docDummy.replaceItemValue("E391", ar.com.ada3d.utilidades.Conversores.bigDecimalToAS400(myPorcentual.getPorc_importeHonorarios(), 2)); break; case 2: docDummy.replaceItemValue("E392", ar.com.ada3d.utilidades.Conversores.bigDecimalToAS400(myPorcentual.getPorc_importeHonorarios(), 2)); break; case 3: docDummy.replaceItemValue("E441", ar.com.ada3d.utilidades.Conversores.bigDecimalToAS400(myPorcentual.getPorc_importeHonorarios(), 2)); break; case 4: docDummy.replaceItemValue("E442", ar.com.ada3d.utilidades.Conversores.bigDecimalToAS400(myPorcentual.getPorc_importeHonorarios(), 2)); break; } } QueryAS400 query = new QueryAS400(); if (query.updateAS("updateEdificiosPH_E01", docDummy)) { if (!query.updateAS("updateEdificiosValoresCTFJ", docDummy)) { if (!query.updateAS("updateEdificiosValoresCTFJ_insert", docDummy)) throw new java.lang.Error("No se pudo actualizar la tabla PH_CTFJ."); } if (!query.updateAS("updateEdificiosDIFED", docDummy)) { throw new java.lang.Error("No se pudo actualizar la tabla PH_DIFED."); } }else{ throw new java.lang.Error("No se pudo actualizar la tabla PH_E01."); } DocLock lock = (DocLock) JSFUtil.resolveVariable("DocLock"); lock.removeLock("edf_" + prm_edificio.getEdf_codigo()); } /** * Chequea los datos del edificio recibido por parmetros antes de guardarlos * @usedIn: Boton save edificio * @return: un texto con: idComponente con error ~ Mensaje a Mostrar en pantalla */ public ArrayList<String> strValidacionEdificio(Edificio prm_edificio){ /*FacesMessage message = new FacesMessage("No es vlido"); // Throw exception so that it prevents document from being saved throw new ValidatorException(message); */ ArrayList<String> listAcumulaErrores = new ArrayList<String>(); String strTemp = ""; /*INI - Codigo Visual(reemplazo) * - la consulta debe ser por SQL * - Puede ser = al codigo del edificio actual * - No puede ser = a un codigo visual existente * - No puede ser = a un codigo sasa que no sea el que estoy */ QueryAS400 query = new QueryAS400(); try { Document docDummy = JSFUtil.getDocDummy(); docDummy.appendItemValue("CodigoVisual", prm_edificio.getEdf_codigoVisual()); ArrayList<String> nl = query.getSelectAS("edificiosValidacionCodigoReemplazo", docDummy, false); for (String strLinea : nl) { if(!strLinea.split("\\|")[0].trim().equals(prm_edificio.getEdf_codigo())){ listAcumulaErrores.add("edf_codigoVisual~Cdigo de reemplazo duplicado." + " El cdigo " + prm_edificio.getEdf_codigoVisual() + " est siendo utilizado en otro edificio."); } } } catch (NotesException e) { e.printStackTrace(); } //FIN - Codigo Visual(reemplazo) //La direccion + localidad max. 27 long. strTemp = prm_edificio.getEdf_direccion() + "-" + prm_edificio.getEdf_localidad(); if(strTemp.length() > 27){ listAcumulaErrores.add("edf_direccion~El domicilio con la localidad, no deben superar los 26 caracteres."); listAcumulaErrores.add("edf_localidad~Los siguientes caracteres exceden el largo permitido: " + strTemp.substring(0, 27) + " --> " + strTemp.substring(27)); } //Prorrateos ArrayList<String> tempArrayCuotaFijaDia = new ArrayList<String>(); for(Prorrateo myProrrateo : prm_edificio.getListaProrrateos()){ tempArrayCuotaFijaDia.add(myProrrateo.getPrt_tipo()); } String tempCuotaFijaDia = prm_edificio.getEdf_cuotaFijaDia(); if(tempCuotaFijaDia.equals("P")){//Chequeo si cambio realmente a P if(tempArrayCuotaFijaDia.contains("C") || tempArrayCuotaFijaDia.contains("B")){ listAcumulaErrores.add("prt_tipo~No puede seleccionar PRESUPUESTO si existe una CUOTA FIJA."); } }else if(tempCuotaFijaDia.equals("C") || tempCuotaFijaDia.equals("B")){//Chequeo si cambio realmente a C if(tempArrayCuotaFijaDia.contains("P")){ listAcumulaErrores.add("prt_tipo~No puede seleccionar CUOTA FIJA si existe un PRESUPUESTO ."); } } //El ttulo de cada valor a prorratear max. 11 long. //Fecha primer y segundo vencimiento if(prm_edificio.getEdf_importeInteresPunitorioDeudores().compareTo(BigDecimal.ZERO) > 0){ Calendar calMin = Calendar.getInstance(); calMin.setTime(prm_edificio.getEdf_fechaProximaLiquidacion()); calMin.add(Calendar.DATE, 1); Calendar calNew = Calendar.getInstance(); calNew.setTime(prm_edificio.getEdf_fechaPrimerVencimientoRecibos()); if (calNew.before(calMin)) { listAcumulaErrores.add("edf_fechaPrimerVencimientoRecibos~La fecha de primer vto. no puede ser menor a " + ar.com.ada3d.utilidades.Conversores.DateToString(calMin.getTime(), "dd/MM/yyyy" )); } if(prm_edificio.getEdf_importeRecargoSegundoVencimiento().compareTo(BigDecimal.ZERO) > 0){ calMin.setTime(prm_edificio.getEdf_fechaPrimerVencimientoRecibos()); calMin.add(Calendar.DATE, 1); calNew.setTime(prm_edificio.getEdf_fechaSegundoVencimientoRecibos()); if (calNew.before(calMin)) { listAcumulaErrores.add("edf_fechaSegundoVencimientoRecibos~La fecha de 2 vto. debe ser mayor al 1 vto "); } } } return listAcumulaErrores; } /** * Validacin cuando se modifica de forma masiva los edificios. * Los edificios modificados van a ser loqueados * Fechas de Vto e Intereses * @usedIn: Boton btnAplicarMasivo en el formulario de Modificacion Automtica * @return: un texto con: idComponente con error ~ Mensaje a Mostrar en pantalla */ public ArrayList<String> strValidacionMasivoEdificios(String prm_campo, Object prm_valor){ ArrayList<String> listAcumulaErrores = new ArrayList<String>(); DocLock lock = (DocLock) JSFUtil.resolveVariable("DocLock"); String strUsuario = JSFUtil.getSession().getEffectiveUserName(); if(prm_valor instanceof String){ if(prm_valor.equals("") || prm_valor.equals("0")) listAcumulaErrores.add(prm_campo + "~Debe ingresar un valor."); }else if(prm_valor instanceof Double || prm_valor instanceof Long){ //Validacion de ambos campos de Intereses BigDecimal valor = new BigDecimal(prm_valor.toString()); if(valor.compareTo(new BigDecimal(9999)) == 1){ listAcumulaErrores.add(prm_campo + "~El % de inters no puede superar el 9999 %" ); return listAcumulaErrores; } valor = valor.setScale(1, RoundingMode.HALF_EVEN);//redondeo si puso mas de 1 decimal for(Edificio myEdificio : listaEdificiosTrabajo){ //Actualizo el edificio //myEdificio = actualizoUnEdificioAs400(myEdificio, ""); //Valido que no este lockeado if( (lock.isLocked("edf_" + myEdificio.getEdf_codigo()) && lock.getLock("edf_" + myEdificio.getEdf_codigo()).equals(strUsuario) ) || !lock.isLocked("edf_" + myEdificio.getEdf_codigo()) ){ if (prm_campo.equals("importeInteresPunitorioDeudoresMasivo")){ myEdificio.setEdf_importeInteresPunitorioDeudores(valor); myEdificio.setEdf_importeMasivoE12(valor); } if (prm_campo.equals("recargoSegundoVencimientoMasivo")){ myEdificio.setEdf_importeRecargoSegundoVencimiento(valor); myEdificio.setEdf_importeMasivoE08A(valor); } lockearEdificio(myEdificio, JSFUtil.getSession().getEffectiveUserName());//lock de los que estoy modificando isMasivoActualizado = true; }else{ listAcumulaErrores.add(prm_campo + "~El edificio " + myEdificio.getEdf_codigo() + " no se pudo actualizar ya que est siendo modificado por: " + lock.getLock("edf_" + myEdificio.getEdf_codigo()).substring(4) ); } } }else if(prm_valor instanceof Date){ //Para las fechas voy a presentar un unico mensaje ya que existen ms validaciones String tempFecha = ar.com.ada3d.utilidades.Conversores.DateToString((Date) prm_valor, "dd/MM/yyyy"); ArrayList<String> arrAcumulaErrorCodigoEdificio = new ArrayList<String>(); int countEdificiosModificados = 0; for(Edificio myEdificio : listaEdificiosTrabajo){ //Valido que no este lockeado if( (lock.isLocked("edf_" + myEdificio.getEdf_codigo()) && lock.getLock("edf_" + myEdificio.getEdf_codigo()).equals(strUsuario) ) || !lock.isLocked("edf_" + myEdificio.getEdf_codigo()) ){ //Voy a validar las fechas ingresadas en cada edificio Calendar calMin = Calendar.getInstance(); calMin.setTime(myEdificio.getEdf_fechaProximaLiquidacion()); calMin.add(Calendar.DATE, 1); //1 Vto if(myEdificio.getEdf_importeInteresPunitorioDeudores().compareTo(BigDecimal.ZERO) > 0 && prm_campo.equals("fechaPrimerVtoMasivo")){ Calendar calNew = Calendar.getInstance(); calNew.setTime((Date) prm_valor); calNew.set(Calendar.HOUR_OF_DAY, 0); calNew.set(Calendar.MINUTE, 0); calNew.set(Calendar.SECOND, 0); calNew.set(Calendar.MILLISECOND, 0); if (calNew.before(calMin) || calNew.equals(calMin)) { arrAcumulaErrorCodigoEdificio.add(myEdificio.getEdf_codigo()); //listAcumulaErrores.add(prm_campo + "~Edificio " + myEdificio.getEdf_codigo() + " la fecha de primer vto. no puede ser menor a " + ar.com.ada3d.utilidades.Conversores.DateToString(calMin.getTime(), "dd/MM/yyyy" )); }else{ myEdificio.setEdf_fechaPrimerVencimientoRecibos((Date) prm_valor); myEdificio.setEdf_fechaMasivoVTOEX1((Date) prm_valor); lockearEdificio(myEdificio, JSFUtil.getSession().getEffectiveUserName());//lock de los que estoy modificando countEdificiosModificados = countEdificiosModificados + 1; isMasivoActualizado = true; } }else if(myEdificio.getEdf_importeInteresPunitorioDeudores().compareTo(BigDecimal.ZERO) == 0 && prm_campo.equals("fechaPrimerVtoMasivo")){ listAcumulaErrores.add(prm_campo + "~El % de inters del edificio " + myEdificio.getEdf_codigo() + " es cero. No se modific la fecha indicada(" + tempFecha + ")." ); } //2 Vto if(myEdificio.getEdf_importeRecargoSegundoVencimiento().compareTo(BigDecimal.ZERO) > 0 && prm_campo.equals("fechaSegundoVtoMasivo")){ calMin.setTime(myEdificio.getEdf_fechaPrimerVencimientoRecibos()); Calendar calNew = Calendar.getInstance(); calNew.setTime((Date) prm_valor); calNew.set(Calendar.HOUR_OF_DAY, 0); calNew.set(Calendar.MINUTE, 0); calNew.set(Calendar.SECOND, 0); calNew.set(Calendar.MILLISECOND, 0); if (calNew.before(calMin) || calNew.equals(calMin)) { arrAcumulaErrorCodigoEdificio.add(myEdificio.getEdf_codigo()); //listAcumulaErrores.add(prm_campo + "~Edificio " + myEdificio.getEdf_codigo() + " la fecha de 2 vto. debe ser mayor al 1 vto "); }else{ myEdificio.setEdf_fechaSegundoVencimientoRecibos((Date) prm_valor); myEdificio.setEdf_fechaMasivoVTOEX2((Date) prm_valor); lockearEdificio(myEdificio, JSFUtil.getSession().getEffectiveUserName());//lock de los que estoy modificando countEdificiosModificados = countEdificiosModificados + 1; isMasivoActualizado = true; } }else if(myEdificio.getEdf_importeRecargoSegundoVencimiento().compareTo(BigDecimal.ZERO) == 0 && prm_campo.equals("fechaSegundoVtoMasivo")){ listAcumulaErrores.add(prm_campo + "~El % de inters del edificio " + myEdificio.getEdf_codigo() + " es cero. No se modific la fecha indicada(" + tempFecha + ")." ); } }else{ listAcumulaErrores.add(prm_campo + "~El edificio " + myEdificio.getEdf_codigo() + " no se pudo actualizar ya que est siendo modificado por: " + lock.getLock("edf_" + myEdificio.getEdf_codigo()).substring(4) ); } } if(!arrAcumulaErrorCodigoEdificio.isEmpty()){ if (countEdificiosModificados > 0){ listAcumulaErrores.add(prm_campo + "~Los edificios " + arrAcumulaErrorCodigoEdificio.toString().replace("[","").replace("]","") + " no han sido modificados con la fecha " + tempFecha + " , favor de revisar. Se actualizaron " + countEdificiosModificados + " edificios."); }else{ listAcumulaErrores.add(prm_campo + "~No se ha modificado ningn edificio con la fecha " + tempFecha + " , favor de revisar."); } } }else{ listAcumulaErrores.add(prm_campo + "~No es un nmero."); } return listAcumulaErrores; } /** * Escribe en AS400 los datos modificados masivamente * Ya fueron validados y estan lockeados, al final se liberan * @usedIn Boton btnConfirmarMasivo en el formulario de Modificacion Automtica * @return Si no actualizaron nada presento el mensaje */ public ArrayList<String> saveMasivoEdificios() { ArrayList<String> listAcumulaErrores = new ArrayList<String>(); if(isMasivoActualizado){ DocLock lock = (DocLock) JSFUtil.resolveVariable("DocLock"); ArrayList<String> listSQL = new ArrayList<String>(); //Voy a utilizar variables temporales para al final hacer como mximo 4 updates ArrayList<String> listaEdificiosE12 = new ArrayList<String>(); String tempE12 = ""; ArrayList<String> listaEdificiosE08A = new ArrayList<String>(); String tempE08A = ""; ArrayList<String> listaEdificiosVTOEX1 = new ArrayList<String>(); String tempVTOEX1 = ""; ArrayList<String> listaEdificiosVTOEX2 = new ArrayList<String>(); String tempVTOEX2 = ""; for(Edificio myEdificio : listaEdificiosTrabajo){ //ini E12 if(myEdificio.getEdf_importeMasivoE12() != null){ if(tempE12.equals("")){ tempE12 = ar.com.ada3d.utilidades.Conversores.bigDecimalToAS400(myEdificio.getEdf_importeMasivoE12(),1); listaEdificiosE12.add(myEdificio.getEdf_codigo()); } else if (tempE12.equals(ar.com.ada3d.utilidades.Conversores.bigDecimalToAS400(myEdificio.getEdf_importeMasivoE12(),1))){ listaEdificiosE12.add(myEdificio.getEdf_codigo()); }else{ listSQL.add("PH_E01~SET E12 = " + tempE12 + " WHERE EDIF IN (" + listaEdificiosE12.toString().replace("[","").replace("]","") + ")"); tempE12 = ar.com.ada3d.utilidades.Conversores.bigDecimalToAS400(myEdificio.getEdf_importeMasivoE12(),1); listaEdificiosE12.clear();//reinicio valores listaEdificiosE12.add(myEdificio.getEdf_codigo()); } myEdificio.setEdf_importeMasivoE12(null);//reinicio valores } //fin E12 //ini E08A if(myEdificio.getEdf_importeMasivoE08A() != null){ if(tempE08A.equals("")){ tempE08A = ar.com.ada3d.utilidades.Conversores.bigDecimalToAS400(myEdificio.getEdf_importeMasivoE08A(),1); listaEdificiosE08A.add(myEdificio.getEdf_codigo()); } else if (tempE08A.equals(ar.com.ada3d.utilidades.Conversores.bigDecimalToAS400(myEdificio.getEdf_importeMasivoE08A(),1))){ listaEdificiosE08A.add(myEdificio.getEdf_codigo()); }else{ listSQL.add("PH_E01~SET E08A = " + tempE12 + " WHERE EDIF IN (" + listaEdificiosE08A.toString().replace("[","").replace("]","") + ")"); tempE08A = ar.com.ada3d.utilidades.Conversores.bigDecimalToAS400(myEdificio.getEdf_importeMasivoE08A(),1); listaEdificiosE08A.clear();//reinicio valores listaEdificiosE08A.add(myEdificio.getEdf_codigo()); } myEdificio.setEdf_importeMasivoE08A(null);//reinicio valores } //fin E08A //ini VTOEX1 if(myEdificio.getEdf_fechaMasivoVTOEX1() != null){ if(tempVTOEX1.equals("")){ tempVTOEX1 = ar.com.ada3d.utilidades.Conversores.DateToString(myEdificio.getEdf_fechaPrimerVencimientoRecibos(), "ddMMyy"); listaEdificiosVTOEX1.add(myEdificio.getEdf_codigo()); } else if (tempVTOEX1.equals(ar.com.ada3d.utilidades.Conversores.DateToString(myEdificio.getEdf_fechaPrimerVencimientoRecibos(), "ddMMyy"))){ listaEdificiosVTOEX1.add(myEdificio.getEdf_codigo()); }else{ listSQL.add("PH_DIFED~SET VTOEX1 = " + tempVTOEX1 + " WHERE EDIF IN (" + listaEdificiosVTOEX1.toString().replace("[","").replace("]","") + ")"); tempVTOEX1 = ar.com.ada3d.utilidades.Conversores.DateToString(myEdificio.getEdf_fechaPrimerVencimientoRecibos(), "ddMMyy"); listaEdificiosVTOEX1.clear();//reinicio valores listaEdificiosVTOEX1.add(myEdificio.getEdf_codigo()); } myEdificio.setEdf_fechaMasivoVTOEX1(null);//reinicio valores } //fin VTOEX1 //ini VTOEX2 if(myEdificio.getEdf_fechaMasivoVTOEX2() != null){ if(tempVTOEX2.equals("")){ tempVTOEX2 = ar.com.ada3d.utilidades.Conversores.DateToString(myEdificio.getEdf_fechaSegundoVencimientoRecibos(), "ddMMyy"); listaEdificiosVTOEX2.add(myEdificio.getEdf_codigo()); } else if (tempVTOEX2.equals(ar.com.ada3d.utilidades.Conversores.DateToString(myEdificio.getEdf_fechaSegundoVencimientoRecibos(), "ddMMyy"))){ listaEdificiosVTOEX2.add(myEdificio.getEdf_codigo()); }else{ listSQL.add("PH_DIFED~SET VTOEX2 = " + tempVTOEX2 + " WHERE EDIF IN (" + listaEdificiosVTOEX2.toString().replace("[","").replace("]","") + ")"); tempVTOEX2 = ar.com.ada3d.utilidades.Conversores.DateToString(myEdificio.getEdf_fechaSegundoVencimientoRecibos(), "ddMMyy"); listaEdificiosVTOEX2.clear();//reinicio valores listaEdificiosVTOEX2.add(myEdificio.getEdf_codigo()); } myEdificio.setEdf_fechaMasivoVTOEX2(null);//reinicio valores } //fin VTOEX2 }// FIN recorrer edificios if(!listaEdificiosE12.isEmpty()){ listSQL.add("PH_E01~SET E12 = " + tempE12 + " WHERE EDIF IN (" + listaEdificiosE12.toString().replace("[","").replace("]","") + ")"); } if(!listaEdificiosE08A.isEmpty()){ listSQL.add("PH_E01~SET E08A = " + tempE12 + " WHERE EDIF IN (" + listaEdificiosE08A.toString().replace("[","").replace("]","") + ")"); } if(!listaEdificiosVTOEX1.isEmpty()){ listSQL.add("PH_DIFED~SET VTOEX1 = " + tempVTOEX1 + " WHERE EDIF IN (" + listaEdificiosVTOEX1.toString().replace("[","").replace("]","") + ")"); } if(!listaEdificiosVTOEX2.isEmpty()){ listSQL.add("PH_DIFED~SET VTOEX2 = " + tempVTOEX2 + " WHERE EDIF IN (" + listaEdificiosVTOEX2.toString().replace("[","").replace("]","") + ")"); } //Al final remuevo los lockeos ArrayList<String> temp1EdificioMerge = ar.com.ada3d.utilidades.Conversores.mergeTwoArrayRemoveDuplicate(listaEdificiosE12, listaEdificiosE08A); ArrayList<String> temp2EdificioMerge = ar.com.ada3d.utilidades.Conversores.mergeTwoArrayRemoveDuplicate(listaEdificiosVTOEX1, listaEdificiosVTOEX2); ArrayList<String> edificioMerge = ar.com.ada3d.utilidades.Conversores.mergeTwoArrayRemoveDuplicate(temp1EdificioMerge, temp2EdificioMerge); for (String temp : edificioMerge) { lock.removeLock("edf_" + temp); getEdificioMap(temp).setEdf_lockedBy(""); } //Hago los Updates al AS400 QueryAS400 query = new QueryAS400(); for(String temp : listSQL){ Document docDummy = JSFUtil.getDocDummy(); String tempLista = temp.split("\\~")[1]; docDummy.appendItemValue("tabla", temp.split("\\~")[0]); docDummy.appendItemValue("LISTA_EDIF", tempLista.replace(",","', '").replace("(","('").replace(")","')")); if (query.updateAS("updateMasivoEdificios", docDummy)) { }else{ throw new java.lang.Error("No se pudo actualizar masivamente la tabla " + temp.split("\\~")[0]); } } isMasivoActualizado = false;//reinicio flag de actualizacion }else{ listAcumulaErrores.add("widgetContainer1" + "~No se ha encontrado ningn cambio. Recuerde presionar 'Aplicar' y una vez que los vea en pantalla podr confirmarlos."); } return listAcumulaErrores; } /** * Lockeo de edificio en el objeto Edificio y en el bean DocLock * @param el obleto edificio * @param el nombre de usuario * */ private void lockearEdificio(Edificio prm_Edificio, String prm_userName){ DocLock lockeos = (DocLock) JSFUtil.resolveVariable("DocLock"); //Agrego el usuario si el edificio est lockeado if(!lockeos.isLocked("edf_" + prm_Edificio.getEdf_codigo())){ lockeos.addLock("edf_" + prm_Edificio.getEdf_codigo(), prm_userName); prm_Edificio.setEdf_lockedBy(lockeos.getLock("edf_" + prm_Edificio.getEdf_codigo())); } }
package com.intellij.psi.impl.search; import com.intellij.ant.PsiAntElement; import com.intellij.aspects.psi.PsiAspect; import com.intellij.aspects.psi.PsiPointcut; import com.intellij.aspects.psi.PsiPointcutDef; import com.intellij.ide.todo.TodoConfiguration; import com.intellij.j2ee.J2EERolesUtil; import com.intellij.j2ee.ejb.role.EjbClassRole; import com.intellij.j2ee.ejb.role.EjbDeclMethodRole; import com.intellij.j2ee.ejb.role.EjbMethodRole; import com.intellij.lang.ASTNode; import com.intellij.lang.Language; import com.intellij.lang.ParserDefinition; import com.intellij.lexer.Lexer; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.impl.ModuleUtil; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFileFilter; import com.intellij.psi.*; import com.intellij.psi.impl.PsiManagerImpl; import com.intellij.psi.impl.RepositoryElementsManager; import com.intellij.psi.impl.cache.RepositoryIndex; import com.intellij.psi.impl.cache.RepositoryManager; import com.intellij.psi.impl.cache.impl.idCache.WordInfo; import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.psi.impl.source.SourceTreeToPsiMap; import com.intellij.psi.impl.source.tree.ElementType; import com.intellij.psi.impl.source.tree.TreeElement; import com.intellij.psi.jsp.*; import com.intellij.psi.search.*; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.TokenSet; import com.intellij.psi.util.*; import com.intellij.psi.xml.XmlAttributeValue; import com.intellij.psi.xml.XmlFile; import com.intellij.psi.xml.XmlTokenType; import com.intellij.uiDesigner.compiler.Utils; import com.intellij.uiDesigner.lw.LwRootContainer; import com.intellij.util.text.CharArrayCharSequence; import com.intellij.util.text.StringSearcher; import gnu.trove.TIntArrayList; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PsiSearchHelperImpl implements PsiSearchHelper { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.search.PsiSearchHelperImpl"); private final PsiManagerImpl myManager; private final JoinPointSearchHelper myJoinPointSearchHelper; private static final TokenSet XML_ATTRIBUTE_VALUE_TOKEN_BIT_SET = TokenSet.create(new IElementType[]{ElementType.XML_ATTRIBUTE_VALUE_TOKEN}); private static final TokenSet FILE_NAME_TOKEN_BIT_SET = TokenSet.create(new IElementType[]{ElementType.XML_ATTRIBUTE_VALUE_TOKEN, ElementType.JSP_DIRECTIVE_ATTRIBUTE_VALUE_TOKEN}); private static final TodoItem[] EMPTY_TODO_ITEMS = new TodoItem[0]; private static final short DEFAULT_OCCURENCE_MASK = WordInfo.IN_CODE | WordInfo.JSP_ATTRIBUTE_VALUE | WordInfo.IN_COMMENTS; public SearchScope getUseScope(PsiElement element) { final GlobalSearchScope maximalUseScope = myManager.getFileManager().getUseScope(element); if (element instanceof PsiPackage) { return maximalUseScope; } else if (element instanceof PsiClass) { if (element instanceof PsiAnonymousClass) { return new LocalSearchScope(element); } PsiFile file = element.getContainingFile(); if (file instanceof JspFile) { return new LocalSearchScope(file); } PsiClass aClass = (PsiClass)element; if (aClass.hasModifierProperty(PsiModifier.PUBLIC)) { return maximalUseScope; } else if (aClass.hasModifierProperty(PsiModifier.PROTECTED)) { return maximalUseScope; } else if (aClass.hasModifierProperty(PsiModifier.PRIVATE)) { PsiClass topClass = getTopLevelClass(aClass); return topClass != null ? new LocalSearchScope(topClass) : new LocalSearchScope(aClass.getContainingFile()); } else { PsiPackage aPackage = null; if (file instanceof PsiJavaFile) { aPackage = element.getManager().findPackage(((PsiJavaFile)file).getPackageName()); } if (aPackage == null) { PsiDirectory dir = file.getContainingDirectory(); if (dir != null) { aPackage = dir.getPackage(); } } if (aPackage != null) { SearchScope scope = GlobalSearchScope.packageScope(aPackage, false); scope = scope.intersectWith(maximalUseScope); return scope; } return new LocalSearchScope(file); } } else if (element instanceof PsiMethod) { PsiFile file = element.getContainingFile(); if (file instanceof JspFile) { return new LocalSearchScope(file); } PsiMethod method = (PsiMethod)element; PsiClass aClass = method.getContainingClass(); if (aClass instanceof PsiAnonymousClass) { //method from anonymous class can be called from outside the class PsiElement methodCallExpr = PsiTreeUtil.getParentOfType(aClass, PsiMethodCallExpression.class); return new LocalSearchScope(methodCallExpr != null ? methodCallExpr : aClass); } if (method.hasModifierProperty(PsiModifier.PUBLIC)) { return maximalUseScope; } else if (method.hasModifierProperty(PsiModifier.PROTECTED)) { return maximalUseScope; } else if (method.hasModifierProperty(PsiModifier.PRIVATE)) { PsiClass topClass = getTopLevelClass(method); return topClass != null ? new LocalSearchScope(topClass) : new LocalSearchScope(method.getContainingFile()); } else { PsiPackage aPackage = file.getContainingDirectory().getPackage(); if (aPackage != null) { SearchScope scope = GlobalSearchScope.packageScope(aPackage, false); scope = scope.intersectWith(maximalUseScope); return scope; } else { return new LocalSearchScope(file); } } } else if (element instanceof PsiField) { PsiFile file = element.getContainingFile(); if (file instanceof JspFile) { return new LocalSearchScope(file); } PsiField field = (PsiField)element; if (field.hasModifierProperty(PsiModifier.PUBLIC)) { return maximalUseScope; } else if (field.hasModifierProperty(PsiModifier.PROTECTED)) { return maximalUseScope; } else if (field.hasModifierProperty(PsiModifier.PRIVATE)) { PsiClass topClass = getTopLevelClass(field); return topClass != null ? new LocalSearchScope(topClass) : new LocalSearchScope(field.getContainingFile()); } else { final PsiDirectory directory = file.getContainingDirectory(); PsiPackage aPackage = directory == null ? null : directory.getPackage(); if (aPackage != null) { SearchScope scope = GlobalSearchScope.packageScope(aPackage, false); scope = scope.intersectWith(maximalUseScope); return scope; } else { return new LocalSearchScope(file); } } } else if (element instanceof ImplicitVariable) { return new LocalSearchScope(((ImplicitVariable)element).getDeclarationScope()); } else if (element instanceof PsiLocalVariable) { PsiElement parent = element.getParent(); if (parent instanceof PsiDeclarationStatement) { return new LocalSearchScope(parent.getParent()); } else { return maximalUseScope; } } else if (element instanceof PsiParameter) { return new LocalSearchScope(((PsiParameter)element).getDeclarationScope()); } else if (element instanceof PsiAntElement) { return ((PsiAntElement)element).getSearchScope(); } else { return maximalUseScope; } } private static PsiClass getTopLevelClass(PsiElement element) { LOG.assertTrue(element.isValid()); final PsiFile file = element.getContainingFile(); if (file instanceof PsiJavaFile) { final PsiClass[] classes = ((PsiJavaFile)file).getClasses(); for (int i = 0; i < classes.length; i++) { PsiClass aClass = classes[i]; if (PsiTreeUtil.isAncestor(aClass, element, false)) return aClass; } } return null; } public interface CustomSearchHelper { short getOccurenceMask(); TokenSet getElementTokenSet(); boolean caseInsensitive(); } public static class XmlCustomSearchHelper implements CustomSearchHelper { private TokenSet myTokenSet = TokenSet.create(new IElementType[] { XmlTokenType.XML_NAME}); private short myOccurenceMask = WordInfo.PLAIN_TEXT; public short getOccurenceMask() { return myOccurenceMask; } public TokenSet getElementTokenSet() { return myTokenSet; } public boolean caseInsensitive() { return false; } } public static class HtmlCustomSearchHelper implements CustomSearchHelper { private TokenSet myTokenSet = XML_ATTRIBUTE_VALUE_TOKEN_BIT_SET; private short myOccurenceMask; public final void registerStyleCustomSearchHelper(CustomSearchHelper helper) { myTokenSet = TokenSet.orSet(myTokenSet,helper.getElementTokenSet()); myOccurenceMask |= helper.getOccurenceMask(); } public short getOccurenceMask() { return myOccurenceMask; } public TokenSet getElementTokenSet() { return myTokenSet; } public boolean caseInsensitive() { return true; } } static class XHtmlCustomSearchHelper extends HtmlCustomSearchHelper { public boolean caseInsensitive() { return false; } } static class JspxCustomSearchHelper extends XHtmlCustomSearchHelper { public TokenSet getElementTokenSet() { return TokenSet.orSet(super.getElementTokenSet(), IDENTIFIER_OR_DOC_VALUE_OR_JSP_ATTRIBUTE_VALUE_BIT_SET); } public short getOccurenceMask() { return (short)(super.getOccurenceMask() | DEFAULT_OCCURENCE_MASK); } } private static final HashMap<FileType,CustomSearchHelper> CUSTOM_SEARCH_HELPERS = new HashMap<FileType, CustomSearchHelper>(); static { registerCustomSearchHelper(StdFileTypes.HTML,new HtmlCustomSearchHelper()); registerCustomSearchHelper(StdFileTypes.XHTML,new XHtmlCustomSearchHelper()); registerCustomSearchHelper(StdFileTypes.JSPX,new JspxCustomSearchHelper()); XmlCustomSearchHelper searchHelper = new XmlCustomSearchHelper(); registerCustomSearchHelper(StdFileTypes.XML,searchHelper); registerCustomSearchHelper(StdFileTypes.DTD,searchHelper); } public static void registerCustomSearchHelper(FileType fileType,CustomSearchHelper searchHelper) { CUSTOM_SEARCH_HELPERS.put(fileType, searchHelper); } public static final CustomSearchHelper getCustomSearchHelper(FileType fileType) { return CUSTOM_SEARCH_HELPERS.get(fileType); } public PsiSearchHelperImpl(PsiManagerImpl manager) { myManager = manager; myJoinPointSearchHelper = new JoinPointSearchHelper(manager, this); } public PsiReference[] findReferences(PsiElement element, SearchScope searchScope, boolean ignoreAccessScope) { LOG.assertTrue(searchScope != null); PsiReferenceProcessor.CollectElements processor = new PsiReferenceProcessor.CollectElements(); processReferences(processor, element, searchScope, ignoreAccessScope); return processor.toArray(PsiReference.EMPTY_ARRAY); } public boolean processReferences(final PsiReferenceProcessor processor, final PsiElement refElement, SearchScope searchScope, boolean ignoreAccessScope) { return processReferences(processor, refElement, searchScope, ignoreAccessScope, true); } private boolean processReferences(final PsiReferenceProcessor processor, final PsiElement refElement, SearchScope originalScope, boolean ignoreAccessScope, boolean isStrictSignatureSearch) { LOG.assertTrue(originalScope != null); if (refElement instanceof PsiAnnotationMethod) { PsiMethod method = (PsiMethod)refElement; if (PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME.equals(method.getName()) && method.getParameterList().getParameters().length == 0) { PsiReference[] references = findReferences(method.getContainingClass(), originalScope, ignoreAccessScope); for (int i = 0; i < references.length; i++) { PsiReference reference = references[i]; if (reference instanceof PsiJavaCodeReferenceElement) { PsiJavaCodeReferenceElement javaReference = (PsiJavaCodeReferenceElement)reference; if (javaReference.getParent() instanceof PsiAnnotation) { PsiNameValuePair[] members = ((PsiAnnotation)javaReference.getParent()).getParameterList().getAttributes(); if (members.length == 1 && members[0].getNameIdentifier() == null) { processor.execute(members[0].getReference()); } } } } } } String text; // final boolean[] refTypes = new boolean[ElementType.LAST + 1]; if (refElement instanceof PsiPackage) { text = ((PsiPackage)refElement).getName(); if (text == null) return true; } else if (refElement instanceof PsiClass) { if (refElement instanceof PsiAnonymousClass) return true; text = ((PsiClass)refElement).getName(); } else if (refElement instanceof PsiVariable) { text = ((PsiVariable)refElement).getName(); if (text == null) return true; } else if (refElement instanceof PsiMethod) { if (((PsiMethod)refElement).isConstructor()) { return processConstructorReferences(processor, (PsiMethod)refElement, originalScope, ignoreAccessScope, isStrictSignatureSearch); } text = ((PsiMethod)refElement).getName(); } else if (refElement instanceof PsiAntElement) { final PsiAntElement antElement = (PsiAntElement)refElement; final SearchScope searchScope = antElement.getSearchScope().intersectWith(originalScope); if (searchScope instanceof LocalSearchScope) { final PsiElement[] scopes = ((LocalSearchScope)searchScope).getScope(); for (int i = 0; i < scopes.length; i++) { final PsiElement scope = scopes[i]; if (!processAntElementScopeRoot(scope, refElement, antElement, processor)) return false; } return true; } else { return true; } } else if (refElement instanceof XmlAttributeValue) { /* if (((XmlAttributeValue)refElement).isAntPropertyDefinition() || ((XmlAttributeValue)refElement).isAntTargetDefinition()) { PsiMetaData metaData = PsiTreeUtil.getParentOfType(refElement, XmlTag.class).getMetaData(); if (metaData instanceof AntPropertyDeclaration) { Set<String> properties = ((AntPropertyDeclaration)metaData).getProperties(); for (Iterator<String> iterator = properties.iterator(); iterator.hasNext();) { String propertyName = iterator.next(); PsiReference[] refs = findReferencesInNonJavaFile(refElement.getContainingFile(), refElement, propertyName); for (int i = 0; i < refs.length; i++) { if (!processor.execute(refs[i])) return false; } } return true; } } */ text = ((XmlAttributeValue)refElement).getValue(); } else if (refElement instanceof PsiPointcutDef) { text = ((PsiPointcutDef)refElement).getName(); } else if (refElement instanceof PsiNamedElement) { text = ((PsiNamedElement)refElement).getName(); } else { return true; } SearchScope searchScope; if (!ignoreAccessScope) { SearchScope accessScope = refElement.getUseScope(); searchScope = originalScope.intersectWith(accessScope); if (searchScope == null) return true; } else { searchScope = originalScope; } if (LOG.isDebugEnabled()) { LOG.debug("visitReferences() search scope: " + searchScope); } final PsiElementProcessorEx processor1 = new PsiElementProcessorEx() { public boolean execute(PsiElement element, int offsetInElement) { final PsiReference reference = element.findReferenceAt(offsetInElement); if (reference == null) return true; if (reference.isReferenceTo(refElement)) { return processor.execute(reference); } else { return true; } } }; final CustomSearchHelper customSearchHelper = getCustomSearchHelper(refElement); short occurrenceMask; if (customSearchHelper!=null) { occurrenceMask = customSearchHelper.getOccurenceMask(); if (customSearchHelper.caseInsensitive()) text = text.toLowerCase(); } else if (refElement instanceof XmlAttributeValue) { occurrenceMask = WordInfo.PLAIN_TEXT; } else { occurrenceMask = DEFAULT_OCCURENCE_MASK; } if (refElement instanceof PsiFileSystemItem) { occurrenceMask = (short)(occurrenceMask | WordInfo.FILE_NAME); } TokenSet elementTypes; if (customSearchHelper!=null) { elementTypes = customSearchHelper.getElementTokenSet(); } else if (refElement instanceof XmlAttributeValue) { elementTypes = XML_ATTRIBUTE_VALUE_TOKEN_BIT_SET; } else { elementTypes = IDENTIFIER_OR_DOC_VALUE_OR_JSP_ATTRIBUTE_VALUE_BIT_SET; } if (refElement instanceof PsiFileSystemItem) { elementTypes = FILE_NAME_TOKEN_BIT_SET; } if (!processElementsWithWord( processor1, searchScope, text, elementTypes, occurrenceMask, customSearchHelper!=null && customSearchHelper.caseInsensitive() )) { return false; } if (refElement instanceof PsiMethod) { PsiMethod method = (PsiMethod)refElement; if (PropertyUtil.isSimplePropertyAccessor(method)) { final String propertyName = PropertyUtil.getPropertyName(method); if (myManager.getNameHelper().isIdentifier(propertyName)) { if (!processElementsWithWord(processor1, searchScope, propertyName, IDENTIFIER_OR_ATTRIBUTE_VALUE_BIT_SET, WordInfo.JSP_ATTRIBUTE_VALUE, false)) { return false; } } } } if (refElement.getContainingFile() instanceof JspFile) { boolean canBeAccessedByIncludes; if (refElement instanceof PsiField || refElement instanceof PsiMethod) { canBeAccessedByIncludes = refElement.getParent() instanceof JspDeclaration; } else if (refElement instanceof JspImplicitVariable) { canBeAccessedByIncludes = true; } else if (refElement instanceof PsiLocalVariable) { canBeAccessedByIncludes = refElement.getParent().getParent() instanceof JspFile; } else { canBeAccessedByIncludes = false; } if (canBeAccessedByIncludes) { PsiElementProcessor processor2 = new PsiBaseElementProcessor() { public boolean execute(PsiElement element) { return processor1.execute(element, 0); } }; PsiFile[] files = JspUtil.findIncludingFiles(refElement.getContainingFile(), searchScope); for (int i = 0; i < files.length; i++) { if (!processIdentifiers(processor2, text, new LocalSearchScope(files[i]), IdentifierPosition.IN_CODE)) return false; } } } if (refElement instanceof PsiPackage && originalScope instanceof GlobalSearchScope) { if (!UIFormUtil.processReferencesInUIForms(processor, (PsiPackage)refElement, (GlobalSearchScope)originalScope)) return false; } else if (refElement instanceof PsiClass && originalScope instanceof GlobalSearchScope) { if (!UIFormUtil.processReferencesInUIForms(processor, (PsiClass)refElement, (GlobalSearchScope)originalScope)) return false; } else if (refElement instanceof PsiField && originalScope instanceof GlobalSearchScope) { if (!UIFormUtil.processReferencesInUIForms(processor, (PsiField)refElement, (GlobalSearchScope)originalScope)) return false; } return true; } private static CustomSearchHelper getCustomSearchHelper(final PsiElement refElement) { PsiFile containingFile = refElement.getContainingFile(); final CustomSearchHelper customSearchHelper = containingFile != null ? CUSTOM_SEARCH_HELPERS.get(containingFile.getFileType()) : null; return customSearchHelper; } private boolean processAntElementScopeRoot(final PsiElement scope, final PsiElement refElement, final PsiAntElement antElement, final PsiReferenceProcessor processor) { final PsiReference[] references = findReferencesInNonJavaFile(scope.getContainingFile(), refElement, antElement.getName()); for (int i = 0; i < references.length; i++) { PsiReference reference = references[i]; if (!processor.execute(reference)) return false; } return true; } private boolean processConstructorReferences(final PsiReferenceProcessor processor, final PsiMethod constructor, final SearchScope searchScope, boolean ignoreAccessScope, final boolean isStrictSignatureSearch) { LOG.assertTrue(searchScope != null); PsiClass aClass = constructor.getContainingClass(); if (aClass == null) return true; if (aClass.isEnum()) { PsiField[] fields = aClass.getFields(); for (int i = 0; i < fields.length; i++) { PsiField field = fields[i]; if (field instanceof PsiEnumConstant) { PsiReference reference = field.getReference(); if (reference != null && reference.isReferenceTo(constructor)) { if (!processor.execute(reference)) return false; } } } } // search usages like "new XXX(..)" PsiReferenceProcessor processor1 = new PsiReferenceProcessor() { public boolean execute(PsiReference reference) { PsiElement parent = reference.getElement().getParent(); if (parent instanceof PsiAnonymousClass) { parent = parent.getParent(); } if (parent instanceof PsiNewExpression) { PsiMethod constructor1 = ((PsiNewExpression)parent).resolveConstructor(); if (constructor1 != null) { if (isStrictSignatureSearch) { if (myManager.areElementsEquivalent(constructor, constructor1)) { return processor.execute(reference); } } else { if (myManager.areElementsEquivalent(constructor.getContainingClass(), constructor1.getContainingClass())) { return processor.execute(reference); } } } } return true; } }; if (!processReferences(processor1, aClass, searchScope, ignoreAccessScope)) return false; // search usages like "this(..)" PsiMethod[] methods = aClass.getMethods(); for (int i = 0; i < methods.length; i++) { PsiMethod method = methods[i]; if (method.isConstructor()) { PsiCodeBlock body = method.getBody(); if (body != null) { PsiStatement[] statements = body.getStatements(); if (statements.length > 0) { PsiStatement statement = statements[0]; if (statement instanceof PsiExpressionStatement) { PsiExpression expr = ((PsiExpressionStatement)statement).getExpression(); if (expr instanceof PsiMethodCallExpression) { PsiReferenceExpression refExpr = ((PsiMethodCallExpression)expr).getMethodExpression(); if (PsiSearchScopeUtil.isInScope(searchScope, refExpr)) { if (refExpr.getText().equals("this")) { PsiElement referencedElement = refExpr.resolve(); if (referencedElement instanceof PsiMethod) { PsiMethod constructor1 = (PsiMethod)referencedElement; if (isStrictSignatureSearch) { if (myManager.areElementsEquivalent(constructor1, constructor)) { if (!processor.execute(refExpr)) return false; } } else { if (myManager.areElementsEquivalent(constructor.getContainingClass(), constructor1.getContainingClass())) { if (!processor.execute(refExpr)) return false; } } } } } } } } } } } // search usages like "super(..)" PsiElementProcessor<PsiClass> processor2 = new PsiBaseElementProcessor<PsiClass>() { public boolean execute(PsiClass element) { PsiClass inheritor = element; PsiMethod[] methods = inheritor.getMethods(); for (int j = 0; j < methods.length; j++) { PsiMethod method = methods[j]; if (method.isConstructor()) { PsiCodeBlock body = method.getBody(); if (body != null) { PsiStatement[] statements = body.getStatements(); if (statements.length > 0) { PsiStatement statement = statements[0]; if (statement instanceof PsiExpressionStatement) { PsiExpression expr = ((PsiExpressionStatement)statement).getExpression(); if (expr instanceof PsiMethodCallExpression) { PsiReferenceExpression refExpr = ((PsiMethodCallExpression)expr).getMethodExpression(); if (PsiSearchScopeUtil.isInScope(searchScope, refExpr)) { if (refExpr.getText().equals("super")) { PsiElement referencedElement = refExpr.resolve(); if (referencedElement instanceof PsiMethod) { PsiMethod constructor1 = (PsiMethod)referencedElement; if (isStrictSignatureSearch) { if (myManager.areElementsEquivalent(constructor1, constructor)) { if (!processor.execute(refExpr)) return false; } } else { if (myManager.areElementsEquivalent(constructor.getContainingClass(), constructor1.getContainingClass())) { if (!processor.execute(refExpr)) return false; } } } } } } } } } } } return true; } }; return processInheritors(processor2, aClass, searchScope, false); } public PsiMethod[] findOverridingMethods(PsiMethod method, SearchScope searchScope, boolean checkDeep) { LOG.assertTrue(searchScope != null); PsiElementProcessor.CollectElements<PsiMethod> processor = new PsiElementProcessor.CollectElements<PsiMethod>(); processOverridingMethods(processor, method, searchScope, checkDeep); return processor.toArray(PsiMethod.EMPTY_ARRAY); } public boolean processOverridingMethods(final PsiElementProcessor<PsiMethod> processor, final PsiMethod method, SearchScope searchScope, final boolean checkDeep) { LOG.assertTrue(searchScope != null); final PsiClass parentClass = method.getContainingClass(); if (parentClass == null || method.isConstructor() || method.hasModifierProperty(PsiModifier.STATIC) || method.hasModifierProperty(PsiModifier.FINAL) || method.hasModifierProperty(PsiModifier.PRIVATE) || parentClass instanceof PsiAnonymousClass || parentClass.hasModifierProperty(PsiModifier.FINAL)) { return true; } PsiElementProcessor<PsiClass> inheritorsProcessor = new PsiBaseElementProcessor<PsiClass>() { public boolean execute(PsiClass element) { PsiClass inheritor = element; PsiSubstitutor substitutor = TypeConversionUtil.getSuperClassSubstitutor(parentClass, inheritor, PsiSubstitutor.EMPTY); MethodSignature signature = method.getSignature(substitutor); PsiMethod method1 = MethodSignatureUtil.findMethodBySignature(inheritor, signature, false); if (method1 == null || method1.hasModifierProperty(PsiModifier.STATIC) || (method.hasModifierProperty(PsiModifier.PACKAGE_LOCAL) && !method1.getManager().arePackagesTheSame(parentClass, inheritor))) { return true; } return processor.execute(method1); } }; if (!processInheritors(inheritorsProcessor, parentClass, searchScope, true)) return false; final EjbMethodRole ejbRole = J2EERolesUtil.getEjbRole(method); if (ejbRole instanceof EjbDeclMethodRole) { final PsiMethod[] implementations = ((EjbDeclMethodRole)ejbRole).findImplementations(); for (int i = 0; i < implementations.length; i++) { PsiMethod implementation = implementations[i]; // same signature methods were processed already if (implementation.getSignature(PsiSubstitutor.EMPTY).equals(method.getSignature(PsiSubstitutor.EMPTY))) continue; if (!processor.execute(implementation)) return false; } } return true; } public PsiPointcutDef[] findOverridingPointcuts(PsiPointcutDef pointcut, SearchScope searchScope, boolean checkDeep) { LOG.assertTrue(searchScope != null); PsiElementProcessor.CollectElements<PsiPointcutDef> processor = new PsiElementProcessor.CollectElements<PsiPointcutDef>(); processOverridingPointcuts(processor, pointcut, searchScope, checkDeep); final Collection<PsiPointcutDef> foundPointcuts = processor.getCollection(); return foundPointcuts.toArray(new PsiPointcutDef[foundPointcuts.size()]); } public boolean processOverridingPointcuts(final PsiElementProcessor processor, final PsiPointcutDef pointcut, SearchScope searchScope, boolean checkDeep) { PsiAspect parentAspect = pointcut.getContainingAspect(); if (parentAspect == null || pointcut.hasModifierProperty(PsiModifier.FINAL)) { return true; } PsiElementProcessor<PsiClass> inheritorsProcessor = new PsiBaseElementProcessor<PsiClass>() { public boolean execute(PsiClass element) { if (!(element instanceof PsiAspect)) return true; PsiAspect inheritor = (PsiAspect)element; PsiPointcutDef pointcut1 = inheritor.findPointcutDefBySignature(pointcut, false); if (pointcut1 == null) return true; return processor.execute(pointcut1); } }; return processInheritors(inheritorsProcessor, parentAspect, searchScope, true); } public PsiReference[] findReferencesIncludingOverriding(final PsiMethod method, SearchScope searchScope, boolean isStrictSignatureSearch) { LOG.assertTrue(searchScope != null); PsiReferenceProcessor.CollectElements processor = new PsiReferenceProcessor.CollectElements(); processReferencesIncludingOverriding(processor, method, searchScope, isStrictSignatureSearch); return processor.toArray(PsiReference.EMPTY_ARRAY); } public boolean processReferencesIncludingOverriding(final PsiReferenceProcessor processor, final PsiMethod method, SearchScope searchScope) { return processReferencesIncludingOverriding(processor, method, searchScope, true); } public boolean processReferencesIncludingOverriding(final PsiReferenceProcessor processor, final PsiMethod method, SearchScope searchScope, final boolean isStrictSignatureSearch) { LOG.assertTrue(searchScope != null); PsiClass parentClass = method.getContainingClass(); if (method.isConstructor()) { return processConstructorReferences(processor, method, searchScope, !isStrictSignatureSearch, isStrictSignatureSearch); } if (isStrictSignatureSearch && (parentClass == null || parentClass instanceof PsiAnonymousClass || parentClass.hasModifierProperty(PsiModifier.FINAL) || method instanceof PsiAnnotationMethod || method.hasModifierProperty(PsiModifier.STATIC) || method.hasModifierProperty(PsiModifier.FINAL) || method.hasModifierProperty(PsiModifier.PRIVATE)) ) { return processReferences(processor, method, searchScope, false); } final String text = method.getName(); final PsiMethod[] methods = isStrictSignatureSearch ? new PsiMethod[]{method} : getOverloadsMayBeOverriden(method); SearchScope accessScope = methods[0].getUseScope(); for (int i = 0; i < methods.length; i++) { SearchScope someScope = PsiSearchScopeUtil.scopesUnion(accessScope, methods[i].getUseScope()); accessScope = someScope == null ? accessScope : someScope; } final PsiClass aClass = method.getContainingClass(); final PsiElementProcessorEx processor1 = new PsiElementProcessorEx() { public boolean execute(PsiElement element, int offsetInElement) { PsiReference reference = element.findReferenceAt(offsetInElement); if (reference != null) { for (int i = 0; i < methods.length; i++) { PsiMethod method = methods[i]; if (reference.isReferenceTo(method)) { return processor.execute(reference); } PsiElement refElement = reference.resolve(); if (refElement instanceof PsiMethod) { PsiMethod refMethod = (PsiMethod)refElement; PsiClass refMethodClass = refMethod.getContainingClass(); if (refMethodClass == null) return true; if (!refMethod.hasModifierProperty(PsiModifier.STATIC)) { PsiSubstitutor substitutor = TypeConversionUtil.getClassSubstitutor(aClass, refMethodClass, PsiSubstitutor.EMPTY); if (substitutor != null) { if (method.getSignature(PsiSubstitutor.EMPTY).equals(refMethod.getSignature(substitutor))) { if (!processor.execute(reference)) return false; } } } if (!isStrictSignatureSearch) { PsiManager manager = method.getManager(); if (manager.areElementsEquivalent(refMethodClass, aClass)) { return processor.execute(reference); } } } else { return true; } } } return true; } }; searchScope = searchScope.intersectWith(accessScope); if (searchScope == null) return true; short occurrenceMask = WordInfo.IN_CODE | WordInfo.IN_COMMENTS; boolean toContinue = processElementsWithWord(processor1, searchScope, text, IDENTIFIER_OR_DOC_VALUE_BIT_SET, occurrenceMask, false); if (!toContinue) return false; if (PropertyUtil.isSimplePropertyAccessor(method)) { String propertyName = PropertyUtil.getPropertyName(method); if (myManager.getNameHelper().isIdentifier(propertyName)) { toContinue = processElementsWithWord(processor1, searchScope, propertyName, IDENTIFIER_OR_ATTRIBUTE_VALUE_BIT_SET, WordInfo.JSP_ATTRIBUTE_VALUE, false); if (!toContinue) return false; } } return true; } public PsiClass[] findInheritors(PsiClass aClass, SearchScope searchScope, boolean checkDeep) { LOG.assertTrue(searchScope != null); PsiElementProcessor.CollectElements<PsiClass> processor = new PsiElementProcessor.CollectElements<PsiClass>(); processInheritors(processor, aClass, searchScope, checkDeep); return processor.toArray(PsiClass.EMPTY_ARRAY); } public boolean processInheritors(PsiElementProcessor<PsiClass> processor, PsiClass aClass, SearchScope searchScope, boolean checkDeep) { return processInheritors(processor, aClass, searchScope, checkDeep, true); } public boolean processInheritors(PsiElementProcessor<PsiClass> processor, PsiClass aClass, SearchScope searchScope, boolean checkDeep, boolean checkInheritance) { LOG.assertTrue(searchScope != null); ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); if (progress != null) { progress.pushState(); String className = aClass.getName(); progress.setText("Searching inheritors" + (className != null ? " of " + className : "") + "..."); } ArrayList<PsiClass> processed = new ArrayList<PsiClass>(); processed.add(aClass); boolean result = processInheritors(processor, aClass, searchScope, checkDeep, processed, checkInheritance); if (progress != null) { progress.popState(); } return result; } private boolean processInheritors(PsiElementProcessor<PsiClass> processor, PsiClass aClass, final SearchScope searchScope, boolean checkDeep, ArrayList<PsiClass> processed, boolean checkInheritance) { LOG.assertTrue(searchScope != null); if (aClass instanceof PsiAnonymousClass) return true; if (aClass.hasModifierProperty(PsiModifier.FINAL)) return true; String name = aClass.getName(); RepositoryManager repositoryManager = myManager.getRepositoryManager(); RepositoryElementsManager repositoryElementsManager = myManager.getRepositoryElementsManager(); if ("java.lang.Object".equals(aClass.getQualifiedName())) { // special case // TODO! } if (aClass instanceof PsiAspect) { PsiAspectManager aspectManager = aClass.getManager().getAspectManager(); PsiAspect[] aspects = aspectManager.getAspects(); for (int i = 0; i < aspects.length; i++) { if (!processInheritorCandidate(processor, aspects[i], aClass, searchScope, checkDeep, processed, checkInheritance)) { return false; } } return true; } final SearchScope searchScope1 = searchScope.intersectWith(aClass.getUseScope()); RepositoryIndex repositoryIndex = repositoryManager.getIndex(); VirtualFileFilter rootFilter; if (searchScope1 instanceof GlobalSearchScope) { rootFilter = repositoryIndex.rootFilterBySearchScope((GlobalSearchScope)searchScope1); } else { rootFilter = null; } long[] candidateIds = repositoryIndex.getNameOccurrencesInExtendsLists(name, rootFilter); for (int i = 0; i < candidateIds.length; i++) { long id = candidateIds[i]; PsiClass candidate = (PsiClass)repositoryElementsManager.findOrCreatePsiElementById(id); LOG.assertTrue(candidate.isValid()); if (!processInheritorCandidate(processor, candidate, aClass, searchScope, checkDeep, processed, checkInheritance)) { return false; } } final EjbClassRole classRole = J2EERolesUtil.getEjbRole(aClass); if (classRole != null && classRole.isDeclarationRole()) { final PsiClass[] implementations = classRole.findImplementations(); for (int i = 0; i < implementations.length; i++) { PsiClass candidate = implementations[i]; if (!processInheritorCandidate(processor, candidate, aClass, searchScope, checkDeep, processed, checkInheritance)) { return false; } } } return true; } private boolean processInheritorCandidate(PsiElementProcessor<PsiClass> processor, PsiClass candidate, PsiClass baseClass, SearchScope searchScope, boolean checkDeep, ArrayList<PsiClass> processed, boolean checkInheritance) { if (checkInheritance || (checkDeep && !(candidate instanceof PsiAnonymousClass))) { if (!candidate.isInheritor(baseClass, false)) return true; } if (processed.contains(candidate)) return true; processed.add(candidate); if (candidate instanceof PsiAnonymousClass) { if (!processor.execute(candidate)) return false; } else { if (PsiSearchScopeUtil.isInScope(searchScope, candidate)) { if (searchScope instanceof GlobalSearchScope) { String qName = candidate.getQualifiedName(); if (qName != null) { PsiClass candidate1 = myManager.findClass(qName, (GlobalSearchScope)searchScope); if (candidate != candidate1) return true; } } if (!processor.execute(candidate)) return false; } if (checkDeep) { if (!processInheritors(processor, candidate, searchScope, checkDeep, processed, checkInheritance)) return false; } } return true; } public JspDirective[] findIncludeDirectives(final PsiFile file, SearchScope searchScope) { LOG.assertTrue(searchScope != null); String name = file.getVirtualFile().getName(); final ArrayList<JspDirective> directives = new ArrayList<JspDirective>(); PsiElementProcessorEx processor = new PsiElementProcessorEx() { public boolean execute(PsiElement element, int offsetInElement) { ASTNode parent = (SourceTreeToPsiMap.psiElementToTree(element)).getTreeParent(); if (parent.getElementType() == ElementType.JSP_FILE_REFERENCE) { ASTNode pparent = parent.getTreeParent(); if (SourceTreeToPsiMap.treeElementToPsi(pparent) instanceof JspAttribute && pparent.getTreeParent().getElementType() == ElementType.JSP_DIRECTIVE) { JspDirective directive = (JspDirective)SourceTreeToPsiMap.treeElementToPsi(pparent.getTreeParent()); if (directive.getName().equals("include")) { JspAttribute attribute = (JspAttribute)SourceTreeToPsiMap.treeElementToPsi(pparent); if (attribute.getName().equals("file")) { PsiFile refFile = (PsiFile)((PsiJavaCodeReferenceElement)SourceTreeToPsiMap.treeElementToPsi(parent)).resolve(); if (file.equals(refFile)) { directives.add(directive); } } } } } return true; } }; processElementsWithWord(processor, searchScope, name, JSP_DIRECTIVE_ATTRIBUTE_BIT_SET, WordInfo.FILE_NAME, false); return directives.toArray(new JspDirective[directives.size()]); } private static final TokenSet JSP_DIRECTIVE_ATTRIBUTE_BIT_SET = TokenSet.create(new IElementType[]{ElementType.JSP_DIRECTIVE_ATTRIBUTE_VALUE_TOKEN}); public PsiFile[] findFilesWithTodoItems() { return myManager.getCacheManager().getFilesWithTodoItems(); } private static final TokenSet XML_COMMENT_BIT_SET = TokenSet.create(new IElementType[]{TreeElement.XML_COMMENT_CHARACTERS}); public TodoItem[] findTodoItems(PsiFile file) { return findTodoItems(file, null); } public TodoItem[] findTodoItems(PsiFile file, int startOffset, int endOffset) { return findTodoItems(file, new TextRange(startOffset, endOffset)); } private TodoItem[] findTodoItems(PsiFile file, TextRange range) { if (file instanceof PsiBinaryFile || file instanceof PsiCompiledElement || file.getVirtualFile() == null) { return EMPTY_TODO_ITEMS; } int count = myManager.getCacheManager().getTodoCount(file.getVirtualFile()); if (count == 0) { return EMPTY_TODO_ITEMS; } TIntArrayList commentStarts = new TIntArrayList(); TIntArrayList commentEnds = new TIntArrayList(); char[] chars = file.textToCharArray(); if (file instanceof PsiPlainTextFile) { commentStarts.add(0); commentEnds.add(file.getTextLength()); } else { // collect comment offsets to prevent long locks by PsiManagerImpl.LOCK synchronized (PsiLock.LOCK) { final Lexer lexer = ((PsiFileImpl)file).createLexer(); TokenSet commentTokens = null; if (file instanceof PsiJavaFile || file instanceof JspFile) { commentTokens = ElementType.COMMENT_BIT_SET; } else if (file instanceof XmlFile) { commentTokens = XML_COMMENT_BIT_SET; } else { final Language lang = file.getLanguage(); if (lang != null) { final ParserDefinition parserDefinition = lang.getParserDefinition(); if (parserDefinition != null) { commentTokens = parserDefinition.getCommentTokens(); } } } if (commentTokens == null) return EMPTY_TODO_ITEMS; for (lexer.start(chars); ; lexer.advance()) { IElementType tokenType = lexer.getTokenType(); if (tokenType == null) break; if (range != null) { if (lexer.getTokenEnd() <= range.getStartOffset()) continue; if (lexer.getTokenStart() >= range.getEndOffset()) break; } if (commentTokens.isInSet(tokenType)) { commentStarts.add(lexer.getTokenStart()); commentEnds.add(lexer.getTokenEnd()); } } } } ArrayList<TodoItem> list = new ArrayList<TodoItem>(); for (int i = 0; i < commentStarts.size(); i++) { int commentStart = commentStarts.get(i); int commentEnd = commentEnds.get(i); TodoPattern[] patterns = TodoConfiguration.getInstance().getTodoPatterns(); for (int j = 0; j < patterns.length; j++) { TodoPattern toDoPattern = patterns[j]; Pattern pattern = toDoPattern.getPattern(); if (pattern != null) { ProgressManager.getInstance().checkCanceled(); CharSequence input = new CharArrayCharSequence(chars, commentStart, commentEnd); Matcher matcher = pattern.matcher(input); while (true) { //long time1 = System.currentTimeMillis(); boolean found = matcher.find(); //long time2 = System.currentTimeMillis(); //System.out.println("scanned text of length " + (lexer.getTokenEnd() - lexer.getTokenStart() + " in " + (time2 - time1) + " ms")); if (!found) break; int start = matcher.start() + commentStart; int end = matcher.end() + commentStart; if (start != end) { if (range == null || range.getStartOffset() <= start && end <= range.getEndOffset()) { list.add(new TodoItemImpl(file, start, end, toDoPattern)); } } ProgressManager.getInstance().checkCanceled(); } } } } return list.toArray(new TodoItem[list.size()]); } public int getTodoItemsCount(PsiFile file) { int count = myManager.getCacheManager().getTodoCount(file.getVirtualFile()); if (count != -1) return count; return findTodoItems(file).length; } public int getTodoItemsCount(PsiFile file, TodoPattern pattern) { int count = myManager.getCacheManager().getTodoCount(file.getVirtualFile(), pattern); if (count != -1) return count; TodoItem[] items = findTodoItems(file); count = 0; for (int i = 0; i < items.length; i++) { TodoItem item = items[i]; if (item.getPattern().equals(pattern)) count++; } return count; } public PsiIdentifier[] findIdentifiers(String identifier, SearchScope searchScope, int position) { LOG.assertTrue(searchScope != null); PsiElementProcessor.CollectElements<PsiIdentifier> processor = new PsiElementProcessor.CollectElements<PsiIdentifier>(); processIdentifiers(processor, identifier, searchScope, position); return processor.toArray(new PsiIdentifier[0]); } public boolean processIdentifiers(final PsiElementProcessor processor, final String identifier, SearchScope searchScope, int position) { LOG.assertTrue(searchScope != null); short occurrenceMask; switch (position) { case IdentifierPosition.ANY: occurrenceMask = WordInfo.ANY; break; case IdentifierPosition.IN_CODE: occurrenceMask = WordInfo.IN_CODE; break; default: LOG.assertTrue(false); return true; } PsiElementProcessorEx processor1 = new PsiElementProcessorEx() { public boolean execute(PsiElement element, int offsetInElement) { if (element.getText().equals(identifier)) { return processor.execute(element); } return true; } }; return processElementsWithWord(processor1, searchScope, identifier, IDENTIFIER_BIT_SET, occurrenceMask, false); } public PsiElement[] findThrowUsages(final PsiThrowStatement aThrow, final SearchScope searchScope) { return new PsiElement[]{aThrow}; } private static final TokenSet IDENTIFIER_BIT_SET = TokenSet.create(new IElementType[]{ElementType.IDENTIFIER}); private static final TokenSet IDENTIFIER_OR_DOC_VALUE_BIT_SET = TokenSet.create(new IElementType[]{ElementType.IDENTIFIER, ElementType.DOC_TAG_VALUE_TOKEN}); private static final TokenSet IDENTIFIER_OR_ATTRIBUTE_VALUE_BIT_SET = TokenSet.create(new IElementType[]{ElementType.IDENTIFIER, ElementType.JSP_ACTION_ATTRIBUTE_VALUE_TOKEN}); private static final TokenSet IDENTIFIER_OR_DOC_VALUE_OR_JSP_ATTRIBUTE_VALUE_BIT_SET = TokenSet.create(new IElementType[]{ ElementType.IDENTIFIER, ElementType.JSP_ACTION_ATTRIBUTE_VALUE_TOKEN, ElementType.DOC_TAG_VALUE_TOKEN}); public PsiElement[] findCommentsContainingIdentifier(String identifier, SearchScope searchScope) { LOG.assertTrue(searchScope != null); final ArrayList<PsiElement> results = new ArrayList<PsiElement>(); PsiElementProcessorEx processor = new PsiElementProcessorEx() { public boolean execute(PsiElement element, int offsetInElement) { if (element.findReferenceAt(offsetInElement) == null) { results.add(element); } return true; } }; processElementsWithWord(processor, searchScope, identifier, COMMENT_BIT_SET, WordInfo.IN_COMMENTS, false); return results.toArray(new PsiElement[results.size()]); } private static final TokenSet COMMENT_BIT_SET = TokenSet.create(new IElementType[]{ ElementType.DOC_COMMENT_DATA, ElementType.DOC_TAG_VALUE_TOKEN, ElementType.C_STYLE_COMMENT, ElementType.END_OF_LINE_COMMENT}); public PsiLiteralExpression[] findStringLiteralsContainingIdentifier(String identifier, SearchScope searchScope) { LOG.assertTrue(searchScope != null); final ArrayList<PsiLiteralExpression> results = new ArrayList<PsiLiteralExpression>(); PsiElementProcessorEx processor = new PsiElementProcessorEx() { public boolean execute(PsiElement element, int offsetInElement) { if (element instanceof PsiLiteralExpression && StringUtil.startsWithChar(element.getText(), '\"')) { results.add((PsiLiteralExpression)element); } return true; } }; processElementsWithWord(processor, searchScope, identifier, LITERAL_EXPRESSION_BIT_SET, WordInfo.IN_STRING_LITERALS, false); return results.toArray(new PsiLiteralExpression[results.size()]); } public boolean processAllClasses(final PsiElementProcessor<PsiClass> processor, SearchScope searchScope) { if (searchScope instanceof GlobalSearchScope) { return processAllClassesInGlobalScope((GlobalSearchScope)searchScope, processor); } PsiElement[] scopeRoots = ((LocalSearchScope)searchScope).getScope(); for (int i = 0; i < scopeRoots.length; i++) { final PsiElement scopeRoot = scopeRoots[i]; if (!processScopeRootForAllClasses(scopeRoot, processor)) return false; } return true; } private static boolean processScopeRootForAllClasses(PsiElement scopeRoot, final PsiElementProcessor<PsiClass> processor) { if (scopeRoot == null) return true; final boolean[] stopped = new boolean[]{false}; scopeRoot.accept(new PsiRecursiveElementVisitor() { public void visitReferenceExpression(PsiReferenceExpression expression) { if (!stopped[0]) { visitElement(expression); } } public void visitClass(PsiClass aClass) { stopped[0] = !processor.execute(aClass); super.visitClass(aClass); } }); return !stopped[0]; } private boolean processAllClassesInGlobalScope(GlobalSearchScope searchScope, PsiElementProcessor<PsiClass> processor) { myManager.getRepositoryManager().updateAll(); LinkedList<PsiDirectory> queue = new LinkedList<PsiDirectory>(); PsiDirectory[] roots = myManager.getRootDirectories(PsiRootPackageType.SOURCE_PATH); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myManager.getProject()).getFileIndex(); for (int i = 0; i < roots.length; i++) { final PsiDirectory root = roots[i]; if (fileIndex.isInContent(root.getVirtualFile())) { queue.addFirst(root); } } roots = myManager.getRootDirectories(PsiRootPackageType.CLASS_PATH); for (int i = 0; i < roots.length; i++) { queue.addFirst(roots[i]); } while (!queue.isEmpty()) { PsiDirectory dir = queue.removeFirst(); Module module = ModuleUtil.findModuleForPsiElement(dir); if (!(module != null ? searchScope.isSearchInModuleContent(module) : searchScope.isSearchInLibraries())) continue; PsiDirectory[] subdirectories = dir.getSubdirectories(); for (int i = 0; i < subdirectories.length; i++) { queue.addFirst(subdirectories[i]); } PsiFile[] files = dir.getFiles(); for (int i = 0; i < files.length; i++) { PsiFile file = files[i]; if (!searchScope.contains(file.getVirtualFile())) continue; if (!(file instanceof PsiJavaFile)) continue; long fileId = myManager.getRepositoryManager().getFileId(file.getVirtualFile()); if (fileId >= 0) { long[] allClasses = myManager.getRepositoryManager().getFileView().getAllClasses(fileId); for (int j = 0; j < allClasses.length; j++) { PsiClass psiClass = (PsiClass)myManager.getRepositoryElementsManager().findOrCreatePsiElementById(allClasses[j]); if (!processor.execute(psiClass)) return false; } } else { if (!processAllClasses(processor, new LocalSearchScope(file))) return false; } } } return true; } public PsiClass[] findAllClasses(SearchScope searchScope) { LOG.assertTrue(searchScope != null); PsiElementProcessor.CollectElements<PsiClass> processor = new PsiElementProcessor.CollectElements<PsiClass>(); processAllClasses(processor, searchScope); return processor.toArray(PsiClass.EMPTY_ARRAY); } static class SearchDescriptor { private HashSet<String> myNames = new HashSet<String>(); private HashSet<PsiFile> myFiles = new HashSet<PsiFile>(); private HashSet<PsiElement> myElements = new HashSet<PsiElement>(); } public SearchDescriptor prepareBundleReferenceSearch(PsiElement[] refElements) { SearchDescriptor descriptor = new SearchDescriptor(); for (int i = 0; i < refElements.length; i++) { PsiElement refElement = refElements[i]; if (refElement instanceof PsiNamedElement) { String name = ((PsiNamedElement)refElement).getName(); if (name != null) { PsiFile[] files = myManager.getCacheManager().getFilesWithWord(name, WordInfo.IN_CODE, GlobalSearchScope.allScope(myManager.getProject())); descriptor.myNames.add(name); descriptor.myFiles.addAll(Arrays.asList(files)); descriptor.myElements.add(refElement); } } } return descriptor; } public boolean processReferencesToElementsInLocalScope(final PsiReferenceProcessor processor, final SearchDescriptor bundleSearchDescriptor, LocalSearchScope scope) { PsiElement[] scopeElements = scope.getScope(); for (int i = 0; i < scopeElements.length; i++) { final PsiElement scopeElement = scopeElements[i]; if (!processReferencesToElementInScopeElement(scopeElement, bundleSearchDescriptor, processor)) { return false; } } return true; } private static boolean processReferencesToElementInScopeElement(PsiElement scopeElement, final SearchDescriptor bundleSearchDescriptor, final PsiReferenceProcessor processor) { if (scopeElement == null) return true; if (!bundleSearchDescriptor.myFiles.contains(scopeElement.getContainingFile())) return true; final PsiElementProcessor processor1 = new PsiBaseElementProcessor() { public boolean execute(PsiElement element) { PsiElement parent = element.getParent(); if (parent instanceof PsiJavaCodeReferenceElement) { PsiReference ref = (PsiJavaCodeReferenceElement)parent; PsiElement target = ref.resolve(); //TODO: including overriding! if (bundleSearchDescriptor.myElements.contains(target)) { return processor.execute(ref); } } return true; } }; ASTNode scopeTreeElement = SourceTreeToPsiMap.psiElementToTree(scopeElement); ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); return LowLevelSearchUtil.processIdentifiersBySet(processor1, scopeTreeElement, IDENTIFIER_BIT_SET, bundleSearchDescriptor.myNames, progress); } public PsiElement[] findJoinPointsByPointcut(PsiPointcut pointcut, SearchScope searchScope) { return myJoinPointSearchHelper.findJoinPointsByPointcut(pointcut, searchScope); } public boolean processJoinPointsByPointcut(PsiElementProcessor processor, PsiPointcut pointcut, SearchScope searchScope) { return myJoinPointSearchHelper.processJoinPointsByPointcut(processor, pointcut, searchScope); } private static final TokenSet LITERAL_EXPRESSION_BIT_SET = TokenSet.create(new IElementType[]{ElementType.LITERAL_EXPRESSION}); private boolean processElementsWithWord(PsiElementProcessorEx processor, SearchScope searchScope, String word, TokenSet elementTypes, short occurrenceMask, boolean caseInsensitive) { LOG.assertTrue(searchScope != null); if (searchScope instanceof GlobalSearchScope) { StringSearcher searcher = new StringSearcher(word); searcher.setCaseSensitive(!caseInsensitive); return processElementsWithWordInGlobalScope(processor, (GlobalSearchScope)searchScope, searcher, elementTypes, occurrenceMask); } else { LocalSearchScope _scope = (LocalSearchScope)searchScope; PsiElement[] scopeElements = _scope.getScope(); for (int i = 0; i < scopeElements.length; i++) { final PsiElement scopeElement = scopeElements[i]; if (!processElementsWithWordInScopeElement(scopeElement, processor, word, elementTypes, caseInsensitive)) return false; } return true; } } private static boolean processElementsWithWordInScopeElement(PsiElement scopeElement, PsiElementProcessorEx processor, String word, TokenSet elementTypes, boolean caseInsensitive) { if (SourceTreeToPsiMap.hasTreeElement(scopeElement)) { StringSearcher searcher = new StringSearcher(word); searcher.setCaseSensitive(!caseInsensitive); return LowLevelSearchUtil.processElementsContainingWordInElement(processor, scopeElement, searcher, elementTypes, null); } else { return true; } } private boolean processElementsWithWordInGlobalScope(PsiElementProcessorEx processor, GlobalSearchScope scope, StringSearcher searcher, TokenSet elementTypes, short occurrenceMask) { ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); if (progress != null) { progress.pushState(); progress.setText("Scanning files..."); } myManager.startBatchFilesProcessingMode(); try { PsiFile[] files = myManager.getCacheManager().getFilesWithWord(searcher.getPattern(), occurrenceMask, scope); if (progress != null) { progress.setText("Searching for " + searcher.getPattern() + "..."); } for (int i = 0; i < files.length; i++) { ProgressManager.getInstance().checkCanceled(); PsiFile file = files[i]; PsiFile[] psiRoots = file.getPsiRoots(); for (int j = 0; j < psiRoots.length; j++) { PsiFile psiRoot = psiRoots[j]; if (!LowLevelSearchUtil.processElementsContainingWordInElement(processor, psiRoot, searcher, elementTypes, progress)) { return false; } } if (progress != null) { double fraction = (double)i / files.length; progress.setFraction(fraction); } myManager.dropResolveCaches(); } } finally { if (progress != null) { progress.popState(); } myManager.finishBatchFilesProcessingMode(); } return true; } public PsiFile[] findFilesWithPlainTextWords(String word) { return myManager.getCacheManager().getFilesWithWord(word, WordInfo.PLAIN_TEXT, GlobalSearchScope.projectScope(myManager.getProject())); } private static PsiReference[] findReferencesInNonJavaFile(PsiFile file, final PsiElement element, String refText) { class MyRefsProcessor implements PsiNonJavaFileReferenceProcessor { private List<PsiReference> myRefs = new ArrayList<PsiReference>(); PsiReference[] getResult() { return myRefs.toArray(new PsiReference[myRefs.size()]); } public boolean process(PsiFile file, int startOffset, int endOffset) { PsiElement elementAt = file.findElementAt(startOffset); if (elementAt != null) { PsiReference ref = elementAt.findReferenceAt(startOffset - elementAt.getTextRange().getStartOffset()); if (ref != null && ref.isReferenceTo(element)) myRefs.add(ref); } return true; } } MyRefsProcessor processor = new MyRefsProcessor(); char[] text = file.textToCharArray(); StringSearcher searcher = new StringSearcher(refText); for (int index = LowLevelSearchUtil.searchWord(text, 0, text.length, searcher); index >= 0;) { if (!processor.process(file, index, index + searcher.getPattern().length())) break; index = LowLevelSearchUtil.searchWord(text, index + searcher.getPattern().length(), text.length, searcher); } return processor.getResult(); } public void processUsagesInNonJavaFiles(String qName, PsiNonJavaFileReferenceProcessor processor, GlobalSearchScope searchScope) { ProgressManager progressManager = ProgressManager.getInstance(); ProgressIndicator progress = progressManager.getProgressIndicator(); int dotIndex = qName.lastIndexOf('.'); int dollarIndex = qName.lastIndexOf('$'); int maxIndex = Math.max(dotIndex, dollarIndex); String wordToSearch = maxIndex >= 0 ? qName.substring(maxIndex + 1) : qName; PsiFile[] files = myManager.getCacheManager().getFilesWithWord(wordToSearch, WordInfo.PLAIN_TEXT, searchScope); StringSearcher searcher = new StringSearcher(qName); searcher.setCaseSensitive(true); searcher.setForwardDirection(true); if (progress != null) { progress.pushState(); progress.setText("Analyzing usages in non-java files..."); } AllFilesLoop: for (int i = 0; i < files.length; i++) { ProgressManager.getInstance().checkCanceled(); PsiFile psiFile = files[i]; char[] text = psiFile.textToCharArray(); for (int index = LowLevelSearchUtil.searchWord(text, 0, text.length, searcher); index >= 0;) { PsiReference referenceAt = psiFile.findReferenceAt(index); if (referenceAt == null || referenceAt.isSoft()) { if (!processor.process(psiFile, index, index + searcher.getPattern().length())) break AllFilesLoop; } index = LowLevelSearchUtil.searchWord(text, index + searcher.getPattern().length(), text.length, searcher); } if (progress != null) { progress.setFraction((double)(i + 1) / files.length); } } if (progress != null) { progress.popState(); } } public PsiFile[] findFormsBoundToClass(String className) { GlobalSearchScope projectScope = GlobalSearchScope.projectScope(myManager.getProject()); PsiFile[] files = myManager.getCacheManager().getFilesWithWord(className, WordInfo.GUI_FORM_CLASS_NAME, projectScope); List<PsiFile> boundForms = new ArrayList<PsiFile>(files.length); for (int i = 0; i < files.length; i++) { PsiFile psiFile = files[i]; LOG.assertTrue(psiFile.getFileType() == StdFileTypes.GUI_DESIGNER_FORM); String text = psiFile.getText(); try { LwRootContainer container = Utils.getRootContainer(text, null); if (className.equals(container.getClassToBind())) boundForms.add(psiFile); } catch (Exception e) { LOG.debug(e); } } return boundForms.toArray(new PsiFile[boundForms.size()]); } public boolean isFieldBoundToForm(PsiField field) { PsiClass aClass = field.getContainingClass(); if (aClass != null && aClass.getQualifiedName() != null) { PsiFile[] formFiles = findFormsBoundToClass(aClass.getQualifiedName()); for (int i = 0; i < formFiles.length; i++) { PsiFile file = formFiles[i]; final PsiReference[] references = file.getReferences(); for (int j = 0; j < references.length; j++) { final PsiReference reference = references[j]; if (reference.isReferenceTo(field)) return true; } } } return false; } public void processAllFilesWithWord(String word, GlobalSearchScope scope, FileSink sink) { PsiFile[] files = myManager.getCacheManager().getFilesWithWord(word, WordInfo.IN_CODE, scope); for (int i = 0; i < files.length; i++) { sink.foundFile(files[i]); } } public void processAllFilesWithWordInComments(String word, GlobalSearchScope scope, FileSink sink) { PsiFile[] files = myManager.getCacheManager().getFilesWithWord(word, WordInfo.IN_COMMENTS, scope); for (int i = 0; i < files.length; i++) { sink.foundFile(files[i]); } } public void processAllFilesWithWordInLiterals(String word, GlobalSearchScope scope, FileSink sink) { PsiFile[] files = myManager.getCacheManager().getFilesWithWord(word, WordInfo.IN_STRING_LITERALS, scope); for (int i = 0; i < files.length; i++) { sink.foundFile(files[i]); } } private static PsiMethod[] getOverloadsMayBeOverriden(PsiMethod method) { PsiClass aClass = method.getContainingClass(); if (aClass == null) return new PsiMethod[]{method}; PsiMethod[] methods = aClass.findMethodsByName(method.getName(), false); List<PsiMethod> result = new ArrayList<PsiMethod>(); for (int i = 0; i < methods.length; i++) { PsiMethod psiMethod = methods[i]; PsiModifierList modList = psiMethod.getModifierList(); if (!modList.hasModifierProperty(PsiModifier.STATIC) && !modList.hasModifierProperty(PsiModifier.FINAL)) { result.add(psiMethod); } } //Should not happen if (result.size() == 0) return new PsiMethod[]{method}; return result.toArray(new PsiMethod[result.size()]); } }
package com.offbytwo.jenkins.client; import static org.apache.commons.lang.StringUtils.isNotBlank; import com.offbytwo.jenkins.client.validator.HttpResponseValidator; import com.offbytwo.jenkins.model.BaseModel; import com.offbytwo.jenkins.model.Crumb; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicHeader; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.util.EntityUtils; import org.codehaus.jackson.map.DeserializationConfig; import org.codehaus.jackson.map.ObjectMapper; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Scanner; public class JenkinsHttpClient { private URI uri; private DefaultHttpClient client; private BasicHttpContext localContext; private HttpResponseValidator httpResponseValidator; private ObjectMapper mapper; private String context; public JenkinsHttpClient(URI uri, DefaultHttpClient defaultHttpClient) { this.context = uri.getPath(); if (!context.endsWith("/")) { context += "/"; } this.uri = uri; this.mapper = getDefaultMapper(); this.client = defaultHttpClient; this.httpResponseValidator = new HttpResponseValidator(); } public JenkinsHttpClient(URI uri) { this(uri, new DefaultHttpClient()); } public JenkinsHttpClient(URI uri, String username, String password) { this(uri); if (isNotBlank(username)) { CredentialsProvider provider = client.getCredentialsProvider(); AuthScope scope = new AuthScope(uri.getHost(), uri.getPort(), "realm"); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); provider.setCredentials(scope, credentials); localContext = new BasicHttpContext(); localContext.setAttribute("preemptive-auth", new BasicScheme()); client.addRequestInterceptor(new PreemptiveAuth(), 0); } } /** * Perform a GET request and parse the response to the given class * * @param path path to request, can be relative or absolute * @param cls class of the response * @param <T> type of the response * @return an instance of the supplied class * @throws IOException, HttpResponseException */ public <T extends BaseModel> T get(String path, Class<T> cls) throws IOException { HttpGet getMethod = new HttpGet(api(path)); HttpResponse response = client.execute(getMethod, localContext); try { httpResponseValidator.validateResponse(response); return objectFromResponse(cls, response); } finally { EntityUtils.consume(response.getEntity()); releaseConnection(getMethod); } } /** * Perform a GET request and parse the response and return a simple string of the content * * @param path path to request, can be relative or absolute * @return the entity text * @throws IOException, HttpResponseException */ public String get(String path) throws IOException { HttpGet getMethod = new HttpGet(api(path)); HttpResponse response = client.execute(getMethod, localContext); try { httpResponseValidator.validateResponse(response); Scanner s = new Scanner(response.getEntity().getContent()); s.useDelimiter("\\z"); StringBuffer sb = new StringBuffer(); while (s.hasNext()) { sb.append(s.next()); } return sb.toString(); } finally { releaseConnection(getMethod); } } /** * Perform a GET request and return the response as InputStream * * @param path path to request, can be relative or absolute * @return the response stream * @throws IOException, HttpResponseException */ public InputStream getFile(URI path) throws IOException { HttpGet getMethod = new HttpGet(path); try { HttpResponse response = client.execute(getMethod, localContext); httpResponseValidator.validateResponse(response); return response.getEntity().getContent(); } finally { releaseConnection(getMethod); } } /** * Perform a POST request and parse the response to the given class * * @param path path to request, can be relative or absolute * @param data data to post * @param cls class of the response * @param <R> type of the response * @param <D> type of the data * @return an instance of the supplied class * @throws IOException, HttpResponseException */ public <R extends BaseModel, D> R post(String path, D data, Class<R> cls) throws IOException { HttpPost request = new HttpPost(api(path)); Crumb crumb = get("/crumbIssuer", Crumb.class); if (crumb != null) { request.addHeader(new BasicHeader(crumb.getCrumbRequestField(), crumb.getCrumb())); } if (data != null) { StringEntity stringEntity = new StringEntity(mapper.writeValueAsString(data), "application/json"); request.setEntity(stringEntity); } HttpResponse response = client.execute(request, localContext); try { httpResponseValidator.validateResponse(response); if (cls != null) { return objectFromResponse(cls, response); } else { return null; } } finally { EntityUtils.consume(response.getEntity()); releaseConnection(request); } } /** * Perform a POST request of XML (instead of using json mapper) and return a string rendering of the response * entity. * * @param path path to request, can be relative or absolute * @param xml_data data data to post * @return A string containing the xml response (if present) * @throws IOException, HttpResponseException */ public String post_xml(String path, String xml_data) throws IOException { HttpPost request = new HttpPost(api(path)); Crumb crumb = get("/crumbIssuer", Crumb.class); if (crumb != null) { request.addHeader(new BasicHeader(crumb.getCrumbRequestField(), crumb.getCrumb())); } if (xml_data != null) { request.setEntity(new StringEntity(xml_data, ContentType.create("text/xml","utf-8"))); } HttpResponse response = client.execute(request, localContext); httpResponseValidator.validateResponse(response); try { InputStream content = response.getEntity().getContent(); Scanner s = new Scanner(content); StringBuffer sb = new StringBuffer(); while (s.hasNext()) { sb.append(s.next()); } return sb.toString(); } finally { EntityUtils.consume(response.getEntity()); releaseConnection(request); } } /** * Perform POST request that takes no parameters and returns no response * * @param path path to request * @throws IOException, HttpResponseException */ public void post(String path) throws IOException { post(path, null, null); } private String urlJoin(String path1, String path2) { if (!path1.endsWith("/")) { path1 += "/"; } if (path2.startsWith("/")) { path2 = path2.substring(1); } return path1 + path2; } private URI api(String path) { if (!path.toLowerCase().matches("https?: path = urlJoin(this.context, path); } if (!path.contains("?")) { path = urlJoin(path, "api/json"); } else { String[] components = path.split("\\?", 2); path = urlJoin(components[0], "api/json") + "?" + components[1]; } return uri.resolve("/").resolve(path); } private <T extends BaseModel> T objectFromResponse(Class<T> cls, HttpResponse response) throws IOException { InputStream content = response.getEntity().getContent(); T result = mapper.readValue(content, cls); result.setClient(this); return result; } private ObjectMapper getDefaultMapper() { ObjectMapper mapper = new ObjectMapper(); DeserializationConfig deserializationConfig = mapper.getDeserializationConfig(); mapper.setDeserializationConfig(deserializationConfig .without(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES)); return mapper; } private void releaseConnection(HttpRequestBase httpRequestBase) { httpRequestBase.releaseConnection(); } }
package com.speedment.common.injector; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.function.Predicate; import static java.util.Objects.requireNonNull; /** * An InjectorProxy can be used to create/manipulate * instances on behalf of the actual injector. This can * be useful when using the Java Platform Module System * to keep down the number of required {@code exports} * in the module-info.java file. * * @author per * @since 3.2.0 */ public interface InjectorProxy { /** * Returns if this InjectorProxy shall be used * with regards to the provided {@code clazz}. * <p> * This feature can be used to control which proxies * shall be used for which classes. E.g. one * InjectorProxy can be used to instantiate classes * from the domain system. * * @param clazz to check * @return if this InjectorProxy shall be used * with regards to the provided {@code clazz} */ boolean isApplicable(Class<?> clazz); void set(Field field, Object instance, Object value) throws IllegalArgumentException, IllegalAccessException; <T> T newInstance(Constructor<T> constructor, Object ... initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException; /** * Returns a {@code Predicate} that will evaluate to true iff * tested with a class that lies in the same package as the * provided {@code classInRootPackage} or a package below the * provided {@code classInRootPackage}. * * @param classInRootPackage as a reference to the root package * @return a {@code Predicate} that will evaluate to true iff * tested with a class that lies in the same package as the * provided {@code classInRootPackage} or a package below the * provided {@code classInRootPackage} */ static Predicate<? super Class<?>> samePackageOrBelow(Class<?> classInRootPackage) { requireNonNull(classInRootPackage); return samePackageOrBelow(classInRootPackage.getPackage().getName()); } /** * Returns a {@code Predicate} that will evaluate to true iff * tested with a class that lies in the same package as the * provided {@code rootPackage} or a package below the * provided {@code rootPackage}. * * @param rootPackage as a reference to the root package * @return a {@code Predicate} that will evaluate to true iff * tested with a class that lies in the same package as the * provided {@code rootPackage} or a package below the * provided {@code rootPackage} */ static Predicate<? super Class<?>> samePackageOrBelow(String rootPackage) { requireNonNull(rootPackage); return c -> c.getName().startsWith(rootPackage); } }
package org.antlr.v4.test.runtime; import org.antlr.v4.Tool; import org.antlr.v4.runtime.misc.Pair; import org.antlr.v4.runtime.misc.Utils; import org.antlr.v4.tool.ANTLRMessage; import org.antlr.v4.tool.DefaultToolListener; import org.junit.*; import org.junit.rules.TestRule; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import org.stringtemplate.v4.ST; import org.stringtemplate.v4.STGroup; import org.stringtemplate.v4.STGroupFile; import org.stringtemplate.v4.StringRenderer; import java.io.File; import java.io.IOException; import java.lang.reflect.Modifier; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.fail; import static junit.framework.TestCase.failNotEquals; import static org.junit.Assume.assumeFalse; /** This class represents a single runtime test. It pulls data from * a {@link RuntimeTestDescriptor} and uses junit to trigger a test. * The only functionality needed to execute a test is defined in * {@link RuntimeTestSupport}. All of the various test rig classes * derived from this one. E.g., see {@link org.antlr.v4.test.runtime.java.TestParserExec}. * * @since 4.6. */ public abstract class BaseRuntimeTest { public final static String[] Targets = { "Cpp", "CSharp", "Dart", "Go", "Java", "Node", "PHP", "Python2", "Python3", "Swift" }; @BeforeClass public static void startHeartbeatToAvoidTimeout() { if(requiresHeartbeat()) startHeartbeat(); } private static boolean requiresHeartbeat() { return isTravisCI() || isAppVeyorCI() || (isCPP() && isRecursion()) || (isCircleCI() && isGo()) || (isCircleCI() && isDotNet() && isRecursion()); } @AfterClass public static void stopHeartbeat() { heartbeat = false; } private static boolean isRecursion() { String s = System.getenv("GROUP"); return "recursion".equalsIgnoreCase(s); } private static boolean isGo() { String s = System.getenv("TARGET"); return "go".equalsIgnoreCase(s); } private static boolean isCPP() { String s = System.getenv("TARGET"); return "cpp".equalsIgnoreCase(s); } private static boolean isDotNet() { String s = System.getenv("TARGET"); return "dotnet".equalsIgnoreCase(s); } private static boolean isCircleCI() { // see https://circleci.com/docs/2.0/env-vars/#built-in-environment-variables String s = System.getenv("CIRCLECI"); return "true".equalsIgnoreCase(s); } private static boolean isAppVeyorCI() { String s = System.getenv("APPVEYOR"); return "true".equalsIgnoreCase(s); } private static boolean isTravisCI() { // see https://docs.travis-ci.com/user/environment-variables/#default-environment-variables String s = System.getenv("TRAVIS"); return "true".equalsIgnoreCase(s); } static boolean heartbeat = false; private static void startHeartbeat() { // Add heartbeat thread to gen minimal output for travis, appveyor to avoid timeout. Thread t = new Thread("heartbeat") { @Override public void run() { heartbeat = true; while (heartbeat) { try { //noinspection BusyWait Thread.sleep(10000); } catch (Exception e) { e.printStackTrace(); } System.out.print('.'); } } }; t.start(); } /** ANTLR isn't thread-safe to process grammars so we use a global lock for testing */ public static final Object antlrLock = new Object(); protected RuntimeTestSupport delegate; protected RuntimeTestDescriptor descriptor; public BaseRuntimeTest(RuntimeTestDescriptor descriptor, RuntimeTestSupport delegate) { this.descriptor = descriptor; this.delegate = delegate; } @Before public void setUp() throws Exception { // "The default JUnit runner treats tests with failing assumptions as ignored" assumeFalse(checkIgnored()); delegate.testSetUp(); } public boolean checkIgnored() { boolean ignored = !TestContext.isSupportedTarget(descriptor.getTarget()) || descriptor.ignore(descriptor.getTarget()); if(ignored) System.out.println("Ignore " + descriptor); return ignored; } @Rule public final TestRule testWatcher = new TestWatcher() { @Override protected void succeeded(Description description) { // remove tmpdir if no error. delegate.eraseTempDir(); } }; @Test public void testOne() throws Exception { // System.out.println(descriptor.getTestName()); // System.out.println(delegate.getTmpDir()); if (descriptor.ignore(descriptor.getTarget()) ) { System.out.println("Ignore " + descriptor); return; } delegate.beforeTest(descriptor); if (descriptor.getTestType().contains("Parser") ) { testParser(descriptor); } else { testLexer(descriptor); } delegate.afterTest(descriptor); } public void testParser(RuntimeTestDescriptor descriptor) { RuntimeTestUtils.mkdir(delegate.getTempParserDirPath()); Pair<String, String> pair = descriptor.getGrammar(); ClassLoader cloader = getClass().getClassLoader(); URL templates = cloader.getResource("org/antlr/v4/test/runtime/templates/"+descriptor.getTarget()+".test.stg"); STGroupFile targetTemplates = new STGroupFile(templates, "UTF-8", '<', '>'); targetTemplates.registerRenderer(String.class, new StringRenderer()); // write out any slave grammars List<Pair<String, String>> slaveGrammars = descriptor.getSlaveGrammars(); if ( slaveGrammars!=null ) { for (Pair<String, String> spair : slaveGrammars) { STGroup g = new STGroup('<', '>'); g.registerRenderer(String.class, new StringRenderer()); g.importTemplates(targetTemplates); ST grammarST = new ST(g, spair.b); writeFile(delegate.getTempParserDirPath(), spair.a+".g4", grammarST.render()); } } String grammarName = pair.a; String grammar = pair.b; STGroup g = new STGroup('<', '>'); g.importTemplates(targetTemplates); g.registerRenderer(String.class, new StringRenderer()); ST grammarST = new ST(g, grammar); grammar = grammarST.render(); String found = delegate.execParser(grammarName+".g4", grammar, grammarName+"Parser", grammarName+"Lexer", grammarName+"Listener", grammarName+"Visitor", descriptor.getStartRule(), descriptor.getInput(), descriptor.showDiagnosticErrors() ); assertCorrectOutput(descriptor, delegate, found); } public void testLexer(RuntimeTestDescriptor descriptor) throws Exception { RuntimeTestUtils.mkdir(delegate.getTempParserDirPath()); Pair<String, String> pair = descriptor.getGrammar(); ClassLoader cloader = getClass().getClassLoader(); URL templates = cloader.getResource("org/antlr/v4/test/runtime/templates/"+descriptor.getTarget()+".test.stg"); STGroupFile targetTemplates = new STGroupFile(templates, "UTF-8", '<', '>'); targetTemplates.registerRenderer(String.class, new StringRenderer()); // write out any slave grammars List<Pair<String, String>> slaveGrammars = descriptor.getSlaveGrammars(); if ( slaveGrammars!=null ) { for (Pair<String, String> spair : slaveGrammars) { STGroup g = new STGroup('<', '>'); g.registerRenderer(String.class, new StringRenderer()); g.importTemplates(targetTemplates); ST grammarST = new ST(g, spair.b); writeFile(delegate.getTempParserDirPath(), spair.a+".g4", grammarST.render()); } } String grammarName = pair.a; String grammar = pair.b; STGroup g = new STGroup('<', '>'); g.registerRenderer(String.class, new StringRenderer()); g.importTemplates(targetTemplates); ST grammarST = new ST(g, grammar); grammar = grammarST.render(); String found = delegate.execLexer(grammarName+".g4", grammar, grammarName, descriptor.getInput(), descriptor.showDFA()); assertCorrectOutput(descriptor, delegate, found); } /** Write a grammar to tmpdir and run antlr */ public static ErrorQueue antlrOnString(String workdir, String targetName, String grammarFileName, String grammarStr, boolean defaultListener, String... extraOptions) { RuntimeTestUtils.mkdir(workdir); writeFile(workdir, grammarFileName, grammarStr); return antlrOnString(workdir, targetName, grammarFileName, defaultListener, extraOptions); } /** Run ANTLR on stuff in workdir and error queue back */ public static ErrorQueue antlrOnString(String workdir, String targetName, String grammarFileName, boolean defaultListener, String... extraOptions) { final List<String> options = new ArrayList<>(); Collections.addAll(options, extraOptions); if ( targetName!=null ) { options.add("-Dlanguage="+targetName); } if ( !options.contains("-o") ) { options.add("-o"); options.add(workdir); } if ( !options.contains("-lib") ) { options.add("-lib"); options.add(workdir); } if ( !options.contains("-encoding") ) { options.add("-encoding"); options.add("UTF-8"); } options.add(new File(workdir,grammarFileName).toString()); final String[] optionsA = new String[options.size()]; options.toArray(optionsA); Tool antlr = new Tool(optionsA); ErrorQueue equeue = new ErrorQueue(antlr); antlr.addListener(equeue); if (defaultListener) { antlr.addListener(new DefaultToolListener(antlr)); } synchronized (antlrLock) { antlr.processGrammarsOnCommandLine(); } List<String> errors = new ArrayList<>(); if ( !defaultListener && !equeue.errors.isEmpty() ) { for (int i = 0; i < equeue.errors.size(); i++) { ANTLRMessage msg = equeue.errors.get(i); ST msgST = antlr.errMgr.getMessageTemplate(msg); errors.add(msgST.render()); } } if ( !defaultListener && !equeue.warnings.isEmpty() ) { for (int i = 0; i < equeue.warnings.size(); i++) { ANTLRMessage msg = equeue.warnings.get(i); // antlrToolErrors.append(msg); warnings are hushed } } return equeue; } public static RuntimeTestDescriptor[] OLD_getRuntimeTestDescriptors(Class<?> clazz, String targetName) { if(!TestContext.isSupportedTarget(targetName)) return new RuntimeTestDescriptor[0]; Class<?>[] nestedClasses = clazz.getClasses(); List<RuntimeTestDescriptor> descriptors = new ArrayList<RuntimeTestDescriptor>(); for (Class<?> nestedClass : nestedClasses) { int modifiers = nestedClass.getModifiers(); if ( RuntimeTestDescriptor.class.isAssignableFrom(nestedClass) && !Modifier.isAbstract(modifiers) ) { try { RuntimeTestDescriptor d = (RuntimeTestDescriptor) nestedClass.newInstance(); if(!d.ignore(targetName)) { d.setTarget(targetName); descriptors.add(d); } } catch (Exception e) { e.printStackTrace(System.err); } } } writeDescriptors(clazz, descriptors); return descriptors.toArray(new RuntimeTestDescriptor[0]); } public static RuntimeTestDescriptor[] getRuntimeTestDescriptors(Class<?> clazz, String targetName) { // Walk all descriptor dirs String group = clazz.getSimpleName().replace("Descriptors",""); String[] descriptorFilenames = new File("/tmp/descriptors/"+group).list(); List<RuntimeTestDescriptor> descriptors = new ArrayList<>(); for (String fname : descriptorFilenames) { System.out.println(fname); try { String dtext = Files.readString(Path.of("/tmp/descriptors",group,fname)); UniversalRuntimeTestDescriptor d = readDescriptor(dtext); d.testGroup = group; d.name = fname.replace(".txt",""); d.targetName = targetName; descriptors.add(d); System.out.println(d); } catch (IOException ioe) { System.err.println("Can't read descriptor file "+fname); } } return descriptors.toArray(new RuntimeTestDescriptor[0]); } /** Write descriptor files. */ private static void writeDescriptors(Class<?> clazz, List<RuntimeTestDescriptor> descriptors) { new File("/tmp/descriptors").mkdir(); String groupName = clazz.getSimpleName(); groupName = groupName.replace("Descriptors", ""); String groupDir = "/tmp/descriptors/" + groupName; new File(groupDir).mkdir(); for (RuntimeTestDescriptor d : descriptors) { try { Pair<String,String> g = d.getGrammar(); String gname = g.a; String grammar = g.b; String filename = d.getTestName()+".txt"; String content = ""; String input = quoteForDescriptorFile(d.getInput()); String output = quoteForDescriptorFile(d.getOutput()); String errors = quoteForDescriptorFile(d.getErrors()); content += "[type]\n"; content += d.getTestType(); content += "\n\n"; content += "[grammar]\n"; content += grammar; if ( !content.endsWith("\n\n") ) content += "\n"; if ( d.getSlaveGrammars()!=null ) { for (Pair<String, String> slaveG : d.getSlaveGrammars()) { String sg = quoteForDescriptorFile(slaveG.b); content += "[slaveGrammar]\n"; content += sg; content += "\n"; } } content += "[start]\n"; content += d.getStartRule(); content += "\n\n"; if ( input!=null ) { content += "[input]\n"; content += input; content += "\n"; } if ( output!=null ) { content += "[output]\n"; content += output; content += "\n"; } if ( errors!=null ) { content += "[errors]\n"; content += errors; } Files.write(Paths.get(groupDir + "/" + filename), content.getBytes()); } catch (IOException e) { //exception handling left as an exercise for the reader System.err.println(e.getMessage()); } } } * """34 * 34""" * """b = 6 * """ * space and no newline inside /** Rules for strings look like this: * * [input] if one line, remove all WS before/after * a b * * [input] need whitespace * * [input] single quote char, remove all WS before/after * " * * [input] same as "b = 6\n" in java * * [input] * * [input] same as java string "\"aaa" * "aaa * * [input] ignore front/back \n except leave last \n * a * b * c * d */ private static String quoteForDescriptorFile(String s) { if ( s==null ) { return null; } long nnl = s.chars().filter(ch -> ch == '\n').count(); if ( nnl==0 ) { // one line input return s + "\n"; } if ( nnl>1 && s.endsWith("\n") ) { return s; } if ( s.endsWith(" ") || // whitespace matters (nnl==1&&s.endsWith("\n")) || // "b = 6\n" s.startsWith("\n") ) { // whitespace matters return "\"\"\"" + s + "\"\"\"\n"; } if ( !s.endsWith("\n") ) { // "a\n b" return "\"\"\"" + s + "\"\"\"\n"; } return s; } """line 1:0 reportAttemptingFullContext d=0 (s), input='abc' """ /** Read stuff like: [grammar] grammar T; s @after {<DumpDFA()>} : ID | ID {} ; ID : 'a'..'z'+; WS : (' '|'\t'|'\n')+ -> skip ; [grammarName] T [start] s [input] abc [output] Decision 0: s0-ID->:s1^=>1 [errors] Some can be missing like [errors]. Get gr names automatically "lexer grammar Unicode;" "grammar T;" "parser grammar S;" Also handle slave grammars: [grammar] grammar M; import S,T; s : a ; B : 'b' ; // defines B from inherited token space WS : (' '|'\n') -> skip ; [slaveGrammar] parser grammar T; a : B {<writeln("\"T.a\"")>};<! hidden by S.a !> [slaveGrammar] parser grammar S; a : b {<writeln("\"S.a\"")>}; b : B; */ public static UniversalRuntimeTestDescriptor readDescriptor(String dtext) throws RuntimeException { String[] fileSections = {"notes","type","grammar","slaveGrammar","start","input","output","errors"}; Set<String> sections = new HashSet<>(Arrays.asList(fileSections)); String currentField = null; String currentValue = null; List<Pair<String, String>> pairs = new ArrayList<>(); String[] lines = dtext.split("\n"); for (String line : lines) { if ( line.startsWith("[") && line.length()>2 && sections.contains(line.substring(1, line.length() - 1)) ) { if ( currentField!=null ) { pairs.add(new Pair<>(currentField,currentValue)); } currentField = line.substring(1, line.length() - 1); currentValue = null; } else { if ( currentValue==null ) { currentValue = ""; } currentValue += line.trim()+"\n"; } } // save last section pairs.add(new Pair<>(currentField,currentValue)); // System.out.println(pairs); UniversalRuntimeTestDescriptor d = new UniversalRuntimeTestDescriptor(); for (Pair<String,String> p : pairs) { String section = p.a; String value = p.b.trim(); if ( value.startsWith("\"\"\"") ) { value = value.replace("\"\"\"", ""); } else if ( value.indexOf('\n')>=0 ) { value = value + "\n"; // if multi line and not quoted, leave \n on end. } switch (section) { case "notes": d.notes = value; break; case "type": d.testType = value; break; case "grammar": d.grammarName = getGrammarName(value.split("\n")[0]); d.grammar = value; break; case "slaveGrammar": String gname = getGrammarName(value.split("\n")[0]); d.slaveGrammars.add(new Pair<>(gname, value)); case "start": d.startRule = value; break; case "input": d.input = value; break; case "output": d.output = value; break; case "errors": d.errors = value; break; default: throw new RuntimeException("Unknown descriptor section ignored: "+section); } } return d; } /** Get A, B, or C from: * "lexer grammar A;" "grammar B;" "parser grammar C;" */ public static String getGrammarName(String grammarDeclLine) { int gi = grammarDeclLine.indexOf("grammar "); if ( gi<0 ) { return "<unknown grammar name>"; } gi += "grammar ".length(); int gsemi = grammarDeclLine.indexOf(';'); return grammarDeclLine.substring(gi, gsemi); } public static void main(String[] args) throws Exception { String dtext = Files.readString(Path.of("/tmp/descriptors/CompositeParsers/DelegatesSeeSameTokenType.txt")); readDescriptor(dtext); } public static void writeFile(String dir, String fileName, String content) { try { Utils.writeFile(dir+"/"+fileName, content, "UTF-8"); } catch (IOException ioe) { System.err.println("can't write file"); ioe.printStackTrace(System.err); } } public static String readFile(String dir, String fileName) { try { return String.copyValueOf(Utils.readFile(dir+"/"+fileName, "UTF-8")); } catch (IOException ioe) { System.err.println("can't read file"); ioe.printStackTrace(System.err); } return null; } protected static void assertCorrectOutput(RuntimeTestDescriptor descriptor, RuntimeTestSupport delegate, String actualOutput) { String actualParseErrors = delegate.getParseErrors(); String actualToolErrors = delegate.getANTLRToolErrors(); String expectedOutput = descriptor.getOutput(); String expectedParseErrors = descriptor.getErrors(); String expectedToolErrors = descriptor.getANTLRToolErrors(); if (actualOutput == null) { actualOutput = ""; } if (actualParseErrors == null) { actualParseErrors = ""; } if (actualToolErrors == null) { actualToolErrors = ""; } if (expectedOutput == null) { expectedOutput = ""; } if (expectedParseErrors == null) { expectedParseErrors = ""; } if (expectedToolErrors == null) { expectedToolErrors = ""; } if (actualOutput.equals(expectedOutput) && actualParseErrors.equals(expectedParseErrors) && actualToolErrors.equals(expectedToolErrors)) { return; } if (actualOutput.equals(expectedOutput)) { if (actualParseErrors.equals(expectedParseErrors)) { failNotEquals("[" + descriptor.getTarget() + ":" + descriptor.getTestName() + "] " + "Parse output and parse errors are as expected, but tool errors are incorrect", expectedToolErrors, actualToolErrors); } else { fail("[" + descriptor.getTarget() + ":" + descriptor.getTestName() + "] " + "Parse output is as expected, but errors are not: " + "expectedParseErrors:<" + expectedParseErrors + ">; actualParseErrors:<" + actualParseErrors + ">; expectedToolErrors:<" + expectedToolErrors + ">; actualToolErrors:<" + actualToolErrors + ">."); } } else { fail("[" + descriptor.getTarget() + ":" + descriptor.getTestName() + "] " + "Parse output is incorrect: " + "expectedOutput:<" + expectedOutput + ">; actualOutput:<" + actualOutput + ">; expectedParseErrors:<" + expectedParseErrors + ">; actualParseErrors:<" + actualParseErrors + ">; expectedToolErrors:<" + expectedToolErrors + ">; actualToolErrors:<" + actualToolErrors + ">."); } } }
package com.badlogic.gdx.ingenuity.utils.helper; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import com.badlogic.gdx.Application.ApplicationType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.ingenuity.IngenuityGdx; import com.badlogic.gdx.ingenuity.utils.common.StrUtil; public class RHelper { private static final String TAG = RHelper.class.getSimpleName(); private static final String ResRoot = "assets"; private static HashMap<String, String> resMap = new HashMap<String, String>(); public static void generated() { // assets name path loadResNames(""); String rPath = RHelper.class.getName().replaceAll("\\.", "/").replace(RHelper.class.getSimpleName(), "") + "R.template"; FileHandle resFileHandle = Gdx.files.classpath(rPath); String line = null; StringBuffer contentBuffer = new StringBuffer(); try (BufferedReader bufferedReader = new BufferedReader(resFileHandle.reader())) { while ((line = bufferedReader.readLine()) != null) { if (line.contains("$")) { String demo = line.replace("$", ""); for (Map.Entry<String, String> entry : resMap.entrySet()) { String a = String.format(demo, entry.getKey(), entry.getValue()) + "\n"; contentBuffer.append(a); } } else if (line.contains(" line = String.format(line.replace("#", ""), getGameClassPath()); line = line.replaceAll("/", "."); contentBuffer.append(line + "\n"); } else { contentBuffer.append(line + "\n"); } } } catch (IOException e) { Gdx.app.error(TAG, "", e); } if (contentBuffer.length() > 0) { String projectname = System.getProperty("user.dir").replace("desktop", "core"); // =/Users/haocao/git/CHGame/my-gdx-game-core projectname = projectname.substring(projectname.lastIndexOf("/") + 1); String coreProjectSrc = String.format("%s/src/", projectname); String resJavaFile = coreProjectSrc + getGameClassPath(); File resFile = new File(resJavaFile); if (!resFile.exists()) { resFile.mkdir(); } FileHandle fileHandle = new FileHandle(resFile + "/GdxR.java"); fileHandle.writeBytes(contentBuffer.toString().getBytes(), false); Gdx.app.debug(TAG, "write GdxR.java --> " + fileHandle); } Gdx.app.debug(TAG, "generated GdxR.java finished"); } /** assets */ private static void loadResNames(String path) { // path C:\development\git-repository\company-project\libgdx-ingenuity\android\assets assets path int idxAssetEnd = path.contains(ResRoot) ? (path.lastIndexOf(ResRoot) + ResRoot.length() + 1) : -1; if (idxAssetEnd > 6) { path = path.substring(idxAssetEnd); } // path file handle FileHandle[] fileHandles = getFileHandles(path); for (FileHandle fileHandle : fileHandles) { String pathAbsolute = fileHandle.path(); if (fileHandle.isDirectory()) { loadResNames(pathAbsolute); } else { String fileName = fileHandle.name().replaceAll("[\\.\\-]", "_"); // mac .DS_Store if (fileName.contains("DS_Store")) { continue; } if (Character.isDigit(fileName.toCharArray()[0])) { fileName = "_" + fileName; } // assets path int assetEnd = pathAbsolute.lastIndexOf(ResRoot); // assets String folderPath = pathAbsolute.substring(assetEnd + ResRoot.length() + 1, pathAbsolute.indexOf(fileHandle.name())); folderPath = folderPath.replaceAll("/", ""); String key = folderPath + (StrUtil.isBlank(folderPath) ? "" : "_") + fileName; String value = pathAbsolute.substring(assetEnd + ResRoot.length() + 1); resMap.put(key, value); } } } private static FileHandle[] getFileHandles(String fileName) { if (Gdx.app.getType() == ApplicationType.Desktop) { try { File directory = new File(""); String courseFile = directory.getCanonicalPath(); courseFile = courseFile.replace("desktop", "android"); File assetFile = new File(courseFile + File.separator + ResRoot + File.separator + fileName); File[] files = assetFile.listFiles(); if (files == null) return new FileHandle[]{}; FileHandle[] handles = new FileHandle[files.length]; for (int i = 0, l = files.length; i < l; i++) { handles[i] = new FileHandle(files[i]); } return handles; } catch (IOException ioException) { Gdx.app.error(TAG, "load assets error :" + ioException.getLocalizedMessage()); } } FileHandle parentFileHandle = Gdx.files.internal(fileName); return parentFileHandle.list(); } /** game */ private static String getGameClassPath() { Class<?> gameclass = IngenuityGdx.class; String gameClassPath = gameclass.getName().replaceAll("\\.", "/"); gameClassPath = gameClassPath.substring(0, gameClassPath.lastIndexOf("/")); return gameClassPath; } }
package com.rsomeara.factorio.modlauncher; import java.io.IOException; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.ButtonBar.ButtonData; import javafx.scene.control.ButtonType; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.TextField; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; public class Controller { @FXML private Button launchButton; @FXML private Button newButton; @FXML private TreeView<String> modPackTree; @FXML private TextField nameField; @FXML private ListView<String> modsList; @FXML private Button deleteButton; @FXML private Label errorLabel; @FXML private void initialize() { // watch for focus on the nameField nameField.focusedProperty().addListener(this::textBoxFocusLost); modPackTree.setShowRoot(false); try { // Check that the current mod pack is unaltered List<String> savedModList = Services.getModPackService().getCurrentSavedModList(); List<String> activeModList = Services.getFactorioService().getEnabledMods(); if (savedModList.size() != activeModList.size() || !savedModList.containsAll(activeModList)) { // Open a dialog box linked into event calls // (update current, create new from, discard // changes) Alert alert = new Alert(AlertType.CONFIRMATION); alert.setTitle("Mods pack changed"); alert.setHeaderText("The mods in " + Services.getModPackService().getActive() + " were changed in factorio. Would you like to save the changes?"); // alert.setContentText(); ButtonType buttonTypeSave = new ButtonType("Save", ButtonData.LEFT); ButtonType buttonTypeSaveAs = new ButtonType("Save As...", ButtonData.LEFT); ButtonType buttonTypeCancel = new ButtonType("Discard Changes", ButtonData.CANCEL_CLOSE); alert.getButtonTypes().setAll(buttonTypeSave, buttonTypeSaveAs, buttonTypeCancel); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == buttonTypeSave) { // ... user chose "save" System.out.println("save"); } else if (result.get() == buttonTypeSaveAs) { // ... user chose "save as" System.out.println("save as"); } else { // ... user chose CANCEL or closed the dialog System.out.println("close"); } } // Load the current mod pack name, available packs, and mod list updateCurrentModPackFields(); updateModPackListFields(); } catch ( IOException e) { throw new RuntimeException("Error loading data", e); } } /** * this button will close the launcher and start Factorio */ @FXML public void launchButtonClick() { System.out.println("you clicked launch"); clearError(); } /** * this button will clone the current pack and create a new one with a user * entered name */ @FXML public void newButtonClick() { clearError(); String newName = nameField.getText() + " (Copy)"; try { String name = Services.getModPackService().create(newName); Services.getModPackService().setActive(name); updateCurrentModPackFields(); updateModPackListFields(); } catch (Exception e) { errorOccured("Error creating modpack" + e.getMessage()); throw new RuntimeException("Error creating modpack", e); } } /** * this will change which mod pack is selected, will update the values in * modsList and nameField */ @FXML public void modPackTreeClick() { clearError(); String selectedName = modPackTree.getSelectionModel().getSelectedItem().getValue(); try { Services.getModPackService().setActive(selectedName); updateCurrentModPackFields(); } catch (Exception e) { errorOccured("Error switching modpack" + e.getMessage()); throw new RuntimeException("Error switching modpack", e); } } /** * this will trigger the name change when the enter key is hit */ @FXML public void onEnter(ActionEvent ae) { clearError(); String newName = nameField.getText(); try { updateCurrentModPackName(newName); updateCurrentModPackFields(); updateModPackListFields(); } catch (Exception e) { errorOccured("Error updating modpack name" + e.getMessage()); throw new RuntimeException("Error updating modpack name", e); } } /** * will delete the selected mod pack when clicked */ public void deleteButtonClicked() { clearError(); try { String currentModPackName = Services.getModPackService().getActive(); // Find next on list Optional<String> next = Services.getModPackService().getAll().stream() .filter(input -> !Objects.equals(input, currentModPackName)).findFirst(); if (!next.isPresent()) { errorOccured("Cannot delete last mod pack"); } else { // Update current pack Services.getModPackService().setActive(next.get()); updateCurrentModPackFields(); // Remove target pack Services.getModPackService().delete(currentModPackName); updateModPackListFields(); } } catch (Exception e) { errorOccured("Error deleting modpack " + e.getMessage()); throw new RuntimeException("Error deleting modpack", e); } } /** * this will show any errors that come up. otherwise there won't be text so * it won't show anything */ public void errorOccured(String errorMsg) { // write to field errorLabel errorLabel.setText(errorMsg); } public void clearError() { errorLabel.setText(""); } private void updateCurrentModPackFields() throws IOException { // Mod pack name String currentModPackName = Services.getModPackService().getActive(); // Current mod list List<String> enabledMods = Services.getFactorioService().getEnabledMods(); nameField.setText(currentModPackName); if (modsList.getItems() == null) { modsList.setItems(FXCollections.observableArrayList()); } modsList.getItems().clear(); modsList.getItems().addAll(enabledMods); } private void updateModPackListFields() throws IOException { // Mod pack list List<TreeItem<String>> modPackNames = Services.getModPackService().getAll().stream() .map(input -> new TreeItem<>(input)).collect(Collectors.toList()); if (modPackTree.getRoot() == null) { TreeItem<String> root = new TreeItem<>("ModPacks"); root.setExpanded(true); modPackTree.setRoot(root); } modPackTree.getRoot().getChildren().clear(); modPackNames.stream().forEach(input -> modPackTree.getRoot().getChildren().add(input)); } private void updateCurrentModPackName(String newName) throws IOException { // Get current name String currentModPackName = Services.getModPackService().getActive(); if (!Objects.equals(currentModPackName, newName)) { // Create and switch to new modpack with name String name = Services.getModPackService().create(newName); Services.getModPackService().setActive(name); // Delete old mod pack Services.getModPackService().delete(currentModPackName); } } /** * this will trigger the name change when the name box it loses focus */ private void textBoxFocusLost(ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) { if (!newPropertyValue) { String newName = nameField.getText(); try { updateCurrentModPackName(newName); updateCurrentModPackFields(); updateModPackListFields(); } catch (IOException e) { throw new RuntimeException("Error updating modpack name", e); } } } }
package bisq.core.btc.wallet; import bisq.core.btc.exceptions.AddressEntryException; import bisq.core.btc.exceptions.InsufficientFundsException; import bisq.core.btc.exceptions.TransactionVerificationException; import bisq.core.btc.exceptions.WalletException; import bisq.core.btc.model.AddressEntry; import bisq.core.btc.model.AddressEntryList; import bisq.core.btc.model.RawTransactionInput; import bisq.core.btc.setup.WalletsSetup; import bisq.core.btc.wallet.http.MemPoolSpaceTxBroadcaster; import bisq.core.provider.fee.FeeService; import bisq.core.user.Preferences; import bisq.common.handlers.ErrorMessageHandler; import bisq.common.util.Tuple2; import org.bitcoinj.core.Address; import org.bitcoinj.core.AddressFormatException; import org.bitcoinj.core.Coin; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.InsufficientMoneyException; import org.bitcoinj.core.SegwitAddress; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionConfidence; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutPoint; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.crypto.DeterministicKey; import org.bitcoinj.crypto.KeyCrypterScrypt; import org.bitcoinj.script.Script; import org.bitcoinj.script.ScriptBuilder; import org.bitcoinj.script.ScriptPattern; import org.bitcoinj.wallet.CoinSelection; import org.bitcoinj.wallet.SendRequest; import org.bitcoinj.wallet.Wallet; import javax.inject.Inject; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.MoreExecutors; import org.bouncycastle.crypto.params.KeyParameter; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.jetbrains.annotations.NotNull; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; public class BtcWalletService extends WalletService { private static final Logger log = LoggerFactory.getLogger(BtcWalletService.class); private final AddressEntryList addressEntryList; // Constructor @Inject public BtcWalletService(WalletsSetup walletsSetup, AddressEntryList addressEntryList, Preferences preferences, FeeService feeService) { super(walletsSetup, preferences, feeService); this.addressEntryList = addressEntryList; walletsSetup.addSetupCompletedHandler(() -> { wallet = walletsSetup.getBtcWallet(); addListenersToWallet(); walletsSetup.getChain().addNewBestBlockListener(block -> chainHeightProperty.set(block.getHeight())); chainHeightProperty.set(walletsSetup.getChain().getBestChainHeight()); }); } // Overridden Methods @Override void decryptWallet(@NotNull KeyParameter key) { super.decryptWallet(key); addressEntryList.getAddressEntriesAsListImmutable().forEach(e -> { DeterministicKey keyPair = e.getKeyPair(); if (keyPair.isEncrypted()) e.setDeterministicKey(keyPair.decrypt(key)); }); addressEntryList.requestPersistence(); } @Override void encryptWallet(KeyCrypterScrypt keyCrypterScrypt, KeyParameter key) { super.encryptWallet(keyCrypterScrypt, key); addressEntryList.getAddressEntriesAsListImmutable().forEach(e -> { DeterministicKey keyPair = e.getKeyPair(); if (keyPair.isEncrypted()) e.setDeterministicKey(keyPair.encrypt(keyCrypterScrypt, key)); }); addressEntryList.requestPersistence(); } @Override String getWalletAsString(boolean includePrivKeys) { StringBuilder sb = new StringBuilder(); getAddressEntryListAsImmutableList().forEach(e -> sb.append(e.toString()).append("\n")); //boolean reallyIncludePrivKeys = includePrivKeys && !wallet.isEncrypted(); return "Address entry list:\n" + sb.toString() + "\n\n" + wallet.toString(true, includePrivKeys, this.aesKey, true, true, walletsSetup.getChain()) + "\n\n" + "All pubKeys as hex:\n" + wallet.printAllPubKeysAsHex(); } // Public Methods // Burn BSQ txs (some proposal txs, asset listing fee tx, proof of burn tx) public Transaction completePreparedBurnBsqTx(Transaction preparedBurnFeeTx, byte[] opReturnData) throws WalletException, InsufficientMoneyException, TransactionVerificationException { return completePreparedProposalTx(preparedBurnFeeTx, opReturnData, null, null); } // Proposal txs public Transaction completePreparedReimbursementRequestTx(Coin issuanceAmount, Address issuanceAddress, Transaction feeTx, byte[] opReturnData) throws TransactionVerificationException, WalletException, InsufficientMoneyException { return completePreparedProposalTx(feeTx, opReturnData, issuanceAmount, issuanceAddress); } public Transaction completePreparedCompensationRequestTx(Coin issuanceAmount, Address issuanceAddress, Transaction feeTx, byte[] opReturnData) throws TransactionVerificationException, WalletException, InsufficientMoneyException { return completePreparedProposalTx(feeTx, opReturnData, issuanceAmount, issuanceAddress); } private Transaction completePreparedProposalTx(Transaction feeTx, byte[] opReturnData, @Nullable Coin issuanceAmount, @Nullable Address issuanceAddress) throws TransactionVerificationException, WalletException, InsufficientMoneyException { // (BsqFee)tx has following structure: // inputs [1-n] BSQ inputs (fee) // outputs [0-1] BSQ request fee change output (>= 546 Satoshi) // preparedCompensationRequestTx has following structure: // inputs [1-n] BSQ inputs for request fee // inputs [1-n] BTC inputs for BSQ issuance and miner fee // outputs [1] Mandatory BSQ request fee change output (>= 546 Satoshi) // outputs [1] Potentially BSQ issuance output (>= 546 Satoshi) - in case of a issuance tx, otherwise that output does not exist // outputs [0-1] BTC change output from issuance and miner fee inputs (>= 546 Satoshi) // outputs [1] OP_RETURN with opReturnData and amount 0 // mining fee: BTC mining fee + burned BSQ fee Transaction preparedTx = new Transaction(params); // Copy inputs from BSQ fee tx feeTx.getInputs().forEach(preparedTx::addInput); int indexOfBtcFirstInput = feeTx.getInputs().size(); // Need to be first because issuance is not guaranteed to be valid and would otherwise burn change output! // BSQ change outputs from BSQ fee inputs. feeTx.getOutputs().forEach(preparedTx::addOutput); // For generic proposals there is no issuance output, for compensation and reimburse requests there is if (issuanceAmount != null && issuanceAddress != null) { // BSQ issuance output preparedTx.addOutput(issuanceAmount, issuanceAddress); } // safety check counter to avoid endless loops int counter = 0; // estimated size of input sig int sigSizePerInput = 106; // typical size for a tx with 3 inputs int txVsizeWithUnsignedInputs = 300; Coin txFeePerVbyte = feeService.getTxFeePerVbyte(); Address changeAddress = getFreshAddressEntry().getAddress(); checkNotNull(changeAddress, "changeAddress must not be null"); BtcCoinSelector coinSelector = new BtcCoinSelector(walletsSetup.getAddressesByContext(AddressEntry.Context.AVAILABLE), preferences.getIgnoreDustThreshold()); List<TransactionInput> preparedBsqTxInputs = preparedTx.getInputs(); List<TransactionOutput> preparedBsqTxOutputs = preparedTx.getOutputs(); Tuple2<Integer, Integer> numInputs = getNumInputs(preparedTx); int numLegacyInputs = numInputs.first; int numSegwitInputs = numInputs.second; Transaction resultTx = null; boolean isFeeOutsideTolerance; do { counter++; if (counter >= 10) { checkNotNull(resultTx, "resultTx must not be null"); log.error("Could not calculate the fee. Tx=" + resultTx); break; } Transaction tx = new Transaction(params); preparedBsqTxInputs.forEach(tx::addInput); preparedBsqTxOutputs.forEach(tx::addOutput); SendRequest sendRequest = SendRequest.forTx(tx); sendRequest.shuffleOutputs = false; sendRequest.aesKey = aesKey; // signInputs needs to be false as it would try to sign all inputs (BSQ inputs are not in this wallet) sendRequest.signInputs = false; sendRequest.fee = txFeePerVbyte.multiply(txVsizeWithUnsignedInputs + sigSizePerInput * numLegacyInputs + sigSizePerInput * numSegwitInputs / 4); sendRequest.feePerKb = Coin.ZERO; sendRequest.ensureMinRequiredFee = false; sendRequest.coinSelector = coinSelector; sendRequest.changeAddress = changeAddress; wallet.completeTx(sendRequest); resultTx = sendRequest.tx; // add OP_RETURN output resultTx.addOutput(new TransactionOutput(params, resultTx, Coin.ZERO, ScriptBuilder.createOpReturnScript(opReturnData).getProgram())); numInputs = getNumInputs(resultTx); numLegacyInputs = numInputs.first; numSegwitInputs = numInputs.second; txVsizeWithUnsignedInputs = resultTx.getVsize(); long estimatedFeeAsLong = txFeePerVbyte.multiply(txVsizeWithUnsignedInputs + sigSizePerInput * numLegacyInputs + sigSizePerInput * numSegwitInputs / 4).value; // calculated fee must be inside of a tolerance range with tx fee isFeeOutsideTolerance = Math.abs(resultTx.getFee().value - estimatedFeeAsLong) > 1000; } while (isFeeOutsideTolerance); // Sign all BTC inputs signAllBtcInputs(indexOfBtcFirstInput, resultTx); checkWalletConsistency(wallet); verifyTransaction(resultTx); // printTx("BTC wallet: Signed tx", resultTx); return resultTx; } // Blind vote tx // We add BTC inputs to pay miner fees and sign the BTC tx inputs // (BsqFee)tx has following structure: // inputs [1-n] BSQ inputs (fee + stake) // outputs [1] BSQ stake // outputs [0-1] BSQ change output (>= 546 Satoshi) // preparedVoteTx has following structure: // inputs [1-n] BSQ inputs (fee + stake) // inputs [1-n] BTC inputs for miner fee // outputs [1] BSQ stake // outputs [0-1] BSQ change output (>= 546 Satoshi) // outputs [0-1] BTC change output from miner fee inputs (>= 546 Satoshi) // outputs [1] OP_RETURN with opReturnData and amount 0 // mining fee: BTC mining fee + burned BSQ fee public Transaction completePreparedBlindVoteTx(Transaction preparedTx, byte[] opReturnData) throws TransactionVerificationException, WalletException, InsufficientMoneyException { // First input index for btc inputs (they get added after bsq inputs) return completePreparedBsqTxWithBtcFee(preparedTx, opReturnData); } private Transaction completePreparedBsqTxWithBtcFee(Transaction preparedTx, byte[] opReturnData) throws InsufficientMoneyException, TransactionVerificationException, WalletException { // Remember index for first BTC input int indexOfBtcFirstInput = preparedTx.getInputs().size(); Transaction tx = addInputsForMinerFee(preparedTx, opReturnData); signAllBtcInputs(indexOfBtcFirstInput, tx); checkWalletConsistency(wallet); verifyTransaction(tx); // printTx("BTC wallet: Signed tx", tx); return tx; } private Transaction addInputsForMinerFee(Transaction preparedTx, byte[] opReturnData) throws InsufficientMoneyException { // safety check counter to avoid endless loops int counter = 0; // estimated size of input sig int sigSizePerInput = 106; // typical size for a tx with 3 inputs int txVsizeWithUnsignedInputs = 300; Coin txFeePerVbyte = feeService.getTxFeePerVbyte(); Address changeAddress = getFreshAddressEntry().getAddress(); checkNotNull(changeAddress, "changeAddress must not be null"); BtcCoinSelector coinSelector = new BtcCoinSelector(walletsSetup.getAddressesByContext(AddressEntry.Context.AVAILABLE), preferences.getIgnoreDustThreshold()); List<TransactionInput> preparedBsqTxInputs = preparedTx.getInputs(); List<TransactionOutput> preparedBsqTxOutputs = preparedTx.getOutputs(); Tuple2<Integer, Integer> numInputs = getNumInputs(preparedTx); int numLegacyInputs = numInputs.first; int numSegwitInputs = numInputs.second; Transaction resultTx = null; boolean isFeeOutsideTolerance; do { counter++; if (counter >= 10) { checkNotNull(resultTx, "resultTx must not be null"); log.error("Could not calculate the fee. Tx=" + resultTx); break; } Transaction tx = new Transaction(params); preparedBsqTxInputs.forEach(tx::addInput); preparedBsqTxOutputs.forEach(tx::addOutput); SendRequest sendRequest = SendRequest.forTx(tx); sendRequest.shuffleOutputs = false; sendRequest.aesKey = aesKey; // signInputs needs to be false as it would try to sign all inputs (BSQ inputs are not in this wallet) sendRequest.signInputs = false; sendRequest.fee = txFeePerVbyte.multiply(txVsizeWithUnsignedInputs + sigSizePerInput * numLegacyInputs + sigSizePerInput * numSegwitInputs / 4); sendRequest.feePerKb = Coin.ZERO; sendRequest.ensureMinRequiredFee = false; sendRequest.coinSelector = coinSelector; sendRequest.changeAddress = changeAddress; wallet.completeTx(sendRequest); resultTx = sendRequest.tx; // add OP_RETURN output resultTx.addOutput(new TransactionOutput(params, resultTx, Coin.ZERO, ScriptBuilder.createOpReturnScript(opReturnData).getProgram())); numInputs = getNumInputs(resultTx); numLegacyInputs = numInputs.first; numSegwitInputs = numInputs.second; txVsizeWithUnsignedInputs = resultTx.getVsize(); final long estimatedFeeAsLong = txFeePerVbyte.multiply(txVsizeWithUnsignedInputs + sigSizePerInput * numLegacyInputs + sigSizePerInput * numSegwitInputs / 4).value; // calculated fee must be inside of a tolerance range with tx fee isFeeOutsideTolerance = Math.abs(resultTx.getFee().value - estimatedFeeAsLong) > 1000; } while (isFeeOutsideTolerance); return resultTx; } private void signAllBtcInputs(int indexOfBtcFirstInput, Transaction tx) throws TransactionVerificationException { for (int i = indexOfBtcFirstInput; i < tx.getInputs().size(); i++) { TransactionInput input = tx.getInputs().get(i); checkArgument(input.getConnectedOutput() != null && input.getConnectedOutput().isMine(wallet), "input.getConnectedOutput() is not in our wallet. That must not happen."); signTransactionInput(wallet, aesKey, tx, input, i); checkScriptSig(tx, input, i); } } // Vote reveal tx // We add BTC fees to the prepared reveal tx // (BsqFee)tx has following structure: // inputs [1] BSQ input (stake) // output [1] BSQ unlocked stake // preparedVoteTx has following structure: // inputs [1] BSQ inputs (stake) // inputs [1-n] BTC inputs for miner fee // outputs [1] BSQ unlocked stake // outputs [0-1] BTC change output from miner fee inputs (>= 546 Satoshi) // outputs [1] OP_RETURN with opReturnData and amount 0 // mining fee: BTC mining fee + burned BSQ fee public Transaction completePreparedVoteRevealTx(Transaction preparedTx, byte[] opReturnData) throws TransactionVerificationException, WalletException, InsufficientMoneyException { return completePreparedBsqTxWithBtcFee(preparedTx, opReturnData); } // Add fee input to prepared BSQ send tx public Transaction completePreparedSendBsqTx(Transaction preparedBsqTx) throws TransactionVerificationException, WalletException, InsufficientMoneyException { // preparedBsqTx has following structure: // inputs [1-n] BSQ inputs // outputs [1] BSQ receiver's output // outputs [0-1] BSQ change output // We add BTC mining fee. Result tx looks like: // inputs [1-n] BSQ inputs // inputs [1-n] BTC inputs // outputs [1] BSQ receiver's output // outputs [0-1] BSQ change output // outputs [0-1] BTC change output // mining fee: BTC mining fee Coin txFeePerVbyte = getTxFeeForWithdrawalPerVbyte(); return completePreparedBsqTx(preparedBsqTx, null, txFeePerVbyte); } public Transaction completePreparedSendBsqTx(Transaction preparedBsqTx, Coin txFeePerVbyte) throws TransactionVerificationException, WalletException, InsufficientMoneyException { return completePreparedBsqTx(preparedBsqTx, null, txFeePerVbyte); } public Transaction completePreparedBsqTx(Transaction preparedBsqTx, @Nullable byte[] opReturnData) throws TransactionVerificationException, WalletException, InsufficientMoneyException { Coin txFeePerVbyte = getTxFeeForWithdrawalPerVbyte(); return completePreparedBsqTx(preparedBsqTx, opReturnData, txFeePerVbyte); } public Transaction completePreparedBsqTx(Transaction preparedBsqTx, @Nullable byte[] opReturnData, Coin txFeePerVbyte) throws TransactionVerificationException, WalletException, InsufficientMoneyException { // preparedBsqTx has following structure: // inputs [1-n] BSQ inputs // outputs [1] BSQ receiver's output // outputs [0-1] BSQ change output // mining fee: optional burned BSQ fee (only if opReturnData != null) // We add BTC mining fee. Result tx looks like: // inputs [1-n] BSQ inputs // inputs [1-n] BTC inputs // outputs [0-1] BSQ receiver's output // outputs [0-1] BSQ change output // outputs [0-1] BTC change output // outputs [0-1] OP_RETURN with opReturnData (only if opReturnData != null) // mining fee: BTC mining fee + optional burned BSQ fee (only if opReturnData != null) // In case of txs for burned BSQ fees we have no receiver output and it might be that there is no change outputs // We need to guarantee that min. 1 valid output is added (OP_RETURN does not count). So we use a higher input // for BTC to force an additional change output. // safety check counter to avoid endless loops int counter = 0; // estimated size of input sig int sigSizePerInput = 106; // typical size for a tx with 2 inputs int txVsizeWithUnsignedInputs = 203; // In case there are no change outputs we force a change by adding min dust to the BTC input Coin forcedChangeValue = Coin.ZERO; Address changeAddress = getFreshAddressEntry().getAddress(); checkNotNull(changeAddress, "changeAddress must not be null"); BtcCoinSelector coinSelector = new BtcCoinSelector(walletsSetup.getAddressesByContext(AddressEntry.Context.AVAILABLE), preferences.getIgnoreDustThreshold()); List<TransactionInput> preparedBsqTxInputs = preparedBsqTx.getInputs(); List<TransactionOutput> preparedBsqTxOutputs = preparedBsqTx.getOutputs(); // We don't know at this point what type the btc input would be (segwit/legacy). // We use legacy to be on the safe side. int numLegacyInputs = preparedBsqTxInputs.size() + 1; // We add 1 for the BTC fee input int numSegwitInputs = 0; Transaction resultTx = null; boolean isFeeOutsideTolerance; boolean opReturnIsOnlyOutput; do { counter++; if (counter >= 10) { checkNotNull(resultTx, "resultTx must not be null"); log.error("Could not calculate the fee. Tx=" + resultTx); break; } Transaction tx = new Transaction(params); preparedBsqTxInputs.forEach(tx::addInput); if (forcedChangeValue.isZero()) { preparedBsqTxOutputs.forEach(tx::addOutput); } else { //TODO test that case checkArgument(preparedBsqTxOutputs.size() == 0, "preparedBsqTxOutputs.size must be null in that code branch"); tx.addOutput(forcedChangeValue, changeAddress); } SendRequest sendRequest = SendRequest.forTx(tx); sendRequest.shuffleOutputs = false; sendRequest.aesKey = aesKey; // signInputs needs to be false as it would try to sign all inputs (BSQ inputs are not in this wallet) sendRequest.signInputs = false; sendRequest.fee = txFeePerVbyte.multiply(txVsizeWithUnsignedInputs + sigSizePerInput * numLegacyInputs + sigSizePerInput * numSegwitInputs / 4); sendRequest.feePerKb = Coin.ZERO; sendRequest.ensureMinRequiredFee = false; sendRequest.coinSelector = coinSelector; sendRequest.changeAddress = changeAddress; wallet.completeTx(sendRequest); resultTx = sendRequest.tx; // We might have the rare case that both inputs matched the required fees, so both did not require // a change output. // In such cases we need to add artificially a change output (OP_RETURN is not allowed as only output) opReturnIsOnlyOutput = resultTx.getOutputs().size() == 0; forcedChangeValue = opReturnIsOnlyOutput ? Restrictions.getMinNonDustOutput() : Coin.ZERO; // add OP_RETURN output if (opReturnData != null) resultTx.addOutput(new TransactionOutput(params, resultTx, Coin.ZERO, ScriptBuilder.createOpReturnScript(opReturnData).getProgram())); Tuple2<Integer, Integer> numInputs = getNumInputs(resultTx); numLegacyInputs = numInputs.first; numSegwitInputs = numInputs.second; txVsizeWithUnsignedInputs = resultTx.getVsize(); final long estimatedFeeAsLong = txFeePerVbyte.multiply(txVsizeWithUnsignedInputs + sigSizePerInput * numLegacyInputs + sigSizePerInput * numSegwitInputs / 4).value; // calculated fee must be inside of a tolerance range with tx fee isFeeOutsideTolerance = Math.abs(resultTx.getFee().value - estimatedFeeAsLong) > 1000; } while (opReturnIsOnlyOutput || isFeeOutsideTolerance || resultTx.getFee().value < txFeePerVbyte.multiply(resultTx.getVsize()).value); // Sign all BTC inputs signAllBtcInputs(preparedBsqTxInputs.size(), resultTx); checkWalletConsistency(wallet); verifyTransaction(resultTx); printTx("BTC wallet: Signed tx", resultTx); return resultTx; } private Tuple2<Integer, Integer> getNumInputs(Transaction tx) { int numLegacyInputs = 0; int numSegwitInputs = 0; for (TransactionInput input : tx.getInputs()) { TransactionOutput connectedOutput = input.getConnectedOutput(); if (connectedOutput == null || ScriptPattern.isP2PKH(connectedOutput.getScriptPubKey()) || ScriptPattern.isP2PK(connectedOutput.getScriptPubKey())) { // If connectedOutput is null, we don't know here the input type. To avoid underpaying fees, // we treat it as a legacy input which will result in a higher fee estimation. numLegacyInputs++; } else if (ScriptPattern.isP2WPKH(connectedOutput.getScriptPubKey())) { numSegwitInputs++; } else { throw new IllegalArgumentException("Inputs should spend a P2PKH, P2PK or P2WPKH output"); } } return new Tuple2<>(numLegacyInputs, numSegwitInputs); } // Commit tx public void commitTx(Transaction tx) { wallet.commitTx(tx); // printTx("BTC commit Tx", tx); } // AddressEntry public Optional<AddressEntry> getAddressEntry(String offerId, @SuppressWarnings("SameParameterValue") AddressEntry.Context context) { return getAddressEntryListAsImmutableList().stream() .filter(e -> offerId.equals(e.getOfferId())) .filter(e -> context == e.getContext()) .findAny(); } public AddressEntry getOrCreateAddressEntry(String offerId, AddressEntry.Context context) { Optional<AddressEntry> addressEntry = getAddressEntryListAsImmutableList().stream() .filter(e -> offerId.equals(e.getOfferId())) .filter(e -> context == e.getContext()) .findAny(); if (addressEntry.isPresent()) { return addressEntry.get(); } else { // We try to use available and not yet used entries Optional<AddressEntry> emptyAvailableAddressEntry = getAddressEntryListAsImmutableList().stream() .filter(e -> AddressEntry.Context.AVAILABLE == e.getContext()) .filter(e -> isAddressUnused(e.getAddress())) .filter(e -> Script.ScriptType.P2WPKH.equals(e.getAddress().getOutputScriptType())) .findAny(); if (emptyAvailableAddressEntry.isPresent()) { return addressEntryList.swapAvailableToAddressEntryWithOfferId(emptyAvailableAddressEntry.get(), context, offerId); } else { DeterministicKey key = (DeterministicKey) wallet.findKeyFromAddress(wallet.freshReceiveAddress(Script.ScriptType.P2WPKH)); AddressEntry entry = new AddressEntry(key, context, offerId, true); log.info("getOrCreateAddressEntry: new AddressEntry={}", entry); addressEntryList.addAddressEntry(entry); return entry; } } } public AddressEntry getArbitratorAddressEntry() { AddressEntry.Context context = AddressEntry.Context.ARBITRATOR; Optional<AddressEntry> addressEntry = getAddressEntryListAsImmutableList().stream() .filter(e -> context == e.getContext()) .findAny(); return getOrCreateAddressEntry(context, addressEntry, false); } public AddressEntry getFreshAddressEntry() { return getFreshAddressEntry(true); } public AddressEntry getFreshAddressEntry(boolean segwit) { AddressEntry.Context context = AddressEntry.Context.AVAILABLE; Optional<AddressEntry> addressEntry = getAddressEntryListAsImmutableList().stream() .filter(e -> context == e.getContext()) .filter(e -> isAddressUnused(e.getAddress())) .filter(e -> { boolean isSegwitOutputScriptType = Script.ScriptType.P2WPKH.equals(e.getAddress().getOutputScriptType()); // We need to ensure that we take only addressEntries which matches our segWit flag return isSegwitOutputScriptType == segwit; }) .findAny(); return getOrCreateAddressEntry(context, addressEntry, segwit); } public void recoverAddressEntry(String offerId, String address, AddressEntry.Context context) { findAddressEntry(address, AddressEntry.Context.AVAILABLE).ifPresent(addressEntry -> addressEntryList.swapAvailableToAddressEntryWithOfferId(addressEntry, context, offerId)); } private AddressEntry getOrCreateAddressEntry(AddressEntry.Context context, Optional<AddressEntry> addressEntry, boolean segwit) { if (addressEntry.isPresent()) { return addressEntry.get(); } else { DeterministicKey key; if (segwit) { key = (DeterministicKey) wallet.findKeyFromAddress(wallet.freshReceiveAddress(Script.ScriptType.P2WPKH)); } else { key = (DeterministicKey) wallet.findKeyFromAddress(wallet.freshReceiveAddress(Script.ScriptType.P2PKH)); } AddressEntry entry = new AddressEntry(key, context, segwit); log.info("getOrCreateAddressEntry: add new AddressEntry {}", entry); addressEntryList.addAddressEntry(entry); return entry; } } private Optional<AddressEntry> findAddressEntry(String address, AddressEntry.Context context) { return getAddressEntryListAsImmutableList().stream() .filter(e -> address.equals(e.getAddressString())) .filter(e -> context == e.getContext()) .findAny(); } public List<AddressEntry> getAvailableAddressEntries() { return getAddressEntryListAsImmutableList().stream() .filter(addressEntry -> AddressEntry.Context.AVAILABLE == addressEntry.getContext()) .collect(Collectors.toList()); } public List<AddressEntry> getAddressEntriesForOpenOffer() { return getAddressEntryListAsImmutableList().stream() .filter(addressEntry -> AddressEntry.Context.OFFER_FUNDING == addressEntry.getContext() || AddressEntry.Context.RESERVED_FOR_TRADE == addressEntry.getContext()) .collect(Collectors.toList()); } public List<AddressEntry> getAddressEntriesForTrade() { return getAddressEntryListAsImmutableList().stream() .filter(addressEntry -> AddressEntry.Context.MULTI_SIG == addressEntry.getContext() || AddressEntry.Context.TRADE_PAYOUT == addressEntry.getContext()) .collect(Collectors.toList()); } public List<AddressEntry> getAddressEntries(AddressEntry.Context context) { return getAddressEntryListAsImmutableList().stream() .filter(addressEntry -> context == addressEntry.getContext()) .collect(Collectors.toList()); } public List<AddressEntry> getFundedAvailableAddressEntries() { return getAvailableAddressEntries().stream() .filter(addressEntry -> getBalanceForAddress(addressEntry.getAddress()).isPositive()) .collect(Collectors.toList()); } public List<AddressEntry> getAddressEntryListAsImmutableList() { return addressEntryList.getAddressEntriesAsListImmutable(); } public void swapTradeEntryToAvailableEntry(String offerId, AddressEntry.Context context) { if (context == AddressEntry.Context.MULTI_SIG) { log.error("swapTradeEntryToAvailableEntry called with MULTI_SIG context. " + "This in not permitted as we must not reuse those address entries and there " + "are no redeemable funds on that addresses. Only the keys are used for creating " + "the Multisig address. offerId={}, context={}", offerId, context); return; } getAddressEntryListAsImmutableList().stream() .filter(e -> offerId.equals(e.getOfferId())) .filter(e -> context == e.getContext()) .forEach(e -> { log.info("swap addressEntry with address {} and offerId {} from context {} to available", e.getAddressString(), e.getOfferId(), context); addressEntryList.swapToAvailable(e); }); } // When funds from MultiSig address is spent we reset the coinLockedInMultiSig value to 0. public void resetCoinLockedInMultiSigAddressEntry(String offerId) { setCoinLockedInMultiSigAddressEntry(offerId, 0); } public void setCoinLockedInMultiSigAddressEntry(String offerId, long value) { getAddressEntryListAsImmutableList().stream() .filter(e -> AddressEntry.Context.MULTI_SIG == e.getContext()) .filter(e -> offerId.equals(e.getOfferId())) .forEach(addressEntry -> setCoinLockedInMultiSigAddressEntry(addressEntry, value)); } public void setCoinLockedInMultiSigAddressEntry(AddressEntry addressEntry, long value) { log.info("Set coinLockedInMultiSig for addressEntry {} to value {}", addressEntry, value); addressEntryList.setCoinLockedInMultiSigAddressEntry(addressEntry, value); } public void resetAddressEntriesForOpenOffer(String offerId) { log.info("resetAddressEntriesForOpenOffer offerId={}", offerId); swapTradeEntryToAvailableEntry(offerId, AddressEntry.Context.OFFER_FUNDING); swapTradeEntryToAvailableEntry(offerId, AddressEntry.Context.RESERVED_FOR_TRADE); } public void resetAddressEntriesForPendingTrade(String offerId) { // We must not swap MULTI_SIG entries as those addresses are not detected in the isAddressUnused // check at getOrCreateAddressEntry and could lead to a reuse of those keys and result in the same 2of2 MS // address if same peers trade again. // We swap TRADE_PAYOUT to be sure all is cleaned up. There might be cases where a user cannot send the funds // to an external wallet directly in the last step of the trade, but the funds are in the Bisq wallet anyway and // the dealing with the external wallet is pure UI thing. The user can move the funds to the wallet and then // send out the funds to the external wallet. As this cleanup is a rare situation and most users do not use // the feature to send out the funds we prefer that strategy (if we keep the address entry it might cause // complications in some edge cases after a SPV resync). swapTradeEntryToAvailableEntry(offerId, AddressEntry.Context.TRADE_PAYOUT); } public void swapAnyTradeEntryContextToAvailableEntry(String offerId) { resetAddressEntriesForOpenOffer(offerId); resetAddressEntriesForPendingTrade(offerId); } public void saveAddressEntryList() { addressEntryList.requestPersistence(); } public DeterministicKey getMultiSigKeyPair(String tradeId, byte[] pubKey) { Optional<AddressEntry> multiSigAddressEntryOptional = getAddressEntry(tradeId, AddressEntry.Context.MULTI_SIG); DeterministicKey multiSigKeyPair; if (multiSigAddressEntryOptional.isPresent()) { AddressEntry multiSigAddressEntry = multiSigAddressEntryOptional.get(); multiSigKeyPair = multiSigAddressEntry.getKeyPair(); if (!Arrays.equals(pubKey, multiSigAddressEntry.getPubKey())) { log.error("Pub Key from AddressEntry does not match key pair from trade data. Trade ID={}\n" + "We try to find the keypair in the wallet with the pubKey we found in the trade data.", tradeId); multiSigKeyPair = findKeyFromPubKey(pubKey); } } else { log.error("multiSigAddressEntry not found for trade ID={}.\n" + "We try to find the keypair in the wallet with the pubKey we found in the trade data.", tradeId); multiSigKeyPair = findKeyFromPubKey(pubKey); } return multiSigKeyPair; } // Balance public Coin getSavingWalletBalance() { return Coin.valueOf(getFundedAvailableAddressEntries().stream() .mapToLong(addressEntry -> getBalanceForAddress(addressEntry.getAddress()).value) .sum()); } public Stream<AddressEntry> getAddressEntriesForAvailableBalanceStream() { Stream<AddressEntry> availableAndPayout = Stream.concat(getAddressEntries(AddressEntry.Context.TRADE_PAYOUT) .stream(), getFundedAvailableAddressEntries().stream()); Stream<AddressEntry> available = Stream.concat(availableAndPayout, getAddressEntries(AddressEntry.Context.ARBITRATOR).stream()); available = Stream.concat(available, getAddressEntries(AddressEntry.Context.OFFER_FUNDING).stream()); return available.filter(addressEntry -> getBalanceForAddress(addressEntry.getAddress()).isPositive()); } // Double spend unconfirmed transaction (unlock in case we got into a tx with a too low mining fee) public void doubleSpendTransaction(String txId, Runnable resultHandler, ErrorMessageHandler errorMessageHandler) throws InsufficientFundsException { AddressEntry addressEntry = getFreshAddressEntry(); checkNotNull(addressEntry.getAddress(), "addressEntry.getAddress() must not be null"); Optional<Transaction> transactionOptional = wallet.getTransactions(true).stream() .filter(t -> t.getTxId().toString().equals(txId)) .findAny(); if (transactionOptional.isPresent()) { Transaction txToDoubleSpend = transactionOptional.get(); Address toAddress = addressEntry.getAddress(); final TransactionConfidence.ConfidenceType confidenceType = txToDoubleSpend.getConfidence().getConfidenceType(); if (confidenceType == TransactionConfidence.ConfidenceType.PENDING) { log.debug("txToDoubleSpend no. of inputs " + txToDoubleSpend.getInputs().size()); Transaction newTransaction = new Transaction(params); txToDoubleSpend.getInputs().forEach(input -> { final TransactionOutput connectedOutput = input.getConnectedOutput(); if (connectedOutput != null && connectedOutput.isMine(wallet) && connectedOutput.getParentTransaction() != null && connectedOutput.getParentTransaction().getConfidence() != null && input.getValue() != null) { //if (connectedOutput.getParentTransaction().getConfidence().getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING) { newTransaction.addInput(new TransactionInput(params, newTransaction, new byte[]{}, new TransactionOutPoint(params, input.getOutpoint().getIndex(), new Transaction(params, connectedOutput.getParentTransaction().bitcoinSerialize())), Coin.valueOf(input.getValue().value))); /* } else { log.warn("Confidence of parent tx is not of type BUILDING: ConfidenceType=" + connectedOutput.getParentTransaction().getConfidence().getConfidenceType()); }*/ } } ); log.info("newTransaction no. of inputs " + newTransaction.getInputs().size()); log.info("newTransaction vsize in vkB " + newTransaction.getVsize() / 1024); if (!newTransaction.getInputs().isEmpty()) { Coin amount = Coin.valueOf(newTransaction.getInputs().stream() .mapToLong(input -> input.getValue() != null ? input.getValue().value : 0) .sum()); newTransaction.addOutput(amount, toAddress); try { Coin fee; int counter = 0; int txVsize = 0; Transaction tx; SendRequest sendRequest; Coin txFeeForWithdrawalPerVbyte = getTxFeeForWithdrawalPerVbyte(); do { counter++; fee = txFeeForWithdrawalPerVbyte.multiply(txVsize); newTransaction.clearOutputs(); newTransaction.addOutput(amount.subtract(fee), toAddress); sendRequest = SendRequest.forTx(newTransaction); sendRequest.fee = fee; sendRequest.feePerKb = Coin.ZERO; sendRequest.ensureMinRequiredFee = false; sendRequest.aesKey = aesKey; sendRequest.coinSelector = new BtcCoinSelector(toAddress, preferences.getIgnoreDustThreshold()); sendRequest.changeAddress = toAddress; wallet.completeTx(sendRequest); tx = sendRequest.tx; txVsize = tx.getVsize(); printTx("FeeEstimationTransaction", tx); sendRequest.tx.getOutputs().forEach(o -> log.debug("Output value " + o.getValue().toFriendlyString())); } while (feeEstimationNotSatisfied(counter, tx)); if (counter == 10) log.error("Could not calculate the fee. Tx=" + tx); Wallet.SendResult sendResult = null; try { sendRequest = SendRequest.forTx(newTransaction); sendRequest.fee = fee; sendRequest.feePerKb = Coin.ZERO; sendRequest.ensureMinRequiredFee = false; sendRequest.aesKey = aesKey; sendRequest.coinSelector = new BtcCoinSelector(toAddress, preferences.getIgnoreDustThreshold()); sendRequest.changeAddress = toAddress; sendResult = wallet.sendCoins(sendRequest); } catch (InsufficientMoneyException e) { // in some cases getFee did not calculate correctly and we still get an InsufficientMoneyException log.warn("We still have a missing fee " + (e.missing != null ? e.missing.toFriendlyString() : "")); amount = amount.subtract(e.missing); newTransaction.clearOutputs(); newTransaction.addOutput(amount, toAddress); sendRequest = SendRequest.forTx(newTransaction); sendRequest.fee = fee; sendRequest.feePerKb = Coin.ZERO; sendRequest.ensureMinRequiredFee = false; sendRequest.aesKey = aesKey; sendRequest.coinSelector = new BtcCoinSelector(toAddress, preferences.getIgnoreDustThreshold(), false); sendRequest.changeAddress = toAddress; try { sendResult = wallet.sendCoins(sendRequest); printTx("FeeEstimationTransaction", newTransaction); // For better redundancy in case the broadcast via BitcoinJ fails we also // publish the tx via mempool nodes. MemPoolSpaceTxBroadcaster.broadcastTx(sendResult.tx); } catch (InsufficientMoneyException e2) { errorMessageHandler.handleErrorMessage("We did not get the correct fee calculated. " + (e2.missing != null ? e2.missing.toFriendlyString() : "")); } } if (sendResult != null) { log.info("Broadcasting double spending transaction. " + sendResult.tx); Futures.addCallback(sendResult.broadcastComplete, new FutureCallback<>() { @Override public void onSuccess(Transaction result) { log.info("Double spending transaction published. " + result); resultHandler.run(); } @Override public void onFailure(@NotNull Throwable t) { log.error("Broadcasting double spending transaction failed. " + t.getMessage()); errorMessageHandler.handleErrorMessage(t.getMessage()); } }, MoreExecutors.directExecutor()); } } catch (InsufficientMoneyException e) { throw new InsufficientFundsException("The fees for that transaction exceed the available funds " + "or the resulting output value is below the min. dust value:\n" + "Missing " + (e.missing != null ? e.missing.toFriendlyString() : "null")); } } else { String errorMessage = "We could not find inputs we control in the transaction we want to double spend."; log.warn(errorMessage); errorMessageHandler.handleErrorMessage(errorMessage); } } else if (confidenceType == TransactionConfidence.ConfidenceType.BUILDING) { errorMessageHandler.handleErrorMessage("That transaction is already in the blockchain so we cannot double spend it."); } else if (confidenceType == TransactionConfidence.ConfidenceType.DEAD) { errorMessageHandler.handleErrorMessage("One of the inputs of that transaction has been already double spent."); } } } // Withdrawal Fee calculation public Transaction getFeeEstimationTransaction(String fromAddress, String toAddress, Coin amount, AddressEntry.Context context) throws AddressFormatException, AddressEntryException, InsufficientFundsException { Optional<AddressEntry> addressEntry = findAddressEntry(fromAddress, context); if (!addressEntry.isPresent()) throw new AddressEntryException("WithdrawFromAddress is not found in our wallet."); checkNotNull(addressEntry.get().getAddress(), "addressEntry.get().getAddress() must nto be null"); try { Coin fee; int counter = 0; int txVsize = 0; Transaction tx; Coin txFeeForWithdrawalPerVbyte = getTxFeeForWithdrawalPerVbyte(); do { counter++; fee = txFeeForWithdrawalPerVbyte.multiply(txVsize); SendRequest sendRequest = getSendRequest(fromAddress, toAddress, amount, fee, aesKey, context); wallet.completeTx(sendRequest); tx = sendRequest.tx; txVsize = tx.getVsize(); printTx("FeeEstimationTransaction", tx); } while (feeEstimationNotSatisfied(counter, tx)); if (counter == 10) log.error("Could not calculate the fee. Tx=" + tx); return tx; } catch (InsufficientMoneyException e) { throw new InsufficientFundsException("The fees for that transaction exceed the available funds " + "or the resulting output value is below the min. dust value:\n" + "Missing " + (e.missing != null ? e.missing.toFriendlyString() : "null")); } } public Transaction getFeeEstimationTransactionForMultipleAddresses(Set<String> fromAddresses, Coin amount) throws AddressFormatException, AddressEntryException, InsufficientFundsException { Coin txFeeForWithdrawalPerVbyte = getTxFeeForWithdrawalPerVbyte(); return getFeeEstimationTransactionForMultipleAddresses(fromAddresses, amount, txFeeForWithdrawalPerVbyte); } public Transaction getFeeEstimationTransactionForMultipleAddresses(Set<String> fromAddresses, Coin amount, Coin txFeeForWithdrawalPerVbyte) throws AddressFormatException, AddressEntryException, InsufficientFundsException { Set<AddressEntry> addressEntries = fromAddresses.stream() .map(address -> { Optional<AddressEntry> addressEntryOptional = findAddressEntry(address, AddressEntry.Context.AVAILABLE); if (!addressEntryOptional.isPresent()) addressEntryOptional = findAddressEntry(address, AddressEntry.Context.OFFER_FUNDING); if (!addressEntryOptional.isPresent()) addressEntryOptional = findAddressEntry(address, AddressEntry.Context.TRADE_PAYOUT); if (!addressEntryOptional.isPresent()) addressEntryOptional = findAddressEntry(address, AddressEntry.Context.ARBITRATOR); return addressEntryOptional; }) .flatMap(Optional::stream) .collect(Collectors.toSet()); if (addressEntries.isEmpty()) throw new AddressEntryException("No Addresses for withdraw found in our wallet"); try { Coin fee; int counter = 0; int txVsize = 0; Transaction tx; do { counter++; fee = txFeeForWithdrawalPerVbyte.multiply(txVsize); // We use a dummy address for the output // We don't know here whether the output is segwit or not but we don't care too much because the size of // a segwit ouput is just 3 byte smaller than the size of a legacy ouput. final String dummyReceiver = SegwitAddress.fromKey(params, new ECKey()).toString(); SendRequest sendRequest = getSendRequestForMultipleAddresses(fromAddresses, dummyReceiver, amount, fee, null, aesKey); wallet.completeTx(sendRequest); tx = sendRequest.tx; txVsize = tx.getVsize(); printTx("FeeEstimationTransactionForMultipleAddresses", tx); } while (feeEstimationNotSatisfied(counter, tx)); if (counter == 10) log.error("Could not calculate the fee. Tx=" + tx); return tx; } catch (InsufficientMoneyException e) { throw new InsufficientFundsException("The fees for that transaction exceed the available funds " + "or the resulting output value is below the min. dust value:\n" + "Missing " + (e.missing != null ? e.missing.toFriendlyString() : "null")); } } private boolean feeEstimationNotSatisfied(int counter, Transaction tx) { return feeEstimationNotSatisfied(counter, tx, getTxFeeForWithdrawalPerVbyte()); } private boolean feeEstimationNotSatisfied(int counter, Transaction tx, Coin txFeeForWithdrawalPerVbyte) { long targetFee = txFeeForWithdrawalPerVbyte.multiply(tx.getVsize()).value; return counter < 10 && (tx.getFee().value < targetFee || tx.getFee().value - targetFee > 1000); } public int getEstimatedFeeTxVsize(List<Coin> outputValues, Coin txFee) throws InsufficientMoneyException, AddressFormatException { Transaction transaction = new Transaction(params); // In reality txs have a mix of segwit/legacy ouputs, but we don't care too much because the size of // a segwit ouput is just 3 byte smaller than the size of a legacy ouput. Address dummyAddress = SegwitAddress.fromKey(params, new ECKey()); outputValues.forEach(outputValue -> transaction.addOutput(outputValue, dummyAddress)); SendRequest sendRequest = SendRequest.forTx(transaction); sendRequest.shuffleOutputs = false; sendRequest.aesKey = aesKey; sendRequest.coinSelector = new BtcCoinSelector(walletsSetup.getAddressesByContext(AddressEntry.Context.AVAILABLE), preferences.getIgnoreDustThreshold()); sendRequest.fee = txFee; sendRequest.feePerKb = Coin.ZERO; sendRequest.ensureMinRequiredFee = false; sendRequest.changeAddress = dummyAddress; wallet.completeTx(sendRequest); return transaction.getVsize(); } // Withdrawal Send public String sendFunds(String fromAddress, String toAddress, Coin receiverAmount, Coin fee, @Nullable KeyParameter aesKey, @SuppressWarnings("SameParameterValue") AddressEntry.Context context, @Nullable String memo, FutureCallback<Transaction> callback) throws AddressFormatException, AddressEntryException, InsufficientMoneyException { SendRequest sendRequest = getSendRequest(fromAddress, toAddress, receiverAmount, fee, aesKey, context); Wallet.SendResult sendResult = wallet.sendCoins(sendRequest); Futures.addCallback(sendResult.broadcastComplete, callback, MoreExecutors.directExecutor()); if (memo != null) { sendResult.tx.setMemo(memo); } // For better redundancy in case the broadcast via BitcoinJ fails we also // publish the tx via mempool nodes. MemPoolSpaceTxBroadcaster.broadcastTx(sendResult.tx); return sendResult.tx.getTxId().toString(); } public Transaction sendFundsForMultipleAddresses(Set<String> fromAddresses, String toAddress, Coin receiverAmount, Coin fee, @Nullable String changeAddress, @Nullable KeyParameter aesKey, @Nullable String memo, FutureCallback<Transaction> callback) throws AddressFormatException, AddressEntryException, InsufficientMoneyException { SendRequest request = getSendRequestForMultipleAddresses(fromAddresses, toAddress, receiverAmount, fee, changeAddress, aesKey); Wallet.SendResult sendResult = wallet.sendCoins(request); Futures.addCallback(sendResult.broadcastComplete, callback, MoreExecutors.directExecutor()); if (memo != null) { sendResult.tx.setMemo(memo); } printTx("sendFunds", sendResult.tx); // For better redundancy in case the broadcast via BitcoinJ fails we also // publish the tx via mempool nodes. MemPoolSpaceTxBroadcaster.broadcastTx(sendResult.tx); return sendResult.tx; } private SendRequest getSendRequest(String fromAddress, String toAddress, Coin amount, Coin fee, @Nullable KeyParameter aesKey, AddressEntry.Context context) throws AddressFormatException, AddressEntryException { Transaction tx = new Transaction(params); final Coin receiverAmount = amount.subtract(fee); Preconditions.checkArgument(Restrictions.isAboveDust(receiverAmount), "The amount is too low (dust limit)."); tx.addOutput(receiverAmount, Address.fromString(params, toAddress)); SendRequest sendRequest = SendRequest.forTx(tx); sendRequest.fee = fee; sendRequest.feePerKb = Coin.ZERO; sendRequest.ensureMinRequiredFee = false; sendRequest.aesKey = aesKey; sendRequest.shuffleOutputs = false; Optional<AddressEntry> addressEntry = findAddressEntry(fromAddress, context); if (!addressEntry.isPresent()) throw new AddressEntryException("WithdrawFromAddress is not found in our wallet."); checkNotNull(addressEntry.get(), "addressEntry.get() must not be null"); checkNotNull(addressEntry.get().getAddress(), "addressEntry.get().getAddress() must not be null"); sendRequest.coinSelector = new BtcCoinSelector(addressEntry.get().getAddress(), preferences.getIgnoreDustThreshold()); sendRequest.changeAddress = addressEntry.get().getAddress(); return sendRequest; } private SendRequest getSendRequestForMultipleAddresses(Set<String> fromAddresses, String toAddress, Coin amount, Coin fee, @Nullable String changeAddress, @Nullable KeyParameter aesKey) throws AddressFormatException, AddressEntryException { Transaction tx = new Transaction(params); final Coin netValue = amount.subtract(fee); checkArgument(Restrictions.isAboveDust(netValue), "The amount is too low (dust limit)."); tx.addOutput(netValue, Address.fromString(params, toAddress)); SendRequest sendRequest = SendRequest.forTx(tx); sendRequest.fee = fee; sendRequest.feePerKb = Coin.ZERO; sendRequest.ensureMinRequiredFee = false; sendRequest.aesKey = aesKey; sendRequest.shuffleOutputs = false; Set<AddressEntry> addressEntries = fromAddresses.stream() .map(address -> { Optional<AddressEntry> addressEntryOptional = findAddressEntry(address, AddressEntry.Context.AVAILABLE); if (!addressEntryOptional.isPresent()) addressEntryOptional = findAddressEntry(address, AddressEntry.Context.OFFER_FUNDING); if (!addressEntryOptional.isPresent()) addressEntryOptional = findAddressEntry(address, AddressEntry.Context.TRADE_PAYOUT); if (!addressEntryOptional.isPresent()) addressEntryOptional = findAddressEntry(address, AddressEntry.Context.ARBITRATOR); return addressEntryOptional; }) .flatMap(Optional::stream) .collect(Collectors.toSet()); if (addressEntries.isEmpty()) throw new AddressEntryException("No Addresses for withdraw found in our wallet"); sendRequest.coinSelector = new BtcCoinSelector(walletsSetup.getAddressesFromAddressEntries(addressEntries), preferences.getIgnoreDustThreshold()); Optional<AddressEntry> addressEntryOptional = Optional.empty(); if (changeAddress != null) addressEntryOptional = findAddressEntry(changeAddress, AddressEntry.Context.AVAILABLE); AddressEntry changeAddressAddressEntry = addressEntryOptional.orElseGet(this::getFreshAddressEntry); checkNotNull(changeAddressAddressEntry, "change address must not be null"); sendRequest.changeAddress = changeAddressAddressEntry.getAddress(); return sendRequest; } // We ignore utxos which are considered dust attacks for spying on users' wallets. // The ignoreDustThreshold value is set in the preferences. If not set we use default non dust // value of 546 sat. @Override protected boolean isDustAttackUtxo(TransactionOutput output) { return output.getValue().value < preferences.getIgnoreDustThreshold(); } // Refund payoutTx public Transaction createRefundPayoutTx(Coin buyerAmount, Coin sellerAmount, Coin fee, String buyerAddressString, String sellerAddressString) throws AddressFormatException, InsufficientMoneyException, WalletException, TransactionVerificationException { Transaction tx = new Transaction(params); Preconditions.checkArgument(buyerAmount.add(sellerAmount).isPositive(), "The sellerAmount + buyerAmount must be positive."); // buyerAmount can be 0 if (buyerAmount.isPositive()) { Preconditions.checkArgument(Restrictions.isAboveDust(buyerAmount), "The buyerAmount is too low (dust limit)."); tx.addOutput(buyerAmount, Address.fromString(params, buyerAddressString)); } // sellerAmount can be 0 if (sellerAmount.isPositive()) { Preconditions.checkArgument(Restrictions.isAboveDust(sellerAmount), "The sellerAmount is too low (dust limit)."); tx.addOutput(sellerAmount, Address.fromString(params, sellerAddressString)); } SendRequest sendRequest = SendRequest.forTx(tx); sendRequest.fee = fee; sendRequest.feePerKb = Coin.ZERO; sendRequest.ensureMinRequiredFee = false; sendRequest.aesKey = aesKey; sendRequest.shuffleOutputs = false; sendRequest.coinSelector = new BtcCoinSelector(walletsSetup.getAddressesByContext(AddressEntry.Context.AVAILABLE), preferences.getIgnoreDustThreshold()); sendRequest.changeAddress = getFreshAddressEntry().getAddress(); checkNotNull(wallet); wallet.completeTx(sendRequest); Transaction resultTx = sendRequest.tx; checkWalletConsistency(wallet); verifyTransaction(resultTx); WalletService.printTx("createRefundPayoutTx", resultTx); return resultTx; } // Find inputs and change public Tuple2<List<RawTransactionInput>, Coin> getInputsAndChange(Coin required) throws InsufficientMoneyException { BtcCoinSelector coinSelector = new BtcCoinSelector(walletsSetup.getAddressesByContext(AddressEntry.Context.AVAILABLE), preferences.getIgnoreDustThreshold()); CoinSelection coinSelection = coinSelector.select(required, Objects.requireNonNull(wallet).calculateAllSpendCandidates()); Coin change; try { change = coinSelector.getChange(required, coinSelection); } catch (InsufficientMoneyException e) { log.error("Missing funds in getSellersBtcInputsForBsqSwapTx. missing={}", e.missing); throw new InsufficientMoneyException(e.missing); } Transaction dummyTx = new Transaction(params); coinSelection.gathered.forEach(dummyTx::addInput); List<RawTransactionInput> inputs = dummyTx.getInputs().stream() .map(RawTransactionInput::new) .collect(Collectors.toList()); return new Tuple2<>(inputs, change); } }
package sagan.app.site; import sagan.blog.web.feed.BlogPostAtomViewer; import sagan.guides.support.GettingStartedGuides; import sagan.util.service.CachedRestClient; import sagan.util.service.DateService; import sagan.util.service.db.DatabaseConfig; import sagan.util.web.SiteUrl; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import javax.sql.DataSource; import org.h2.server.web.WebServlet; import org.simpleframework.xml.Serializer; import org.simpleframework.xml.core.Persister; import org.tuckey.web.filters.urlrewrite.UrlRewriteFilter; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.context.embedded.FilterRegistrationBean; import org.springframework.boot.context.embedded.ServletRegistrationBean; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.concurrent.ConcurrentMapCache; import org.springframework.cache.support.SimpleCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.web.client.RestTemplate; import org.springframework.web.servlet.DispatcherServlet; import com.google.common.cache.CacheBuilder; @EnableAutoConfiguration @Configuration @EnableCaching(proxyTargetClass = true) @ComponentScan(basePackageClasses = sagan.Package.class) public class ApplicationConfiguration { public static final String REWRITE_FILTER_NAME = "rewriteFilter"; public static final String REWRITE_FILTER_CONF_PATH = "urlrewrite.xml"; public static void main(String[] args) { SpringApplication.run(ApplicationConfiguration.class, args); } @Bean public HealthIndicator<Map<String, Object>> healthIndicator(DataSource dataSource) { if (dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource) { final org.apache.tomcat.jdbc.pool.DataSource tcDataSource = (org.apache.tomcat.jdbc.pool.DataSource) dataSource; return new HealthIndicator<Map<String, Object>>() { @Override public Map<String, Object> health() { Map<String, Object> health = new HashMap<>(); health.put("active", tcDataSource.getActive()); health.put("max_active", tcDataSource.getMaxActive()); health.put("idle", tcDataSource.getIdle()); health.put("max_idle", tcDataSource.getMaxIdle()); health.put("min_idle", tcDataSource.getMinIdle()); health.put("wait_count", tcDataSource.getWaitCount()); health.put("max_wait", tcDataSource.getMaxWait()); return health; } }; } return new HealthIndicator<Map<String, Object>>() { @Override public Map<String, Object> health() { return Collections.emptyMap(); } }; } @Bean public BlogPostAtomViewer blogPostAtomViewer() { return new BlogPostAtomViewer(siteUrl(), dateService()); } @Bean public SiteUrl siteUrl() { return new SiteUrl(); } @Bean public DateService dateService() { return new DateService(); } @Bean public RestTemplate restTemplate() { return new RestTemplate(); } @Bean public Serializer simpleXmlSerializer() { return new Persister(); } @Bean public FilterRegistrationBean rewriteFilterConfig() { FilterRegistrationBean reg = new FilterRegistrationBean(); reg.setName(REWRITE_FILTER_NAME); reg.setFilter(new UrlRewriteFilter()); reg.addInitParameter("confPath", REWRITE_FILTER_CONF_PATH); reg.addInitParameter("confReloadCheckInterval", "-1"); reg.addInitParameter("statusPath", "/redirect"); reg.addInitParameter("statusEnabledOnHosts", "*"); reg.addInitParameter("logLevel", "WARN"); return reg; } @Bean @Profile("development") public ServletRegistrationBean h2Console() {
package ch.ntb.inf.deep.linkerPPC; import java.io.PrintStream; import ch.ntb.inf.deep.classItems.Class; import ch.ntb.inf.deep.classItems.Constant; import ch.ntb.inf.deep.classItems.ICclassFileConsts; import ch.ntb.inf.deep.classItems.ICdescAndTypeConsts; import ch.ntb.inf.deep.classItems.Item; import ch.ntb.inf.deep.classItems.Method; import ch.ntb.inf.deep.classItems.StringLiteral; import ch.ntb.inf.deep.classItems.Type; import ch.ntb.inf.deep.config.Configuration; import ch.ntb.inf.deep.config.IAttributes; import ch.ntb.inf.deep.config.Segment; import ch.ntb.inf.deep.config.Device; import ch.ntb.inf.deep.host.ErrorReporter; import ch.ntb.inf.deep.strings.HString; public class Linker implements ICclassFileConsts, ICdescAndTypeConsts, IAttributes { protected static final boolean dbg = true; // enable/disable debugging outputs for the linker public static int sizeInByte = 0; public static int sLength = 0; public static TargetMemorySegment targetImage; private static TargetMemorySegment lastTargetMemorySegment; private static final int stringHeaderSize = 4; // byte private static final ErrorReporter reporter = ErrorReporter.reporter; private static PrintStream vrb = System.out; private static Class object; private static int[] systemTable; private static int systemTableSize; public static void calculateOffsets(Class clazz) { int c1, c2, c3; vrb.println("[LINKER] START: Calculating offsets for class \"" + clazz.name +"\":\n"); // TODO @Martin: set all necessary indexes for all fields in a single loop! // Constant Fields (for the constant pool) vrb.println(" 1) Constant pool:"); c1 = 0; // offset counter for the constant floating point numbers (in byte) if(clazz.constPool != null) { for(int i = 0; i < clazz.constPool.length; i++) { if(clazz.constPool[i].type == Type.wellKnownTypes[txFloat]) { vrb.println(" constPool[" + i + "] Type: float, Offset: " + c1); clazz.constPool[i].index = c1; c1 += Float.SIZE/8; } else if(clazz.constPool[i].type == Type.wellKnownTypes[txDouble]) { vrb.println(" constPool[" + i + "] Type: double, Offset: " + c1); clazz.constPool[i].index = c1; c1 += Double.SIZE/8; } } clazz.constantPoolSize = roundUpToNextWord(c1); // set the size of the constant pool of this class } // Constant strings (for the string pool) vrb.println(" 2) String pool:"); c1 = 0; // offset counter for the constant strings (in byte) if(clazz.constPool != null) { for(int i = 0; i < clazz.constPool.length; i++) { if(clazz.constPool[i].type == Type.wellKnownTypes[txString]) { vrb.println(" constPool[=" + i + "] Type: String, Offset: " + c1); clazz.constPool[i].index = c1; int stringSize = ((StringLiteral)clazz.constPool[i]).string.sizeInByte(); c1 += stringHeaderSize + roundUpToNextWord(stringSize); } } clazz.stringPoolSize = roundUpToNextWord(c1); // set the size of the constant pool of this class } // Calculate the total size of all instance fields of all base classes vrb.println(" 3a) Calculating the total size of all instance fields of all base classes:"); int bcifs = 0; Class bc = (Class)clazz.type; while(bc != null) { bcifs += bc.instanceFieldsSize; bc = (Class)bc.type; } // Fields (the two upper blocks should be integrated here...) vrb.println(" 3b) Fields (rest):"); c1 = 0; // offset counter for static fields (in byte) c2 = 0; // offset counter for instance fields (in byte) c3 = 0; // counter for the number or static fields which are references to objects if(clazz.nOfClassFields > 0 || clazz.nOfInstanceFields > 0) { Item field = clazz.fields; int size; while(field != null) { size = ((Type)field.type).sizeInBits; // size in bits if(size < 8) size = 1; // use one byte even if the size is smaller (e.g. for a boolean) else size /= 8; // convert from bits to bytes if((field.accAndPropFlags & (1 << apfStatic)) != 0 && (field.accAndPropFlags & (1 << dpfConst)) == 0) { // class field, but not constant! c1 = getCorrectOffset(c1, size); vrb.println(" Name: " + field.name + ", Static: yes, Type: " + field.type.name + ", Offset: " + c1); field.offset = c1; // save offset c1 += size; // prepare offset counter for next round if(((Type)field.type).category == tcRef) c3++; // count references } else { // instance field c2 = getCorrectOffset(c2, size); vrb.println(" Name: " + field.name + ", Static: no, Type: " + field.type.name + ", Index: " + c2); field.index = c2 + bcifs; c2 += size; } field = field.next; } clazz.classFieldsSize = roundUpToNextWord(c1); clazz.instanceFieldsSize = roundUpToNextWord(c2); clazz.nOfReferences = c3; } // Methods vrb.println(" 4) Methods:"); c1 = (2 + clazz.nOfInterfaces) * 4; // constant offset for all methods if(clazz.nOfMethods > 0) { Method method = (Method)clazz.methods; while(method != null) { vrb.println(" Name: " + method.name + ", Index: " + c1); method.index = c1; c1 += 4; method = (Method)method.next; } } vrb.println("\n[LINKER] END: calculating offsets for class \"" + clazz.name +"\"\n"); } public static void calculateRequiredSize(Class clazz) { vrb.println("[LINKER] START: Calculating required size for class \"" + clazz.name +"\":\n"); // machine code size vrb.print(" 1) Code:"); Method m = (Method)clazz.methods; int codeSize = 0; while(m != null) { if(m.machineCode != null) { if(m.offset <= 0) { // offset not given by configuration m.offset = codeSize; codeSize += m.machineCode.iCount * 4; // iCount = number of instructions! } else { // offset given by configuration if(codeSize < m.machineCode.iCount * 4 + m.offset) codeSize = m.machineCode.iCount * 4 + m.offset; } vrb.println(" > " + m.name + ": codeSize = " + m.machineCode.iCount * 4 + " byte"); } m = (Method)m.next; } clazz.machineCodeSize = codeSize; vrb.println(" Total code size: " + codeSize + " byte"); // size of class fields --> already set while calculating offsets vrb.print(" 2) Constant block: "); // constant block size clazz.classDescriptorSize = (clazz.nOfInstanceMethods + clazz.nOfInterfaces + clazz.nOfBaseClasses + 3) * 4; clazz.constantBlockSize = 4 // constBlockSize field + 4 // codeBase field + 4 // codeSize field + 4 // varBase field + 4 // varSize field + 4 // clinitAddr field + 4 // nofPtrs field + 4 * clazz.nOfReferences + clazz.classDescriptorSize + clazz.constantPoolSize // size of the constant pool already set while calculating offsets + clazz.stringPoolSize // size of the string pool already set while calculating offsets + 4; // Checksum field vrb.println(clazz.constantBlockSize + " byte"); vrb.println("\n[LINKER] END: Calculating required size for class \"" + clazz.name +"\"\n"); } public static void freezeMemoryMap() { systemTableSize = 8 + 2 * Configuration.getNumberOfStacks() + 2 * Configuration.getNumberOfHeaps() + Type.nofClasses; // TODO @Martin this should'nt be here! Move it to a better place... // 1) Set a segment for the code, the static fields and the constant block for each class Class c = Type.classList; Segment s; while(c != null) { // Code s = Configuration.getCodeSegmentOf(c.name); if(s == null) reporter.error(550, "Can't get a memory segment for the code of class " + c.name + "!\n"); else { if(s.subSegments != null) s = getFirstFittingSegment(s.subSegments, atrCode, c.machineCodeSize); c.codeOffset = s.getRequiredSize(); s.addToRequiredSize(c.machineCodeSize); // TODO move this to getFirstFittingSegment and rename the method c.codeSegment = s; } // Var s = Configuration.getVarSegmentOf(c.name); if(s == null) reporter.error(551, "Can't get a memory segment for the static variables of class " + c.name + "!\n"); else { if(s.subSegments != null) s = getFirstFittingSegment(s, atrVar, c.classFieldsSize); c.varOffset = s.getRequiredSize(); s.addToRequiredSize(c.classFieldsSize); // TODO move this to getFirstFittingSegment and rename the method c.varSegment = s; } // Const s = Configuration.getConstSegmentOf(c.name); if(s == null) reporter.error(552, "Can't get a memory segment for the constant block of class " + c.name + "!\n"); else { if(s.subSegments != null) s = getFirstFittingSegment(s, atrConst, c.constantBlockSize); c.constOffset = s.getRequiredSize(); s.addToRequiredSize(c.constantBlockSize); // TODO move this to getFirstFittingSegment and rename the method c.constSegment = s; } c = (Class)c.next; } Segment[] sysTabs = Configuration.getSysTabSegments(); // TODO @Martin: implement this for more than one system table! if(sysTabs != null && sysTabs.length > 0) { for(int i = 0; i < sysTabs.length; i++) { sysTabs[i].addToRequiredSize(systemTableSize * 4); } } else reporter.error(9445, "Error: no Systemtable defined!"); // TODO define drror number // 2) Check and set the size for each used segment Device d = Configuration.getFirstDevice(); while(d != null) { // System.out.println("Device: " + d.getName() + "\n"); if(d.lastSegment != null) setSegmentSize(d.lastSegment); d = d.next; } // 3) Set base addresses for each used segment d = Configuration.getFirstDevice(); //usedSegments = new Segment[nOfUsedSegments]; while(d != null) { vrb.println("Start setting base addresses for segments in device \"" + d.getName() +"\":"); //System.out.println("Device: " + d.getName() + "\n"); if(d.segments != null) setBaseAddress(d.segments, d.getbaseAddress()); vrb.println("End setting base addresses for segments in device \"" + d.getName() +"\":\n"); d = d.next; } } public static void calculateAbsoluteAddresses(Class clazz) { vrb.println("\n[LINKER] START: Calculating absolute addresses for class \"" + clazz.name +"\":\n"); int varBase = clazz.varSegment.getBaseAddress() + clazz.varOffset; int codeBase = clazz.codeSegment.getBaseAddress() + clazz.codeOffset; // Class/static fields if(clazz.nOfClassFields > 0) { Item field = clazz.fields; vrb.println(" Static fields:"); while(field != null) { if((field.accAndPropFlags & (1 << apfStatic)) != 0) { // class field if((field.accAndPropFlags & (1 << dpfConst)) != 0) { // constant field if(field.type == Type.wellKnownTypes[txFloat] || field.type == Type.wellKnownTypes[txDouble]) { // constant pool if float or double field.address = clazz.constSegment.getBaseAddress() + 7 + clazz.nOfReferences * 4 + clazz.classDescriptorSize + clazz.stringPoolSize + field.index; } else if(field.type == Type.wellKnownTypes[txString]) { // string pool field.address = clazz.constSegment.getBaseAddress() + 7 + clazz.nOfReferences * 4 + clazz.classDescriptorSize + field.index; } } else { // non constant field -> var section if(varBase != -1 && field.offset != -1) field.address = varBase + field.offset; else reporter.error(9999, "varBase of class " + clazz.name + " not set or offset of field " + field.name + " not set!"); vrb.print(" > " + field.name + ": Offset = " + field.offset + ", Address = 0x" + Integer.toHexString(field.address) + "\n"); } } field = field.next; } } // Methods if(clazz.nOfMethods > 0) { Method method = (Method)clazz.methods; vrb.println(" Methods:"); while(method != null) { if(codeBase != -1 && method.offset != -1) method.address = codeBase + method.offset; vrb.print(" > " + method.name + ": Offset = " + method.offset + ", Address = 0x" + Integer.toHexString(method.address) + "\n"); method = (Method)method.next; } } // Class descriptor clazz.address = clazz.constSegment.getBaseAddress() + clazz.constOffset + 4 * (6 + clazz.nOfReferences + clazz.nOfInstanceMethods + clazz.nOfInterfaces + 2); vrb.println("\n[LINKER] END: Calculating absolute addresses for class \"" + clazz.name +"\"\n"); } public static void createConstantBlock(Class clazz) { vrb.println("[LINKER] START: Creating constant block for class \"" + clazz.name +"\":\n"); clazz.constantBlock = new int[clazz.constantBlockSize/4]; vrb.println(" Constant block size: " + clazz.constantBlockSize + " byte -> array size: " + clazz.constantBlock.length); vrb.println(" Number of references: " + clazz.nOfReferences); vrb.println(" Class descriptor size: " + clazz.classDescriptorSize + " byte"); vrb.println(" Number of instance methods: " + clazz.nOfInstanceMethods); vrb.println(" Number of interfaces: " + clazz.nOfInterfaces); // 1) Insert Header clazz.constantBlock[0] = clazz.constantBlockSize; // constBlockSize clazz.constantBlock[1] = clazz.codeSegment.getBaseAddress() + clazz.codeOffset; // codeBase clazz.constantBlock[2] = clazz.machineCodeSize; // codeSize clazz.constantBlock[3] = clazz.varSegment.getBaseAddress() + clazz.varOffset; // varBase clazz.constantBlock[4] = clazz.classFieldsSize; // varSize Method clinit = clazz.getClassConstructor(); // clinitAddr if(clinit != null) clazz.constantBlock[5] = clinit.address; else clazz.constantBlock[5] = -1; // TODO @Urs is this ok? // 2) Insert References (Pointers) clazz.constantBlock[6] = clazz.nOfReferences; if(clazz.nOfReferences > 0) { Item field = clazz.fields; int index = 0; while(field != null) { if((field.accAndPropFlags & (1 << apfStatic)) != 0 && ((Type)field.type).category == tcRef) clazz.constantBlock[7 + index] = field.address; field = field.next; } } // 3) Class descriptor // 3a) Insert instance method addresses int classDescriptorOffset = 6 + clazz.nOfReferences; int imc = 0; if(clazz.nOfInstanceMethods > 0) { Method m = (Method)clazz.methods; while(m != null) { if((m.accAndPropFlags & (1 << apfStatic)) == 0 && (m.accAndPropFlags & (1 << dpfSynthetic)) == 0) { clazz.constantBlock[classDescriptorOffset + clazz.nOfInstanceMethods - imc] = m.address; imc++; } m = (Method)m.next; } } // 3b) Insert interfaces if(clazz.nOfInterfaces > 0) { for(int i = 0; i < clazz.nOfInterfaces; i++) { assert clazz.interfaces[i] != null: "ERROR: Interface is NULL! Current Interface: " + i +"/" + clazz.nOfInterfaces; clazz.constantBlock[classDescriptorOffset + clazz.nOfInstanceMethods + clazz.nOfInterfaces - i] = clazz.interfaces[i].address; } } // 3c) Insert extension level clazz.constantBlock[classDescriptorOffset + clazz.nOfInstanceMethods + clazz.nOfInterfaces + 1] = clazz.nOfBaseClasses; // 3d) Insert size clazz.constantBlock[classDescriptorOffset + clazz.nOfInstanceMethods + clazz.nOfInterfaces + 2] = clazz.objectSizeOrDim; // 3e) Insert class name address clazz.constantBlock[classDescriptorOffset + clazz.nOfInstanceMethods + clazz.nOfInterfaces + 3] = 0x12345678; // TODO set the right value here! -> address of the first entrie of the const/string pool? // 3f) Insert base classes if(clazz.nOfBaseClasses > 0) { Class bc = (Class)clazz.type; for(int i = 0; i < clazz.nOfBaseClasses; i++) { assert bc != null: "ERROR: Base class is NULL! Current base class: " + i + "/" + clazz.nOfBaseClasses; clazz.constantBlock[classDescriptorOffset + clazz.nOfInstanceMethods + clazz.nOfInterfaces + 3 + i] = bc.address; bc = (Class)bc.type; } } // 4) String pool int stringPoolOffset = classDescriptorOffset + clazz.classDescriptorSize / 4 + 1; if(clazz.constPool != null) { for(int i = 0; i < clazz.constPool.length; i++) { int index = clazz.constPool[i].index/4; if(clazz.constPool[i].type == Type.wellKnownTypes[txString]) { HString s = ((StringLiteral)clazz.constPool[i]).string; sizeInByte = s.sizeInByte(); sLength = s.length(); if(s.sizeInByte()/s.length() == 1) { // string is a H8String int c = 0, word = 0; clazz.constantBlock[stringPoolOffset + index++] = (s.length() << 16) + 0x0800; // add string header for(int j = 0; j < s.length(); j++) { word = (word << 8) + s.charAt(j); c++; if(c > 3 || j == s.length() - 1) { clazz.constantBlock[stringPoolOffset + index] = word; c = 0; word = 0; index++; } } } else { // string is a H16String assert s.sizeInByte()/s.length() == 2: "String is neighter a 8bit nor a 16bit char array!"; int c = 0, word = 0; clazz.constantBlock[stringPoolOffset + index++] = (s.length() << 16) + 0x1000; // add string header for(int j = 0; j < s.length(); j++) { word = (word << 16) + s.charAt(j); c++; if(c > 1 || j == s.length() - 1) { clazz.constantBlock[stringPoolOffset + index] = word; c = 0; word = 0; index++; } } } } } } // 5) Constant pool int constantPoolOffset = stringPoolOffset + clazz.stringPoolSize / 4; if(clazz.constPool != null) { for(int i = 0; i < clazz.constPool.length; i++) { int index = clazz.constPool[i].index/4; if(clazz.constPool[i].type == Type.wellKnownTypes[Type.txFloat]) { clazz.constantBlock[constantPoolOffset + index] = ((Constant)clazz.constPool[i]).valueH; } else if(clazz.constPool[i].type == Type.wellKnownTypes[Type.txDouble]) { clazz.constantBlock[constantPoolOffset + index] = ((Constant)clazz.constPool[i]).valueH; clazz.constantBlock[constantPoolOffset + index + 1] = ((Constant)clazz.constPool[i]).valueL; } } } // 6 Checksum clazz.constantBlock[clazz.constantBlock.length - 1] = 0; // TODO implement crc32 checksum // print // clazz.printConstantBlock(); vrb.println("\n[LINKER] END: Creating constant block for class \"" + clazz.name +"\"\n"); } public static void createSystemTable() { vrb.println("[LINKER] START: Creating systemtable:\n"); int nOfStacks = Configuration.getNumberOfStacks(); int nOfHeaps = Configuration.getNumberOfHeaps(); vrb.println(" Number of stacks: " + nOfStacks); vrb.println(" Number of heaps: " + nOfHeaps); vrb.println(" Number of classes: " + Type.nofClasses); // create the systemtable systemTable = new int[systemTableSize]; vrb.println(" Size of the system table: " + systemTable.length * 4 + " byte -> array size: " + systemTable.length); // offset to the beginning of the class references systemTable[0] = 6 + 2 * nOfStacks + 2 * nOfHeaps; // offset to the beginning of the stack information systemTable[1] = 5; // offset to the beginning of the heap information systemTable[2] = 5 + 2 * nOfStacks; Item c = Type.classList; HString kernelClassName = Configuration.getKernelClassname(); Item kernelClinit = null; int kernelClinitAddr = 0; while(c != null && !c.name.equals(kernelClassName)) { c = c.next; } if(c != null) { // System.out.println("Kernel class name: " + c.name); // kernelClinit = ((Class)c).methods.getItemByName("<clinit>"); kernelClinit = ((Class)c).getClassConstructor(); if(kernelClinit != null) { // System.out.println("kernelClinit: " + kernelClinit.name); kernelClinitAddr = kernelClinit.address; } } systemTable[3] = kernelClinitAddr; // number of stacks systemTable[4] = nOfStacks; // reference to each stack and the size of each stack for(int i = 0; i < nOfStacks; i++) { systemTable[5 + 2 * i] = Configuration.getStackSegments()[i].getBaseAddress(); systemTable[5 + 2 * i + 1] = Configuration.getStackSegments()[i].getSize(); } // number of heaps systemTable[5 + 2 * nOfStacks] = nOfHeaps; //reference to each heap and the size of each heap for(int i = 0; i < nOfHeaps; i++) { systemTable[6 + 2 * nOfStacks + 2 * i] = Configuration.getHeapSegments()[i].getBaseAddress(); systemTable[6 + 2 * nOfStacks + 2 * i + 1] = Configuration.getHeapSegments()[i].getSize(); } systemTable[7 + 2 * nOfStacks + 2 * nOfHeaps] = Type.nofClasses; // reference to the constant block of each class Class clazz = Type.classList; int i = 7 + 2 * nOfStacks + 2 * nOfHeaps; while(clazz != null) { //systemTable[i] = clazz.address; systemTable[i] = clazz.constSegment.getBaseAddress() + clazz.constOffset; i++; clazz = (Class)clazz.next; } // End of system table -> should always be zero! systemTable[systemTable.length - 1] = 0; vrb.println("[LINKER] END: Creating systemtable\n"); } public static void generateTargetImage() { vrb.println("[LINKER] START: Generating target image:\n"); Class clazz = Type.classList; Method m; while(clazz != null) { vrb.println(" Proceeding class \"" + clazz.name + "\":"); // code m = (Method)clazz.methods; vrb.println(" 1) Code:"); while(m != null) { if(m.machineCode != null) { vrb.println(" > Method \"" + m.name + "\":"); clazz.codeSegment.tms.addData(clazz.codeSegment.getBaseAddress() + clazz.codeOffset + m.offset, m.machineCode.instructions); addTargetMemorySegment(clazz.codeSegment.tms); } m = (Method)m.next; } // consts vrb.println(" 2) Constantblock:"); clazz.constSegment.tms.addData(clazz.constSegment.getBaseAddress() + clazz.constOffset, clazz.constantBlock); addTargetMemorySegment(clazz.constSegment.tms); clazz = (Class)clazz.next; } vrb.println(" Proceeding system table:"); Segment[] s = Configuration.getSysTabSegments(); s[0].tms.addData(s[0].getBaseAddress(), systemTable); addTargetMemorySegment(s[0].tms); vrb.println("[LINKER] END: Generating target image\n"); } public static int getSizeOfObject() { if(object == null) { Class clazz = Class.classList; while(clazz != null && clazz.name != HString.getHString("java/lang/Object")) { clazz = (Class)clazz.next; } object = clazz; } return object.objectSizeOrDim; } private static void setBaseAddress(Segment s, int baseAddress) { //descend if(s.subSegments != null) setBaseAddress(s.subSegments, baseAddress); //set baseaddress if((s.getSize() > 0 && s.getRequiredSize() > 0) || ((s.getAttributes() & ((1 << atrStack) | (1 << atrHeap) | (1 << atrSysTab))) != 0)){ s.setBaseAddress(baseAddress); // usedSegments[usedSegmentsIndex++] = s; // TODO remove this s.tms = new TargetMemorySegment(s.getBaseAddress(), s.getSize()); vrb.println("\t Segment "+s.getName() +" address = "+ Integer.toHexString(baseAddress) + ", size = " + s.getSize()); } // traverse from left to right if(s.next != null) setBaseAddress(s.next, s.getSize()+ baseAddress); } private static Segment getFirstFittingSegment(Segment s, byte contentAttribute, int requiredSize) { Segment t = s; while(t != null) { if((t.getAttributes() & (1 << contentAttribute)) != 0) { if(t.subSegments != null) t = getFirstFittingSegment(t.subSegments, contentAttribute, requiredSize); if(t.getSize() <= 0 || t.getSize() - t.getRequiredSize() > requiredSize) return t; } t = t.next; } return null; } private static void setSegmentSize(Segment s) { if(s.lastSubSegment != null) { setSegmentSize(s.lastSubSegment); } if(s.getSize() <= 0) { s.setSize(roundUpToNextWord(s.getRequiredSize())); } else if(s.getSize() < s.getRequiredSize()) { reporter.error(560, "Segment " + s.getName() + " is too small! Size is manually set to " + s.getSize() + " byte, but required size is " + s.getRequiredSize() + " byte!\n"); } // System.out.println(" Segment " + s.getName() + ": size = " + s.getSize() + "byte!\n"); if(s.prev != null) { setSegmentSize(s.prev); } } private static int getCorrectOffset(int potentialOffset, int size) { if(size == 8) size = 4; // handle double word items like word items if(potentialOffset % size == 0) return potentialOffset; return potentialOffset + (4 - (potentialOffset % size)); } private static int roundUpToNextWord(int val) { if(val % 4 == 0) return val; return val + (4 - (val % 4)); } private static void addTargetMemorySegment(TargetMemorySegment tms) { if(targetImage == null) { targetImage = tms; lastTargetMemorySegment = tms; } else { TargetMemorySegment current = targetImage; while(current != null) { if(current == tms) return; current = current.next; } lastTargetMemorySegment.next = tms; lastTargetMemorySegment = lastTargetMemorySegment.next; } } public static void printSystemTable() { int i = 0; int nOfStacks = systemTable[4]; int nOfHeaps = systemTable[5 + 2 * nOfStacks]; int nOfClasses = Type.nofClasses; vrb.print("System table:\n"); vrb.printf(" >%4d", i); vrb.print(" ["); vrb.printf("%8x", systemTable[i]); vrb.print("] classConstOffset\n"); i++; vrb.printf(" >%4d", i); vrb.print(" ["); vrb.printf("%8x", systemTable[i]); vrb.print("] stackOffset\n"); i++; vrb.printf(" >%4d", i); vrb.print(" ["); vrb.printf("%8x", systemTable[i]); vrb.print("] heapOffset\n"); i++; vrb.printf(" >%4d", i); vrb.print(" ["); vrb.printf("%8x", systemTable[i]); vrb.print("] kernelClinitAddr\n"); i++; vrb.printf(" >%4d", i); vrb.print(" ["); vrb.printf("%8x", systemTable[i]); vrb.print("] nofStacks\n"); i++; for(int j = 0; j < nOfStacks; j++) { vrb.printf(" >%4d", i); vrb.print(" ["); vrb.printf("%8x", systemTable[i]); vrb.print("] baseStack" + j + "\n"); i++; vrb.printf(" >%4d", i); vrb.print(" ["); vrb.printf("%8x", systemTable[i]); vrb.print("] sizeStack" + j + "\n"); i++; } vrb.printf(" >%4d", i); vrb.print(" ["); vrb.printf("%8x", systemTable[i]); vrb.print("] nofHeaps\n"); i++; for(int j = 0; j < nOfHeaps; j++) { vrb.printf(" >%4d", i); vrb.print(" ["); vrb.printf("%8x", systemTable[i]); vrb.print("] baseHeap" + j + "\n"); i++; vrb.printf(" >%4d", i); vrb.print(" ["); vrb.printf("%8x", systemTable[i]); vrb.print("] sizeHeap" + j + "\n"); i++; } vrb.printf(" >%4d", i); vrb.print(" ["); vrb.printf("%8x", systemTable[i]); vrb.print("] nofClasses\n"); i++; for(int j = 0; j < nOfClasses; j++) { vrb.printf(" >%4d", i); vrb.print(" ["); vrb.printf("%8x", systemTable[i]); vrb.print("] constBlkBaseClass" + j + "\n"); i++; } vrb.printf(" >%4d", i); vrb.print(" ["); vrb.printf("%8x", systemTable[i]); vrb.print("] endOfSysTab\n"); i++; } public static void printTargetImage() { TargetMemorySegment tms = targetImage; while(tms != null) { vrb.print(tms); tms = tms.next; } } public static void printClassList() { vrb.println("\n[LINKER] PRINT: This is a list of all classes with their methodes, fields and constant blocks\n"); Class c = Type.classList; Method m; Item f; int cc = 0, mc = 0, fc = 0; while(c != null) { vrb.println(" Class: " + c.name + " ( vrb.println(" Number of class methods: " + c.nOfClassMethods); vrb.println(" Number of instance methods: " + c.nOfInstanceMethods); vrb.println(" Number of class fields: " + c.nOfClassFields); vrb.println(" Number of instance fields: " + c.nOfInstanceFields); vrb.println(" Number of interfaces: " + c.nOfInterfaces); vrb.println(" Number of base classes: " + c.nOfBaseClasses); vrb.println(" Number of references: " + c.nOfReferences); vrb.println(" Machine code size: " + c.machineCodeSize + " byte"); vrb.println(" Constant block size: " + c.constantBlockSize + " byte"); vrb.println(" Class fields size: " + c.classFieldsSize + " byte"); vrb.println(" Code offset: 0x" + Integer.toHexString(c.codeOffset)); vrb.println(" Var offset: 0x" + Integer.toHexString(c.varOffset)); vrb.println(" Const offset: 0x" + Integer.toHexString(c.constOffset)); vrb.println(" Code segment: " + c.codeSegment.getName() + " (Base address: 0x" + Integer.toHexString(c.codeSegment.getBaseAddress()) + ", size: " + c.codeSegment.getSize() + " byte)"); vrb.println(" Var segment: " + c.varSegment.getName() + " (Base address: 0x" + Integer.toHexString(c.varSegment.getBaseAddress()) + ", size: " + c.varSegment.getSize() + " byte)"); vrb.println(" Const segment: " + c.constSegment.getName() + " (Base address: 0x" + Integer.toHexString(c.constSegment.getBaseAddress()) + ", size: " + c.constSegment.getSize() + " byte)"); vrb.println(" Class descriptor address: 0x" + c.address); vrb.println(" Base address of the constant block: 0x" + Integer.toHexString(c.constSegment.getBaseAddress() + c.constOffset)); vrb.println(" Base address of the code: 0x" + Integer.toHexString(c.codeSegment.getBaseAddress() + c.codeOffset)); vrb.println(" Base address of the non constant class fields: 0x" + Integer.toHexString(c.varSegment.getBaseAddress() + c.varOffset)); vrb.println(" Method list:"); m = (Method)c.methods; mc = 0; if(m == null) vrb.println(" No methods in this class"); else { while(m != null) { vrb.println(" > Method: " + m.name + " ( vrb.println(" Access and property flags: 0x" + Integer.toHexString(m.accAndPropFlags)); if((m.accAndPropFlags & (1 << apfStatic)) != 0) vrb.println(" Static: yes"); else vrb.println(" Static: no"); vrb.println(" address: 0x" + Integer.toHexString(m.address)); vrb.println(" offset: 0x" + Integer.toHexString(m.offset)); vrb.println(" index: 0x" + Integer.toHexString(m.index)); if(m.machineCode != null) vrb.println(" Code size: 0x" + Integer.toHexString(m.machineCode.iCount * 4) + " (" + m.machineCode.iCount * 4 +" byte)"); m = (Method)m.next; } } vrb.println(" Field list:"); f = c.fields; fc = 0; if(f == null) vrb.println(" No fields in this class"); else { while(f != null) { vrb.println(" > Field: " + f.name + " ( vrb.println(" Access and property flags: 0x" + Integer.toHexString(f.accAndPropFlags)); if((f.accAndPropFlags & (1 << apfStatic)) != 0) vrb.println(" Static: yes"); else vrb.println(" Static: no"); vrb.println(" address: 0x" + Integer.toHexString(f.address)); vrb.println(" offset: 0x" + Integer.toHexString(f.offset)); vrb.println(" index: 0x" + Integer.toHexString(f.index)); f = f.next; } } vrb.println(" Constant block:"); c.printConstantBlock(2); c = (Class)c.next; vrb.println(" } vrb.println("\n[LINKER] PRINT: End of class list\n"); } }
package org.openmrs.reference; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.experimental.categories.Category; import org.openmrs.reference.page.HeaderPage; import org.openmrs.reference.page.HomePage; import org.openmrs.reference.page.PatientCaptureVitalsPage; import org.openmrs.reference.page.PatientDashboardPage; import org.openmrs.uitestframework.test.TestBase; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.openmrs.uitestframework.test.TestData.PatientInfo; public class CaptureVitalsTest extends TestBase { private HeaderPage headerPage; private HomePage homePage; private PatientDashboardPage patientDashboardPage; private PatientCaptureVitalsPage patientCaptureVitalsPage; private PatientInfo patient; @Before public void setUp() throws InterruptedException { loginPage.loginAsAdmin(); homePage = new HomePage(driver); patientDashboardPage = new PatientDashboardPage(driver); patientCaptureVitalsPage = new PatientCaptureVitalsPage(driver); assertPage(homePage); } private void registerAPatient() throws InterruptedException{ patient = createTestPatient(); currentPage().goToPage(PatientDashboardPage.URL_PATH + "?patientId=" + patient.uuid); } @After public void tearDown() throws Exception { headerPage.clickOnHomeIcon(); deletePatient(patient.uuid); //waitForPatientDeletion(patient.uuid); headerPage.logOut(); } @Test @Category(org.openmrs.reference.groups.BuildTests.class) public void captureVital() throws InterruptedException { registerAPatient(); patientDashboardPage.startVisit(); patientDashboardPage.goToCaptureVitals(); patientCaptureVitalsPage.waitForJsVariable("Navigator.isReady"); patientCaptureVitalsPage.setHeightField("185"); patientCaptureVitalsPage.setWeightField("78"); patientCaptureVitalsPage.setTemperatureField("36.6"); patientCaptureVitalsPage.setPulseField("120"); patientCaptureVitalsPage.setRespiratoryField("110"); patientCaptureVitalsPage.setBloodPressureFields("120", "70"); patientCaptureVitalsPage.setBloodOxygenSaturationField("50"); patientCaptureVitalsPage.confirm(); patientCaptureVitalsPage.save(); } }
package com.jme3.renderer.lwjgl; import org.lwjgl.opengl.EXTAbgr; import com.jme3.texture.Image; import com.jme3.texture.Image.Format; import java.nio.ByteBuffer; import org.lwjgl.opengl.ARBDepthBufferFloat; import org.lwjgl.opengl.ARBHalfFloatPixel; import org.lwjgl.opengl.ARBTextureFloat; import org.lwjgl.opengl.ARBTextureMultisample; import org.lwjgl.opengl.EXTPackedFloat; import org.lwjgl.opengl.EXTTextureArray; import org.lwjgl.opengl.EXTTextureSharedExponent; import org.lwjgl.opengl.NVDepthBufferFloat; import static org.lwjgl.opengl.EXTTextureCompressionS3TC.*; import static org.lwjgl.opengl.EXTTextureCompressionLATC.*; import static org.lwjgl.opengl.ATITextureCompression3DC.*; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL12.*; import static org.lwjgl.opengl.GL13.*; import static org.lwjgl.opengl.GL14.*; public class TextureUtil { public static int convertTextureFormat(Format fmt){ switch (fmt){ case Alpha16: return GL_ALPHA16; case Alpha8: return GL_ALPHA8; case DXT1: return GL_COMPRESSED_RGB_S3TC_DXT1_EXT; case DXT1A: return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; case DXT3: return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; case DXT5: return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; case LATC: return GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT; case Depth: return GL_DEPTH_COMPONENT; case Depth16: return GL_DEPTH_COMPONENT16; case Depth24: return GL_DEPTH_COMPONENT24; case Depth32: return GL_DEPTH_COMPONENT32; case Depth32F: return ARBDepthBufferFloat.GL_DEPTH_COMPONENT32F; case Luminance8Alpha8: return GL_LUMINANCE8_ALPHA8; case Luminance16Alpha16: return GL_LUMINANCE16_ALPHA16; case Luminance16FAlpha16F: return ARBTextureFloat.GL_LUMINANCE_ALPHA16F_ARB; case Intensity8: return GL_INTENSITY8; case Intensity16: return GL_INTENSITY16; case Luminance8: return GL_LUMINANCE8; case Luminance16: return GL_LUMINANCE16; case Luminance16F: return ARBTextureFloat.GL_LUMINANCE16F_ARB; case Luminance32F: return ARBTextureFloat.GL_LUMINANCE32F_ARB; case RGB10: return GL_RGB10; case RGB16: return GL_RGB16; case RGB111110F: return EXTPackedFloat.GL_R11F_G11F_B10F_EXT; case RGB9E5: return EXTTextureSharedExponent.GL_RGB9_E5_EXT; case RGB16F: return ARBTextureFloat.GL_RGB16F_ARB; case RGBA16F: return ARBTextureFloat.GL_RGBA16F_ARB; case RGB32F: return ARBTextureFloat.GL_RGB32F_ARB; case RGB5A1: return GL_RGB5_A1; case BGR8: return GL_RGB8; case RGB8: return GL_RGB8; case RGBA16: return GL_RGBA16; case RGBA8: return GL_RGBA8; default: throw new UnsupportedOperationException("Unrecognized format: "+fmt); } } public static void uploadTexture(Image img, int target, int index, int border, boolean tdc){ Image.Format fmt = img.getFormat(); ByteBuffer data; if (index >= 0 && img.getData() != null && img.getData().size() > 0){ data = img.getData(index); }else{ data = null; } int width = img.getWidth(); int height = img.getHeight(); int depth = img.getDepth(); boolean compress = false; int internalFormat = -1; int format = -1; int dataType = -1; switch (fmt){ case Alpha16: internalFormat = GL_ALPHA16; format = GL_ALPHA; dataType = GL_UNSIGNED_BYTE; break; case Alpha8: internalFormat = GL_ALPHA8; format = GL_ALPHA; dataType = GL_UNSIGNED_BYTE; break; case DXT1: compress = true; internalFormat = GL_COMPRESSED_RGB_S3TC_DXT1_EXT; format = GL_RGB; dataType = GL_UNSIGNED_BYTE; break; case DXT1A: compress = true; internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; format = GL_RGBA; dataType = GL_UNSIGNED_BYTE; break; case DXT3: compress = true; internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; format = GL_RGBA; dataType = GL_UNSIGNED_BYTE; break; case DXT5: compress = true; internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; format = GL_RGBA; dataType = GL_UNSIGNED_BYTE; break; case LATC: compress = true; if (tdc){ internalFormat = GL_COMPRESSED_LUMINANCE_ALPHA_3DC_ATI; }else{ internalFormat = GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT; } format = GL_LUMINANCE_ALPHA; dataType = GL_UNSIGNED_BYTE; break; case LTC: compress = true; internalFormat = GL_COMPRESSED_LUMINANCE_LATC1_EXT; format = GL_LUMINANCE_ALPHA; dataType = GL_UNSIGNED_BYTE; break; case Depth: internalFormat = GL_DEPTH_COMPONENT; format = GL_DEPTH_COMPONENT; dataType = GL_UNSIGNED_BYTE; break; case Depth16: internalFormat = GL_DEPTH_COMPONENT16; format = GL_DEPTH_COMPONENT; dataType = GL_UNSIGNED_BYTE; break; case Depth24: internalFormat = GL_DEPTH_COMPONENT24; format = GL_DEPTH_COMPONENT; dataType = GL_UNSIGNED_BYTE; break; case Depth32: internalFormat = GL_DEPTH_COMPONENT32; format = GL_DEPTH_COMPONENT; dataType = GL_UNSIGNED_BYTE; break; case Depth32F: internalFormat = NVDepthBufferFloat.GL_DEPTH_COMPONENT32F_NV; format = GL_DEPTH_COMPONENT; dataType = GL_FLOAT; break; case Luminance16FAlpha16F: internalFormat = ARBTextureFloat.GL_LUMINANCE_ALPHA16F_ARB; format = GL_LUMINANCE_ALPHA; dataType = GL_UNSIGNED_BYTE; break; case Intensity8: internalFormat = GL_INTENSITY8; format = GL_INTENSITY; dataType = GL_UNSIGNED_BYTE; break; case Intensity16: internalFormat = GL_INTENSITY16; format = GL_INTENSITY; dataType = GL_UNSIGNED_BYTE; break; case Luminance8: internalFormat = GL_LUMINANCE8; format = GL_LUMINANCE; dataType = GL_UNSIGNED_BYTE; break; case Luminance8Alpha8: internalFormat = GL_LUMINANCE8_ALPHA8; format = GL_LUMINANCE_ALPHA; dataType = GL_UNSIGNED_BYTE; break; case Luminance16Alpha16: internalFormat = GL_LUMINANCE16_ALPHA16; format = GL_LUMINANCE_ALPHA; dataType = GL_UNSIGNED_BYTE; break; case Luminance16: internalFormat = GL_LUMINANCE16; format = GL_LUMINANCE; dataType = GL_UNSIGNED_BYTE; break; case Luminance16F: internalFormat = ARBTextureFloat.GL_LUMINANCE16F_ARB; format = GL_LUMINANCE; dataType = ARBHalfFloatPixel.GL_HALF_FLOAT_ARB; break; case Luminance32F: internalFormat = ARBTextureFloat.GL_LUMINANCE32F_ARB; format = GL_LUMINANCE; dataType = GL_FLOAT; break; case RGB10: internalFormat = GL_RGB10; format = GL_RGB; dataType = GL_UNSIGNED_BYTE; break; case RGB16: internalFormat = GL_RGB16; format = GL_RGB; dataType = GL_UNSIGNED_BYTE; break; case RGB111110F: internalFormat = EXTPackedFloat.GL_R11F_G11F_B10F_EXT; format = GL_RGB; dataType = EXTPackedFloat.GL_UNSIGNED_INT_10F_11F_11F_REV_EXT; break; case RGB16F_to_RGB111110F: internalFormat = EXTPackedFloat.GL_R11F_G11F_B10F_EXT; format = GL_RGB; dataType = ARBHalfFloatPixel.GL_HALF_FLOAT_ARB; break; case RGB16F_to_RGB9E5: internalFormat = EXTTextureSharedExponent.GL_RGB9_E5_EXT; format = GL_RGB; dataType = ARBHalfFloatPixel.GL_HALF_FLOAT_ARB; break; case RGB9E5: internalFormat = EXTTextureSharedExponent.GL_RGB9_E5_EXT; format = GL_RGB; dataType = EXTTextureSharedExponent.GL_UNSIGNED_INT_5_9_9_9_REV_EXT; break; case RGB16F: internalFormat = ARBTextureFloat.GL_RGB16F_ARB; format = GL_RGB; dataType = ARBHalfFloatPixel.GL_HALF_FLOAT_ARB; break; case RGBA16F: internalFormat = ARBTextureFloat.GL_RGBA16F_ARB; format = GL_RGBA; dataType = ARBHalfFloatPixel.GL_HALF_FLOAT_ARB; break; case RGB32F: internalFormat = ARBTextureFloat.GL_RGB32F_ARB; format = GL_RGB; dataType = GL_FLOAT; break; case RGBA32F: internalFormat = ARBTextureFloat.GL_RGBA32F_ARB; format = GL_RGBA; dataType = GL_FLOAT; break; case RGB5A1: internalFormat = GL_RGB5_A1; format = GL_RGBA; dataType = GL_UNSIGNED_BYTE; break; case RGB8: internalFormat = GL_RGB8; format = GL_RGB; dataType = GL_UNSIGNED_BYTE; break; case BGR8: internalFormat = GL_RGB8; format = GL_BGR; dataType = GL_UNSIGNED_BYTE; break; case RGBA16: internalFormat = GL_RGBA16; format = GL_RGBA; dataType = GL_UNSIGNED_BYTE; break; case RGBA8: internalFormat = GL_RGBA8; format = GL_RGBA; dataType = GL_UNSIGNED_BYTE; break; case ABGR8: internalFormat = GL_RGBA8; format = EXTAbgr.GL_ABGR_EXT; dataType = GL_UNSIGNED_BYTE; break; default: throw new UnsupportedOperationException("Unrecognized format: "+fmt); } if (data != null) glPixelStorei(GL_UNPACK_ALIGNMENT, 1); int[] mipSizes = img.getMipMapSizes(); int pos = 0; // TODO: Remove unneccessary allocation if (mipSizes == null){ if (data != null) mipSizes = new int[]{ data.capacity() }; else mipSizes = new int[]{ width * height * fmt.getBitsPerPixel() / 8 }; } boolean subtex = false; int samples = img.getMultiSamples(); for (int i = 0; i < mipSizes.length; i++){ int mipWidth = Math.max(1, width >> i); int mipHeight = Math.max(1, height >> i); int mipDepth = Math.max(1, depth >> i); if (data != null){ data.position(pos); data.limit(pos + mipSizes[i]); } if (compress && data != null){ if (target == GL_TEXTURE_3D){ glCompressedTexImage3D(target, i, internalFormat, mipWidth, mipHeight, mipDepth, border, data); }else{ //all other targets use 2D: array, cubemap, 2d glCompressedTexImage2D(target, i, internalFormat, mipWidth, mipHeight, border, data); } }else{ if (target == GL_TEXTURE_3D){ glTexImage3D(target, i, internalFormat, mipWidth, mipHeight, mipDepth, border, format, dataType, data); }else if (target == EXTTextureArray.GL_TEXTURE_2D_ARRAY_EXT){ // prepare data for 2D array // or upload slice if (index == -1){ glTexImage3D(target, 0, internalFormat, mipWidth, mipHeight, img.getData().size(), //# of slices border, format, dataType, 0); }else{ glTexSubImage3D(target, i, // level 0, // xoffset 0, // yoffset index, // zoffset width, // width height, // height 1, // depth format, dataType, data); } }else{ if (subtex){ if (samples > 1) throw new IllegalStateException("Cannot update multisample textures"); glTexSubImage2D(target, i, 0, 0, mipWidth, mipHeight, format, dataType, data); }else{ if (samples > 1){ ARBTextureMultisample.glTexImage2DMultisample(target, samples, internalFormat, mipWidth, mipHeight, true); }else{ glTexImage2D(target, i, internalFormat, mipWidth, mipHeight, border, format, dataType, data); } } } } pos += mipSizes[i]; } } }
package de.pitkley.ddcci.monitor; import java.util.Iterator; import java.util.ServiceConfigurationError; import java.util.ServiceLoader; public class Monitors { private static MonitorManager monitorManager = null; static { loadManagers(); } private static void loadManagers() { Iterator<MonitorManager> managers = ServiceLoader.load(MonitorManager.class).iterator(); MonitorManager manager = null; //noinspection WhileLoopReplaceableByForEach while (managers.hasNext()) { try { MonitorManager curManager = managers.next(); manager = curManager; break; } catch (ServiceConfigurationError e) { if (!(e.getCause() instanceof UnsupportedOperatingSystemException)) { throw e; } } } if (manager == null) { // TODO Throw appropriate error if we found no manager // For now, we just stop with a error throw new Error("no manager found"); } else { monitorManager = manager; } } public static MonitorManager getMonitorManager() { return monitorManager; } }
package me.yokeyword.fragmentation; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.annotation.IntDef; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentationMagician; import android.support.v4.view.ViewCompat; import android.support.v4.widget.ViewDragHelper; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.FrameLayout; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import me.yokeyword.fragmentation_swipeback.core.ISwipeBackActivity; public class SwipeBackLayout extends FrameLayout { /** * Edge flag indicating that the left edge should be affected. */ public static final int EDGE_LEFT = ViewDragHelper.EDGE_LEFT; /** * Edge flag indicating that the right edge should be affected. */ public static final int EDGE_RIGHT = ViewDragHelper.EDGE_RIGHT; public static final int EDGE_ALL = EDGE_LEFT | EDGE_RIGHT; /** * A view is not currently being dragged or animating as a result of a * fling/snap. */ public static final int STATE_IDLE = ViewDragHelper.STATE_IDLE; /** * A view is currently being dragged. The position is currently changing as * a result of user input or simulated user input. */ public static final int STATE_DRAGGING = ViewDragHelper.STATE_DRAGGING; /** * A view is currently settling into place as a result of a fling or * predefined non-interactive motion. */ public static final int STATE_SETTLING = ViewDragHelper.STATE_SETTLING; private static final int DEFAULT_SCRIM_COLOR = 0x99000000; private static final float DEFAULT_PARALLAX = 0.33f; private static final int FULL_ALPHA = 255; private static final float DEFAULT_SCROLL_THRESHOLD = 0.4f; private static final int OVERSCROLL_DISTANCE = 10; private float mScrollFinishThreshold = DEFAULT_SCROLL_THRESHOLD; private ViewDragHelper mHelper; private float mScrollPercent; private float mScrimOpacity; private FragmentActivity mActivity; private View mContentView; private ISupportFragment mFragment; private Fragment mPreFragment; private Drawable mShadowLeft; private Drawable mShadowRight; private Rect mTmpRect = new Rect(); private int mEdgeFlag; private boolean mEnable = true; private int mCurrentSwipeOrientation; private float mParallaxOffset = DEFAULT_PARALLAX; private boolean mCallOnDestroyView; private boolean mInLayout; private int mContentLeft; private int mContentTop; /** * The set of listeners to be sent events through. */ private List<OnSwipeListener> mListeners; private Context mContext; public enum EdgeLevel { MAX, MIN, MED } public SwipeBackLayout(Context context) { this(context, null); } public SwipeBackLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public SwipeBackLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.mContext = context; init(); } private void init() { mHelper = ViewDragHelper.create(this, new ViewDragCallback()); setShadow(me.yokeyword.fragmentation_swipeback.R.drawable.shadow_left, EDGE_LEFT); setEdgeOrientation(EDGE_LEFT); } /** * Set scroll threshold, we will close the activity, when scrollPercent over * this value * * @param threshold */ public void setScrollThresHold(float threshold) { if (threshold >= 1.0f || threshold <= 0) { throw new IllegalArgumentException("Threshold value should be between 0 and 1.0"); } mScrollFinishThreshold = threshold; } public void setParallaxOffset(float offset) { this.mParallaxOffset = offset; } /** * Enable edge tracking for the selected edges of the parent view. * The callback's {@link ViewDragHelper.Callback#onEdgeTouched(int, int)} and * {@link ViewDragHelper.Callback#onEdgeDragStarted(int, int)} methods will only be invoked * for edges for which edge tracking has been enabled. * * @param orientation Combination of edge flags describing the edges to watch * @see #EDGE_LEFT * @see #EDGE_RIGHT */ public void setEdgeOrientation(@EdgeOrientation int orientation) { mEdgeFlag = orientation; mHelper.setEdgeTrackingEnabled(orientation); if (orientation == EDGE_RIGHT || orientation == EDGE_ALL) { setShadow(me.yokeyword.fragmentation_swipeback.R.drawable.shadow_right, EDGE_RIGHT); } } @IntDef({EDGE_LEFT, EDGE_RIGHT, EDGE_ALL}) @Retention(RetentionPolicy.SOURCE) public @interface EdgeOrientation { } /** * Set a drawable used for edge shadow. */ public void setShadow(Drawable shadow, int edgeFlag) { if ((edgeFlag & EDGE_LEFT) != 0) { mShadowLeft = shadow; } else if ((edgeFlag & EDGE_RIGHT) != 0) { mShadowRight = shadow; } invalidate(); } /** * Set a drawable used for edge shadow. */ public void setShadow(int resId, int edgeFlag) { setShadow(getResources().getDrawable(resId), edgeFlag); } /** * Add a callback to be invoked when a swipe event is sent to this view. * * @param listener the swipe listener to attach to this view */ public void addSwipeListener(OnSwipeListener listener) { if (mListeners == null) { mListeners = new ArrayList<>(); } mListeners.add(listener); } /** * Removes a listener from the set of listeners * * @param listener */ public void removeSwipeListener(OnSwipeListener listener) { if (mListeners == null) { return; } mListeners.remove(listener); } public interface OnSwipeListener { /** * Invoke when state change * * @param state flag to describe scroll state * @see #STATE_IDLE * @see #STATE_DRAGGING * @see #STATE_SETTLING */ void onDragStateChange(int state); /** * Invoke when edge touched * * @param oritentationEdgeFlag edge flag describing the edge being touched * @see #EDGE_LEFT * @see #EDGE_RIGHT */ void onEdgeTouch(int oritentationEdgeFlag); /** * Invoke when scroll percent over the threshold for the first time * * @param scrollPercent scroll percent of this view */ void onDragScrolled(float scrollPercent); } @Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) { boolean isDrawView = child == mContentView; boolean drawChild = super.drawChild(canvas, child, drawingTime); if (isDrawView && mScrimOpacity > 0 && mHelper.getViewDragState() != ViewDragHelper.STATE_IDLE) { drawShadow(canvas, child); drawScrim(canvas, child); } return drawChild; } private void drawShadow(Canvas canvas, View child) { final Rect childRect = mTmpRect; child.getHitRect(childRect); if ((mCurrentSwipeOrientation & EDGE_LEFT) != 0) { mShadowLeft.setBounds(childRect.left - mShadowLeft.getIntrinsicWidth(), childRect.top, childRect.left, childRect.bottom); mShadowLeft.setAlpha((int) (mScrimOpacity * FULL_ALPHA)); mShadowLeft.draw(canvas); } else if ((mCurrentSwipeOrientation & EDGE_RIGHT) != 0) { mShadowRight.setBounds(childRect.right, childRect.top, childRect.right + mShadowRight.getIntrinsicWidth(), childRect.bottom); mShadowRight.setAlpha((int) (mScrimOpacity * FULL_ALPHA)); mShadowRight.draw(canvas); } } private void drawScrim(Canvas canvas, View child) { final int baseAlpha = (DEFAULT_SCRIM_COLOR & 0xff000000) >>> 24; final int alpha = (int) (baseAlpha * mScrimOpacity); final int color = alpha << 24; if ((mCurrentSwipeOrientation & EDGE_LEFT) != 0) { canvas.clipRect(0, 0, child.getLeft(), getHeight()); } else if ((mCurrentSwipeOrientation & EDGE_RIGHT) != 0) { canvas.clipRect(child.getRight(), 0, getRight(), getHeight()); } canvas.drawColor(color); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { mInLayout = true; if (mContentView != null) { mContentView.layout(mContentLeft, mContentTop, mContentLeft + mContentView.getMeasuredWidth(), mContentTop + mContentView.getMeasuredHeight()); } mInLayout = false; } @Override public void requestLayout() { if (!mInLayout) { super.requestLayout(); } } @Override public void computeScroll() { mScrimOpacity = 1 - mScrollPercent; if (mScrimOpacity >= 0) { if (mHelper.continueSettling(true)) { ViewCompat.postInvalidateOnAnimation(this); } if (mPreFragment != null && mPreFragment.getView() != null) { if (mCallOnDestroyView) { mPreFragment.getView().setX(0); return; } if (mHelper.getCapturedView() != null) { int leftOffset = (int) ((mHelper.getCapturedView().getLeft() - getWidth()) * mParallaxOffset * mScrimOpacity); mPreFragment.getView().setX(leftOffset > 0 ? 0 : leftOffset); } } } } /** * hide */ public void internalCallOnDestroyView() { mCallOnDestroyView = true; } public void setFragment(final ISupportFragment fragment, View view) { this.mFragment = fragment; mContentView = view; } public void hiddenFragment() { if (mPreFragment != null && mPreFragment.getView() != null) { mPreFragment.getView().setVisibility(GONE); } } public void attachToActivity(FragmentActivity activity) { mActivity = activity; TypedArray a = activity.getTheme().obtainStyledAttributes(new int[]{ android.R.attr.windowBackground }); int background = a.getResourceId(0, 0); a.recycle(); ViewGroup decor = (ViewGroup) activity.getWindow().getDecorView(); ViewGroup decorChild = (ViewGroup) decor.getChildAt(0); decorChild.setBackgroundResource(background); decor.removeView(decorChild); addView(decorChild); setContentView(decorChild); decor.addView(this); } public void attachToFragment(ISupportFragment fragment, View view) { addView(view); setFragment(fragment, view); } private void setContentView(View view) { mContentView = view; } public void setEnableGesture(boolean enable) { mEnable = enable; } public void setEdgeLevel(EdgeLevel edgeLevel) { validateEdgeLevel(-1, edgeLevel); } public void setEdgeLevel(int widthPixel) { validateEdgeLevel(widthPixel, null); } private void validateEdgeLevel(int widthPixel, EdgeLevel edgeLevel) { try { DisplayMetrics metrics = new DisplayMetrics(); WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); windowManager.getDefaultDisplay().getMetrics(metrics); Field mEdgeSize = mHelper.getClass().getDeclaredField("mEdgeSize"); mEdgeSize.setAccessible(true); if (widthPixel >= 0) { mEdgeSize.setInt(mHelper, widthPixel); } else { if (edgeLevel == EdgeLevel.MAX) { mEdgeSize.setInt(mHelper, metrics.widthPixels); } else if (edgeLevel == EdgeLevel.MED) { mEdgeSize.setInt(mHelper, metrics.widthPixels / 2); } else { mEdgeSize.setInt(mHelper, ((int) (20 * metrics.density + 0.5f))); } } } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } private class ViewDragCallback extends ViewDragHelper.Callback { @Override public boolean tryCaptureView(View child, int pointerId) { boolean dragEnable = mHelper.isEdgeTouched(mEdgeFlag, pointerId); if (dragEnable) { if (mHelper.isEdgeTouched(EDGE_LEFT, pointerId)) { mCurrentSwipeOrientation = EDGE_LEFT; } else if (mHelper.isEdgeTouched(EDGE_RIGHT, pointerId)) { mCurrentSwipeOrientation = EDGE_RIGHT; } if (mListeners != null && !mListeners.isEmpty()) { for (OnSwipeListener listener : mListeners) { listener.onEdgeTouch(mCurrentSwipeOrientation); } } if (mPreFragment == null) { if (mFragment != null) { List<Fragment> fragmentList = FragmentationMagician.getActiveFragments(((Fragment) mFragment).getFragmentManager()); if (fragmentList != null && fragmentList.size() > 1) { int index = fragmentList.indexOf(mFragment); for (int i = index - 1; i >= 0; i Fragment fragment = fragmentList.get(i); if (fragment != null && fragment.getView() != null) { fragment.getView().setVisibility(VISIBLE); mPreFragment = fragment; break; } } } } } else { View preView = mPreFragment.getView(); if (preView != null && preView.getVisibility() != VISIBLE) { preView.setVisibility(VISIBLE); } } } return dragEnable; } @Override public int clampViewPositionHorizontal(View child, int left, int dx) { int ret = 0; if ((mCurrentSwipeOrientation & EDGE_LEFT) != 0) { ret = Math.min(child.getWidth(), Math.max(left, 0)); } else if ((mCurrentSwipeOrientation & EDGE_RIGHT) != 0) { ret = Math.min(0, Math.max(left, -child.getWidth())); } return ret; } @Override public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) { super.onViewPositionChanged(changedView, left, top, dx, dy); if ((mCurrentSwipeOrientation & EDGE_LEFT) != 0) { mScrollPercent = Math.abs((float) left / (mContentView.getWidth() + mShadowLeft.getIntrinsicWidth())); } else if ((mCurrentSwipeOrientation & EDGE_RIGHT) != 0) { mScrollPercent = Math.abs((float) left / (mContentView.getWidth() + mShadowRight.getIntrinsicWidth())); } mContentLeft = left; mContentTop = top; invalidate(); if (mListeners != null && !mListeners.isEmpty() && mHelper.getViewDragState() == STATE_DRAGGING && mScrollPercent <= 1 && mScrollPercent > 0) { for (OnSwipeListener listener : mListeners) { listener.onDragScrolled(mScrollPercent); } } if (mScrollPercent > 1) { if (mFragment != null) { if (mCallOnDestroyView) return; if (mPreFragment instanceof ISupportFragment) { ((ISupportFragment) mPreFragment).getSupportDelegate().mLockAnim = true; } if (!((Fragment) mFragment).isDetached()) { mFragment.getSupportDelegate().popForSwipeBack(); } if (mPreFragment instanceof ISupportFragment) { ((ISupportFragment) mPreFragment).getSupportDelegate().mLockAnim = false; } } else { if (!mActivity.isFinishing()) { mActivity.finish(); mActivity.overridePendingTransition(0, 0); } } } } @Override public int getViewHorizontalDragRange(View child) { if (mFragment != null) { return 1; } if (mActivity instanceof ISwipeBackActivity && ((ISwipeBackActivity) mActivity).swipeBackPriority()) { return 1; } return 0; } @Override public void onViewReleased(View releasedChild, float xvel, float yvel) { final int childWidth = releasedChild.getWidth(); int left = 0, top = 0; if ((mCurrentSwipeOrientation & EDGE_LEFT) != 0) { left = xvel > 0 || xvel == 0 && mScrollPercent > mScrollFinishThreshold ? (childWidth + mShadowLeft.getIntrinsicWidth() + OVERSCROLL_DISTANCE) : 0; } else if ((mCurrentSwipeOrientation & EDGE_RIGHT) != 0) { left = xvel < 0 || xvel == 0 && mScrollPercent > mScrollFinishThreshold ? -(childWidth + mShadowRight.getIntrinsicWidth() + OVERSCROLL_DISTANCE) : 0; } mHelper.settleCapturedViewAt(left, top); invalidate(); } @Override public void onViewDragStateChanged(int state) { super.onViewDragStateChanged(state); if (mListeners != null && !mListeners.isEmpty()) { for (OnSwipeListener listener : mListeners) { listener.onDragStateChange(state); } } } @Override public void onEdgeTouched(int edgeFlags, int pointerId) { super.onEdgeTouched(edgeFlags, pointerId); if ((mEdgeFlag & edgeFlags) != 0) { mCurrentSwipeOrientation = edgeFlags; } } } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (!mEnable) return super.onInterceptTouchEvent(ev); try { return mHelper.shouldInterceptTouchEvent(ev); } catch (Exception ignored) { ignored.printStackTrace(); } return false; } @Override public boolean onTouchEvent(MotionEvent event) { if (!mEnable) return super.onTouchEvent(event); try { mHelper.processTouchEvent(event); return true; } catch (Exception ignored) { ignored.printStackTrace(); } return false; } }
package com.namelessdev.mpdroid; import org.a0z.mpd.MPD; import org.a0z.mpd.MPDStatus; import org.a0z.mpd.exception.MPDServerException; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.StrictMode; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.KeyEvent; import android.view.View; import android.widget.ArrayAdapter; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.ActionBar.OnNavigationListener; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.namelessdev.mpdroid.MPDroidActivities.MPDroidFragmentActivity; import com.namelessdev.mpdroid.fragments.NowPlayingFragment; import com.namelessdev.mpdroid.fragments.PlaylistFragment; import com.namelessdev.mpdroid.fragments.PlaylistFragmentCompat; import com.namelessdev.mpdroid.library.LibraryTabActivity; import com.namelessdev.mpdroid.tools.Tools; public class MainMenuActivity extends MPDroidFragmentActivity implements OnNavigationListener { public static final int PLAYLIST = 1; public static final int ARTISTS = 2; public static final int SETTINGS = 5; public static final int STREAM = 6; public static final int LIBRARY = 7; public static final int CONNECT = 8; /** * The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the * sections. We use a {@link android.support.v4.app.FragmentPagerAdapter} derivative, which will * keep every loaded fragment in memory. If this becomes too memory intensive, it may be best * to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}. */ SectionsPagerAdapter mSectionsPagerAdapter; /** * The {@link ViewPager} that will host the section contents. */ ViewPager mViewPager; private int backPressExitCount; private Handler exitCounterReset; private boolean isDualPaneMode; @SuppressLint("NewApi") @TargetApi(11) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); isDualPaneMode = (findViewById(R.id.playlist_fragment) != null); exitCounterReset = new Handler(); if (android.os.Build.VERSION.SDK_INT >= 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } // Create the adapter that will return a fragment for each of the three primary sections // of the app. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the action bar. final ActionBar actionBar = getSupportActionBar(); if (!isDualPaneMode) { actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); actionBar.setDisplayShowTitleEnabled(false); actionBar.setDisplayShowHomeEnabled(true); } else { actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayShowTitleEnabled(true); actionBar.setDisplayShowHomeEnabled(true); setTitle(R.string.nowPlaying); } ArrayAdapter<CharSequence> actionBarAdapter = new ArrayAdapter<CharSequence>(getSupportActionBar().getThemedContext(), R.layout.sherlock_spinner_item); actionBarAdapter.add(getString(R.string.nowPlaying)); actionBarAdapter.add(getString(R.string.playQueue)); if(Build.VERSION.SDK_INT >= 14) { //Bug on ICS with sherlock's layout actionBarAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } else { actionBarAdapter.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item); } actionBar.setListNavigationCallbacks(actionBarAdapter, this); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); if (android.os.Build.VERSION.SDK_INT >= 9) mViewPager.setOverScrollMode(View.OVER_SCROLL_NEVER); // When swiping between different sections, select the corresponding tab. // We can also use ActionBar.Tab#select() to do this if we have a reference to the // Tab. mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); } @Override public void onStart() { super.onStart(); MPDApplication app = (MPDApplication) getApplicationContext(); app.setActivity(this); } @Override public void onStop() { super.onStop(); MPDApplication app = (MPDApplication) getApplicationContext(); app.unsetActivity(this); } @Override protected void onResume() { super.onResume(); backPressExitCount = 0; } /** * Called when Back button is pressed, displays message to user indicating the if back button is pressed again the application will exit. We keep a count of how many time back * button is pressed within 5 seconds. If the count is greater than 1 then call system.exit(0) * * Starts a post delay handler to reset the back press count to zero after 5 seconds * * @return None */ @Override public void onBackPressed() { final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); final boolean exitConfirmationRequired = settings.getBoolean("enableExitConfirmation", false); if (exitConfirmationRequired && backPressExitCount < 1) { Tools.notifyUser(String.format(getResources().getString(R.string.backpressToQuit)), this); backPressExitCount += 1; exitCounterReset.postDelayed(new Runnable() { @Override public void run() { backPressExitCount = 0; } }, 5000); } else { /* * Nasty force quit, should shutdown everything nicely but there just too many async tasks maybe I'll correctly implement app.terminateApplication(); */ System.exit(0); } return; } @Override public boolean onNavigationItemSelected(int itemPosition, long itemId) { mViewPager.setCurrentItem(itemPosition); return true; } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary * sections of the app. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int i) { Fragment fragment = null; switch (i) { case 0: fragment = new NowPlayingFragment(); break; case 1: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { fragment = new PlaylistFragment(); } else { fragment = new PlaylistFragmentCompat(); } break; } return fragment; } @Override public int getCount() { return isDualPaneMode ? 1 : 2; } @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: return getString(R.string.nowPlaying); case 1: return getString(R.string.playQueue); } return null; } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getSupportMenuInflater().inflate(R.menu.mpd_mainmenu, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { //Reminder : never disable buttons that are shown as actionbar actions here super.onPrepareOptionsMenu(menu); MPDApplication app = (MPDApplication) this.getApplication(); MPD mpd = app.oMPDAsyncHelper.oMPD; if (!mpd.isConnected()) { if (menu.findItem(CONNECT) == null) { menu.add(0, CONNECT, 0, R.string.connect); } } else { if (menu.findItem(CONNECT) != null) { menu.removeItem(CONNECT); } } setMenuChecked(menu.findItem(R.id.GMM_Stream), app.getApplicationState().streamingMode); final MPDStatus mpdStatus = app.getApplicationState().currentMpdStatus; if (mpdStatus != null) { setMenuChecked(menu.findItem(R.id.GMM_Single), mpdStatus.isSingle()); setMenuChecked(menu.findItem(R.id.GMM_Consume), mpdStatus.isConsume()); } return true; } private void setMenuChecked(MenuItem item, boolean checked) { // Set the icon to a checkbox so 2.x users also get one item.setChecked(checked); item.setIcon(checked ? R.drawable.btn_check_buttonless_on : R.drawable.btn_check_buttonless_off); } private void openLibrary() { final Intent i = new Intent(this, LibraryTabActivity.class); startActivity(i); } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent i = null; final MPDApplication app = (MPDApplication) this.getApplication(); final MPD mpd = app.oMPDAsyncHelper.oMPD; // Handle item selection switch (item.getItemId()) { case R.id.menu_search: this.onSearchRequested(); return true; case R.id.GMM_LibTab: openLibrary(); return true; case R.id.GMM_Settings: i = new Intent(this, SettingsActivity.class); startActivityForResult(i, SETTINGS); return true; case R.id.GMM_Outputs: i = new Intent(this, SettingsActivity.class); i.putExtra(SettingsActivity.OPEN_OUTPUT, true); startActivityForResult(i, SETTINGS); return true; case CONNECT: ((MPDApplication) this.getApplication()).connect(); return true; case R.id.GMM_Stream: if (app.getApplicationState().streamingMode) { i = new Intent(this, StreamingService.class); i.setAction("com.namelessdev.mpdroid.DIE"); this.startService(i); ((MPDApplication) this.getApplication()).getApplicationState().streamingMode = false; // Toast.makeText(this, "MPD Streaming Stopped", Toast.LENGTH_SHORT).show(); } else { if (app.oMPDAsyncHelper.oMPD.isConnected()) { i = new Intent(this, StreamingService.class); i.setAction("com.namelessdev.mpdroid.START_STREAMING"); this.startService(i); ((MPDApplication) this.getApplication()).getApplicationState().streamingMode = true; // Toast.makeText(this, "MPD Streaming Started", Toast.LENGTH_SHORT).show(); } } return true; case R.id.GMM_bonjour: startActivity(new Intent(this, ServerListActivity.class)); return true; case R.id.GMM_Consume: try { mpd.setConsume(!mpd.getStatus().isConsume()); } catch (MPDServerException e) { } return true; case R.id.GMM_Single: try { mpd.setSingle(!mpd.getStatus().isSingle()); } catch (MPDServerException e) { } return true; default: return super.onOptionsItemSelected(item); } } @Override public boolean onKeyLongPress(int keyCode, KeyEvent event) { final MPDApplication app = (MPDApplication) getApplicationContext(); switch (event.getKeyCode()) { case KeyEvent.KEYCODE_VOLUME_UP: new Thread(new Runnable() { @Override public void run() { try { app.oMPDAsyncHelper.oMPD.next(); } catch (MPDServerException e) { e.printStackTrace(); } } }).start(); return true; case KeyEvent.KEYCODE_VOLUME_DOWN: new Thread(new Runnable() { @Override public void run() { try { app.oMPDAsyncHelper.oMPD.previous(); } catch (MPDServerException e) { e.printStackTrace(); } } }).start(); return true; } return super.onKeyLongPress(keyCode, event); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP) { // For onKeyLongPress to work event.startTracking(); return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, final KeyEvent event) { final MPDApplication app = (MPDApplication) getApplicationContext(); switch (event.getKeyCode()) { case KeyEvent.KEYCODE_VOLUME_UP: case KeyEvent.KEYCODE_VOLUME_DOWN: if (event.isTracking() && !event.isCanceled() && !app.getApplicationState().streamingMode) { new Thread(new Runnable() { @Override public void run() { try { app.oMPDAsyncHelper.oMPD.adjustVolume(event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP ? NowPlayingFragment.VOLUME_STEP : -NowPlayingFragment.VOLUME_STEP); } catch (MPDServerException e) { e.printStackTrace(); } } }).start(); } return true; } return super.onKeyUp(keyCode, event); } }
// 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.crowd.chat.client; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.samskivert.util.RandomUtil; import com.threerings.util.Name; import static com.threerings.crowd.Log.log; /** * A chat filter that can filter out curse words from user chat. */ public abstract class CurseFilter implements ChatFilter { /** Indicates how messages should be handled. */ public enum Mode { DROP, COMIC, VERNACULAR, UNFILTERED; } /** * Creates a curse filter. The curse words should be a string in the following format: * * <pre> * *penis*=John_Thomas shit*=barnacle muff=britches * </pre> * * The key/value pairs are separated by spaces, * matches word characters and the value after * the = is the string into which to convert the text when converting to the vernacular. * Underscores in the target string will be turned into spaces. * * <p> And stopWords should be in the following format: * * <pre> * *faggot* rape rapes raped raping * </pre> * * Words are separated by spaces and * matches any other word characters. */ public CurseFilter (String curseWords, String stopWords) { configureCurseWords(curseWords); configureStopWords(stopWords); } /** * The client will need to provide a way to look up our current chat filter mode. */ public abstract Mode getFilterMode (); // from interface ChatFilter public String filter (String msg, Name otherUser, boolean outgoing) { // first, check against the drop-always list _stopMatcher.reset(msg); if (_stopMatcher.find()) { return null; } // then see what kind of curse filtering the user has configured Mode level = getFilterMode(); if (level == Mode.UNFILTERED) { return msg; } StringBuffer inbuf = new StringBuffer(msg); StringBuffer outbuf = new StringBuffer(msg.length()); for (int ii=0, nn=_matchers.length; ii < nn; ii++) { Matcher m = _matchers[ii]; m.reset(inbuf); while (m.find()) { switch (level) { case DROP: return null; case COMIC: m.appendReplacement(outbuf, _replacements[ii].replace(" ", comicChars(_comicLength[ii]))); break; case VERNACULAR: String vernacular = _vernacular[ii]; if (Character.isUpperCase(m.group(2).codePointAt(0))) { int firstCharLen = Character.charCount(vernacular.codePointAt(0)); vernacular = vernacular.substring(0, firstCharLen).toUpperCase() + vernacular.substring(firstCharLen); } m.appendReplacement(outbuf, _replacements[ii].replace(" ", vernacular)); break; case UNFILTERED: // We returned the msg unadulterated above in this case, so it should be // impossible to wind up here, but let's enumerate it so we can let the compiler // scream about missing enum values in a switch log.warning("Omg? We're trying to filter chat even though we're unfiltered?"); break; } } if (outbuf.length() == 0) { // optimization: if we didn't find a match, jump to the next // pattern without doing any StringBuilder jimmying continue; } m.appendTail(outbuf); // swap the buffers around and clear the output StringBuffer temp = inbuf; inbuf = outbuf; outbuf = temp; outbuf.setLength(0); } return inbuf.toString(); } /** * Configure the curse word portion of our filtering. */ protected void configureCurseWords (String curseWords) { StringTokenizer st = new StringTokenizer(curseWords); int numWords = st.countTokens(); _matchers = new Matcher[numWords]; _replacements = new String[numWords]; _vernacular = new String[numWords]; _comicLength = new int[numWords]; for (int ii=0; ii < numWords; ii++) { String mapping = st.nextToken(); StringTokenizer st2 = new StringTokenizer(mapping, "="); if (st2.countTokens() != 2) { log.warning("Something looks wrong in the x.cursewords properties (" + mapping + "), skipping."); continue; } String curse = st2.nextToken(); String s = ""; String p = ""; if (curse.startsWith("*")) { curse = curse.substring(1); p += "([\\p{L}\\p{Digit}]*)"; s += "$1"; } else { p += "()"; } s += " "; p += " "; if (curse.endsWith("*")) { curse = curse.substring(0, curse.length() - 1); p += "([\\p{L}\\p{Digit}]*)"; s += "$3"; } String pattern = "\\b" + p.replace(" ", "(" + curse + ")") + "\\b"; Pattern pat = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); _matchers[ii] = pat.matcher(""); _replacements[ii] = s; _vernacular[ii] = st2.nextToken().replace('_', ' '); _comicLength[ii] = curse.codePointCount(0, curse.length()); } } /** * Configure the words that will stop. */ protected void configureStopWords (String stopWords) { StringTokenizer st = new StringTokenizer(stopWords); String pattern = ""; while (st.hasMoreTokens()) { if ("".equals(pattern)) { pattern += "("; } else { pattern += "|"; } pattern += getStopWordRegexp(st.nextToken()); } pattern += ")"; setStopPattern(pattern); } /** * Sets our stop word matcher to one for the given regular expression. */ protected void setStopPattern (String pattern) { _stopMatcher = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE).matcher(""); } /** * Turns a naughty word into a regular expression to catch it. */ protected String getStopWordRegexp (String word) { return "\\b" + word.replace("*", "[A-Za-z]*") + "\\b"; } /** * Return a comicy replacement of the specified length. */ protected String comicChars (int length) { StringBuilder buf = new StringBuilder(); for (int ii=0; ii < length; ii++) { buf.append(RandomUtil.pickRandom(COMIC_CHARS)); } return buf.toString(); } /** A matcher that will always cause a message to be dropped if it matches. */ protected Matcher _stopMatcher; /** Matchers for each curseword. */ protected Matcher[] _matchers; /** Length of comic-y replacements for each curseword. */ protected int[] _comicLength; /** Replacements. */ protected String[] _replacements; /** Replacements for each curseword "in the vernacular". */ protected String[] _vernacular; /** Comic replacement characters. */ protected static final String[] COMIC_CHARS = { "!", "@", " }
package org.springframework.jdbc.core; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeanWrapper; import org.springframework.beans.BeanWrapperImpl; import org.springframework.beans.BeansException; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.PropertyValue; import org.springframework.dao.InvalidDataAccessApiUsageException; /** * DEMONSTRATION OF THIS APPROACH ONLY: NOT FULLY IMPLEMENTED, * DOCUMENTED OR TESTED. */ public class ReflectionRowExtractor extends RowCountCallbackHandler implements ResultReader { protected final Log logger = LogFactory.getLog(getClass()); private List resultList; private Class resultClass; /** Column extractor to use */ //private ColumnExtractor columnExtractor; public ReflectionRowExtractor(Class resultClass, int rowsExpected) throws InvalidDataAccessApiUsageException { // Use the more efficient collection if we know how many rows to expect this.resultList = (rowsExpected > 0) ? (List) new ArrayList(rowsExpected) : (List) new LinkedList(); this.resultClass = resultClass; //this.columnExtractor = new DefaultColumnExtractor(); try { new BeanWrapperImpl(resultClass); } catch (BeansException ex) { // TODO: CORRECT EXCEPTION TYPE? throw new InvalidDataAccessApiUsageException("Can't introspect results: " + ex); } } protected void processRow(ResultSet rs, int rowNum) throws SQLException, InvalidDataAccessApiUsageException { //resultList.add(columnExtractor.extractColumn(1, requiredType, rs)); MutablePropertyValues pvs = new MutablePropertyValues(); for (int i = 0; i < getColumnCount(); i++) { String colname = getColumnNames()[i]; // HACK!!!! colname = colname.toLowerCase(); // TODO: clean up types PropertyValue pv = new PropertyValue(colname, rs.getObject(colname)); logger.info("Found property value " + pv); pvs.addPropertyValue(pv); } try { BeanWrapper bw = new BeanWrapperImpl(resultClass); bw.setPropertyValues(pvs); resultList.add(bw.getWrappedInstance()); } catch (BeansException ex) { throw new InvalidDataAccessApiUsageException("Can't add row results: " + ex); } } public List getResults() { return resultList; } }
package org.traccar.protocol; import org.junit.Test; import org.traccar.ProtocolTest; public class CarscopProtocolDecoderTest extends ProtocolTest { @Test public void testDecode() throws Exception { CarscopProtocolDecoder decoder = new CarscopProtocolDecoder(new CarscopProtocol()); verifyNull(decoder, text( "*170724163029UB05ORANGE000000010061825V0000.0000N00000.0000E000.0040331309.62")); verifyNull(decoder, text( "*160618233129UB00HSO")); verifyNull(decoder, text( "*160618232614UD00232614A5009.1747N01910.3829E0.000160618298.2811000000L000000")); verifyNull(decoder, text( "*160618232529UB05CW9999C00000538232529A5009.1747N01910.3829E0.000160618298.2811000000L000000")); verifyPosition(decoder, text( "*040331141830UB05123456789012345061825A2934.0133N10627.2544E000.0040331309.6200000000L000000"), position("2004-03-31 06:18:25.000", true, 29.56689, 106.45424)); verifyPosition(decoder, text( "*040331141830UB04999999984061825A2934.0133N10627.2544E000.0040331309.6200000000L000000")); verifyPosition(decoder, text( "*040331141830UA012Hi-jack061825A2934.0133N10627.2544E000.0040331309.6200000000L000000")); verifyPosition(decoder, text( "*150817160254UB05CC8011400042499160254A2106.8799S14910.2583E000.0150817158.3511111111L000000")); } }
import java.util.Random; import javax.swing.JOptionPane; import java.util.Arrays; public class LotteryGeneratorGui { public static void main (String []args) { int duplicate = Integer.parseInt(JOptionPane.showInputDialog("How many tickets do you want to make?")); int digits = Integer.parseInt(JOptionPane.showInputDialog("Input how many numbers, not including bonus.")); int range = Integer.parseInt(JOptionPane.showInputDialog("Input highest number range, inclusive.")); Random randGen = new Random(); for(int d = 0; d < duplicate; d++) { int[] randInt = new int[digits]; for(int i = 0; i < digits; i++) { randInt[i] = randGen.nextInt(range) + 1; } JOptionPane.showMessageDialog(null, "" + Arrays.toString(randInt) + ""); } int yn = JOptionPane.showConfirmDialog(null, "Is there a bonus number?", "Choose One", JOptionPane.YES_NO_OPTION); if(yn == 0){ int bRange = Integer.parseInt(JOptionPane.showInputDialog("Input bonus number range, inclusive.")); for(int d = 0; d < duplicate; d++){ int bonus = randGen.nextInt(bRange) + 1; JOptionPane.showMessageDialog(null, "" + bonus + ""); } } } }
package com.axelor.rpc; import java.io.IOException; import java.io.Writer; import java.lang.reflect.Method; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.inject.Inject; import javax.inject.Provider; import javax.persistence.EntityTransaction; import javax.persistence.OptimisticLockException; import org.hibernate.StaleObjectStateException; import org.hibernate.proxy.HibernateProxy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.axelor.common.StringUtils; import com.axelor.db.JPA; import com.axelor.db.JpaRepository; import com.axelor.db.JpaSecurity; import com.axelor.db.Model; import com.axelor.db.Query; import com.axelor.db.QueryBinder; import com.axelor.db.Repository; import com.axelor.db.mapper.Mapper; import com.axelor.db.mapper.Property; import com.axelor.db.mapper.PropertyType; import com.axelor.i18n.I18n; import com.axelor.i18n.I18nBundle; import com.axelor.meta.db.MetaTranslation; import com.axelor.rpc.filter.Filter; import com.google.common.base.CaseFormat; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Objects; import com.google.common.base.Splitter; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.primitives.Longs; import com.google.inject.Injector; import com.google.inject.TypeLiteral; import com.google.inject.persist.Transactional; /** * This class defines CRUD like interface. * */ public class Resource<T extends Model> { private Class<T> model; private Provider<JpaSecurity> security; private Logger LOG = LoggerFactory.getLogger(Resource.class); private Resource(Class<T> model, Provider<JpaSecurity> security) { this.model = model; this.security = security; } @Inject @SuppressWarnings("unchecked") public Resource(TypeLiteral<T> typeLiteral, Provider<JpaSecurity> security) { this((Class<T>) typeLiteral.getRawType(), security); } /** * Returns the resource class. * */ public Class<?> getModel() { return model; } private Long findId(Map<String, Object> values) { try { return Long.parseLong(values.get("id").toString()); } catch (Exception e){} return null; } public Response fields() { final Response response = new Response(); final Repository<?> repository = JpaRepository.of(model); final Map<String, Object> meta = Maps.newHashMap(); final List<Object> fields = Lists.newArrayList(); if (repository == null) { for (Property p : JPA.fields(model)) { fields.add(p.toMap()); } } else { for (Property p : repository.fields()) { fields.add(p.toMap()); } } meta.put("model", model.getName()); meta.put("fields", fields); response.setData(meta); response.setStatus(Response.STATUS_SUCCESS); return response; } public static Response models(Request request) { Response response = new Response(); List<String> data = Lists.newArrayList(); for(Class<?> type : JPA.models()) { data.add(type.getName()); } Collections.sort(data); response.setData(ImmutableList.copyOf(data)); response.setStatus(Response.STATUS_SUCCESS); return response; } public Response perms() { Set<JpaSecurity.AccessType> perms = security.get().getAccessTypes(model, null); Response response = new Response(); response.setData(perms); response.setStatus(Response.STATUS_SUCCESS); return response; } public Response perms(Long id) { Set<JpaSecurity.AccessType> perms = security.get().getAccessTypes(model, id); Response response = new Response(); response.setData(perms); response.setStatus(Response.STATUS_SUCCESS); return response; } public Response perms(Long id, String perm) { Response response = new Response(); JpaSecurity sec = security.get(); JpaSecurity.AccessType type = JpaSecurity.CAN_READ; try { type = JpaSecurity.AccessType.valueOf(perm.toUpperCase()); } catch (Exception e) { } try { sec.check(type, model, id); response.setStatus(Response.STATUS_SUCCESS); } catch (Exception e) { response.addError(perm, e.getMessage()); response.setStatus(Response.STATUS_VALIDATION_ERROR); } return response; } private List<String> getSortBy(Request request) { final List<String> sortBy = Lists.newArrayList(); final List<String> sortOn = Lists.newArrayList(); final Mapper mapper = Mapper.of(model); boolean unique = true; boolean desc = true; if (request.getSortBy() != null) { sortOn.addAll(request.getSortBy()); } if (sortOn.isEmpty()) { Property nameField = mapper.getNameField(); if (nameField == null) { nameField = mapper.getProperty("name"); } if (nameField == null) { nameField = mapper.getProperty("code"); } if (nameField != null) { sortOn.add(nameField.getName()); } } for(String spec : sortOn) { String name = spec; if (name.startsWith("-")) { name = name.substring(1); } else { desc = false; } Property property = mapper.getProperty(name); if (property == null || property.isPrimary()) { sortOn.add(spec); continue; } if (property.isReference()) { // use name field to sort many-to-one column Mapper m = Mapper.of(property.getTarget()); Property p = m.getNameField(); if (p != null) { spec = spec + "." + p.getName(); } } if (!property.isUnique()) { unique = false; } sortBy.add(spec); } if (!unique && (!sortBy.contains("id") || !sortBy.contains("-id"))) { sortBy.add(desc ? "-id" : "id"); } return sortBy; } private Criteria getCriteria(Request request) { if (request.getData() != null) { Object domain = request.getData().get("_domain"); if (domain != null) { try { String qs = request.getCriteria().createQuery(model).toString(); JPA.em().createQuery(qs); } catch (Exception e) { throw new IllegalArgumentException("Invalid domain: " + domain); } } } return request.getCriteria(); } private Query<?> getQuery(Request request) { Criteria criteria = getCriteria(request); Filter filter = security.get().getFilter(JpaSecurity.CAN_READ, model); Query<?> query = JPA.all(model); if (criteria != null) { query = criteria.createQuery(model, filter); } else if (filter != null) { query = filter.build(model); } for(String spec : getSortBy(request)) { query = query.order(spec); } return query; } public Response search(Request request) { security.get().check(JpaSecurity.CAN_READ, model); LOG.debug("Searching '{}' with {}", model.getCanonicalName(), request.getData()); Response response = new Response(); int offset = request.getOffset(); int limit = request.getLimit(); Query<?> query = getQuery(request); List<?> data = null; try { if (request.getFields() != null) { Query<?>.Selector selector = query.cacheable().select(request.getFields().toArray(new String[]{})); LOG.debug("JPQL: {}", selector); data = selector.fetch(limit, offset); } else { LOG.debug("JPQL: {}", query); data = query.cacheable().fetch(limit, offset); } response.setTotal(query.count()); } catch (Exception e) { EntityTransaction txn = JPA.em().getTransaction(); if (txn.isActive()) { txn.rollback(); } data = Lists.newArrayList(); LOG.error("Error: {}", e, e); } LOG.debug("Records found: {}", data.size()); data = Lists.transform(data, new Function<Object, Object>() { @Override public Object apply(Object input) { if (input instanceof Model) { return toMap((Model) input); } return input; }; }); try { // check for children (used by tree view) doChildCount(request, data); } catch (NullPointerException | ClassCastException e) {}; response.setData(data); response.setOffset(offset); response.setStatus(Response.STATUS_SUCCESS); return response; } @SuppressWarnings("all") private void doChildCount(Request request, List<?> result) throws NullPointerException, ClassCastException { final Map context = (Map) request.getData().get("_domainContext"); final String parent = (String) context.get("_countOn"); if (StringUtils.isBlank(parent) || result == null || result.isEmpty()) { return; } final StringBuilder builder = new StringBuilder(); builder.append("SELECT new map(_parent.id as id, count(self.id) as count) FROM ") .append(model.getName()).append(" self ") .append("LEFT JOIN self.").append(parent).append(" AS _parent ") .append("WHERE _parent.id IN (:ids) GROUP BY _parent"); final List ids = Lists.newArrayList(); for (Object item : result) { ids.add(((Map) item).get("id")); } javax.persistence.Query q = JPA.em().createQuery(builder.toString()); q.setParameter("ids", ids); Map counts = Maps.newHashMap(); for (Object item : q.getResultList()) { counts.put(((Map)item).get("id"), ((Map)item).get("count")); } for (Object item : result) { ((Map) item).put("_children", counts.get(((Map) item).get("id"))); } } @SuppressWarnings("unchecked") public void export(Request request, Writer writer) throws IOException { security.get().check(JpaSecurity.CAN_READ, model); LOG.debug("Exporting '{}' with {}", model.getName(), request.getData()); List<String> fields = request.getFields(); List<String> header = Lists.newArrayList(); List<String> names = Lists.newArrayList(); Map<Integer, Map<String, String>> selection = Maps.newHashMap(); Mapper mapper = Mapper.of(model); for(String field : fields) { Iterator<String> iter = Splitter.on(".").split(field).iterator(); Property prop = mapper.getProperty(iter.next()); while(iter.hasNext() && prop != null) { prop = Mapper.of(prop.getTarget()).getProperty(iter.next()); } if (prop == null || prop.isCollection()) { continue; } String name = prop.getName(); String title = prop.getTitle(); if(iter != null) { name = field; } if (title == null) { title = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, prop.getName()); title = humanize(title); } if (prop.isReference()) { prop = Mapper.of(prop.getTarget()).getNameField(); if (prop == null) { continue; } name = name + '.' + prop.getName(); } else if(prop.getSelection() != null && !"".equals(prop.getSelection().trim())) { javax.persistence.Query q = JPA.em().createQuery("SELECT new List(self.value, self.title) FROM MetaSelectItem self " + "JOIN self.select metaSelect " + "WHERE metaSelect.name = ?1"); q.setParameter(1, prop.getSelection()); List<List<?>> result = q.getResultList(); if (result == null || result.isEmpty()) { continue; } Map<String, String> map = Maps.newHashMap(); for (List<?> object : result) { map.put(object.get(0).toString(), object.get(1).toString()); } selection.put(header.size(), map); } title = I18n.get(title); names.add(name); header.add(escapeCsv(title)); } writer.write(Joiner.on(";").join(header)); int limit = 100; int offset = 0; Query<?> query = getQuery(request); Query<?>.Selector selector = query.select(names.toArray(new String[0])); List<?> data = selector.values(limit, offset); while(!data.isEmpty()) { for(Object item : data) { List<?> row = (List<?>) item; List<String> line = Lists.newArrayList(); int index = 0; for(Object value: row) { if (index++ < 2) continue; // ignore first two items (id, version) Object objValue = value == null ? "" : value; if(selection.containsKey(index-3)) { objValue = selection.get(index-3).get(objValue.toString()); } String strValue = objValue == null ? "" : escapeCsv(objValue.toString()); line.add(strValue); } writer.write("\n"); writer.write(Joiner.on(";").join(line)); } offset += limit; data = selector.values(limit, offset); } } private String escapeCsv(String value) { if (value == null) return ""; if (value.indexOf('"') > -1) value = value.replaceAll("\"", "\"\""); return '"' + value + '"'; } private String humanize(String value) { if (value.endsWith("_id")) value = value.substring(0, value.length() - 3); if (value.endsWith("_set")) value = value.substring(0, value.length() - 5); if (value.endsWith("_list")) value = value.substring(0, value.length() - 6); return value.substring(0, 1).toUpperCase() + value.substring(1).replaceAll("_+", " "); } public Response read(long id) { security.get().check(JpaSecurity.CAN_READ, model, id); Response response = new Response(); List<Object> data = Lists.newArrayList(); Model entity = JPA.find(model, id); if (entity != null) data.add(entity); response.setData(data); response.setStatus(Response.STATUS_SUCCESS); return response; } public Response fetch(long id, Request request) { security.get().check(JpaSecurity.CAN_READ, model, id); final Response response = new Response(); final Model entity = JPA.find(model, id); response.setStatus(Response.STATUS_SUCCESS); if (entity == null) { return response; } final List<Object> data = Lists.newArrayList(); final String[] fields = request.getFields().toArray(new String[]{}); final Map<String, List<String>> related = request.getRelated(); final Map<String, Object> values = toMap(entity, fields); if (related != null) { final Mapper mapper = Mapper.of(model); for (final String name : related.keySet()) { final String[] names = related.get(name).toArray(new String[] {}); Object value = mapper.get(entity, name); if (value instanceof Collection<?>) { value = Collections2.transform( (Collection<?>) value, new Function<Object, Object>() { @Override public Object apply(Object input) { return toMap(input, names); } }); } else if (value instanceof Model) { value = toMap(value, names); } values.put(name, value); } } data.add(values); response.setData(data); return response; } public Response verify(Request request) { Response response = new Response(); try { JPA.verify(model, request.getData()); response.setStatus(Response.STATUS_SUCCESS); } catch (OptimisticLockException e) { response.setStatus(Response.STATUS_VALIDATION_ERROR); } return response; } @Transactional @SuppressWarnings("all") public Response save(final Request request) { final Response response = new Response(); final Repository repository = JpaRepository.of(model); List<Object> records = request.getRecords(); List<Object> data = Lists.newArrayList(); if (records == null) { records = Lists.newArrayList(); records.add(request.getData()); } for(Object record : records) { Long id = findId((Map) record); if (id == null || id <= 0L) { security.get().check(JpaSecurity.CAN_CREATE, model); } Map<String, Object> orig = (Map) ((Map) record).get("_original"); JPA.verify(model, orig); Model bean = JPA.edit(model, (Map) record); id = bean.getId(); if (bean != null && id != null && id > 0L) { security.get().check(JpaSecurity.CAN_WRITE, model, id); } bean = JPA.manage(bean); if (repository != null) { bean = repository.save(bean); } data.add(bean); // if it's a translation object, invalidate cache if (bean instanceof MetaTranslation) { I18nBundle.invalidate(); } } response.setData(data); response.setStatus(Response.STATUS_SUCCESS); return response; } @Transactional public Response updateMass(Request request) { security.get().check(JpaSecurity.CAN_WRITE, model); LOG.debug("Mass update '{}' with {}", model.getCanonicalName(), request.getData()); Response response = new Response(); Query<?> query = getQuery(request); List<?> data = request.getRecords(); LOG.debug("JPQL: {}", query); @SuppressWarnings("all") Map<String, Object> values = (Map) data.get(0); response.setTotal(query.update(values)); LOG.debug("Records updated: {}", response.getTotal()); response.setStatus(Response.STATUS_SUCCESS); return response; } @Transactional @SuppressWarnings("all") public Response remove(long id, Request request) { security.get().check(JpaSecurity.CAN_REMOVE, model, id); final Response response = new Response(); final Repository repository = JpaRepository.of(model); final Map<String, Object> data = Maps.newHashMap(); data.put("id", id); data.put("version", request.getData().get("version")); Model bean = JPA.edit(model, data); if (bean.getId() != null) { if (repository == null) { JPA.remove(bean); } else { repository.remove(bean); } } response.setData(ImmutableList.of(toMapCompact(bean))); response.setStatus(Response.STATUS_SUCCESS); return response; } @Transactional @SuppressWarnings("all") public Response remove(Request request) { final Response response = new Response(); final Repository repository = JpaRepository.of(model); final List<Object> records = request.getRecords(); if (records == null || records.isEmpty()) { response.setException(new IllegalArgumentException("No records provides.")); return response; } final List<Model> entities = Lists.newArrayList(); for(Object record : records) { Map map = (Map) record; Long id = Longs.tryParse(map.get("id").toString()); Object version = map.get("version"); security.get().check(JpaSecurity.CAN_REMOVE, model, id); Model bean = JPA.find(model, id); if (version != null && !Objects.equal(version, bean.getVersion())) { throw new OptimisticLockException( new StaleObjectStateException(model.getName(), id)); } entities.add(bean); } for(Model entity : entities) { if (JPA.em().contains(entity)) { if (repository == null) { JPA.remove(entity); } else { repository.remove(entity); } } } response.setData(records); response.setStatus(Response.STATUS_SUCCESS); return response; } @SuppressWarnings("all") public Response copy(long id) { security.get().check(JpaSecurity.CAN_CREATE, model, id); final Response response = new Response(); final Repository repository = JpaRepository.of(model); Model bean = JPA.find(model, id); if (repository == null) { bean = JPA.copy(bean, true); } else { bean = repository.copy(bean, true); } response.setData(ImmutableList.of(bean)); response.setStatus(Response.STATUS_SUCCESS); return response; } @Inject private Injector injector; public ActionResponse action(ActionRequest request) { ActionResponse response = new ActionResponse(); String[] parts = request.getAction().split("\\:"); if (parts.length != 2) { response.setStatus(Response.STATUS_FAILURE); return response; } String controller = parts[0]; String method = parts[1]; try { Class<?> klass = Class.forName(controller); Method m = klass.getDeclaredMethod(method, ActionRequest.class, ActionResponse.class); Object obj = injector.getInstance(klass); m.setAccessible(true); m.invoke(obj, new Object[] { request, response }); response.setStatus(Response.STATUS_SUCCESS); } catch (Exception e) { LOG.debug(e.toString(), e); response.setException(e); } return response; } /** * Get the name of the record. This method should be used to get the value * of name field if it's a function field. * * @param request * the request containing the current values of the record * @return response with the updated values with record name */ public Response getRecordName(Request request) { Response response = new Response(); Mapper mapper = Mapper.of(model); Map<String, Object> data = request.getData(); Property property = null; try { property = mapper.getProperty(request.getFields().get(0)); } catch (Exception e) { } if (property == null) { property = mapper.getNameField(); } if (property != null) { String qs = String.format( "SELECT self.%s FROM %s self WHERE self.id = :id", property.getName(), model.getSimpleName()); javax.persistence.Query query = JPA.em().createQuery(qs); QueryBinder.of(query).bind(data); Object name = query.getSingleResult(); data.put(property.getName(), name); } response.setData(ImmutableList.of(data)); response.setStatus(Response.STATUS_SUCCESS); return response; } public static Map<String, Object> toMap(Object bean, String... names) { return _toMap(bean, unflatten(null, names), false, 0); } public static Map<String, Object> toMapCompact(Object bean) { return _toMap(bean, null, true, 1); } @SuppressWarnings("all") private static Map<String, Object> _toMap(Object bean, Map<String, Object> fields, boolean compact, int level) { if (bean == null) { return null; } if (bean instanceof HibernateProxy) { bean = ((HibernateProxy) bean).getHibernateLazyInitializer().getImplementation(); } if (fields == null) { fields = Maps.newHashMap(); } Map<String, Object> result = new HashMap<String, Object>(); Mapper mapper = Mapper.of(bean.getClass()); boolean isSaved = ((Model)bean).getId() != null; boolean isCompact = compact || fields.containsKey("$version"); if ((isCompact && isSaved) || (isSaved && level >= 1 ) || (level > 1)) { Property pn = mapper.getNameField(); Property pc = mapper.getProperty("code"); result.put("id", mapper.get(bean, "id")); result.put("$version", mapper.get(bean, "version")); if (pn != null) result.put(pn.getName(), mapper.get(bean, pn.getName())); if (pc != null) result.put(pc.getName(), mapper.get(bean, pc.getName())); for(String name: fields.keySet()) { Object child = mapper.get(bean, name); if (child instanceof Model) { child = _toMap(child, (Map) fields.get(name), true, level + 1); } if (child != null) { result.put(name, child); } } return result; } for (final Property prop : mapper.getProperties()) { String name = prop.getName(); PropertyType type = prop.getType(); if (type == PropertyType.BINARY && !name.toLowerCase().matches(".*(image|photo|picture).*")) { continue; } if (isSaved && prop.isCollection() && !fields.isEmpty() && !fields.containsKey(name)) { continue; } Object value = mapper.get(bean, name); if (prop.isImage() && byte[].class.isInstance(value)) { value = new String((byte[]) value); } // decimal values should be rounded accordingly otherwise the // json mapper may use wrong scale. if (value instanceof BigDecimal) { BigDecimal decimal = (BigDecimal) value; int scale = prop.getScale(); if (decimal.scale() == 0 && scale > 0 && scale != decimal.scale()) { value = decimal.setScale(scale, RoundingMode.HALF_UP); } } if (value instanceof Model) { // m2o Map<String, Object> _fields = (Map) fields.get(prop.getName()); value = _toMap(value, _fields, true, level + 1); } if (value instanceof Collection) { // o2m | m2m List<Object> items = Lists.newArrayList(); for(Model input : (Collection<Model>) value) { Map<String, Object> item; if (input.getId() != null) { item = _toMap(input, null, true, level+1); } else { item = _toMap(input, null, false, 1); } if (item != null) { items.add(item); } } value = items; } result.put(name, value); } return result; } @SuppressWarnings("all") private static Map<String, Object> unflatten(Map<String, Object> map, String... names) { if (map == null) map = Maps.newHashMap(); for(String name : names) { if (map.containsKey(name)) continue; if (name.contains(".")) { String[] parts = name.split("\\.", 2); Map<String, Object> child = (Map) map.get(parts[0]); if (child == null) { child = Maps.newHashMap(); } map.put(parts[0], unflatten(child, parts[1])); } else { map.put(name, Maps.newHashMap()); } } return map; } }
package halive.visualsort.core; import halive.visualsort.core.algorithms.datageneration.DataGenerator; import halive.visualsort.core.algorithms.options.OptionDialogResult; import halive.visualsort.core.algorithms.sorting.SortingAlgorithm; import halive.visualsort.core.export.SortingExporter; import halive.visualsort.core.interfaces.IVisualSortUI; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import java.util.Timer; import java.util.TimerTask; //TODO Document SortingHandler /** * This class is Responsible for Handling/invoking the DataGeneration and sorting. * It also counts the swaps and comparisons. * <p> * This class can be used In testing mode when the given gui is null. */ @SuppressWarnings({"FieldCanBeLocal", "EmptyCatchBlock"}) public class SortingHandler implements Runnable { public static final int MAX_HEIGHT_VAL = 1000; private static final int TIMER_INTERVAL = 20; private Timer statusUpdater; private long swaps = 0; private long comparisons = 0; private long elapsedTime = 0; private SortingAlgorithm sortingAlgorithm; private OptionDialogResult algorithmResult = null; private DataGenerator dataGenerator; private OptionDialogResult dataGenResult = null; private DataEntry[] entries; private int renderWidth; private int delay; private boolean delayOnSwap; private boolean delayOnComp; private boolean stopOnNextComp = false; private boolean stopOnNextSwap = false; private boolean paused = false; private boolean allowRendering = false; private Thread sortingThread; private IVisualSortUI gui; private int amtEntries; private int maxValue = SortingHandler.MAX_HEIGHT_VAL; private SortingExporter exporter; private boolean export = false; public SortingHandler(IVisualSortUI ui) { this.gui = ui; } /** * Initializes the Sorting Thread */ public void init() { statusUpdater = new Timer("Status Updater"); sortingThread = new Thread(this, "Sorting Handler"); sortingThread.start(); gui.displayStatus("Generating Data"); } /** * The SortingThreads Main Routine, Sorting and Datageneration is * Invoked and Mostly Perfomed by this Method */ @Override public void run() { swaps = 0; comparisons = 0; elapsedTime = -TIMER_INTERVAL; allowRendering = false; entries = null; dataGenerator.init(dataGenResult, this); sortingAlgorithm.init(algorithmResult, this); entries = new DataEntry[amtEntries]; for (int i = 0; i < entries.length; i++) { entries[i] = new DataEntry(this.renderWidth, this); } gui.displayStatus("Created array with " + entries.length + " Entries"); dataGenerator.generateData(entries, MAX_HEIGHT_VAL); gui.displayStatus("Data generated"); this.allowRendering = true; gui.enableStopButtons(true); statusUpdater.schedule(new StatusUpdater(this, gui), 0, TIMER_INTERVAL); gui.displayStatus("Sorting"); logStep(); sortingAlgorithm.doSort(entries, this, 0, entries.length); statusUpdater.cancel(); if (export) { exporter.export(); } gui.displayStatus("Done"); this.manualDataUptdate(); gui.getStartButton().setEnabled(true); gui.enableAlgorithmSelection(true); gui.enableStopButtons(false); sortingAlgorithm.clearOptions(); dataGenerator.clearOptions(); sortingAlgorithm = null; dataGenerator = null; algorithmResult = null; dataGenResult = null; export = false; exporter = null; } /** * Adds A New Export Step. This is Invoked whenever A Item Gest Swapped. * It is Invoked by the onSwapped() Method */ public void logStep() { if (export) { exporter.addStep(entries); } } /** * Swaps the Values of the 2 Entries. The objets do not get swapped using this method * * @param p1 position 1 * @param p2 position 2 */ public void swap(int p1, int p2) { int v1 = entries[p1].getValue(); entries[p1].setValue(entries[p2].getValue()); entries[p2].setValue(v1); onSwapped(); } /** * Swaps the Objects at the Given Postions * * @param p1 pos1 Postion 1 * @param p2 pos2 Postion 2 */ public void swapObject(int p1, int p2) { DataEntry entry = entries[p1]; entries[p1] = entries[p2]; entries[p2] = entry; onSwapped(); } /** * This Increments the Comparisons and it delays if the delay for COmparisons is active. * * @param b the value to return * @return returns b (unmodified) */ public boolean compare(boolean b) { onCompared(); return b; } /** * Does the same as compare() is just does not return the value */ @SuppressWarnings("Duplicates") public void onCompared() { comparisons++; if (delayOnComp) { try { Thread.sleep(delay); } catch (InterruptedException e) { } } if (stopOnNextComp) { pauseOrUnpause(); while (stopOnNextComp) { Thread.yield(); } pauseOrUnpause(); } } /** * @return The Data Entry Array that gets Sorted */ public DataEntry[] getEntries() { return entries; } /** * Sets the entries Array to the Given Parameter * * @param entries see Above */ public void setEntries(DataEntry[] entries) { this.entries = entries; } /** * Sets the Current SortingAlgorithm * * @param currentAlgorithm the Sorting algortihm to set To */ public void setSortingAlgorithm(SortingAlgorithm currentAlgorithm) { this.sortingAlgorithm = currentAlgorithm; } /** * @return true this sorting Handler Has a DataGenerator set */ public boolean hasDataGenerator() { return dataGenerator != null; } /** * @return true this sorting Handler Has a SortingAlgorithm set */ public boolean hasSortingAlgorithm() { return sortingAlgorithm != null; } /** * @param delayOnComp If this is true the Sorting will Delay on the next Comparison. * If its False the Sorting will not delay */ public void setDelayOnComp(boolean delayOnComp) { this.delayOnComp = delayOnComp; } /** * @param delayOnSwap If this is true the Sorting will Delay on the next swap. * If its False the Sorting will not delay */ public void setDelayOnSwap(boolean delayOnSwap) { this.delayOnSwap = delayOnSwap; } /** * @param stopOnNextComp If this is true the Sorting will Pause on the next Comparison. * If its False the Sorting will Continue (if it was Paused before) */ public void setStopOnNextComp(boolean stopOnNextComp) { this.stopOnNextComp = stopOnNextComp; } /** * @param stopOnNextSwap If this is true the Sorting will Pause on the next swap. * If its False the Sorting will Continue (if it was Paused before) */ public void setStopOnNextSwap(boolean stopOnNextSwap) { this.stopOnNextSwap = stopOnNextSwap; } /** * @return true if the Data Contained By the Handler is allowed to Be rendered. * In other words this returns true if the data should get Rendered */ public boolean isAllowRendering() { return allowRendering; } /** * @return the renderWidth for every Value (Bar) */ public int getRenderWidth() { return renderWidth; } /** * Sets the renderWitdh of the bar of every Vlaues * * @param renderWidth see above */ public void setRenderWidth(int renderWidth) { this.renderWidth = renderWidth; if (entries != null) { for (DataEntry entry : entries) { entry.setWidth(renderWidth); } } } /** * @return The Amount of entries to Sort. this si Going to be the Length of the DataEntries Array */ public int getAmtEntries() { return amtEntries; } /** * Sets the Amount of entries the Soring Handler should have * * @param amtEntries see Above */ public void setAmtEntries(int amtEntries) { this.amtEntries = amtEntries; } /** * If the Sorting Was Paused in any way this will unpause Sorting * It does nothing if the Soring isnt paused. * or triggered to be Paused on the Next Swap/Comparison */ public void clearPause() { stopOnNextComp = false; stopOnNextSwap = false; } /** * Tells the Gui to Manually update the Data */ private void manualDataUptdate() { gui.updateStatusLabels(comparisons, swaps, null); } /** * @return true if the Sorting is not Paused. This is also true if the Handler has not been started */ public boolean isRunning() { return !paused; } @SuppressWarnings("Duplicates") public void onSwapped() { swaps++; logStep(); if (delayOnSwap) { try { Thread.sleep(delay); } catch (InterruptedException e) { } } if (stopOnNextSwap) { pauseOrUnpause(); while (stopOnNextSwap) { Thread.yield(); } pauseOrUnpause(); } } private void pauseOrUnpause() { paused = !paused; } public SortingAlgorithm getSortingAlgorithm() { return sortingAlgorithm; } public DataGenerator getDataGenerator() { return dataGenerator; } public void setDataGenerator(DataGenerator dataGenerator) { this.dataGenerator = dataGenerator; } public int getMaxValue() { return maxValue; } public int getDelay() { return delay; } public void setDelay(int delay) { this.delay = delay; } public SortingExporter getSortingExporter() { return exporter; } public void updateStatus(String msg) { if (gui != null) { gui.displayStatus(msg); } else { System.out.println(msg); } } public void setSortingExporter(SortingExporter exporter) { export = true; this.exporter = exporter; } public long getSwaps() { return swaps; } public long getComparisons() { return comparisons; } public IVisualSortUI getGui() { return gui; } public void setAlgorithmResult(OptionDialogResult algorithmResult) { this.algorithmResult = algorithmResult; } public void setDataGenResult(OptionDialogResult dataGenResult) { this.dataGenResult = dataGenResult; } private static class StatusUpdater extends TimerTask { private SortingHandler handler; private IVisualSortUI ui; private StatusUpdater(SortingHandler handler, IVisualSortUI ui) { this.handler = handler; this.ui = ui; } @Override public void run() { if (handler.isRunning()) { handler.elapsedTime += TIMER_INTERVAL; DateFormat outFormat = new SimpleDateFormat("HH:mm:ss.SS"); outFormat.setTimeZone(TimeZone.getTimeZone("UTC")); Date d = new Date(handler.elapsedTime); String result = outFormat.format(d); ui.updateStatusLabels(handler.comparisons, handler.swaps, result); } } } }
package com.namelessdev.mpdroid; import java.util.ArrayList; import java.util.List; import org.a0z.mpd.MPD; import org.a0z.mpd.MPDStatus; import org.a0z.mpd.exception.MPDServerException; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.ActionBar; import android.app.ActionBar.OnNavigationListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Bundle; import android.os.Handler; import android.os.StrictMode; import android.preference.PreferenceManager; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentManager.OnBackStackChangedListener; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import com.namelessdev.mpdroid.MPDroidActivities.MPDroidFragmentActivity; import com.namelessdev.mpdroid.fragments.BrowseFragment; import com.namelessdev.mpdroid.fragments.LibraryFragment; import com.namelessdev.mpdroid.fragments.NowPlayingFragment; import com.namelessdev.mpdroid.library.ILibraryFragmentActivity; import com.namelessdev.mpdroid.library.ILibraryTabActivity; import com.namelessdev.mpdroid.tools.LibraryTabsUtil; import com.namelessdev.mpdroid.tools.Tools; public class MainMenuActivity extends MPDroidFragmentActivity implements OnNavigationListener, ILibraryFragmentActivity, ILibraryTabActivity, OnBackStackChangedListener { public static enum DisplayMode { MODE_NOWPLAYING, MODE_QUEUE, MODE_LIBRARY } public static class DrawerItem { public static enum Action { ACTION_NOWPLAYING, ACTION_LIBRARY, ACTION_OUTPUTS } public Action action; public String label; public DrawerItem(String label, Action action) { this.label = label; this.action = action; } @Override public String toString() { return label; } } public static final int PLAYLIST = 1; public static final int ARTISTS = 2; public static final int SETTINGS = 5; public static final int STREAM = 6; public static final int LIBRARY = 7; public static final int CONNECT = 8; private static final String FRAGMENT_TAG_LIBRARY = "library"; private int backPressExitCount; private Handler exitCounterReset; private boolean isDualPaneMode; private MPDApplication app; private View nowPlayingDualPane; private ViewPager nowPlayingPager; private View libraryRootFrame; private List<DrawerItem> mDrawerItems; private DrawerLayout mDrawerLayout; private ListView mDrawerList; private ActionBarDrawerToggle mDrawerToggle; private int oldDrawerPosition; private LibraryFragment libraryFragment; private FragmentManager fragmentManager; private ArrayList<String> mTabList; private DisplayMode currentDisplayMode; @SuppressLint("NewApi") @TargetApi(11) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); app = (MPDApplication) getApplication(); setContentView(app.isTabletUiEnabled() ? R.layout.main_activity_nagvigation_tablet : R.layout.main_activity_nagvigation); nowPlayingDualPane = findViewById(R.id.nowplaying_dual_pane); nowPlayingPager = (ViewPager) findViewById(R.id.pager); libraryRootFrame = findViewById(R.id.library_root_frame); isDualPaneMode = (nowPlayingDualPane != null); switchMode(DisplayMode.MODE_NOWPLAYING); exitCounterReset = new Handler(); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); // Set up the action bar. final ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); mDrawerItems = new ArrayList<DrawerItem>(); mDrawerItems.add(new DrawerItem(getString(R.string.nowPlaying), DrawerItem.Action.ACTION_NOWPLAYING)); mDrawerItems.add(new DrawerItem(getString(R.string.libraryTabActivity), DrawerItem.Action.ACTION_LIBRARY)); mDrawerItems.add(new DrawerItem(getString(R.string.outputs), DrawerItem.Action.ACTION_OUTPUTS)); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.left_drawer); mDrawerToggle = new ActionBarDrawerToggle( this, /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */ R.string.drawer_open, /* "open drawer" description */ R.string.drawer_close /* "close drawer" description */ ) { /** Called when a drawer has settled in a completely closed state. */ public void onDrawerClosed(View view) { refreshActionBarTitle(); } /** Called when a drawer has settled in a completely open state. */ public void onDrawerOpened(View drawerView) { actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle(R.string.app_name); } }; // Set the drawer toggle as the DrawerListener mDrawerLayout.setDrawerListener(mDrawerToggle); // Set the adapter for the list view mDrawerList.setAdapter(new ArrayAdapter<DrawerItem>(this, R.layout.drawer_list_item, mDrawerItems)); oldDrawerPosition = 0; mDrawerList.setItemChecked(oldDrawerPosition, true); // Set the list's click listener mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); /* * Setup the library tab */ fragmentManager = getSupportFragmentManager(); fragmentManager.addOnBackStackChangedListener(this); // Get the list of the currently visible tabs mTabList = LibraryTabsUtil.getCurrentLibraryTabs(this.getApplicationContext()); ArrayAdapter<CharSequence> actionBarAdapter = new ArrayAdapter<CharSequence>(actionBar.getThemedContext(), android.R.layout.simple_spinner_item); for (int i = 0; i < mTabList.size(); i++) { actionBarAdapter.add(getText(LibraryTabsUtil.getTabTitleResId(mTabList.get(i)))); } actionBarAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); actionBar.setListNavigationCallbacks(actionBarAdapter, this); libraryFragment = (LibraryFragment) fragmentManager.findFragmentByTag(FRAGMENT_TAG_LIBRARY); if (libraryFragment == null) { libraryFragment = new LibraryFragment(); final FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); ft.replace(R.id.library_root_frame, libraryFragment, FRAGMENT_TAG_LIBRARY); ft.commit(); } // Setup the pager if (nowPlayingPager != null) { nowPlayingPager.setAdapter(new MainMenuPagerAdapter()); nowPlayingPager.setOnPageChangeListener( new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { refreshActionBarTitle(); } }); } } @Override public void onStart() { super.onStart(); MPDApplication app = (MPDApplication) getApplicationContext(); app.setActivity(this); } @Override public void onStop() { super.onStop(); MPDApplication app = (MPDApplication) getApplicationContext(); app.unsetActivity(this); } @Override protected void onResume() { super.onResume(); backPressExitCount = 0; } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } /** * Called when Back button is pressed, displays message to user indicating the if back button is pressed again the application will * exit. We keep a count of how many time back * button is pressed within 5 seconds. If the count is greater than 1 then call system.exit(0) * * Starts a post delay handler to reset the back press count to zero after 5 seconds * * @return None */ @Override public void onBackPressed() { if (currentDisplayMode == DisplayMode.MODE_LIBRARY) { final int fmStackCount = fragmentManager.getBackStackEntryCount(); if (fmStackCount > 0) { super.onBackPressed(); return; } } final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); final boolean exitConfirmationRequired = settings.getBoolean("enableExitConfirmation", false); if (exitConfirmationRequired && backPressExitCount < 1) { Tools.notifyUser(String.format(getResources().getString(R.string.backpressToQuit)), this); backPressExitCount += 1; exitCounterReset.postDelayed(new Runnable() { @Override public void run() { backPressExitCount = 0; } }, 5000); } else { /* * Nasty force quit, should shutdown everything nicely but there just too many async tasks maybe I'll correctly implement * app.terminateApplication(); */ System.exit(0); } return; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.mpd_mainmenu, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { // Reminder : never disable buttons that are shown as actionbar actions here super.onPrepareOptionsMenu(menu); MPDApplication app = (MPDApplication) this.getApplication(); MPD mpd = app.oMPDAsyncHelper.oMPD; if (!mpd.isConnected()) { if (menu.findItem(CONNECT) == null) { menu.add(0, CONNECT, 0, R.string.connect); } } else { if (menu.findItem(CONNECT) != null) { menu.removeItem(CONNECT); } } setMenuChecked(menu.findItem(R.id.GMM_Stream), app.getApplicationState().streamingMode); final MPDStatus mpdStatus = app.getApplicationState().currentMpdStatus; if (mpdStatus != null) { setMenuChecked(menu.findItem(R.id.GMM_Single), mpdStatus.isSingle()); setMenuChecked(menu.findItem(R.id.GMM_Consume), mpdStatus.isConsume()); } return true; } private void setMenuChecked(MenuItem item, boolean checked) { // Set the icon to a checkbox so 2.x users also get one item.setChecked(checked); item.setIcon(checked ? R.drawable.btn_check_buttonless_on : R.drawable.btn_check_buttonless_off); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } Intent i = null; final MPDApplication app = (MPDApplication) this.getApplication(); final MPD mpd = app.oMPDAsyncHelper.oMPD; // Handle item selection switch (item.getItemId()) { case R.id.menu_search: this.onSearchRequested(); return true; case R.id.GMM_Settings: i = new Intent(this, SettingsActivity.class); startActivityForResult(i, SETTINGS); return true; case CONNECT: ((MPDApplication) this.getApplication()).connect(); return true; case R.id.GMM_Stream: if (app.getApplicationState().streamingMode) { i = new Intent(this, StreamingService.class); i.setAction("com.namelessdev.mpdroid.DIE"); this.startService(i); ((MPDApplication) this.getApplication()).getApplicationState().streamingMode = false; // Toast.makeText(this, "MPD Streaming Stopped", Toast.LENGTH_SHORT).show(); } else { if (app.oMPDAsyncHelper.oMPD.isConnected()) { i = new Intent(this, StreamingService.class); i.setAction("com.namelessdev.mpdroid.START_STREAMING"); this.startService(i); ((MPDApplication) this.getApplication()).getApplicationState().streamingMode = true; // Toast.makeText(this, "MPD Streaming Started", Toast.LENGTH_SHORT).show(); } } return true; case R.id.GMM_bonjour: startActivity(new Intent(this, ServerListActivity.class)); return true; case R.id.GMM_Consume: try { mpd.setConsume(!mpd.getStatus().isConsume()); } catch (MPDServerException e) { } return true; case R.id.GMM_Single: try { mpd.setSingle(!mpd.getStatus().isSingle()); } catch (MPDServerException e) { } return true; default: return super.onOptionsItemSelected(item); } } @Override public boolean onKeyLongPress(int keyCode, KeyEvent event) { final MPDApplication app = (MPDApplication) getApplicationContext(); switch (event.getKeyCode()) { case KeyEvent.KEYCODE_VOLUME_UP: new Thread(new Runnable() { @Override public void run() { try { app.oMPDAsyncHelper.oMPD.next(); } catch (MPDServerException e) { e.printStackTrace(); } } }).start(); return true; case KeyEvent.KEYCODE_VOLUME_DOWN: new Thread(new Runnable() { @Override public void run() { try { app.oMPDAsyncHelper.oMPD.previous(); } catch (MPDServerException e) { e.printStackTrace(); } } }).start(); return true; } return super.onKeyLongPress(keyCode, event); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP) { // For onKeyLongPress to work event.startTracking(); return !app.getApplicationState().streamingMode; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, final KeyEvent event) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_VOLUME_UP: case KeyEvent.KEYCODE_VOLUME_DOWN: if (event.isTracking() && !event.isCanceled() && !app.getApplicationState().streamingMode) { new Thread(new Runnable() { @Override public void run() { try { app.oMPDAsyncHelper.oMPD .adjustVolume(event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP ? NowPlayingFragment.VOLUME_STEP : -NowPlayingFragment.VOLUME_STEP); } catch (MPDServerException e) { e.printStackTrace(); } } }).start(); } return true; } return super.onKeyUp(keyCode, event); } /** * Library methods */ @Override public void onBackStackChanged() { refreshActionBarTitle(); } @Override public boolean onNavigationItemSelected(int itemPosition, long itemId) { libraryFragment.setCurrentItem(itemPosition, true); return true; } @Override public void pushLibraryFragment(Fragment fragment, String label) { String title = ""; if (fragment instanceof BrowseFragment) { title = ((BrowseFragment) fragment).getTitle(); } else { title = fragment.toString(); } final FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); ft.replace(R.id.library_root_frame, fragment); ft.addToBackStack(label); ft.setBreadCrumbTitle(title); ft.commit(); } @Override public ArrayList<String> getTabList() { return mTabList; } @Override public void pageChanged(int position) { final ActionBar actionBar = getActionBar(); if (currentDisplayMode == DisplayMode.MODE_LIBRARY && actionBar.getNavigationMode() == ActionBar.NAVIGATION_MODE_LIST) actionBar.setSelectedNavigationItem(position); } /** * Navigation Drawer helpers */ private void refreshActionBarTitle() { final ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(true); switch (currentDisplayMode) { case MODE_QUEUE: case MODE_NOWPLAYING: actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); if (nowPlayingPager != null && nowPlayingPager.getCurrentItem() > 0) { actionBar.setTitle(R.string.playQueue); } else { actionBar.setTitle(R.string.nowPlaying); } break; case MODE_LIBRARY: final int fmStackCount = fragmentManager.getBackStackEntryCount(); if (fmStackCount > 0) { actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setTitle(fragmentManager.getBackStackEntryAt(fmStackCount - 1).getBreadCrumbTitle()); } else { actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); actionBar.setDisplayShowTitleEnabled(false); } break; } } private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mDrawerLayout.closeDrawer(mDrawerList); switch (((DrawerItem) parent.getItemAtPosition(position)).action) { default: case ACTION_LIBRARY: // If we are already on the library, pop the whole stack. Acts like an "up" button if (currentDisplayMode == DisplayMode.MODE_LIBRARY) { final int fmStackCount = fragmentManager.getBackStackEntryCount(); if (fmStackCount > 0) { fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); } } switchMode(DisplayMode.MODE_LIBRARY); break; case ACTION_NOWPLAYING: switchMode(DisplayMode.MODE_NOWPLAYING); break; case ACTION_OUTPUTS: mDrawerList.setItemChecked(oldDrawerPosition, true); final Intent i = new Intent(MainMenuActivity.this, SettingsActivity.class); i.putExtra(SettingsActivity.OPEN_OUTPUT, true); startActivityForResult(i, SETTINGS); break; } oldDrawerPosition = position; } } /** Swaps fragments in the main content view */ public void switchMode(DisplayMode newMode) { currentDisplayMode = newMode; switch (currentDisplayMode) { case MODE_QUEUE: case MODE_NOWPLAYING: if (isDualPaneMode) { nowPlayingDualPane.setVisibility(View.VISIBLE); } else { nowPlayingPager.setVisibility(View.VISIBLE); if (currentDisplayMode == DisplayMode.MODE_NOWPLAYING) { nowPlayingPager.setCurrentItem(0, true); } else { nowPlayingPager.setCurrentItem(1, true); } } libraryRootFrame.setVisibility(View.GONE); // Force MODE_NOWPLAYING even if MODE_QUEUE was asked currentDisplayMode = DisplayMode.MODE_NOWPLAYING; break; case MODE_LIBRARY: if (isDualPaneMode) { nowPlayingDualPane.setVisibility(View.GONE); } else { nowPlayingPager.setVisibility(View.GONE); } libraryRootFrame.setVisibility(View.VISIBLE); break; } refreshActionBarTitle(); } class MainMenuPagerAdapter extends PagerAdapter { public Object instantiateItem(View collection, int position) { int resId = 0; switch (position) { case 0: resId = R.id.nowplaying_fragment; break; case 1: resId = R.id.playlist_fragment; break; } return findViewById(resId); } @Override public int getCount() { return 2; } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == ((View) arg1); } @Override public void destroyItem(ViewGroup container, int position, Object object) { return; } } }
package okapi.service; import okapi.bean.ModuleDescriptor; import okapi.bean.ModuleInstance; import okapi.bean.Modules; import okapi.bean.Ports; import okapi.bean.ProcessModuleHandle; import okapi.bean.Tenant; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.HttpClient; import io.vertx.core.http.HttpClientRequest; import io.vertx.core.json.DecodeException; import io.vertx.core.json.Json; import io.vertx.core.streams.ReadStream; import io.vertx.ext.web.RoutingContext; import java.util.ArrayList; import java.util.List; import java.util.Iterator; public class ModuleService { private Modules modules; private Ports ports; private HttpClient httpClient; private TenantService tenantService; final private Vertx vertx; public ModuleService(Vertx vertx, int port_start, int port_end, TenantService ts) { this.vertx = vertx; this.ports = new Ports(port_start, port_end); this.modules = new Modules(); this.tenantService = ts; this.httpClient = vertx.createHttpClient(); } public void create(RoutingContext ctx) { try { final ModuleDescriptor md = Json.decodeValue(ctx.getBodyAsString(), ModuleDescriptor.class); final String name = md.getName(); ModuleInstance m = modules.get(name); if (m != null) { ctx.response().setStatusCode(400).end("module " + name + " already deployed"); return; } final String uri = ctx.request().uri() + "/" + name; final int use_port = ports.get(); if (use_port == -1) { ctx.response().setStatusCode(400).end("module " + name + " can not be deployed: all ports in use"); } // enable it now so that activation for 2nd one will fail ProcessModuleHandle pmh = new ProcessModuleHandle(vertx, md.getDescriptor(), use_port); modules.put(name, new ModuleInstance(md, pmh, use_port)); pmh.start(future -> { if (future.succeeded()) { ctx.response().setStatusCode(201).putHeader("Location", uri).end(); } else { modules.remove(md.getName()); ports.free(use_port); ctx.response().setStatusCode(500).end(future.cause().getMessage()); } }); } catch (DecodeException ex) { ctx.response().setStatusCode(400).end(ex.getMessage()); } } public void get(RoutingContext ctx) { final String id = ctx.request().getParam("id"); ModuleInstance m = modules.get(id); if (m == null) { ctx.response().setStatusCode(404).end(); return; } String s = Json.encodePrettily(modules.get(id).getModuleDescriptor()); ctx.response().end(s); } public void list(RoutingContext ctx) { String s = Json.encodePrettily(modules.list()); ctx.response().end(s); } public void delete(RoutingContext ctx) { final String id = ctx.request().getParam("id"); ModuleInstance m = modules.get(id); if (m == null) { ctx.response().setStatusCode(404).end(); return; } ProcessModuleHandle pmh = m.getProcessModuleHandle(); pmh.stop(future -> { if (future.succeeded()) { modules.remove(id); ports.free(pmh.getPort()); ctx.response().setStatusCode(204).end(); } else { ctx.response().setStatusCode(500).end(future.cause().getMessage()); } }); } /** * Add the trace headers to the response */ private void addTraceHeaders(RoutingContext ctx, List<String> traceHeaders) { for ( String th : traceHeaders ) { ctx.response().headers().add("X-Okapi-Trace", th); } } private void makeTraceHeader(RoutingContext ctx, ModuleInstance mi, int statusCode, long startTime, List<String> traceHeaders) { long timeDiff = (System.nanoTime() - startTime) / 1000; traceHeaders.add(ctx.request().method() + " " + mi.getModuleDescriptor().getName() + ":" + statusCode+ " " + timeDiff + "us"); addTraceHeaders(ctx, traceHeaders); } public void proxy(RoutingContext ctx) { String tenant_id = ctx.request().getHeader("X-Okapi-Tenant"); if (tenant_id == null) { ctx.response().setStatusCode(403).end("Missing Tenant"); return; } Tenant tenant = tenantService.get(tenant_id); if (tenant == null) { ctx.response().setStatusCode(400).end("No such Tenant " + tenant_id); return; } Iterator<ModuleInstance> it = modules.getModulesForRequest(ctx.request(), tenant); List<String> traceHeaders = new ArrayList<>(); ReadStream<Buffer> content = ctx.request(); content.pause(); proxyR(ctx, it, traceHeaders, content, null); } private void proxyRequestHttpClient(RoutingContext ctx, Iterator<ModuleInstance> it, List<String> traceHeaders, Buffer bcontent, ModuleInstance mi, long startTime) { HttpClientRequest c_req = httpClient.request(ctx.request().method(), mi.getPort(), "localhost", ctx.request().uri(), res -> { if (res.statusCode() < 200 || res.statusCode() >= 300) { ctx.response().setChunked(true); ctx.response().setStatusCode(res.statusCode()); ctx.response().headers().setAll(res.headers()); makeTraceHeader(ctx, mi, res.statusCode(), startTime, traceHeaders); res.handler(data -> { ctx.response().write(data); }); res.endHandler(x -> { ctx.response().end(); }); res.exceptionHandler(x -> { System.out.println("res exception " + x.getMessage()); }); } else if (it.hasNext()) { makeTraceHeader(ctx, mi, res.statusCode(), startTime, traceHeaders); proxyR(ctx, it, traceHeaders, null, bcontent); } else { ctx.response().setChunked(true); ctx.response().setStatusCode(res.statusCode()); ctx.response().headers().setAll(res.headers()); makeTraceHeader(ctx, mi, res.statusCode(), startTime, traceHeaders); res.endHandler(x -> { ctx.response().end(bcontent); }); res.exceptionHandler(x -> { System.out.println("res exception " + x.getMessage()); }); } }); c_req.exceptionHandler(res -> { ctx.response().setStatusCode(500).end("connect port " + mi.getPort() + ": " + res.getMessage()); }); c_req.setChunked(true); c_req.headers().setAll(ctx.request().headers()); c_req.end(bcontent); } private void proxyRequestOnly(RoutingContext ctx, Iterator<ModuleInstance> it, List<String> traceHeaders, ReadStream<Buffer> content, Buffer bcontent, ModuleInstance mi, long startTime) { if (bcontent != null) { proxyRequestHttpClient(ctx, it, traceHeaders, bcontent, mi, startTime); } else { final Buffer incoming = Buffer.buffer(); content.handler(data -> { incoming.appendBuffer(data); }); content.endHandler(v -> { proxyRequestHttpClient(ctx, it, traceHeaders, incoming, mi, startTime); }); content.resume(); } } private void proxyRequestResponse(RoutingContext ctx, Iterator<ModuleInstance> it, List<String> traceHeaders, ReadStream<Buffer> content, Buffer bcontent, ModuleInstance mi, long startTime) { HttpClientRequest c_req = httpClient.request(ctx.request().method(), mi.getPort(), "localhost", ctx.request().uri(), res -> { if (res.statusCode() >= 200 && res.statusCode() < 300 && it.hasNext()) { makeTraceHeader(ctx, mi, res.statusCode(), startTime, traceHeaders); res.pause(); proxyR(ctx, it, traceHeaders, res, null); } else { ctx.response().setChunked(true); ctx.response().setStatusCode(res.statusCode()); ctx.response().headers().setAll(res.headers()); makeTraceHeader(ctx, mi, res.statusCode(), startTime, traceHeaders); res.handler(data -> { ctx.response().write(data); }); res.endHandler(v -> { ctx.response().end(); }); res.exceptionHandler(v -> { System.out.println("res exception " + v.getMessage()); }); } }); c_req.exceptionHandler(res -> { ctx.response().setStatusCode(500).end("connect port " + mi.getPort() + ": " + res.getMessage()); }); c_req.setChunked(true); c_req.headers().setAll(ctx.request().headers()); if (bcontent != null) { c_req.end(bcontent); } else { content.handler(data -> { c_req.write(data); }); content.endHandler(v -> { c_req.end(); }); content.exceptionHandler(v -> { System.out.println("content exception " + v.getMessage()); }); content.resume(); } } private void proxyHeaders(RoutingContext ctx, Iterator<ModuleInstance> it, List<String> traceHeaders, ReadStream<Buffer> content, Buffer bcontent, ModuleInstance mi, long startTime) { HttpClientRequest c_req = httpClient.request(ctx.request().method(), mi.getPort(), "localhost", ctx.request().uri(), res -> { if (res.statusCode() < 200 || res.statusCode() >= 300) { ctx.response().setChunked(true); ctx.response().setStatusCode(res.statusCode()); ctx.response().headers().setAll(res.headers()); makeTraceHeader(ctx, mi, res.statusCode(), startTime, traceHeaders); res.handler(data -> { ctx.response().write(data); }); res.endHandler(v -> { ctx.response().end(); }); res.exceptionHandler(v -> { System.out.println("res exception " + v.getMessage()); }); } else if (it.hasNext()) { res.endHandler(x -> { proxyR(ctx, it, traceHeaders, content, bcontent); }); } else { ctx.response().setChunked(true); ctx.response().setStatusCode(res.statusCode()); ctx.response().headers().setAll(res.headers()); makeTraceHeader(ctx, mi, res.statusCode(), startTime, traceHeaders); if (bcontent == null) { content.handler(data -> { ctx.response().write(data); }); content.endHandler(v -> { ctx.response().end(); }); content.exceptionHandler(v -> { System.out.println("content exception " + v.getMessage()); }); content.resume(); } else { ctx.response().end(bcontent); } } }); c_req.exceptionHandler(res -> { ctx.response().setStatusCode(500).end("connect port " + mi.getPort() + ": " + res.getMessage()); }); // c_req.setChunked(true); // c_req.headers().setAll(ctx.request().headers()); c_req.end(); } private void proxyR(RoutingContext ctx, Iterator<ModuleInstance> it, List<String> traceHeaders, ReadStream<Buffer> content, Buffer bcontent) { if (!it.hasNext()) { content.resume(); addTraceHeaders(ctx, traceHeaders); ctx.response().setStatusCode(404).end(); } else { ModuleInstance mi = it.next(); final long startTime = System.nanoTime(); String rtype = mi.getRoutingEntry().getType(); if ("request-only".equals(rtype)) { proxyRequestOnly(ctx, it, traceHeaders, content, bcontent, mi, startTime); } else if ("request-response".equals(rtype)) { proxyRequestResponse(ctx, it, traceHeaders, content, bcontent, mi, startTime); } else if ("headers".equals(rtype)) { proxyHeaders(ctx, it, traceHeaders, content, bcontent, mi, startTime); } else { System.out.println("rtype = " + rtype); } } } } // class
package com.topsy.jmxproxy.resource; import java.io.UnsupportedEncodingException; import java.lang.StringBuilder; import java.net.URLEncoder; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import org.apache.log4j.Logger; import org.springframework.stereotype.Service; import org.springframework.web.util.HtmlUtils; import com.sun.jersey.spi.inject.Inject; import com.topsy.jmxproxy.service.JMXConnectionManager; import com.topsy.jmxproxy.domain.Attribute; @Service @Path("/") public class JMXProxyResource { private static Logger logger = Logger.getLogger(JMXProxyResource.class); @Inject private static JMXConnectionManager manager; private String encode(Object item) { try { return URLEncoder.encode(item.toString(), "UTF-8"); } catch (UnsupportedEncodingException e) { return item.toString(); } } private String escape(Object item) { return HtmlUtils.htmlEscape(item.toString()); } @GET @Path("/{host}") public Response processJMXRequest(@PathParam("host") String host) { logger.debug("requested jmx domains from " + host); try { StringBuilder sb = new StringBuilder("<html><head><title>" + escape(host) + "</title></head><body><ul>"); for (String domain : manager.getDomains(host)) { sb.append("\n<li><a href='" + encode(host) + "/" + encode(domain) + "'>" + escape(domain) + "</a></li>"); } sb.append("\n</ul></body></html>"); return Response.ok(sb.toString()).build(); } catch (Exception e) { logger.debug(e.fillInStackTrace()); return Response.status(Response.Status.NOT_FOUND).build(); } } @GET @Path("/{host}/{object}") public Response processJMXRequest(@PathParam("host") String host, @PathParam("object") String object) { try { StringBuilder sb = new StringBuilder("<html><head><title>" + escape(host) + "</title></head><body><ul>"); if (object.indexOf(':') == -1) { logger.debug("requested jmx domain mbeans from " + host + "/" + object); for (String mbean : manager.getMBeans(host, object)) { sb.append("\n<li><a href='" + encode(mbean) + "'>" + escape(mbean) + "</a></li>"); } } else { logger.debug("requested jmx mbean attributes from " + host + "/" + object); for (String attribute : manager.getAttributes(host, object)) { sb.append("\n<li><a href='" + encode(object) + "/" + encode(attribute) + "'>" + escape(attribute) + "</a></li>"); } } sb.append("\n</ul></body></html>"); return Response.ok(sb.toString()).build(); } catch (Exception e) { logger.debug(e.fillInStackTrace()); return Response.status(Response.Status.NOT_FOUND).build(); } } @GET @Produces("application/json") @Path("/{host}/{mbean}/{attribute}") public Response processJMXRequest(@PathParam("host") String host, @PathParam("mbean") String mbean, @PathParam("attribute") String attribute) { logger.debug("requested jmx attribute value of " + host + "/" + mbean + "/" + attribute); try { Object value = manager.getAttributeValue(host, mbean, attribute); return Response.ok(Attribute.toJSONString(value)).build(); } catch (Exception e) { logger.debug(e.fillInStackTrace()); return Response.status(Response.Status.NOT_FOUND).build(); } } }
package com.jakewharton.scalpel; import android.content.Context; import android.graphics.Camera; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Rect; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.widget.FrameLayout; import java.util.ArrayDeque; import java.util.Deque; import static android.graphics.Paint.ANTI_ALIAS_FLAG; import static android.graphics.Paint.Style.STROKE; import static android.view.MotionEvent.ACTION_DOWN; import static android.view.MotionEvent.ACTION_POINTER_UP; import static android.view.MotionEvent.INVALID_POINTER_ID; /** * Renders your view hierarchy as an interactive 3D visualization. * <p> * Interactions: * <ul> * <li>Single touch: controls the rotation of the model.</li> * <li>Two finger vertical drag: Adjust zoom.</li> * <li>Two finger horizontal drag: Adjust layer spacing.</li> * </ul> */ public class ScalpelFrameLayout extends FrameLayout { private static final int TRACKING_UNKNOWN = 0; private static final int TRACKING_VERTICALLY = 1; private static final int TRACKING_HORIZONTALLY = -1; private static final int ROTATION_MAX = 60; private static final int ROTATION_MIN = -ROTATION_MAX; private static final int ROTATION_DEFAULT_X = -10; private static final int ROTATION_DEFAULT_Y = 15; private static final float ZOOM_DEFAULT = 0.6f; private static final float ZOOM_MIN = 0.33f; private static final float ZOOM_MAX = 2f; private static final int SPACING_DEFAULT = 25; private static final int SPACING_MIN = 10; private static final int SPACING_MAX = 100; private static final int BORDER_COLOR = 0xFF888888; private static final boolean DEBUG = false; private static void log(String message, Object... args) { Log.d("Scalpel", String.format(message, args)); } private final Rect viewBoundsRect = new Rect(); private final Paint viewBorderPaint = new Paint(ANTI_ALIAS_FLAG); private final Camera camera = new Camera(); private final Matrix matrix = new Matrix(); private final int[] location = new int[2]; private final Deque<View> viewQueue = new ArrayDeque<>(); private final Deque<Integer> levelQueue = new ArrayDeque<>(); private final float density; private final float slop; private boolean enabled; private int pointerOne = INVALID_POINTER_ID; private float lastOneX; private float lastOneY; private int pointerTwo = INVALID_POINTER_ID; private float lastTwoX; private float lastTwoY; private int multiTouchTracking = TRACKING_UNKNOWN; private float rotationY = ROTATION_DEFAULT_Y; private float rotationX = ROTATION_DEFAULT_X; private float zoom = ZOOM_DEFAULT; private float spacing = SPACING_DEFAULT; private int[] visibilities = new int[50]; public ScalpelFrameLayout(Context context) { this(context, null); } public ScalpelFrameLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ScalpelFrameLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); density = context.getResources().getDisplayMetrics().density; slop = ViewConfiguration.get(context).getScaledTouchSlop(); viewBorderPaint.setColor(BORDER_COLOR); viewBorderPaint.setStyle(STROKE); } public void setLayerInteractionEnabled(boolean enabled) { if (this.enabled != enabled) { this.enabled = enabled; setWillNotDraw(!enabled); invalidate(); } } public boolean isLayerInteractionEnabled() { return enabled; } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { return enabled || super.onInterceptTouchEvent(ev); } @Override public boolean onTouchEvent(@SuppressWarnings("NullableProblems") MotionEvent event) { if (!enabled) { return super.onTouchEvent(event); } int action = event.getActionMasked(); switch (action) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: { int index = (action == ACTION_DOWN) ? 0 : event.getActionIndex(); if (pointerOne == INVALID_POINTER_ID) { pointerOne = event.getPointerId(index); lastOneX = event.getX(index); lastOneY = event.getY(index); if (DEBUG) log("Got pointer 1! id: %s x: %s y: %s", pointerOne, lastOneY, lastOneY); } else if (pointerTwo == INVALID_POINTER_ID) { pointerTwo = event.getPointerId(index); lastTwoX = event.getX(index); lastTwoY = event.getY(index); if (DEBUG) log("Got pointer 2! id: %s x: %s y: %s", pointerTwo, lastTwoY, lastTwoY); } else { if (DEBUG) log("Ignoring additional pointer. id: %s", event.getPointerId(index)); } break; } case MotionEvent.ACTION_MOVE: { if (pointerTwo == INVALID_POINTER_ID) { // Single pointer controlling 3D rotation. for (int i = 0, count = event.getPointerCount(); i < count; i++) { if (pointerOne == event.getPointerId(i)) { float eventX = event.getX(i); float eventY = event.getY(i); float dx = eventX - lastOneX; float dy = eventY - lastOneY; float drx = 90 * (dx / getWidth()); float dry = 90 * (-dy / getHeight()); // Invert Y-axis. // An 'x' delta affects 'y' rotation and vise versa. rotationY = Math.min(Math.max(rotationY + drx, ROTATION_MIN), ROTATION_MAX); rotationX = Math.min(Math.max(rotationX + dry, ROTATION_MIN), ROTATION_MAX); if (DEBUG) { log("Single pointer moved (%s, %s) affecting rotation (%s, %s).", dx, dy, drx, dry); } lastOneX = eventX; lastOneY = eventY; invalidate(); } } } else { // We know there's two pointers and we only care about pointerOne and pointerTwo int pointerOneIndex = event.findPointerIndex(pointerOne); int pointerTwoIndex = event.findPointerIndex(pointerTwo); float xOne = event.getX(pointerOneIndex); float yOne = event.getY(pointerOneIndex); float xTwo = event.getX(pointerTwoIndex); float yTwo = event.getY(pointerTwoIndex); float dxOne = xOne - lastOneX; float dyOne = yOne - lastOneY; float dxTwo = xTwo - lastTwoX; float dyTwo = yTwo - lastTwoY; if (multiTouchTracking == TRACKING_UNKNOWN) { float adx = Math.abs(dxOne) + Math.abs(dxTwo); float ady = Math.abs(dyOne) + Math.abs(dyTwo); if (adx > slop * 2 || ady > slop * 2) { if (adx > ady) { // Left/right movement wins. Track horizontal. multiTouchTracking = TRACKING_HORIZONTALLY; } else { // Up/down movement wins. Track vertical. multiTouchTracking = TRACKING_VERTICALLY; } } } if (multiTouchTracking == TRACKING_VERTICALLY) { if (yOne >= yTwo) { zoom += dyOne / getHeight() - dyTwo / getHeight(); } else { zoom += dyTwo / getHeight() - dyOne / getHeight(); } zoom = Math.min(Math.max(zoom, ZOOM_MIN), ZOOM_MAX); invalidate(); } else if (multiTouchTracking == TRACKING_HORIZONTALLY) { if (xOne >= xTwo) { spacing += (dxOne / getWidth() * SPACING_MAX) - (dxTwo / getWidth() * SPACING_MAX); } else { spacing += (dxTwo / getWidth() * SPACING_MAX) - (dxOne / getWidth() * SPACING_MAX); } spacing = Math.min(Math.max(spacing, SPACING_MIN), SPACING_MAX); invalidate(); } if (multiTouchTracking != TRACKING_UNKNOWN) { lastOneX = xOne; lastOneY = yOne; lastTwoX = xTwo; lastTwoY = yTwo; } } break; } case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: { int index = (action != ACTION_POINTER_UP) ? 0 : event.getActionIndex(); int pointerId = event.getPointerId(index); if (pointerOne == pointerId) { // Shift pointer two (real or invalid) up to pointer one. pointerOne = pointerTwo; lastOneX = lastTwoX; lastOneY = lastTwoY; if (DEBUG) log("Promoting pointer 2 (%s) to pointer 1.", pointerTwo); // Clear pointer two and tracking. pointerTwo = INVALID_POINTER_ID; multiTouchTracking = TRACKING_UNKNOWN; } else if (pointerTwo == pointerId) { if (DEBUG) log("Lost pointer 2 (%s).", pointerTwo); pointerTwo = INVALID_POINTER_ID; multiTouchTracking = TRACKING_UNKNOWN; } break; } } return true; } @Override public void draw(@SuppressWarnings("NullableProblems") Canvas canvas) { if (!enabled) { super.draw(canvas); return; } getLocationInWindow(location); float x = location[0]; float y = location[1]; int saveCount = canvas.save(); float cx = getWidth() / 2f; float cy = getHeight() / 2f; camera.save(); camera.rotate(rotationX, rotationY, 0); camera.getMatrix(matrix); camera.restore(); matrix.preTranslate(-cx, -cy); matrix.postTranslate(cx, cy); canvas.concat(matrix); canvas.scale(zoom, zoom, cx, cy); if (!viewQueue.isEmpty() || !levelQueue.isEmpty()) { throw new AssertionError("Queues are not empty."); } // We don't want to be rendered so seed the queue with our children. for (int i = 0, count = getChildCount(); i < count; i++) { viewQueue.add(getChildAt(i)); levelQueue.add(0); } // TODO Multiple queues suck. Deque of levels represented as Deque<View>, maybe? while (!viewQueue.isEmpty()) { View view = viewQueue.removeFirst(); int level = levelQueue.removeFirst(); // Hide any children. if (view instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup) view; int count = viewGroup.getChildCount(); if (count > visibilities.length) { visibilities = new int[count]; if (DEBUG) log("Grow visibilities array to %s.", count); } for (int i = 0; i < count; i++) { View child = viewGroup.getChildAt(i); //noinspection ConstantConditions visibilities[i] = child.getVisibility(); child.setVisibility(INVISIBLE); } } int viewSaveCount = canvas.save(); // Scale the layer level translation by the rotation amount. float translateShowX = rotationY / ROTATION_MAX; float translateShowY = rotationX / ROTATION_MAX; float tx = level * spacing * density * translateShowX; float ty = level * spacing * density * translateShowY; canvas.translate(tx, -ty); view.getLocationInWindow(location); canvas.translate(location[0] - x, location[1] - y); viewBoundsRect.set(0, 0, view.getWidth(), view.getHeight()); canvas.drawRect(viewBoundsRect, viewBorderPaint); view.draw(canvas); canvas.restoreToCount(viewSaveCount); // Restore any children and queue any visible ones for later drawing. if (view instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup) view; for (int i = 0, count = viewGroup.getChildCount(); i < count; i++) { View child = viewGroup.getChildAt(i); int newVisibility = visibilities[i]; //noinspection ConstantConditions,MagicConstant child.setVisibility(newVisibility); if (newVisibility == VISIBLE) { viewQueue.addLast(child); levelQueue.add(level + 1); } } } } canvas.restoreToCount(saveCount); } }
package hudson.scm; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.core.wc.SVNEvent; import org.tmatesoft.svn.core.wc.SVNEventAction; import org.tmatesoft.svn.core.wc.SVNEventAdapter; import org.tmatesoft.svn.core.wc.SVNStatusType; import org.tmatesoft.svn.core.wc.ISVNEventHandler; import java.io.File; import java.io.PrintStream; /** * {@link ISVNEventHandler} that emulates the SVN CLI behavior. * * @author Kohsuke Kawaguchi */ public class SubversionEventHandlerImpl extends SVNEventAdapter { protected final PrintStream out; protected final File baseDir; public SubversionEventHandlerImpl(PrintStream out, File baseDir) { this.out = out; this.baseDir = baseDir; } public void handleEvent(SVNEvent event, double progress) { File file = event.getFile(); String path = null; if (file != null) { path = getRelativePath(file); path = getLocalPath(path); } SVNEventAction action = event.getAction(); {// commit notifications if (action == SVNEventAction.COMMIT_ADDED) { out.println("Adding "+path); return; } if (action == SVNEventAction.COMMIT_DELETED) { out.println("Deleting "+path); return; } if (action == SVNEventAction.COMMIT_MODIFIED) { out.println("Sending "+path); return; } if (action == SVNEventAction.COMMIT_REPLACED) { out.println("Replacing "+path); return; } if (action == SVNEventAction.COMMIT_DELTA_SENT) { out.println("Transmitting file data...."); return; } } String pathChangeType = " "; if (action == SVNEventAction.UPDATE_ADD) { pathChangeType = "A"; SVNStatusType contentsStatus = event.getContentsStatus(); if(contentsStatus== SVNStatusType.UNCHANGED) { // happens a lot with merges pathChangeType = " "; }else if (contentsStatus == SVNStatusType.CONFLICTED) { pathChangeType = "C"; } else if (contentsStatus == SVNStatusType.MERGED) { pathChangeType = "G"; } } else if (action == SVNEventAction.UPDATE_DELETE) { pathChangeType = "D"; } else if (action == SVNEventAction.UPDATE_UPDATE) { SVNStatusType contentsStatus = event.getContentsStatus(); if (contentsStatus == SVNStatusType.CHANGED) { /* * the item was modified in the repository (got the changes * from the repository */ pathChangeType = "U"; }else if (contentsStatus == SVNStatusType.CONFLICTED) { /* * The file item is in a state of Conflict. That is, changes * received from the repository during an update, overlap with * local changes the user has in his working copy. */ pathChangeType = "C"; } else if (contentsStatus == SVNStatusType.MERGED) { /* * The file item was merGed (those changes that came from the * repository did not overlap local changes and were merged * into the file). */ pathChangeType = "G"; } } else if (action == SVNEventAction.UPDATE_COMPLETED) { // finished updating out.println("At revision " + event.getRevision()); return; } else if (action == SVNEventAction.ADD){ out.println("A " + path); return; } else if (action == SVNEventAction.DELETE){ out.println("D " + path); return; } else if (action == SVNEventAction.LOCKED){ out.println("L " + path); return; } else if (action == SVNEventAction.LOCK_FAILED){ out.println("failed to lock " + path); return; } /* * Now getting the status of properties of an item. SVNStatusType also * contains information on the properties state. */ SVNStatusType propertiesStatus = event.getPropertiesStatus(); String propertiesChangeType = " "; if (propertiesStatus == SVNStatusType.CHANGED) { propertiesChangeType = "U"; } else if (propertiesStatus == SVNStatusType.CONFLICTED) { propertiesChangeType = "C"; } else if (propertiesStatus == SVNStatusType.MERGED) { propertiesChangeType = "G"; } String lockLabel = " "; SVNStatusType lockType = event.getLockStatus(); if (lockType == SVNStatusType.LOCK_UNLOCKED) { // The lock is broken by someone. lockLabel = "B"; } if(pathChangeType.equals(" ") && propertiesChangeType.equals(" ") && lockLabel.equals(" ")) // nothing to display here. return; out.println(pathChangeType + propertiesChangeType + lockLabel + " " + path); } public String getRelativePath(File file) { String inPath = file.getAbsolutePath().replace(File.separatorChar, '/'); String basePath = baseDir.getAbsolutePath().replace(File.separatorChar, '/'); String commonRoot = getCommonAncestor(inPath, basePath); if (commonRoot != null) { if (equals(inPath , commonRoot)) { return ""; } else if (startsWith(inPath, commonRoot + "/")) { return inPath.substring(commonRoot.length() + 1); } } return inPath; } private static String getCommonAncestor(String p1, String p2) { if (SVNFileUtil.isWindows || SVNFileUtil.isOpenVMS) { String ancestor = SVNPathUtil.getCommonPathAncestor(p1.toLowerCase(), p2.toLowerCase()); if (equals(ancestor, p1)) { return p1; } else if (equals(ancestor, p2)) { return p2; } else if (startsWith(p1, ancestor)) { return p1.substring(0, ancestor.length()); } return ancestor; } return SVNPathUtil.getCommonPathAncestor(p1, p2); } private static boolean startsWith(String p1, String p2) { if (SVNFileUtil.isWindows || SVNFileUtil.isOpenVMS) { return p1.toLowerCase().startsWith(p2.toLowerCase()); } return p1.startsWith(p2); } private static boolean equals(String p1, String p2) { if (SVNFileUtil.isWindows || SVNFileUtil.isOpenVMS) { return p1.toLowerCase().equals(p2.toLowerCase()); } return p1.equals(p2); } public static String getLocalPath(String path) { path = path.replace('/', File.separatorChar); if ("".equals(path)) { path = "."; } return path; } }
package okapi; import io.vertx.core.Vertx; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.folio.okapi.bean.DeploymentDescriptor; import org.folio.okapi.bean.Ports; import org.folio.okapi.bean.LaunchDescriptor; import org.folio.okapi.deployment.DeploymentManager; import org.folio.okapi.discovery.DiscoveryManager; import org.folio.okapi.env.EnvManager; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import org.junit.runner.RunWith; @RunWith(VertxUnitRunner.class) public class DeploymentManagerTest { private final Logger logger = LoggerFactory.getLogger("okapi"); Vertx vertx; Async async; Ports ports; DiscoveryManager dis; DeploymentManager dm; EnvManager em; @Before public void setUp(TestContext context) { async = context.async(); vertx = Vertx.vertx(); ports = new Ports(9131, 9140); em = new EnvManager(); em.init(vertx, res1 -> { dis = new DiscoveryManager(); dis.init(vertx, res2 -> { dm = new DeploymentManager(vertx, dis, em, "myhost.index", ports, 9130); async.complete(); }); }); } @After public void tearDown(TestContext context) { async = context.async(); vertx.close(x -> { async.complete(); }); } @Test public void test1(TestContext context) { async = context.async(); LaunchDescriptor descriptor = new LaunchDescriptor(); descriptor.setExec( "java -Dport=%p -jar " + "../okapi-test-module/target/okapi-test-module-fat.jar"); DeploymentDescriptor dd = new DeploymentDescriptor("1", "sid", descriptor); dm.deploy(dd, res1 -> { assertTrue(res1.succeeded()); if (res1.failed()) { async.complete(); } else { assertEquals("http://myhost.index:9131", res1.result().getUrl()); dm.undeploy(res1.result().getInstId(), res2 -> { assertTrue(res2.succeeded()); async.complete(); }); } }); } @Test public void test2(TestContext context) { async = context.async(); LaunchDescriptor descriptor = new LaunchDescriptor(); descriptor.setExec( "java -Dport=%p -jar " + "../okapi-test-module/target/unknown.jar"); DeploymentDescriptor dd = new DeploymentDescriptor("2", "sid", descriptor); dm.deploy(dd, res1 -> { assertFalse(res1.succeeded()); if (res1.failed()) { logger.info(res1.cause().getMessage()); async.complete(); } else { dm.undeploy(res1.result().getInstId(), res2 -> { async.complete(); }); } }); } }
package com.topsy.jmxproxy.resource; import java.io.UnsupportedEncodingException; import java.lang.StringBuilder; import java.net.URLEncoder; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import org.apache.log4j.Logger; import org.springframework.stereotype.Service; import org.springframework.web.util.HtmlUtils; import com.sun.jersey.spi.inject.Inject; import com.topsy.jmxproxy.service.JMXConnectionManager; import com.topsy.jmxproxy.domain.Attribute; @Service @Path("/") public class JMXProxyResource { private static Logger logger = Logger.getLogger(JMXProxyResource.class); @Inject private static JMXConnectionManager manager; private String encode(Object item) { try { return URLEncoder.encode(item.toString(), "UTF-8").replace("+", "%20"); } catch (UnsupportedEncodingException e) { return item.toString(); } } private String escape(Object item) { return HtmlUtils.htmlEscape(item.toString()); } @GET @Path("/{host}") public Response processJMXRequest(@PathParam("host") String host) { logger.debug("requested jmx domains from " + host); try { StringBuilder sb = new StringBuilder("<html><head><title>" + escape(host) + "</title></head><body><ul>"); for (String domain : manager.getDomains(host)) { sb.append("\n<li><a href='" + encode(host) + "/" + encode(domain) + "'>" + escape(domain) + "</a></li>"); } sb.append("\n</ul></body></html>"); return Response.ok(sb.toString()).build(); } catch (Exception e) { logger.debug("failed parameters: " + host, e); return Response.status(Response.Status.NOT_FOUND).build(); } } @GET @Path("/{host}/{object}") public Response processJMXRequest(@PathParam("host") String host, @PathParam("object") String object) { try { StringBuilder sb = new StringBuilder("<html><head><title>" + escape(host) + "</title></head><body><ul>"); if (object.indexOf(':') == -1) { logger.debug("requested jmx domain mbeans from " + host + "/" + object); for (String mbean : manager.getMBeans(host, object)) { sb.append("\n<li><a href='" + encode(mbean) + "'>" + escape(mbean) + "</a></li>"); } } else { logger.debug("requested jmx mbean attributes from " + host + "/" + object); for (String attribute : manager.getAttributes(host, object)) { sb.append("\n<li><a href='" + encode(object) + "/" + encode(attribute) + "'>" + escape(attribute) + "</a></li>"); } } sb.append("\n</ul></body></html>"); return Response.ok(sb.toString()).build(); } catch (Exception e) { logger.debug("failed parameters: " + host + "/" + object, e); return Response.status(Response.Status.NOT_FOUND).build(); } } @GET @Produces("application/json") @Path("/{host}/{mbean}/{attribute}") public Response processJMXRequest(@PathParam("host") String host, @PathParam("mbean") String mbean, @PathParam("attribute") String attribute) { logger.debug("requested jmx attribute value of " + host + "/" + mbean + "/" + attribute); try { Object value = manager.getAttributeValue(host, mbean, attribute); return Response.ok(Attribute.toJSONString(value)).build(); } catch (Exception e) { logger.debug("failed parameters: " + host + "/" + mbean + "/" + attribute, e); return Response.status(Response.Status.NOT_FOUND).build(); } } }
package org.jvnet.hudson.test; import hudson.Extension; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.BuildListener; import hudson.model.Descriptor; import hudson.model.Result; import hudson.tasks.Builder; import java.io.IOException; import net.sf.json.JSONObject; import org.kohsuke.stapler.StaplerRequest; /** * Forces the build result to be some pre-configured value. * * @author Kohsuke Kawaguchi */ public class MockBuilder extends Builder { public final Result result; public MockBuilder(Result result) { this.result = result; } public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { listener.getLogger().println("Simulating a specific result code "+result); build.setResult(result); return true; } @Override public Descriptor<Builder> getDescriptor() { return new DescriptorImpl(); } @Extension public static final class DescriptorImpl extends Descriptor<Builder> { public Builder newInstance(StaplerRequest req, JSONObject data) { throw new UnsupportedOperationException(); } public String getDisplayName() { return "Force the build result"; } } }
package com.wizzardo.http.websocket; import com.wizzardo.epoll.ByteBufferProvider; import com.wizzardo.epoll.readable.ReadableBuilder; import com.wizzardo.epoll.readable.ReadableData; import com.wizzardo.http.Handler; import com.wizzardo.http.HttpConnection; import com.wizzardo.http.InputListener; import com.wizzardo.http.request.Header; import com.wizzardo.http.request.Request; import com.wizzardo.http.response.Response; import com.wizzardo.http.response.Status; import com.wizzardo.tools.security.Base64; import com.wizzardo.tools.security.SHA1; import java.io.IOException; public class WebSocketHandler implements Handler { @Override public Response handle(Request request, Response response) { if (request.method() != Request.Method.GET) return response.status(Status._405).header(Header.KEY_ALLOW, Request.Method.GET.name()); if (!Header.VALUE_WEBSOCKET.value.equals(request.header(Header.KEY_UPGRADE))) return response.status(Status._400); if (!Header.VALUE_UPGRADE.value.equals(request.header(Header.KEY_CONNECTION))) return response.status(Status._400); if (request.headerLong(Header.KEY_SEC_WEBSOCKET_VERSION, -1) != 13) return response.status(Status._400); String key = request.header(Header.KEY_SEC_WEBSOCKET_KEY); if (key == null || key.isEmpty()) return response.status(Status._400); key += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; // websocket magic key = Base64.encodeToString(SHA1.getSHA1(key.getBytes())); request.connection().upgrade(new WebSocketListener(request.connection(), this)); return response.status(Status._101) .header(Header.KEY_UPGRADE, Header.VALUE_WEBSOCKET) .header(Header.KEY_CONNECTION, Header.VALUE_UPGRADE) .header(Header.KEY_SEC_WEBSOCKET_ACCEPT, key); } public static class WebSocketListener implements InputListener<HttpConnection> { private HttpConnection connection; private WebSocketHandler webSocketHandler; private Message tempMessage; private Frame tempFrame; private int read = 0; private WebSocketListener(HttpConnection connection, WebSocketHandler webSocketHandler) { this.connection = connection; this.webSocketHandler = webSocketHandler; } @Override public void onReadyToRead(HttpConnection connection) { try { byte[] buffer = connection.getBuffer(); int r; outer: while ((r = connection.read(buffer, read, buffer.length - read, (ByteBufferProvider) Thread.currentThread())) > 0) { read += r; while (read > 0) { if (tempFrame == null) { if (!Frame.hasHeaders(buffer, 0, read)) continue outer; tempFrame = new Frame(); } int k = tempFrame.read(buffer, 0, read); read -= k; if (read != 0) System.arraycopy(buffer, k, buffer, 0, read); if (tempFrame.isComplete()) { if (tempFrame.isMasked()) tempFrame.unmask(); if (handlePing()) continue; if (handleClose()) continue; if (tempMessage == null) tempMessage = new Message(); tempMessage.add(tempFrame); tempFrame = null; } if (tempMessage != null && tempMessage.isComplete()) { webSocketHandler.onMessage(this, tempMessage); tempMessage = null; } } } } catch (IOException e) { e.printStackTrace(); try { connection.close(); webSocketHandler.onDisconnect(this); } catch (IOException e1) { e1.printStackTrace(); } } } private boolean handlePing() { if (tempFrame.isPing()) { tempFrame.setOpcode(Frame.OPCODE_PONG); sendFrame(tempFrame); tempFrame = null; return true; } return false; } private boolean handleClose() { if (tempFrame.isClose()) { connection.setCloseOnFinishWriting(true); sendFrame(tempFrame); tempFrame = null; webSocketHandler.onDisconnect(this); return true; } return false; } @Override public void onReady(HttpConnection connection) { webSocketHandler.onConnect(this); } public synchronized void sendMessage(Message message) { for (Frame frame : message.getFrames()) { connection.write(convertFrameToReadableData(frame), (ByteBufferProvider) Thread.currentThread()); } } private synchronized void sendFrame(Frame frame) { connection.write(convertFrameToReadableData(frame), (ByteBufferProvider) Thread.currentThread()); } public void close() { sendFrame(new Frame(Frame.OPCODE_CONNECTION_CLOSE)); } private ReadableData convertFrameToReadableData(Frame frame) { return new ReadableBuilder().append(frame.getFrameBytes(), frame.getFrameOffset(), frame.getFrameLength()); } } public void onConnect(WebSocketListener listener) { } public void onDisconnect(WebSocketListener listener) { } public void onMessage(WebSocketListener listener, Message message) { } }
package reflection; import junit.UnitTestRunner; import org.junit.Test; import static org.junit.Assert.*; public class ClassLoaderTest { public static void main(String[] args) { UnitTestRunner.run(ClassLoaderTest.class); } @Test public void sysClassLoader() { ClassLoader sysCl = ClassLoader.getSystemClassLoader(); assertEquals("sun.misc.Launcher$AppClassLoader", sysCl.getClass().getName()); ClassLoader extCl = sysCl.getParent(); assertEquals("sun.misc.Launcher$ExtClassLoader", extCl.getClass().getName()); ClassLoader bootCl = extCl.getParent(); assertNull(bootCl); } @Test public void getClassLoader() { ClassLoader bootCl = Object.class.getClassLoader(); assertNull(bootCl); ClassLoader appCl = ClassLoaderTest.class.getClassLoader(); ClassLoader sysCl = ClassLoader.getSystemClassLoader(); assertSame(sysCl, appCl); } @Test public void loadClass() throws Exception { ClassLoader sysCl = ClassLoader.getSystemClassLoader(); assertSame(Object.class, sysCl.loadClass("java.lang.Object")); assertSame(ClassLoaderTest.class, sysCl.loadClass("reflection.ClassLoaderTest")); } }
package org.jenetics; import static org.jenetics.util.arrays.subset; import java.util.Random; import org.jenetics.util.IndexStream; import org.jenetics.util.RandomRegistry; public abstract class Recombinator<G extends Gene<?, G>> extends AbstractAlterer<G> { private final int _order; public Recombinator(final double probability, final int order) { super(probability); if (order < 2) { throw new IllegalArgumentException(String.format( "Order must be greater than one, but was %d.", order )); } _order = order; } /** * Return the number of individuals involved in the * {@link #recombine(Population, int[], int)} step. * * @return the number of individuals involved in the recombination step. */ public int getOrder() { return _order; } @Override public final <C extends Comparable<? super C>> int alter( final Population<G, C> population, final int generation ) { final Random random = RandomRegistry.getRandom(); final int order = Math.min(_order, population.size()); final IndexStream stream = IndexStream.Random( population.size(), _probability ); int alterations = 0; for (int i = stream.next(); i != -1; i = stream.next()) { final int[] individuals = subset(population.size(), order, random); individuals[0] = i; alterations += recombine(population, individuals, generation); } return alterations; } /** * Recombination template method. * * @param <C> the fitness result type * @param population the population to recombine * @param individuals the array with the indexes of the individuals which * are involved in the <i>recombination</i> step. The length of the * array is {@link #getOrder()}. The first individual is the * <i>primary</i> individual. * @param generation the current generation. * @return the number of genes that has been altered. */ protected abstract <C extends Comparable<? super C>> int recombine( final Population<G, C> population, final int[] individuals, final int generation ); }
package com.genymobile.scrcpy.wrappers; import com.genymobile.scrcpy.Ln; import android.os.IInterface; import android.view.InputEvent; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public final class InputManager { public static final int INJECT_INPUT_EVENT_MODE_ASYNC = 0; public static final int INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT = 1; public static final int INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH = 2; private final IInterface manager; private Method injectInputEventMethod; private boolean alternativeInjectInputEventMethod; private static Method setDisplayIdMethod; public InputManager(IInterface manager) { this.manager = manager; } private Method getInjectInputEventMethod() throws NoSuchMethodException { if (injectInputEventMethod == null) { try { injectInputEventMethod = manager.getClass().getMethod("injectInputEvent", InputEvent.class, int.class); } catch (NoSuchMethodException e) { injectInputEventMethod = manager.getClass().getMethod("injectInputEvent", InputEvent.class, int.class, int.class); alternativeInjectInputEventMethod = true; } } return injectInputEventMethod; } public boolean injectInputEvent(InputEvent inputEvent, int mode) { try { Method method = getInjectInputEventMethod(); if (alternativeInjectInputEventMethod) { return (boolean) method.invoke(manager, inputEvent, mode, 0); } return (boolean) method.invoke(manager, inputEvent, mode); } catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException e) { Ln.e("Could not invoke method", e); return false; } } private static Method getSetDisplayIdMethod() throws NoSuchMethodException { if (setDisplayIdMethod == null) { setDisplayIdMethod = InputEvent.class.getMethod("setDisplayId", int.class); } return setDisplayIdMethod; } public static boolean setDisplayId(InputEvent inputEvent, int displayId) { try { Method method = getSetDisplayIdMethod(); method.invoke(inputEvent, displayId); return true; } catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException e) { Ln.e("Cannot associate a display id to the input event", e); return false; } } }
package com.metamx.druid.coordination; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Throwables; import com.google.common.collect.Lists; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.metamx.common.lifecycle.LifecycleStart; import com.metamx.common.lifecycle.LifecycleStop; import com.metamx.druid.client.DataSegment; import com.metamx.druid.initialization.ZkPathsConfig; import com.metamx.druid.loading.SegmentLoadingException; import com.metamx.emitter.EmittingLogger; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.cache.ChildData; import org.apache.curator.framework.recipes.cache.PathChildrenCache; import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent; import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener; import org.apache.curator.utils.ZKPaths; import java.io.File; import java.io.IOException; import java.util.List; public class ZkCoordinator implements DataSegmentChangeHandler { private static final EmittingLogger log = new EmittingLogger(ZkCoordinator.class); private final Object lock = new Object(); private final ObjectMapper jsonMapper; private final ZkCoordinatorConfig config; private final ZkPathsConfig zkPaths; private final DruidServerMetadata me; private final DataSegmentAnnouncer announcer; private final CuratorFramework curator; private final ServerManager serverManager; private volatile PathChildrenCache loadQueueCache; private volatile boolean started; public ZkCoordinator( ObjectMapper jsonMapper, ZkCoordinatorConfig config, ZkPathsConfig zkPaths, DruidServerMetadata me, DataSegmentAnnouncer announcer, CuratorFramework curator, ServerManager serverManager ) { this.jsonMapper = jsonMapper; this.config = config; this.zkPaths = zkPaths; this.me = me; this.announcer = announcer; this.curator = curator; this.serverManager = serverManager; } @LifecycleStart public void start() throws IOException { log.info("Starting zkCoordinator for server[%s]", me); synchronized (lock) { if (started) { return; } final String loadQueueLocation = ZKPaths.makePath(zkPaths.getLoadQueuePath(), me.getName()); final String servedSegmentsLocation = ZKPaths.makePath(zkPaths.getServedSegmentsPath(), me.getName()); final String liveSegmentsLocation = ZKPaths.makePath(zkPaths.getLiveSegmentsPath(), me.getName()); loadQueueCache = new PathChildrenCache( curator, loadQueueLocation, true, true, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("ZkCoordinator-%s").build() ); try { config.getSegmentInfoCacheDirectory().mkdirs(); curator.newNamespaceAwareEnsurePath(loadQueueLocation).ensure(curator.getZookeeperClient()); curator.newNamespaceAwareEnsurePath(servedSegmentsLocation).ensure(curator.getZookeeperClient()); curator.newNamespaceAwareEnsurePath(liveSegmentsLocation).ensure(curator.getZookeeperClient()); if (config.isLoadFromSegmentCacheEnabled()) { try { loadCache(); } catch (Exception e) { log.makeAlert(e, "Exception loading from cache") .emit(); } } loadQueueCache.getListenable().addListener( new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { final ChildData child = event.getData(); switch (event.getType()) { case CHILD_ADDED: final String path = child.getPath(); final DataSegmentChangeRequest segment = jsonMapper.readValue( child.getData(), DataSegmentChangeRequest.class ); log.info("New node[%s] with segmentClass[%s]", path, segment.getClass()); try { segment.go(ZkCoordinator.this); curator.delete().guaranteed().forPath(path); log.info("Completed processing for node[%s]", path); } catch (Exception e) { try { curator.delete().guaranteed().forPath(path); } catch (Exception e1) { log.info(e1, "Failed to delete node[%s], but ignoring exception.", path); } log.makeAlert(e, "Segment load/unload: uncaught exception.") .addData("node", path) .addData("nodeProperties", segment) .emit(); } break; case CHILD_REMOVED: log.info("%s was removed", event.getData().getPath()); break; default: log.info("Ignoring event[%s]", event); } } } ); loadQueueCache.start(); } catch (Exception e) { Throwables.propagateIfPossible(e, IOException.class); throw Throwables.propagate(e); } started = true; } } @LifecycleStop public void stop() { log.info("Stopping ZkCoordinator with config[%s]", config); synchronized (lock) { if (!started) { return; } try { loadQueueCache.close(); } catch (Exception e) { throw Throwables.propagate(e); } finally { loadQueueCache = null; started = false; } } } private void loadCache() { File baseDir = config.getSegmentInfoCacheDirectory(); if (!baseDir.exists()) { return; } List<DataSegment> cachedSegments = Lists.newArrayList(); for (File file : baseDir.listFiles()) { log.info("Loading segment cache file [%s]", file); try { DataSegment segment = jsonMapper.readValue(file, DataSegment.class); if (serverManager.isSegmentCached(segment)) { cachedSegments.add(segment); } else { log.warn("Unable to find cache file for %s. Deleting lookup entry", segment.getIdentifier()); File segmentInfoCacheFile = new File(config.getSegmentInfoCacheDirectory(), segment.getIdentifier()); if (!segmentInfoCacheFile.delete()) { log.warn("Unable to delete segmentInfoCacheFile[%s]", segmentInfoCacheFile); } } } catch (Exception e) { log.makeAlert(e, "Failed to load segment from segmentInfo file") .addData("file", file) .emit(); } } addSegments(cachedSegments); } @Override public void addSegment(DataSegment segment) { try { log.info("Loading segment %s", segment.getIdentifier()); try { serverManager.loadSegment(segment); } catch (Exception e) { removeSegment(segment); throw new SegmentLoadingException(e, "Exception loading segment[%s]", segment.getIdentifier()); } File segmentInfoCacheFile = new File(config.getSegmentInfoCacheDirectory(), segment.getIdentifier()); if (!segmentInfoCacheFile.exists()) { try { jsonMapper.writeValue(segmentInfoCacheFile, segment); } catch (IOException e) { removeSegment(segment); throw new SegmentLoadingException( e, "Failed to write to disk segment info cache file[%s]", segmentInfoCacheFile ); } } try { announcer.announceSegment(segment); } catch (IOException e) { throw new SegmentLoadingException(e, "Failed to announce segment[%s]", segment.getIdentifier()); } } catch (SegmentLoadingException e) { log.makeAlert(e, "Failed to load segment for dataSource") .addData("segment", segment) .emit(); } } public void addSegments(Iterable<DataSegment> segments) { try { final List<String> segmentFailures = Lists.newArrayList(); final List<DataSegment> validSegments = Lists.newArrayList(); for (DataSegment segment : segments) { log.info("Loading segment %s", segment.getIdentifier()); try { serverManager.loadSegment(segment); } catch (Exception e) { log.error(e, "Exception loading segment[%s]", segment.getIdentifier()); removeSegment(segment); segmentFailures.add(segment.getIdentifier()); } File segmentInfoCacheFile = new File(config.getSegmentInfoCacheDirectory(), segment.getIdentifier()); if (!segmentInfoCacheFile.exists()) { try { jsonMapper.writeValue(segmentInfoCacheFile, segment); } catch (IOException e) { log.error(e, "Failed to write to disk segment info cache file[%s]", segmentInfoCacheFile); removeSegment(segment); segmentFailures.add(segment.getIdentifier()); } } validSegments.add(segment); } try { announcer.announceSegments(validSegments); } catch (IOException e) { throw new SegmentLoadingException(e, "Failed to announce segments[%s]", segments); } if (!segmentFailures.isEmpty()) { log.error("Exception loading segments: %s", segmentFailures); throw new SegmentLoadingException("%,d errors seen while loading segments", segmentFailures.size()); } } catch (SegmentLoadingException e) { log.makeAlert(e, "Failed to load segments for dataSource") .addData("segments", segments) .emit(); } } @Override public void removeSegment(DataSegment segment) { try { serverManager.dropSegment(segment); File segmentInfoCacheFile = new File(config.getSegmentInfoCacheDirectory(), segment.getIdentifier()); if (!segmentInfoCacheFile.delete()) { log.warn("Unable to delete segmentInfoCacheFile[%s]", segmentInfoCacheFile); } announcer.unannounceSegment(segment); } catch (Exception e) { log.makeAlert(e, "Failed to remove segment") .addData("segment", segment) .emit(); } } public void removeSegments(Iterable<DataSegment> segments) { try { for (DataSegment segment : segments) { serverManager.dropSegment(segment); File segmentInfoCacheFile = new File(config.getSegmentInfoCacheDirectory(), segment.getIdentifier()); if (!segmentInfoCacheFile.delete()) { log.warn("Unable to delete segmentInfoCacheFile[%s]", segmentInfoCacheFile); } } announcer.unannounceSegments(segments); } catch (Exception e) { log.makeAlert(e, "Failed to remove segments") .addData("segments", segments) .emit(); } } }
package cz.brmlab.yodaqa.analysis.tycor; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.uima.UimaContext; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.fit.component.JCasAnnotator_ImplBase; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cz.brmlab.yodaqa.analysis.ansscore.AnswerFV; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_LATANone; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_LATANoWordNet; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_LATQNoWordNet; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_NoTyCor; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_SpWordNet; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorADBp; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorADBpOntology; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorADBpProperty; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorAFBOntology; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorANE; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorAQuantity; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorAQuantityCD; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorAWnInstance; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorPassageDist; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorSpAHit; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorSpNoHit; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorSpQHit; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorSpQAHit; import cz.brmlab.yodaqa.model.CandidateAnswer.AnswerFeature; import cz.brmlab.yodaqa.model.CandidateAnswer.AnswerInfo; import cz.brmlab.yodaqa.model.TyCor.DBpLAT; import cz.brmlab.yodaqa.model.TyCor.DBpOntologyLAT; import cz.brmlab.yodaqa.model.TyCor.DBpPropertyLAT; import cz.brmlab.yodaqa.model.TyCor.FBOntologyLAT; import cz.brmlab.yodaqa.model.TyCor.LAT; import cz.brmlab.yodaqa.model.TyCor.NELAT; import cz.brmlab.yodaqa.model.TyCor.QuantityLAT; import cz.brmlab.yodaqa.model.TyCor.QuantityCDLAT; import cz.brmlab.yodaqa.model.TyCor.WnInstanceLAT; import cz.brmlab.yodaqa.model.TyCor.WordnetLAT; /** * Estimate answer specificity in CandidateAnswerCAS via type coercion * by question LAT to answer LAT matching. * * Basically, we try to find any matches of answer LAT set with the * question LAT set, and generate AFs accordingly. The crucial aspect * is the mesh of LATWordnets that we pre-generated and that represent * various generalizations of the (hopefully specific) LATs we * generated earlier. * * There are many ways to approach this. We allow generalizations * of both the question and answer LATs to match, because e.g. when * asking about a "site" of Lindbergh's flight, "New York" will be * generated as a "city" and the match is "location". But clearly * direct ('hit') matches are better than 'sibling' matches. */ public class LATMatchTyCor extends JCasAnnotator_ImplBase { final Logger logger = LoggerFactory.getLogger(LATMatchTyCor.class); /** A single match of a (question, answer) LAT tuple. The match * has a total specificity (sum of constituent specificities). */ protected class LATMatch { public LAT lat1, lat2; public double specificity; public LATMatch(LAT lat1_, LAT lat2_) { lat1 = lat1_; lat2 = lat2_; specificity = lat1.getSpecificity() + lat2.getSpecificity(); } public LAT getLat1() { return lat1; } public LAT getLat2() { return lat2; } public double getSpecificity() { return specificity; } public LAT getBaseLat1() { return _getBaseLat(getLat1()); } public LAT getBaseLat2() { return _getBaseLat(getLat2()); } protected LAT _getBaseLat(LAT lat) { while (lat.getBaseLAT() != null) lat = lat.getBaseLAT(); return lat; } public void logMatch(Logger logger, String prefix) { logger.debug(prefix + " " + getBaseLat1().getText() + "-" + getBaseLat2().getText() + " match " + getLat1().getText() /* == LAT2 text */ + "/" + getLat1().getSynset() + " sp. " + getSpecificity() + " (q " + getLat1().getSpecificity() + ", a " + getLat2().getSpecificity() + ")"); } /** Record details on this LATMatch in the given AnswerFV * (and log it too). This is worth calling for all LATMatches * that are hits for at least one side. */ public void record(AnswerFV fv, String ansText) { if (lat1.getSpecificity() == 0) fv.setFeature(AF_TyCorSpQHit.class, 1.0); if (lat2.getSpecificity() == 0) fv.setFeature(AF_TyCorSpAHit.class, 1.0); if (lat1.getSpecificity() == 0 || lat2.getSpecificity() == 0) { /* Generate a TyCor if this has been a direct * match from at least one direction (i.e. not * just a "semantic sibling"). */ LAT baselat2 = getBaseLat2(); if (baselat2 instanceof NELAT) fv.setFeature(AF_TyCorANE.class, 1.0); else if (baselat2 instanceof DBpLAT) fv.setFeature(AF_TyCorADBp.class, 1.0); else if (baselat2 instanceof QuantityLAT) fv.setFeature(AF_TyCorAQuantity.class, 1.0); else if (baselat2 instanceof QuantityCDLAT) fv.setFeature(AF_TyCorAQuantityCD.class, 1.0); else if (baselat2 instanceof WnInstanceLAT) fv.setFeature(AF_TyCorAWnInstance.class, 1.0); else if (baselat2 instanceof DBpOntologyLAT) fv.setFeature(AF_TyCorADBpOntology.class, 1.0); else if (baselat2 instanceof DBpPropertyLAT) fv.setFeature(AF_TyCorADBpProperty.class, 1.0); else if (baselat2 instanceof FBOntologyLAT) fv.setFeature(AF_TyCorAFBOntology.class, 1.0); else assert(false); } if (lat1.getSpecificity() != 0 && lat2.getSpecificity() != 0) { /* If we had to generalize both LATs, that * seems to be a negative signal that the * answer is less specifit than we want. */ logger.debug("generalizing both LATs for <<{}>>", ansText); fv.setFeature(AF_TyCorSpNoHit.class, -1.0); } else if (lat1.getSpecificity() == 0 && lat2.getSpecificity() == 0) { /* If both LATs match sharp, that's a good * sign OTOH. */ logger.debug("sharp LAT match for <<{}>>", ansText); fv.setFeature(AF_TyCorSpQAHit.class, 1.0); } else { /* Fuzzy match, just produce a debug print * as well for grep's sake. */ if (lat1.getSpecificity() == 0) { logger.debug("q-hit LAT match for <<{}>>", ansText); } else if (lat2.getSpecificity() == 0) { logger.debug("a-hit LAT match for <<{}>>", ansText); } } } } /* Synset blacklist - this blacklist will not permit using these * LATWordnet LATs for generalization. Therefore, "language" * will not match "area" through "cognition" and "time" will * not match "region" via "measure". * * This covers only matching LATWordnet pairs! So when * LATByQuantity generates "measure" answer LAT, this will still * match all measure-derived question LATs. * * N.B. this is a generalization limit applied in addition to the * LATByWordnet Tops synset list. * * XXX: Compiled manually by cursory logs investigation. We should * build a TyCor dataset and train it by that. */ protected static Long wnwn_synsetbl_list[] = { /* communication/ */ 33319L, /* cognition/ */ 23451L, /* ability/ */ 5624029L, /* higher cognitive process/ */ 5778661L, /* relation/ */ 32220L, /* ability/ */ 5624029L, /* measure/ */ 33914L, /* instrumentality/ */ 3580409L, /* artifact/ */ 22119L, /* fundamental quantity/ */ 13597072L, /* organization/ */ 8024893L, /* group/ */ 31563L, /* unit/ */ 8206589L, /* attribute/ */ 24444L, /* trait/ */ 4623416L, /* device/ */ 3187746L, /* social group/ */ 7967506L, /* act/ */ 30657L, /* activity/ */ 408356L, /* state/ */ 24900L, /* extent/ */ 5130681L, /* magnitude/ */ 5097645L, /* organism/ */ 4475L, /* creation/ */ 3133774L, /* product/ */ 4014270L, /* abstraction/ */ 2137L, /* medium/ */ 6264799L, /* gathering/ */ 7991473L, /* idea/ */ 5842164L, /* kind/ */ 5847533L, /* property/ */ 4923519L, /* quality/ */ 4731092L, /* concept/ */ 5844071L, /* thing/ */ 2452L, }; protected Set<Long> wnwn_synsetbl; public void initialize(UimaContext aContext) throws ResourceInitializationException { if (wnwn_synsetbl == null) wnwn_synsetbl = new HashSet<Long>(Arrays.asList(wnwn_synsetbl_list)); super.initialize(aContext); } public void process(JCas jcas) throws AnalysisEngineProcessException { JCas questionView, answerView; try { questionView = jcas.getView("Question"); answerView = jcas.getView("Answer"); } catch (Exception e) { throw new AnalysisEngineProcessException(e); } boolean qNoWordnetLAT = !hasWordnetLAT(questionView); boolean aNoWordnetLAT = !hasWordnetLAT(answerView); boolean aNoLAT = JCasUtil.select(answerView, LAT.class).isEmpty(); AnswerInfo ai = JCasUtil.selectSingle(answerView, AnswerInfo.class); AnswerFV fv = new AnswerFV(ai); /* Find the best match. Note that this will also * process and generate features for other nice * (hit) matches encountered on the way. */ LATMatch match = matchLATs(questionView, answerView, fv); if (match != null) { fv.setFeature(AF_SpWordNet.class, Math.exp(match.getSpecificity())); /* We were the only ones doing type coercion here. */ } else if (!fv.isFeatureSet(AF_TyCorPassageDist.class)) { /* XXX: Make the following a separate annotator? * When we get another type coercion stage. */ /* There is no LAT generated for this answer at all; * a pretty interesting negative feature on its own? */ if (aNoLAT) { logger.debug("no LAT for <<{}>>", answerView.getDocumentText()); fv.setFeature(AF_LATANone.class, -1.0); /* There is no type coercion match, but wordnet LATs * generated for both question and answer. This means * we are fairly sure this answer is of a wrong type. */ } else if (!qNoWordnetLAT && !aNoWordnetLAT && !fv.isFeatureSet(AF_TyCorPassageDist.class)) { logger.debug("failed TyCor for <<{}>>", answerView.getDocumentText()); fv.setFeature(AF_NoTyCor.class, -1.0); } } if (qNoWordnetLAT) fv.setFeature(AF_LATQNoWordNet.class, -1.0); if (!aNoLAT && aNoWordnetLAT) fv.setFeature(AF_LATANoWordNet.class, -1.0); if (ai.getFeatures() != null) for (FeatureStructure af : ai.getFeatures().toArray()) ((AnswerFeature) af).removeFromIndexes(); ai.removeFromIndexes(); ai.setFeatures(fv.toFSArray(answerView)); ai.addToIndexes(); } /** Check whether a given CAS (view) contains an LAT featureset * associated with a WordNet object. This is an indicator that * there is some "non-weird" LAT generated. */ protected boolean hasWordnetLAT(JCas jcas) { /* This is not a simple matter of checking for WordnetLAT * as we may have some other LAT with synset associated and * non-expanded to WordnetLATs. */ for (LAT lat : JCasUtil.select(jcas, LAT.class)) if (lat.getSynset() != 0) return true; return false; } protected LATMatch matchLATs(JCas questionView, JCas answerView, AnswerFV fv) throws AnalysisEngineProcessException { Map<String, LAT> answerLats = new HashMap<String, LAT>(); LATMatch bestMatch = null; /* FIXME: Allow matching LATs that have same text but * different senses. */ /* Load LATs from answerView. */ for (LAT la : JCasUtil.select(answerView, LAT.class)) { if (la.getIsHierarchical() && !(la instanceof WordnetLAT)) continue; LAT la0 = answerLats.get(la.getText()); if (la0 == null || la0.getSpecificity() < la.getSpecificity()) answerLats.put(la.getText(), la); } if (answerLats.isEmpty()) return null; /* Match LATs from questionView. */ for (LAT lq : JCasUtil.select(questionView, LAT.class)) { if (lq.getIsHierarchical() && !(lq instanceof WordnetLAT)) continue; LAT la = answerLats.get(lq.getText()); if (la == null) continue; if (lq.getSynset() != 0 && la.getSynset() != 0 && lq.getSynset() != la.getSynset()) continue; /* We have a match! */ LATMatch match = new LATMatch(lq, la); // match.logMatch(logger, " maybe "); if (match.getLat1().getSpecificity() == 0 || match.getLat2().getSpecificity() == 0) { /* A hit match too! Record it right away. * (We may encounter a variety of these. */ match.logMatch(logger, ".. TyCor hit"); match.record(fv, answerView.getDocumentText()); } if (bestMatch == null || match.getSpecificity() > bestMatch.getSpecificity()) bestMatch = match; } if (bestMatch != null) { if (bestMatch.getLat1() instanceof WordnetLAT && bestMatch.getLat2() instanceof WordnetLAT && wnwn_synsetbl.contains(bestMatch.getLat1().getSynset())) { bestMatch.logMatch(logger, ".. ignoring blacklisted TyCor"); return null; } bestMatch.logMatch(logger, ".. TyCor best"); } return bestMatch; } }
package controllers.user; import javax.validation.Valid; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Controller; import org.springframework.util.Assert; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import controllers.AbstractController; import domain.Shipment; import domain.ShipmentOffer; import domain.User; import services.PayPalService; import services.ShipmentOfferService; import services.ShipmentService; import services.UserService; @Controller @RequestMapping("/shipmentOffer/user") public class ShipmentOfferUserController extends AbstractController { static Logger log = Logger.getLogger(ShipmentOfferUserController.class); @Autowired private ShipmentOfferService shipmentOfferService; @Autowired private UserService userService; @Autowired private ShipmentService shipmentService; @Autowired private PayPalService payPalService; public ShipmentOfferUserController() { super(); } @RequestMapping(value = "/list", method = RequestMethod.GET) public ModelAndView list(@RequestParam(required=false, defaultValue="-1") int shipmentId, @RequestParam(required=false, defaultValue="-1") int userId, @RequestParam(required=false, defaultValue="1") int page) { ModelAndView result; Page<ShipmentOffer> shipmentOffers; Pageable pageable; User currentUser; Shipment shipment; pageable = new PageRequest(page - 1, 5); shipmentOffers = shipmentOfferService.findAllByOrShipmentIdAndOrUserId(shipmentId, userId, pageable); currentUser = userService.findByPrincipal(); shipment = shipmentService.findOne(shipmentId); result = new ModelAndView("shipmentOffer/list"); result.addObject("shipmentOffers", shipmentOffers.getContent()); result.addObject("paypalObjects", payPalService.findByShipmentId(shipmentId)); result.addObject("p", page); result.addObject("total_pages", shipmentOffers.getTotalPages()); result.addObject("shipmentId", shipmentId); result.addObject("userId", userId); result.addObject("currentUser", currentUser); result.addObject("shipment", shipment); result.addObject("urlPage", "shipmentOffer/user/list.do?shipmentId=" + shipmentId + "&userId=" + userId + "&page="); return result; } @RequestMapping(value = "/create", method = RequestMethod.GET) public ModelAndView create(@RequestParam int shipmentId) { ModelAndView result; ShipmentOffer offer; offer = shipmentOfferService.create(shipmentId); result = createEditModelAndView(offer); return result; } @RequestMapping(value = "/createClone", method = RequestMethod.GET) public ModelAndView createFromClone(@RequestParam int shipmentOfferId) { ModelAndView result; ShipmentOffer shipmentOffer; shipmentOffer = shipmentOfferService.createFromClone(shipmentOfferId); result = createEditModelAndView(shipmentOffer); return result; } @RequestMapping(value = "/edit", method = RequestMethod.GET) public ModelAndView edit(@RequestParam int shipmentOfferId) { ModelAndView result; ShipmentOffer shipmentOffer; shipmentOffer = shipmentOfferService.findOne(shipmentOfferId); Assert.notNull(shipmentOffer, "controller.user.shipmentOffer.edit.isNull"); result = createEditModelAndView(shipmentOffer); return result; } @RequestMapping(value = "/edit", method = RequestMethod.POST, params = "save") public ModelAndView save(@Valid ShipmentOffer shipmentOffer, BindingResult binding) { ModelAndView result; String messageError; if (binding.hasErrors()) { result = createEditModelAndView(shipmentOffer); } else { try { shipmentOffer = shipmentOfferService.save(shipmentOffer); result = new ModelAndView("redirect:list.do?shipmentId=" + shipmentOffer.getShipment().getId()); } catch (Throwable oops) { log.error(oops.getMessage()); messageError = "shipmentOffer.commit.error"; if(oops.getMessage().contains("message.error")){ messageError = oops.getMessage(); } result = createEditModelAndView(shipmentOffer, messageError); } } return result; } @RequestMapping(value = "/accept", method = RequestMethod.GET) public ModelAndView accept(@RequestParam int shipmentOfferId){ ModelAndView result; String messageError; ShipmentOffer shipmentOffer = shipmentOfferService.findOne(shipmentOfferId); try{ result = new ModelAndView("redirect:../../feepayment/user/create.do?type=3&id=" + shipmentOfferId); }catch(Throwable oops){ log.error(oops.getMessage()); messageError = "shipmentOffer.commit.error"; if(oops.getMessage().contains("message.error")){ messageError = oops.getMessage(); } result = createEditModelAndView2(shipmentOffer, messageError); } return result; } @RequestMapping(value = "/deny", method = RequestMethod.GET) public ModelAndView deny(@RequestParam int shipmentOfferId){ ModelAndView result; String messageError; ShipmentOffer shipmentOffer = shipmentOfferService.findOne(shipmentOfferId); Shipment shipment = shipmentOffer.getShipment(); try{ shipmentOfferService.deny(shipmentOfferId); // This reditect may be change to other url. result = new ModelAndView("redirect:../user/list.do?shipmentId="+shipment.getId()); }catch(Throwable oops){ log.error(oops.getMessage()); messageError = "shipmentOffer.commit.error"; if(oops.getMessage().contains("message.error")){ messageError = oops.getMessage(); } result = createEditModelAndView2(shipmentOffer, messageError); } return result; } protected ModelAndView createEditModelAndView(ShipmentOffer input) { ModelAndView result; result = createEditModelAndView(input, null); return result; } protected ModelAndView createEditModelAndView(ShipmentOffer input, String message) { ModelAndView result; User user; user = userService.findByPrincipal(); Assert.notNull(user); result = new ModelAndView("shipmentOffer/edit"); result.addObject("shipmentOffer", input); result.addObject("message", message); result.addObject("user", user); return result; } protected ModelAndView createEditModelAndView2(ShipmentOffer input) { ModelAndView result; result = createEditModelAndView(input, null); return result; } protected ModelAndView createEditModelAndView2(ShipmentOffer input, String message) { ModelAndView result; result = new ModelAndView("shipmentOffer/list"); result.addObject("shipmentOffer", input); result.addObject("message", message); return result; } }
package io.spine.server.aggregate.imports; import com.google.common.collect.Streams; import io.spine.core.EventClass; import io.spine.core.TenantId; import io.spine.server.aggregate.ImportEvent; import io.spine.server.bus.Bus; import io.spine.server.bus.BusBuilder; import io.spine.server.bus.DeadMessageHandler; import io.spine.server.bus.DispatcherRegistry; import io.spine.server.bus.EnvelopeValidator; import io.spine.server.bus.MessageUnhandled; import io.spine.server.bus.MulticastBus; import io.spine.server.tenant.TenantIndex; import io.spine.system.server.SystemGateway; import static com.google.common.base.Preconditions.checkState; import static io.spine.server.bus.BusBuilder.FieldCheck.gatewayNotSet; import static io.spine.server.bus.BusBuilder.FieldCheck.tenantIndexNotSet; /** * Dispatches import events to aggregates that import these events. * * @author Alexander Yevsyukov */ public class ImportBus extends MulticastBus<ImportEvent, ImportEnvelope, EventClass, ImportDispatcher<?>> { private final ImportValidator validator = new ImportValidator(); private final DeadImportEventHandler deadImportEventHandler = new DeadImportEventHandler(); private final SystemGateway systemGateway; private final TenantIndex tenantIndex; protected ImportBus(Builder builder) { super(builder); this.systemGateway = builder.systemGateway() .orElseThrow(gatewayNotSet()); this.tenantIndex = builder.tenantIndex() .orElseThrow(tenantIndexNotSet()); } @Override protected DeadMessageHandler<ImportEnvelope> getDeadMessageHandler() { return deadImportEventHandler; } @Override protected EnvelopeValidator<ImportEnvelope> getValidator() { return validator; } @Override protected DispatcherRegistry<EventClass, ImportDispatcher<?>> createRegistry() { return new Registry(); } @Override protected ImportEnvelope toEnvelope(ImportEvent wrapper) { return new ImportEnvelope(wrapper); } @Override protected void dispatch(ImportEnvelope envelope) { int dispatchersCalled = callDispatchers(envelope); checkState(dispatchersCalled != 0, "The event with class: `%s` has no import dispatchers.", envelope.getMessageClass()); } /** * Does nothing because instances of {@link ImportEvent} are transient. */ @Override protected void store(Iterable<ImportEvent> events) { TenantId tenantId = tenantOf(events); tenantIndex.keep(tenantId); } private static TenantId tenantOf(Iterable<ImportEvent> events) { return Streams.stream(events) .map((e) -> e.getContext() .getTenantId()) .findAny() .orElse(TenantId.getDefaultInstance()); } /** * Creates {@link UnsupportedImportEventException} in response to an event message * of unsupported type. */ private static class DeadImportEventHandler implements DeadMessageHandler<ImportEnvelope> { @Override public MessageUnhandled handle(ImportEnvelope envelope) { return new UnsupportedImportEventException(envelope); } } /** * The registry of import dispatchers. * * @author Alexander Yevsyukov */ private static final class Registry extends DispatcherRegistry<EventClass, ImportDispatcher<?>> { } /** * The builder for {@link ImportBus}. */ public static class Builder extends BusBuilder<ImportEnvelope, ImportEvent, Builder> { @Override public Bus<?, ImportEnvelope, ?, ?> build() { return new ImportBus(this); } @Override protected Builder self() { return this; } } }
package de.exciteproject.refext.train.pipe; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import cc.mallet.pipe.Pipe; import cc.mallet.types.Instance; import cc.mallet.types.Token; import cc.mallet.types.TokenSequence; /** * Computes features based on the layout of lines in the PDF file <br> * Input per line: * text[tab]x-coordinate[tab]y-coordinate[tab]height[tab]width[tab]zone-id */ public abstract class LayoutPipe extends Pipe implements Serializable { private static final long serialVersionUID = 1L; private static final int CURRENT_SERIAL_VERSION = 0; protected double prevXPos = Double.MAX_VALUE; protected double prevYPos = Double.MAX_VALUE; protected double prevHeight = Double.MAX_VALUE; protected double prevWidth = Double.MAX_VALUE; protected double prevZoneId = 0.0; protected double thisXPos; protected double thisYPos; protected double thisHeight; protected double thisWidth; protected double thisZoneId; protected String featureLabel; private String csvSeparator; public LayoutPipe(String featureLabel, String csvSeparator) { this.featureLabel = featureLabel; this.csvSeparator = csvSeparator; } @Override public Instance pipe(Instance carrier) { TokenSequence tokenSequence = (TokenSequence) carrier.getData(); for (int i = 0; i < tokenSequence.size(); i++) { Token token = tokenSequence.get(i); String tokenText = token.getText(); String[] tokenSplit = tokenText.split(this.csvSeparator); if (tokenSplit.length != 6) { System.err.println("length!=6: " + tokenText); continue; } // format (copied from CermineLineLayoutExtractor) // fixedLine += "\t" + bxLine.getX() + "\t" + bxLine.getY() + "\t" + // bxLine.getHeight() + "\t" + bxLine.getWidth() this.thisXPos = Double.parseDouble(tokenSplit[1]); this.thisYPos = Double.parseDouble(tokenSplit[2]); this.thisHeight = Double.parseDouble(tokenSplit[3]); this.thisWidth = Double.parseDouble(tokenSplit[4]); this.thisZoneId = Double.parseDouble(tokenSplit[5]); this.computeFeatureLabel(token); // token.setText(tokenSplit[0]); this.prevXPos = this.thisXPos; this.prevYPos = this.thisYPos; this.prevHeight = this.thisHeight; this.prevWidth = this.thisWidth; this.prevZoneId = this.thisZoneId; } return carrier; } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // read serial version in.readInt(); this.featureLabel = (String) in.readObject(); this.csvSeparator = (String) in.readObject(); // this.yPosFeatureLabel = (String) in.readObject(); } private void writeObject(ObjectOutputStream out) throws IOException { out.writeInt(CURRENT_SERIAL_VERSION); out.writeObject(this.featureLabel); out.writeObject(this.csvSeparator); // out.writeObject(this.yPosFeatureLabel); } protected abstract void computeFeatureLabel(Token token); }
package com.google.android.apps.paco; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import android.annotation.SuppressLint; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; /** * This class helps open, create, and upgrade the database file. */ @SuppressLint("UseSparseArrays") public class DatabaseHelper extends SQLiteOpenHelper { // private InputStream sqlInput; private Context context; DatabaseHelper(Context context/*, InputStream in*/) { super(context, ExperimentProvider.DATABASE_NAME, null, ExperimentProvider.DATABASE_VERSION); // this.sqlInput = in; this.context = context; } // For testing DatabaseHelper(Context context, String dbName, int dbVersion) { super(context, dbName, null, dbVersion); this.context = context; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + ExperimentProvider.EXPERIMENTS_TABLE_NAME + " (" + ExperimentColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + ExperimentColumns.SERVER_ID + " INTEGER," + ExperimentColumns.TITLE + " TEXT, " + ExperimentColumns.VERSION + " INTEGER," + ExperimentColumns.DESCRIPTION + " TEXT, " + ExperimentColumns.CREATOR + " TEXT, " + ExperimentColumns.INFORMED_CONSENT + " TEXT, " + ExperimentColumns.HASH + " TEXT, " + ExperimentColumns.FIXED_DURATION + " INTEGER, " + ExperimentColumns.START_DATE + " TEXT, " + ExperimentColumns.END_DATE + " TEXT, " + ExperimentColumns.JOIN_DATE + " TEXT, " + ExperimentColumns.QUESTIONS_CHANGE + " INTEGER, " + ExperimentColumns.ICON + " BLOB, " + ExperimentColumns.WEB_RECOMMENDED + " INTEGER, " + ExperimentColumns.JSON + " TEXT " + ");"); db.execSQL("CREATE TABLE " + ExperimentProvider.SCHEDULES_TABLE_NAME + " (" + SignalScheduleColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + SignalScheduleColumns.SERVER_ID + " INTEGER, " + SignalScheduleColumns.EXPERIMENT_ID + " INTEGER, " + SignalScheduleColumns.SCHEDULE_TYPE + " INTEGER, " + SignalScheduleColumns.ESM_FREQUENCY + " INTEGER, " + SignalScheduleColumns.ESM_PERIOD + " INTEGER, " + SignalScheduleColumns.ESM_START_HOUR + " INTEGER, " + SignalScheduleColumns.ESM_END_HOUR + " INTEGER, " + SignalScheduleColumns.ESM_WEEKENDS + " INTEGER, " + SignalScheduleColumns.TIMES_CSV + " TEXT, " + SignalScheduleColumns.REPEAT_RATE + " INTEGER, " + SignalScheduleColumns.WEEKDAYS_SCHEDULED + " INTEGER, " + SignalScheduleColumns.NTH_OF_MONTH + " INTEGER, " + SignalScheduleColumns.BY_DAY_OF_MONTH + " INTEGER, " + SignalScheduleColumns.DAY_OF_MONTH + " INTEGER, " + SignalScheduleColumns.BEGIN_DATE + " INTEGER, " + SignalScheduleColumns.USER_EDITABLE + " INTEGER, " + SignalScheduleColumns.TIME_OUT + " INTEGER " + ");"); db.execSQL("CREATE TABLE " + ExperimentProvider.INPUTS_TABLE_NAME + " (" + InputColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + InputColumns.EXPERIMENT_ID + " INTEGER, " + InputColumns.SERVER_ID + " INTEGER, " + InputColumns.NAME + " TEXT," + InputColumns.TEXT + " TEXT," + InputColumns.MANDATORY + " INTEGER," + InputColumns.SCHEDULED_DATE + " INTEGER," + InputColumns.QUESTION_TYPE + " INTEGER," + InputColumns.RESPONSE_TYPE + " INTEGER," + InputColumns.LIKERT_STEPS + " INTEGER," + InputColumns.LEFT_SIDE_LABEL + " TEXT," + InputColumns.RIGHT_SIDE_LABEL + " TEXT," + InputColumns.LIST_CHOICES_JSON + " TEXT," + InputColumns.CONDITIONAL + " INTEGER," + InputColumns.CONDITIONAL_EXPRESSION + " TEXT," + InputColumns.MULTISELECT + " INTEGER" + ");"); db.execSQL("CREATE TABLE " + ExperimentProvider.EVENTS_TABLE_NAME + " (" + EventColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + EventColumns.EXPERIMENT_ID + " INTEGER, " + EventColumns.EXPERIMENT_SERVER_ID + " INTEGER, " + EventColumns.EXPERIMENT_NAME + " TEXT, " + EventColumns.EXPERIMENT_VERSION + " INTEGER, " + EventColumns.SCHEDULE_TIME + " INTEGER, " + EventColumns.RESPONSE_TIME + " INTEGER," + EventColumns.UPLOADED + " INTEGER" + ");"); db.execSQL("CREATE TABLE " + ExperimentProvider.OUTPUTS_TABLE_NAME + " (" + OutputColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + OutputColumns.EVENT_ID + " INTEGER, " + OutputColumns.INPUT_SERVER_ID + " INTEGER, " + OutputColumns.NAME + " TEXT," + OutputColumns.ANSWER + " TEXT" + ");"); db.execSQL("CREATE TABLE " + ExperimentProvider.FEEDBACK_TABLE_NAME + " (" + FeedbackColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + FeedbackColumns.EXPERIMENT_ID + " INTEGER, " + FeedbackColumns.SERVER_ID + " INTEGER, " + FeedbackColumns.FEEDBACK_TYPE + " TEXT," + FeedbackColumns.TEXT + " TEXT" + ");"); db.execSQL("CREATE TABLE " + ExperimentProvider.NOTIFICATION_TABLE_NAME + " (" + NotificationHolderColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + NotificationHolderColumns.ALARM_TIME + " INTEGER, " + NotificationHolderColumns.EXPERIMENT_ID + " INTEGER, " + NotificationHolderColumns.NOTICE_COUNT + " INTEGER, " + NotificationHolderColumns.TIMEOUT_MILLIS + " INTEGER" + ");"); // insertValues(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(ExperimentProvider.TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + "."); if (oldVersion <= 8) { db.execSQL("ALTER TABLE " + ExperimentProvider.INPUTS_TABLE_NAME + " ADD " + InputColumns.MULTISELECT + " INTEGER default 0" + ";"); } if (oldVersion <= 9) { db.execSQL("ALTER TABLE " + ExperimentProvider.SCHEDULES_TABLE_NAME + " ADD " + SignalScheduleColumns.USER_EDITABLE + " INTEGER default 1" + ";"); } if (oldVersion <= 10) { db.execSQL("ALTER TABLE " + ExperimentProvider.EXPERIMENTS_TABLE_NAME + " ADD " + ExperimentColumns.WEB_RECOMMENDED + " INTEGER default 0" + ";"); } if (oldVersion <= 11) { db.execSQL("ALTER TABLE " + ExperimentProvider.EXPERIMENTS_TABLE_NAME + " ADD " + ExperimentColumns.VERSION + " INTEGER default 0" + ";"); db.execSQL("ALTER TABLE " + ExperimentProvider.EVENTS_TABLE_NAME + " ADD " + EventColumns.EXPERIMENT_VERSION + " INTEGER default 0" + ";"); db.execSQL("ALTER TABLE " + ExperimentProvider.SCHEDULES_TABLE_NAME + " ADD " + SignalScheduleColumns.TIME_OUT + " INTEGER" + ";"); } if (oldVersion <= 12) { db.execSQL("ALTER TABLE " + ExperimentProvider.EXPERIMENTS_TABLE_NAME + " ADD " + ExperimentColumns.JSON + " TEXT " + ";"); ExperimentProviderUtil eu = new ExperimentProviderUtil(context); List<Experiment> joined = eu.getJoinedExperiments(); for (Experiment experiment : joined) { eu.updateJoinedExperiment(experiment); } } if (oldVersion <= 13) { HashMap<Integer, String> startDatePairs = convertDateLongsToStrings(db, ExperimentProvider.EXPERIMENTS_TABLE_NAME, ExperimentColumns.START_DATE, ExperimentColumns._ID); HashMap<Integer, String> endDatePairs = convertDateLongsToStrings(db, ExperimentProvider.EXPERIMENTS_TABLE_NAME, ExperimentColumns.END_DATE, ExperimentColumns._ID); HashMap<Integer, String> joinDatePairs = convertDateLongsToTzStrings(db, ExperimentProvider.EXPERIMENTS_TABLE_NAME, ExperimentColumns.JOIN_DATE, ExperimentColumns._ID); createTruncatedExperimentsTable(db); insertNewDateColumnWithData(db, ExperimentProvider.EXPERIMENTS_TABLE_NAME, startDatePairs, ExperimentColumns.START_DATE, ExperimentColumns._ID); insertNewDateColumnWithData(db, ExperimentProvider.EXPERIMENTS_TABLE_NAME, endDatePairs, ExperimentColumns.END_DATE, ExperimentColumns._ID); insertNewDateColumnWithData(db, ExperimentProvider.EXPERIMENTS_TABLE_NAME, joinDatePairs, ExperimentColumns.JOIN_DATE, ExperimentColumns._ID); } } private static HashMap<Integer, String> convertDateLongsToStrings(SQLiteDatabase db, String tableName, String dateCol, String refCol) { String[] columns = {dateCol, refCol}; HashMap<Integer, String> data = new HashMap<Integer, String>(); Cursor cursor = db.query(tableName, columns, null, null, null, null, null); try { if (cursor != null) { while (cursor.moveToNext()) { Long longVal = cursor.getLong(cursor.getColumnIndex(dateCol)); if (longVal != null) { String dateStr = TimeUtil.formatDate(longVal); Integer id = cursor.getInt(cursor.getColumnIndex(refCol)); data.put(id, dateStr); } } } } finally { cursor.close(); } return data; } private static HashMap<Integer, String> convertDateLongsToTzStrings(SQLiteDatabase db, String tableName, String dateCol, String refCol) { String[] columns = {dateCol, refCol}; HashMap<Integer, String> data = new HashMap<Integer, String>(); Cursor cursor = db.query(tableName, columns, null, null, null, null, null); try { if (cursor != null) { while (cursor.moveToNext()) { Long longVal = cursor.getLong(cursor.getColumnIndex(dateCol)); if (longVal != null) { String dateStr = TimeUtil.formatDateWithZone(longVal); Integer id = cursor.getInt(cursor.getColumnIndex(refCol)); data.put(id, dateStr); } } } } finally { cursor.close(); } return data; } private static void createTruncatedExperimentsTable(SQLiteDatabase db) { String tempTable = "tempTable"; db.execSQL("CREATE TABLE " + tempTable + " AS SELECT " + ExperimentColumns._ID + ", " + ExperimentColumns.SERVER_ID + ", " + ExperimentColumns.TITLE + ", " + ExperimentColumns.VERSION + ", " + ExperimentColumns.DESCRIPTION + ", " + ExperimentColumns.CREATOR + ", " + ExperimentColumns.INFORMED_CONSENT + ", " + ExperimentColumns.HASH + ", " + ExperimentColumns.FIXED_DURATION + ", " + ExperimentColumns.QUESTIONS_CHANGE + ", " + ExperimentColumns.ICON + ", " + ExperimentColumns.WEB_RECOMMENDED + ", " + ExperimentColumns.JSON + " FROM " + ExperimentProvider.EXPERIMENTS_TABLE_NAME + ";"); db.execSQL("DROP TABLE " + ExperimentProvider.EXPERIMENTS_TABLE_NAME); db.execSQL("ALTER TABLE " + tempTable + " RENAME TO " + ExperimentProvider.EXPERIMENTS_TABLE_NAME); } private static void insertNewDateColumnWithData(SQLiteDatabase db, String tableName, HashMap<Integer,String> data, String dateCol, String refCol) { db.execSQL("ALTER TABLE " + tableName + " ADD " + dateCol + " TEXT " + ";"); for (Map.Entry<Integer, String> entry : data.entrySet()) { db.execSQL("UPDATE " + tableName + " SET " + dateCol + " = " + "\'" + entry.getValue() + "\'" + " WHERE " + refCol + " = " + entry.getKey() + ";"); } } }
package cz.brmlab.yodaqa.analysis.tycor; import java.util.Arrays; 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 net.didion.jwnl.data.IndexWord; import net.didion.jwnl.data.POS; import net.didion.jwnl.data.PointerTarget; import net.didion.jwnl.data.PointerType; import net.didion.jwnl.data.Synset; import net.didion.jwnl.data.Word; import org.apache.uima.UimaContext; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.fit.component.JCasAnnotator_ImplBase; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cz.brmlab.yodaqa.model.TyCor.LAT; import cz.brmlab.yodaqa.model.TyCor.WordnetLAT; import cz.brmlab.yodaqa.provider.JWordnet; import de.tudarmstadt.ukp.dkpro.core.api.ner.type.NamedEntity; /** * Generate less specific LAT annotations from existing LAT annotations * based on Wordnet relationships. At this point, we generate LATs * with gradually reduced specificity based on hypernymy. */ public class LATByWordnet extends JCasAnnotator_ImplBase { final Logger logger = LoggerFactory.getLogger(LATByWordnet.class); /* We don't generalize further over the noun.Tops words that * represent the most abstract hierarchy and generally words * that have nothing in common anymore. * * sed -ne 's/^{ //p' data/wordnet/dict/dbfiles//noun.Tops | sed -re 's/[.:^_a-zA-Z0-9]+,[^ ]+ //g; s/ \(.*$//; s/\[ | \]|,//g; s/ .*$//' * * XXX: It would be better to have these as synset IDs, but that * would be more complicated to obtain. */ protected static String tops_list[] = { "entity", "physical_entity", "abstraction", "thing", "object", "whole", "congener", "living_thing", "organism", "benthos", "dwarf", "heterotroph", "parent", "life", "biont", "cell", "causal_agent", "person", "animal", "plant", "native", "natural_object", "substance", "substance1", "matter", "food", "nutrient1", "artifact", "article", "psychological_feature", "cognition", "motivation", "attribute", "state", "feeling", "location", "shape", "time", "space", "absolute_space", "phase_space", "event", "process", "act", "group", "relation", "possession", "social_relation", "communication", "measure", "phenomenon", }; protected Set<String> tops; public void initialize(UimaContext aContext) throws ResourceInitializationException { if (tops == null) tops = new HashSet<String>(Arrays.asList(tops_list)); super.initialize(aContext); } public void process(JCas jcas) throws AnalysisEngineProcessException { /* Gather all LATs. */ List<LAT> lats = new LinkedList<LAT>(); for (LAT lat : JCasUtil.select(jcas, LAT.class)) lats.add(lat); /* Generate derived LATs. */ Map<Synset, WordnetLAT> latmap = new HashMap<Synset, WordnetLAT>(); /* TODO: Populate with existing LATs for deduplication. */ for (LAT lat : lats) { try { genDerivedLATs(latmap, lat, lat.getPos().getPosValue()); } catch (Exception e) { throw new AnalysisEngineProcessException(e); } } /* Add the remaining LATs. */ for (WordnetLAT lat : latmap.values()) lat.addToIndexes(); } protected void genDerivedLATs(Map<Synset, WordnetLAT> latmap, LAT lat, String latpos) throws Exception { /* TODO: Use pos information from the parser? * Currently, we just assume a noun and the rest is * a fallback path that derives the noun. * (Typically: How hot is the sun? -> hotness) */ POS wnpos; if (lat.getBase() instanceof NamedEntity) { wnpos = POS.NOUN; } else if (latpos.matches("^NN.*")) { wnpos = POS.NOUN; } else if (latpos.matches("^JJ.*")) { wnpos = POS.ADJECTIVE; } else if (latpos.matches("^RB.*")) { wnpos = POS.ADVERB; } else if (latpos.matches("^VB.*")) { wnpos = POS.VERB; } else { logger.info("?! cannot expand LAT of POS " + latpos); return; } /* For a debug message, concatenate all generated wordnet LATs * in this string. */ boolean foundNoun = false; StringBuilder wnlist = new StringBuilder(); if (lat.getSynset() == 0) { IndexWord w = JWordnet.getDictionary().lookupIndexWord(wnpos, lat.getText()); if (w == null) { logger.info("?! word " + lat.getText() + " of POS " + latpos + " not in Wordnet"); return; } if (wnpos == POS.NOUN) { /* Got a noun right away. */ genDerivedSynsets(latmap, lat, w, wnlist, lat.getSpecificity() - 1); logger.debug("expanded LAT " + lat.getText() + " to wn LATs: " + wnlist.toString()); return; } /* Try to derive a noun. */ for (Synset synset : w.getSenses()) { boolean fnhere = genNounSynsets(latmap, lat, synset, wnpos, wnlist); foundNoun = foundNoun || fnhere; if (wnpos == POS.VERB) { // ignore other senses since // nominalization is highly noisy; // see getNounSynsets() for details break; } } } else { Synset s = JWordnet.getDictionary().getSynsetAt(wnpos, lat.getSynset()); if (s == null) { logger.warn("?! word " + lat.getText() + "/" + lat.getSynset() + " of POS " + latpos + " not in Wordnet even though it has Wordnet sense assigned"); return; } if (wnpos == POS.NOUN) { /* Got a noun right away. */ for (PointerTarget t : s.getTargets(PointerType.HYPERNYM)) { genDerivedSynsets(latmap, lat, (Synset) t, wnlist, lat.getSpecificity() - 1); } logger.debug("expanded LAT " + lat.getText() + "/" + lat.getSynset() + " to wn LATs: " + wnlist.toString()); return; } /* Try to derive a noun. */ foundNoun = genNounSynsets(latmap, lat, s, wnpos, wnlist); } if (!foundNoun && !latpos.matches(".*XSURROGATE$")) { /* We didn't find a noun but it turns out that * we may need to flip adverb/adjective tag, e.g. * for "how long" we need to consider "long" as * an adjective to get to "length". */ if (wnpos == POS.ADVERB) { genDerivedLATs(latmap, lat, "JJXSURROGATE"); return; } else if (wnpos == POS.ADJECTIVE) { genDerivedLATs(latmap, lat, "RBXSURROGATE"); return; } } if (!foundNoun) { logger.info("?! word " + lat.getText() + " of POS " + latpos + " in Wordnet as non-noun but derived from no noun"); } } protected boolean genNounSynsets(Map<Synset, WordnetLAT> latmap, LAT lat, Synset synset, POS wnpos, StringBuilder wnlist) throws Exception { boolean foundNoun = false; logger.debug("checking noun synsets of " + synset.getWord(0).getLemma() + "/" + synset.getOffset()); for (PointerTarget t : synset.getTargets(PointerType.ATTRIBUTE)) { Synset noun = (Synset) t; foundNoun = true; logger.debug(".. adding LAT noun " + noun.getWord(0).getLemma()); genDerivedSynsets(latmap, lat, noun, wnlist, lat.getSpecificity()); logger.debug("expanded LAT " + lat.getText() + " to wn LATs: " + wnlist.toString()); } if (wnpos == POS.VERB) { /* For other non-nouns, this is too wide. E.g. for * "how deep", we want "depth" but not "mystery", * "richness", "deepness", "obscureness", ... */ Word nominalw = null; for (PointerTarget t : synset.getTargets(PointerType.NOMINALIZATION)) { Word nounw = (Word) t; foundNoun = true; if (nounw.getPOS() != POS.NOUN) continue; nominalw = nounw; } /* Take only the last word (which is the most common * one), to avoid pulling in anything obscure - and * there is a lot of obscure stuff. E.g. for die: * death Death die breakdown dead_person end passing * failure */ if (nominalw != null) { logger.debug(".. adding LAT noun " + nominalw.getLemma()); genDerivedSynsets(latmap, lat, nominalw.getSynset(), wnlist, lat.getSpecificity()); logger.debug("expanded LAT " + lat.getText() + " to wn LATs: " + wnlist.toString()); } } return foundNoun; } protected void genDerivedSynsets(Map<Synset, WordnetLAT> latmap, LAT lat, IndexWord wnoun, StringBuilder wnlist, double spec) throws Exception { for (Synset synset : wnoun.getSenses()) { for (PointerTarget t : synset.getTargets(PointerType.HYPERNYM)) { genDerivedSynsets(latmap, lat, (Synset) t, wnlist, spec); } } } protected void genDerivedSynsets(Map<Synset, WordnetLAT> latmap, LAT lat, Synset synset2, StringBuilder wnlist, double spec) throws Exception { WordnetLAT l2 = latmap.get(synset2); if (l2 != null) { /* Ok, already exists. Try to raise * specificity if possible. */ if (l2.getSpecificity() < spec) { l2.setSpecificity(spec); l2.setBase(lat.getBase()); l2.setBaseLAT(lat); } return; } String lemma = synset2.getWord(0).getLemma(); /* New LAT. */ l2 = new WordnetLAT(lat.getCAS().getJCas()); l2.setBegin(lat.getBegin()); l2.setEnd(lat.getEnd()); l2.setBase(lat.getBase()); l2.setBaseLAT(lat); l2.setText(lemma); l2.setSpecificity(spec); l2.setIsHierarchical(true); l2.setSynset(synset2.getOffset()); latmap.put(synset2, l2); wnlist.append(" | " + lemma + "/" + synset2.getOffset() + ":" + Double.toString(spec)); /* ...and recurse, unless we got into the noun.Tops * realm already. */ if (!tops.contains(lemma)) { for (PointerTarget t : synset2.getTargets(PointerType.HYPERNYM)) { genDerivedSynsets(latmap, l2, (Synset) t, wnlist, spec - 1); } } } }
package org.bouncycastle.asn1.test; import java.text.DateFormat; import java.util.Date; import java.util.Locale; import org.bouncycastle.asn1.DERGeneralizedTime; import org.bouncycastle.asn1.DERUTCTime; import org.bouncycastle.util.test.SimpleTest; public class LocaleTest extends SimpleTest { public String getName() { return "LocaleTest"; } private void doTestLocale(Locale l) throws Exception { long time = 1538063166000L; String timeString = "180927154606GMT+00:00"; String longTimeString = "20180927154606Z"; Locale.setDefault(l); isTrue("a", time == new DERUTCTime(timeString).getAdjustedDate().getTime()); isTrue("b", time == new DERGeneralizedTime(longTimeString).getDate().getTime()); isTrue("c", time == new DERUTCTime(new Date(time)).getAdjustedDate().getTime()); isTrue("d", time == new DERGeneralizedTime(new Date(time)).getDate().getTime()); Date d = new Date(); isTrue("e", (d.getTime() - (d.getTime() % 1000)) == new DERUTCTime(d).getAdjustedDate().getTime()); isTrue("f", (d.getTime() - (d.getTime() % 1000)) == new DERGeneralizedTime(d).getDate().getTime()); } public void performTest() throws Exception { Locale defLocale = Locale.getDefault(); Locale list[] = DateFormat.getAvailableLocales(); for (int i = 0; i != list.length; i++) { if (!list[i].getCountry().equals("TH") // skip Thailand as it appears the JVM is now a day out on this one. && !list[i].getCountry().equals("JP")) // and it appears the change in era is causing issues here. { doTestLocale(list[i]); } } Locale.setDefault(defLocale); } public static void main( String[] args) { runTest(new LocaleTest()); } }
package de.i3mainz.chronontology.rest; import de.i3mainz.chronontology.chronontology.ChronOntology; import de.i3mainz.chronontology.errorlog.Logging; import de.i3mainz.chronontology.restconfig.ResponseGZIP; import javax.ws.rs.Produces; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.json.simple.JSONArray; import org.json.simple.JSONObject; @Path("/place") public class GenericResource { /** * creates a GeoJSON out of a query * @param acceptEncoding * @param acceptHeader * @param periodid * @return GeoJSON */ @GET @Path("/") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") public Response getGeoJSON(@HeaderParam("Accept-Encoding") String acceptEncoding, @HeaderParam("Accept") String acceptHeader, @QueryParam("periodid") String periodid) { try { JSONObject geojson = new JSONObject(); if (periodid != null) { if (!periodid.equals("")) { geojson.put("type", "FeatureCollection"); geojson.put("features", ChronOntology.getGeoJSON(periodid)); return ResponseGZIP.setResponse(acceptEncoding, geojson.toJSONString()); } else { geojson.put("type", "FeatureCollection"); geojson.put("features", new JSONArray()); return ResponseGZIP.setResponse(acceptEncoding, geojson.toJSONString()); } } else { geojson.put("type", "FeatureCollection"); geojson.put("features", new JSONArray()); return ResponseGZIP.setResponse(acceptEncoding, geojson.toJSONString()); } } catch (Exception e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(Logging.getMessageJSON(e, "de.i3mainz.chronontology.rest.GenericResource")) .header("Content-Type", "application/json;charset=UTF-8").build(); } } }
package de.webshop.kundenverwaltung.domain; public class Kunde { private String Name; private String Vorname; private long ID; public String getName() { return Name; } public void setName(String name) { Name = name; } public String getVorname() { return Vorname; } public void setVorname(String vorname) { Vorname = vorname; } public Kunde(String name, String vorname) { super(); Name = name; Vorname = vorname; } public long getID() { return ID; } public void setID(long id) { ID = id; } }
package org.zanata.security; import static org.jboss.seam.ScopeType.SESSION; import static org.jboss.seam.annotations.Install.APPLICATION; import javax.servlet.http.HttpServletRequest; import org.jboss.seam.Component; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.Create; import org.jboss.seam.annotations.Install; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import org.jboss.seam.annotations.intercept.BypassInterceptors; import org.jboss.seam.core.Events; import org.jboss.seam.log.LogProvider; import org.jboss.seam.log.Logging; import org.jboss.seam.security.openid.OpenIdPrincipal; import org.openid4java.consumer.ConsumerException; import org.openid4java.message.ParameterList; import java.util.List; import javax.faces.context.ExternalContext; import org.jboss.seam.faces.FacesManager; import org.jboss.seam.faces.Redirect; import org.jboss.seam.security.Identity; import org.openid4java.OpenIDException; import org.openid4java.consumer.ConsumerManager; import org.openid4java.consumer.VerificationResult; import org.openid4java.discovery.DiscoveryInformation; import org.openid4java.discovery.Identifier; import org.openid4java.message.AuthRequest; import org.openid4java.message.ax.FetchRequest; import org.zanata.ApplicationConfiguration; @Name("org.jboss.seam.security.fedoraOpenId") @Scope(SESSION) @Install(precedence = APPLICATION) @BypassInterceptors /* * based on org.jboss.seam.security.openid.OpenId class */ public class FedoraOpenId { private static final long serialVersionUID = 1L; private static String FEDORA_HOST = ".id.fedoraproject.org/"; private static final LogProvider log = Logging.getLogProvider(FedoraOpenId.class); private ZanataIdentity identity; private ZanataJpaIdentityStore identityStore; private ApplicationConfiguration applicationConfiguration; private ZanataExternalLoginBean zanataExternalLoginBean; private String id; private String validatedId; private ConsumerManager manager; private DiscoveryInformation discovered; public String getId() { return id; } public void setId(String id) { this.id = id; } public void login() { validatedId = null; String returnToUrl = returnToUrl(); String url = authRequest(id, returnToUrl); if (url != null) { Redirect redirect = Redirect.instance(); redirect.captureCurrentView(); FacesManager.instance().redirectToExternalURL(url); } } @SuppressWarnings("rawtypes") protected String authRequest(String userSuppliedString, String returnToUrl) { try { // perform discovery on the user-supplied identifier List discoveries = manager.discover(userSuppliedString); // attempt to associate with the OpenID provider // and retrieve one service endpoint for authentication discovered = manager.associate(discoveries); // // store the discovery information in the user's session // httpReq.getSession().setAttribute("openid-disc", discovered); // obtain a AuthRequest message to be sent to the OpenID provider AuthRequest authReq = manager.authenticate(discovered, returnToUrl); // Attribute Exchange example: fetching the 'email' attribute FetchRequest fetch = FetchRequest.createFetchRequest(); fetch.addAttribute("email", "http://schema.openid.net/contact/email", // type // URI true); // required // attach the extension to the authentication request authReq.addExtension(fetch); return authReq.getDestinationUrl(true); } catch (OpenIDException e) { log.warn(e); } return null; } public void verify() { ExternalContext context = javax.faces.context.FacesContext.getCurrentInstance().getExternalContext(); HttpServletRequest request = (HttpServletRequest) context.getRequest(); validatedId = verifyResponse(request); } public boolean loginImmediately() { if (validatedId != null) { Identity.instance().acceptExternallyAuthenticatedPrincipal((new OpenIdPrincipal(validatedId))); return true; } return false; } public boolean isValid() { return validatedId != null; } public String getValidatedId() { return validatedId; } public String verifyResponse(HttpServletRequest httpReq) { try { // extract the parameters from the authentication response // (which comes in as a HTTP request from the OpenID provider) ParameterList response = new ParameterList(httpReq.getParameterMap()); StringBuffer receivingURL = new StringBuffer(returnToUrl()); String queryString = httpReq.getQueryString(); if (queryString != null && queryString.length() > 0) receivingURL.append("?").append(httpReq.getQueryString()); // verify the response; ConsumerManager needs to be the same // (static) instance used to place the authentication request VerificationResult verification = manager.verify(receivingURL.toString(), response, discovered); // examine the verification result and extract the verified identifier Identifier verified = verification.getVerifiedId(); if (verified != null) { // AuthSuccess authSuccess = // (AuthSuccess) verification.getAuthResponse(); // if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) { // FetchResponse fetchResp = (FetchResponse) authSuccess // .getExtension(AxMessage.OPENID_NS_AX); // List emails = fetchResp.getAttributeValues("email"); // String email = (String) emails.get(0); return verified.getIdentifier(); } } catch (OpenIDException e) { log.warn(e); } return null; } public void logout() throws ConsumerException { init(); } @Create public void init() { try { manager = new ConsumerManager(); discovered = null; id = null; validatedId = null; } catch (ConsumerException e) { throw new RuntimeException(e); } identity = (ZanataIdentity) Component.getInstance(ZanataIdentity.class, ScopeType.SESSION); identityStore = (ZanataJpaIdentityStore) Component.getInstance(ZanataJpaIdentityStore.class, ScopeType.APPLICATION); applicationConfiguration = (ApplicationConfiguration) Component.getInstance(ApplicationConfiguration.class, ScopeType.APPLICATION); zanataExternalLoginBean = (ZanataExternalLoginBean) Component.getInstance(ZanataExternalLoginBean.class, ScopeType.SESSION); } public String loginImmediate() { if (loginImmediately()) { identity.getCredentials().setInitialized(true); identity.setPreAuthenticated(true); zanataExternalLoginBean.checkDisabledUser(); if (!identity.isLoggedIn()) { return "failure"; } if (Events.exists()) Events.instance().raiseEvent(ZanataIdentity.EVENT_LOGIN_SUCCESSFUL); if (identityStore.isNewUser(identity.getCredentials().getUsername())) { return "new"; } return "success"; } else { return "failure"; } } public void login(String username) { try { String var = "http://" + username + FEDORA_HOST; setId(var); log.info("openid:" + getId()); login(); } catch (Exception e) { throw new RuntimeException(e); } } public String returnToUrl() { return applicationConfiguration.getServerPath() + "/openid.seam"; } }
package de.maredit.tar.controllers; import com.unboundid.ldap.sdk.LDAPException; import de.maredit.tar.models.User; import de.maredit.tar.models.Vacation; import de.maredit.tar.models.enums.FormMode; import de.maredit.tar.models.enums.State; import de.maredit.tar.models.validators.VacationValidator; import de.maredit.tar.properties.VersionProperties; import de.maredit.tar.providers.VersionProvider; import de.maredit.tar.repositories.UserRepository; import de.maredit.tar.repositories.VacationRepository; import de.maredit.tar.services.LdapService; import de.maredit.tar.services.MailService; import de.maredit.tar.services.mail.MailObject; import de.maredit.tar.services.mail.SubstitutionApprovedMail; import de.maredit.tar.services.mail.SubstitutionRejectedMail; import de.maredit.tar.services.mail.VacationApprovedMail; import de.maredit.tar.services.mail.VacationCanceledMail; import de.maredit.tar.services.mail.VacationCreateMail; import de.maredit.tar.services.mail.VacationDeclinedMail; import de.maredit.tar.services.mail.VacationModifiedMail; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.propertyeditors.StringTrimmerEditor; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; @Controller public class VacationController extends WebMvcConfigurerAdapter { private static final Logger LOG = LogManager.getLogger(VacationController.class); @Autowired private VacationRepository vacationRepository; @Autowired private UserRepository userRepository; @Autowired private MailService mailService; @Autowired private LdapService ldapService; @Autowired private VersionProperties versionProperties; @Autowired private ApplicationController applicationController; @Autowired private VersionProvider versionProvider; @ModelAttribute("vacation") public Vacation getVacation(@RequestParam(value = "id", required = false) String id) { if (StringUtils.isBlank(id)) { return new Vacation(); } return vacationRepository.findOne(id); } @InitBinder("vacation") protected void initBinder(WebDataBinder binder) { binder.addValidators(new VacationValidator()); binder.registerCustomEditor(String.class, "id", new StringTrimmerEditor(true)); } @RequestMapping("/") public String index(HttpServletRequest request, Model model, @ModelAttribute("vacation") Vacation vacation) { vacation.setUser(applicationController.getConnectedUser()); User selectedUser = getUser(request); setIndexModelValues(model, selectedUser); model.addAttribute("formMode", FormMode.NEW); return "application/index"; } @RequestMapping("/substitution") public String substitution(@ModelAttribute("vacation") Vacation vacation, @RequestParam(value = "approve") boolean approve) { vacation.setState((approve) ? State.WAITING_FOR_APPROVEMENT : State.REJECTED); this.vacationRepository.save(vacation); MailObject mail = (approve ? new SubstitutionApprovedMail(vacation) : new SubstitutionRejectedMail(vacation)); this.mailService.sendMail(mail); return "redirect:/"; } @RequestMapping("/approval") @PreAuthorize("hasRole('SUPERVISOR')") public String approval(@ModelAttribute("vacation") Vacation vacation, @RequestParam(value = "approve") boolean approve) { vacation.setState((approve) ? State.APPROVED : State.REJECTED); this.vacationRepository.save(vacation); MailObject mail = (approve ? new VacationApprovedMail(vacation) : new VacationDeclinedMail(vacation)); this.mailService.sendMail(mail); return "redirect:/"; } @RequestMapping(value = "/vacation", method = {RequestMethod.GET}, params = "id") public String vacation(@ModelAttribute("vacation") Vacation vacation, @RequestParam(value = "action", required = false) String action, Model model) { switch (action) { case "edit": model.addAttribute("users", getSortedUserList()); model.addAttribute("managers", getManagerList()); model.addAttribute("formMode", FormMode.EDIT); break; case "approve": model.addAttribute("formMode", FormMode.MANAGER_APPROVAL); break; case "substitute": model.addAttribute("formMode", FormMode.SUBSTITUTE_APPROVAL); break; case "view": model.addAttribute("formMode", FormMode.VIEW); break; default: model.addAttribute("formMode", FormMode.VIEW); break; } return "components/vacationForm"; } @RequestMapping("/newVacation") public String newVacation(@ModelAttribute("vacation") Vacation vacation, Model model) { vacation.setUser(applicationController.getConnectedUser()); model.addAttribute("managers", getManagerList()); model.addAttribute("users", getSortedUserList()); model.addAttribute("vacation", vacation); model.addAttribute("formMode", FormMode.NEW); return "components/vacationForm"; } @RequestMapping(value = "/saveVacation", method = RequestMethod.POST) @PreAuthorize("hasRole('SUPERVISOR') or #vacation.user.username == authentication.name") public String saveVacation(@ModelAttribute("vacation") @Valid Vacation vacation, BindingResult bindingResult, Model model, HttpServletRequest request) { if (bindingResult.hasErrors()) { bindingResult.getFieldErrors().forEach( fieldError -> LOG.error(fieldError.getField() + " " + fieldError.getDefaultMessage())); User selectedUser = getUser(request); setIndexModelValues(model, selectedUser); model.addAttribute("formMode", FormMode.EDIT); return "application/index"; } else { boolean newVacation = StringUtils.isBlank(vacation.getId()); if (newVacation) { vacation.setAuthor(applicationController.getConnectedUser()); } else { vacation.setState(vacation.getSubstitute() == null ? State.WAITING_FOR_APPROVEMENT : State.REQUESTED_SUBSTITUTE); } this.vacationRepository.save(vacation); this.mailService.sendMail(newVacation ? new VacationCreateMail(vacation) : new VacationModifiedMail(vacation, applicationController .getConnectedUser())); return "redirect:/"; } } @RequestMapping(value = "/cancelVacation", method = RequestMethod.GET) @PreAuthorize("hasRole('SUPERVISOR') or #vacation.user.username == authentication.name") public String cancelVacation(@ModelAttribute("vacation") Vacation vacation) { VacationCanceledMail mail = new VacationCanceledMail(vacation); vacation.setState(State.CANCELED); this.vacationRepository.save(vacation); this.mailService.sendMail(mail); return "redirect:/"; } private void setIndexModelValues(Model model, User selectedUser) { List<User> users = getSortedUserList(); List<User> managerList = getManagerList(); List<Vacation> vacations = getVacationsForUser(selectedUser); List<Vacation> substitutes = getSubstitutesForUser(selectedUser); List<Vacation> substitutesForApproval = getVacationsForSubstituteApprovalForUser(applicationController.getConnectedUser()); List<Vacation> approvals = getVacationsForApprovalForUser(applicationController.getConnectedUser()); model.addAttribute("users", users); model.addAttribute("vacations", vacations); model.addAttribute("selectedUser", selectedUser); model.addAttribute("managers", managerList); model.addAttribute("substitutes", substitutes); model.addAttribute("substitutesForApproval", substitutesForApproval); model.addAttribute("approvals", approvals); model.addAttribute("loginUser", applicationController.getConnectedUser()); model.addAttribute("appVersion", versionProvider.getApplicationVersion()); model.addAttribute("buildnumber", versionProperties.getBuild()); } private List<User> getSortedUserList() { List<User> userList = new ArrayList<User>(); userList = userRepository.findAll(); userList = userList .stream() .filter(e -> e.isActive()) .sorted( (e1, e2) -> e1.getLastname().toUpperCase() .compareTo(e2.getLastname().toUpperCase())).collect(Collectors.toList()); return userList; } private List<User> getManagerList() { List<User> managerList = new ArrayList<User>(); try { managerList = userRepository.findByUsernames(ldapService.getLdapSupervisorList()); managerList = managerList.stream().filter(e -> e.isActive()) .sorted((e1, e2) -> e1.getLastname().compareTo(e2.getLastname())) .collect(Collectors.toList()); } catch (LDAPException e) { LOG.error("Error while reading manager list for vacation form", e); } return managerList; } private User getUser(HttpServletRequest request) { User user = null; Object selected = request.getParameter("selected"); if (selected == null) { user = applicationController.getConnectedUser(); } else { user = this.userRepository.findUserByUsername(String.valueOf(selected)); } return user; } private List<Vacation> getSubstitutesForUser(User user) { List<Vacation> substitutes = this.vacationRepository.findVacationBySubstituteAndStateNotAndToAfterOrderByFromAsc( user, State.CANCELED, LocalDate.now().minusDays(1)); return substitutes; } private List<Vacation> getVacationsForUser(User user) { List<Vacation> vacations = this.vacationRepository.findVacationByUserAndStateNotOrderByFromAsc(user, State.CANCELED); return vacations; } private List<Vacation> getVacationsForApprovalForUser(User user) { List<Vacation> approvals = this.vacationRepository.findVacationByManagerAndState( user, State.WAITING_FOR_APPROVEMENT); return approvals; } private List<Vacation> getVacationsForSubstituteApprovalForUser(User user) { List<Vacation> substitutesForApproval = this.vacationRepository.findVacationBySubstituteAndState( user, State.REQUESTED_SUBSTITUTE); return substitutesForApproval; } }
package de.lessvoid.nifty.controls; import java.util.ArrayList; import java.util.List; import de.lessvoid.nifty.input.NiftyInputEvent; import de.lessvoid.nifty.input.NiftyInputMapping; import de.lessvoid.nifty.input.keyboard.KeyboardInputEvent; import de.lessvoid.nifty.screen.KeyInputHandler; import de.lessvoid.nifty.screen.Screen; /** * NiftyInputControl. * @author void */ public class NiftyInputControl { /** * controller. */ private Controller controller; /** * input mapper this control uses. */ private NiftyInputMapping inputMapper; /** * list of additional input handlers. */ private List < KeyInputHandler > additionalInputHandler = new ArrayList < KeyInputHandler >(); /** * @param controllerParam controller * @param inputMapperParam input mapper */ public NiftyInputControl(final Controller controllerParam, final NiftyInputMapping inputMapperParam) { this.controller = controllerParam; this.inputMapper = inputMapperParam; } /** * keyboard event. * @param inputEvent keyboard event */ public void keyEvent(final KeyboardInputEvent inputEvent) { NiftyInputEvent converted = inputMapper.convert(inputEvent); controller.inputEvent(converted); for (KeyInputHandler handler : additionalInputHandler) { if (handler.keyEvent(converted)) { break; } } } /** * add an additional input handler. * @param handler KeyInputHandler */ public void addInputHandler(final KeyInputHandler handler) { additionalInputHandler.add(handler); } /** * forward the onStartScreen event to the controller. * @param screen screen */ public void onStartScreen(final Screen screen) { controller.onStartScreen(screen); } /** * forward the onForward method to the controller. * @param getFocus get focus */ public void onFocus(final boolean getFocus) { controller.onFocus(getFocus); } /** * get controller. * @return controller */ public Controller getController() { return controller; } /** * Get control when it matches the given class. * @param <T> type of class * @param requestedControlClass class that is requested * @return the instance or null */ public < T extends Controller > T getControl(final Class < T > requestedControlClass) { if (requestedControlClass.isInstance(controller)) { return requestedControlClass.cast(controller); } return null; } }
package de.retest.recheck.ui.review; import java.util.Collections; import java.util.Map; import java.util.function.Predicate; import java.util.stream.Collectors; import de.retest.recheck.report.ActionReplayResult; import de.retest.recheck.ui.descriptors.IdentifyingAttributes; import de.retest.recheck.ui.diff.ElementDifference; import de.retest.recheck.ui.diff.RootElementDifference; import de.retest.recheck.ui.diff.StateDifference; import de.retest.recheck.ui.image.Screenshot; import lombok.AccessLevel; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor( access = AccessLevel.PRIVATE ) public class ScreenshotChanges { private static final ScreenshotChanges EMPTY_SCREENSHOTS = new ScreenshotChanges( Collections.emptyMap() ); private final Map<IdentifyingAttributes, Screenshot> screenshotMap; public static ScreenshotChanges empty() { return EMPTY_SCREENSHOTS; } public static ScreenshotChanges actual( final ActionReplayResult result ) { final StateDifference stateDifference = result.getStateDifference(); if ( stateDifference == null ) { return EMPTY_SCREENSHOTS; } return new ScreenshotChanges( stateDifference.getRootElementDifferences().stream() .filter( actualScreenshotNotNull() ) .map( RootElementDifference::getElementDifference ) .collect( Collectors.toMap( ElementDifference::getIdentifyingAttributes, ElementDifference::getActualScreenshot ) ) ); } private static Predicate<RootElementDifference> actualScreenshotNotNull() { return difference -> difference.getActualScreenshot() != null; } public Screenshot getScreenshot( final IdentifyingAttributes attribute ) { return screenshotMap.get( attribute ); } }
package de.thischwa.c5c.requestcycle; import javax.servlet.ServletContext; import de.thischwa.c5c.Connector; /** * Interface for building the path to <i>userfiles</i>. <br/> * <br/> * <b>Hint:</b> You are free to implement this interface they way you need it. The return value * can be global (regardless of a request) or on a per-request basis. */ public interface UserPathBuilder { /** * Returns the server-side <i>userfiles</i> absolute path. The provided implementation of {@link Connector} * will use this value to resolve the server-side location of resources. <br/> * <br/> * <b>Hint:</b> E.g. {@link Context} and/or {@link ServletContext} can be used to to implement a * filesystem storage for each user. * * @param urlPath * @param context * @param servletContext * @return the constructed server-side path */ public String getServerPath(String urlPath, Context context, ServletContext servletContext); }
package de.theit.hudson.crowd; import static de.theit.hudson.crowd.ErrorMessages.accountExpired; import static de.theit.hudson.crowd.ErrorMessages.applicationAccessDenied; import static de.theit.hudson.crowd.ErrorMessages.applicationPermission; import static de.theit.hudson.crowd.ErrorMessages.expiredCredentials; import static de.theit.hudson.crowd.ErrorMessages.invalidAuthentication; import static de.theit.hudson.crowd.ErrorMessages.operationFailed; import hudson.security.SecurityRealm; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.acegisecurity.Authentication; import org.acegisecurity.GrantedAuthority; import org.acegisecurity.ui.rememberme.RememberMeServices; import com.atlassian.crowd.exception.ApplicationAccessDeniedException; import com.atlassian.crowd.exception.ApplicationPermissionException; import com.atlassian.crowd.exception.ExpiredCredentialException; import com.atlassian.crowd.exception.InactiveAccountException; import com.atlassian.crowd.exception.InvalidAuthenticationException; import com.atlassian.crowd.exception.InvalidTokenException; import com.atlassian.crowd.exception.OperationFailedException; import com.atlassian.crowd.model.authentication.ValidationFactor; import com.atlassian.crowd.model.user.User; /** * An implementation of the {@link RememberMeServices} to use SSO with Crowd. * * @author <a href="mailto:theit@gmx.de">Thorsten Heit (theit@gmx.de)</a> * @since 06.09.2011 * @version $Id$ */ public class CrowdRememberMeServices implements RememberMeServices { /** Used for logging purposes. */ private static final Logger LOG = Logger .getLogger(CrowdRememberMeServices.class.getName()); /** * The configuration data necessary for accessing the services on the remote * Crowd server. */ private CrowdConfigurationService configuration; /** * Creates a new instance of this class. * * @param pConfiguration * The configuration to access the services on the remote Crowd * server. May not be <code>null</code>. */ public CrowdRememberMeServices(CrowdConfigurationService pConfiguration) { this.configuration = pConfiguration; } /** * {@inheritDoc} * * @see org.acegisecurity.ui.rememberme.RememberMeServices#autoLogin(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override public Authentication autoLogin(HttpServletRequest request, HttpServletResponse response) { Authentication result = null; List<ValidationFactor> validationFactors = this.configuration.tokenHelper .getValidationFactorExtractor().getValidationFactors(request); // check whether a SSO token is available if (LOG.isLoggable(Level.FINER)) { LOG.finer("Checking whether a SSO token is available..."); } String ssoToken = this.configuration.tokenHelper.getCrowdToken(request, this.configuration.clientProperties.getCookieTokenKey()); // auto-login is only possible when the SSO token was found if (null != ssoToken) { try { // SSO token available => check whether it is still valid if (LOG.isLoggable(Level.FINER)) { LOG.finer("SSO token available => check whether it is still valid..."); } this.configuration.crowdClient.validateSSOAuthentication( ssoToken, validationFactors); // retrieve the user that is logged in via SSO if (LOG.isLoggable(Level.FINER)) { LOG.finer("Retrieving SSO user..."); } User user = this.configuration.crowdClient .findUserFromSSOToken(ssoToken); // check whether the user is a member of the user group in Crowd // that specifies who is allowed to login into Hudson / Jenkins if (LOG.isLoggable(Level.FINER)) { LOG.finer("Validating group membership of user..."); } if (this.configuration.isGroupActive() && this.configuration.isGroupMember(user.getName())) { // user is authenticated and validated // => create the user object and finalize the auto-login // process List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); authorities.add(SecurityRealm.AUTHENTICATED_AUTHORITY); authorities.addAll(this.configuration .getAuthoritiesForUser(user.getName())); result = new CrowdAuthenticationToken(user.getName(), null, authorities, ssoToken, user.getDisplayName()); } } catch (InvalidTokenException ex) { // LOG.log(Level.INFO, invalidToken(), ex); } catch (ApplicationPermissionException ex) { LOG.warning(applicationPermission()); } catch (InvalidAuthenticationException ex) { LOG.warning(invalidAuthentication()); } catch (OperationFailedException ex) { LOG.log(Level.SEVERE, operationFailed(), ex); } } return result; } /** * {@inheritDoc} * * @see org.acegisecurity.ui.rememberme.RememberMeServices#loginFail(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override public void loginFail(HttpServletRequest request, HttpServletResponse response) { try { if (LOG.isLoggable(Level.FINE)) { LOG.fine("Login failed"); } this.configuration.crowdHttpAuthenticator.logout(request, response); } catch (ApplicationPermissionException ex) { LOG.warning(applicationPermission()); } catch (InvalidAuthenticationException ex) { LOG.warning(invalidAuthentication()); } catch (OperationFailedException ex) { LOG.log(Level.SEVERE, operationFailed(), ex); } } /** * {@inheritDoc} * * @see org.acegisecurity.ui.rememberme.RememberMeServices#loginSuccess(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse, * org.acegisecurity.Authentication) */ @Override public void loginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) { if (!(successfulAuthentication instanceof CrowdAuthenticationToken)) { // authentication token doesn't belong to us... return; } CrowdAuthenticationToken crowdAuthenticationToken = (CrowdAuthenticationToken) successfulAuthentication; List<ValidationFactor> validationFactors = this.configuration.tokenHelper .getValidationFactorExtractor().getValidationFactors(request); // check if there's already a SSO token in the authentication object String ssoToken = crowdAuthenticationToken.getSSOToken(); try { if (null == ssoToken) { // SSO token not yet available => authenticate the user and // create the SSO token if (LOG.isLoggable(Level.FINE)) { LOG.fine("SSO token not yet available => authenticate user..."); } this.configuration.crowdHttpAuthenticator.authenticate(request, response, crowdAuthenticationToken.getPrincipal(), crowdAuthenticationToken.getCredentials()); // user is successfully authenticated // => retrieve the SSO token if (LOG.isLoggable(Level.FINER)) { LOG.finer("Retrieve SSO token..."); } ssoToken = this.configuration.tokenHelper .getCrowdToken(request, this.configuration.clientProperties .getCookieTokenKey()); } if (null == ssoToken) { // SSO token could not be retrieved (should normally not happen) // => logout loginFail(request, response); return; } // validate the SSO authentication if (LOG.isLoggable(Level.FINE)) { LOG.fine("Validate the SSO authentication..."); } this.configuration.crowdClient.validateSSOAuthentication(ssoToken, validationFactors); // alright, we're successfully authenticated via SSO if (LOG.isLoggable(Level.FINE)) { LOG.fine("Successfully authenticated via SSO"); } } catch (InvalidTokenException ex) { // LOG.log(Level.INFO, invalidToken(), ex); } catch (ApplicationPermissionException ex) { LOG.warning(applicationPermission()); } catch (InvalidAuthenticationException ex) { LOG.warning(invalidAuthentication()); } catch (ExpiredCredentialException ex) { LOG.warning(expiredCredentials(crowdAuthenticationToken .getPrincipal())); } catch (InactiveAccountException ex) { LOG.warning(accountExpired(crowdAuthenticationToken.getPrincipal())); } catch (ApplicationAccessDeniedException ex) { LOG.warning(applicationAccessDenied(crowdAuthenticationToken .getPrincipal())); } catch (OperationFailedException ex) { LOG.log(Level.SEVERE, operationFailed(), ex); } } /** * Logout the actual user and close the SSO session. * * @param request * The servlet request. May not be <code>null</code>. * @param response * The servlet response. May not be <code>null</code>. */ public void logout(HttpServletRequest request, HttpServletResponse response) { try { // logout the user and close the SSO session if (LOG.isLoggable(Level.FINE)) { LOG.fine("Logout user and close SSO session"); } this.configuration.crowdHttpAuthenticator.logout(request, response); } catch (ApplicationPermissionException ex) { LOG.warning(applicationPermission()); } catch (InvalidAuthenticationException ex) { LOG.warning(invalidAuthentication()); } catch (OperationFailedException ex) { LOG.log(Level.SEVERE, operationFailed(), ex); } } }
package de.htwberlin.liar.activities; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Observable; import java.util.Observer; import java.util.UUID; import com.neurosky.thinkgear.TGDevice; import android.app.LoaderManager; import android.app.LoaderManager.LoaderCallbacks; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.CursorLoader; import android.content.DialogInterface; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import de.htwberlin.liar.R; import de.htwberlin.liar.database.LiarContract.Questions; import de.htwberlin.liar.game.Game; import de.htwberlin.liar.game.Game.Phase; import de.htwberlin.liar.model.GameInfo; import de.htwberlin.liar.utils.ConnectedThread; import de.htwberlin.liar.utils.Constants; import de.htwberlin.liar.utils.DialogUtil; import de.htwberlin.liar.utils.MatheBerechnungen; /** * This class handels the game screen. */ public class GameActivity extends LiarActivity implements Observer, LoaderCallbacks<Cursor>{ private static final double LIE_FACTOR_0_1 = 0.1; /**The class containing the business logic of teh game*/ private Game game; /**Container with the yes/no buttons*/ private View mAnswerButtonContainer; /**The Button for the next question or to switch to the {@link ScoreActivity}*/ private Button mNextButton; /**The yes button for an answer*/ private View mYesButton; /**The yes no for an answer*/ private View mNoButton; /**The view showing the current and max rounds*/ private TextView mRoundsTextView; /**The view with the current player*/ private TextView mCurrentPlayerTextView; /**The view with the question or other informations*/ private TextView mQuestionTextView; private UUID gameId; /**The projection for the {@link LoaderManager}*/ private String[] projection = { Questions.QUESTION_ID, Questions.QUESTION }; /** * Sets the layout and calls {@link #setUp()}. */ private static final String TAG = "bluetooth2"; private static final int BLUETOOTH_INTENT_CODE = 2; private static final String YOUR_ATTENTION = "Ihre Aufmerksamkeit"; private static final String YOUR_MEDITATION = "Ihre Meditation"; private static final String YOUR_BLINKS = "Ihre Blinzler"; private static final String YOUR_GALVANIC = "Ihre Hautleitfhigkeit"; //the blink counter from eeg int blinkCounter; //A string to output the galvanic value String sbprint = ""; //array for compute the standard derivation private static final int ARRAYLENGTH = 10; int[] std_att, std_med, std_resis; //Status zum Datensameln private boolean enabled_attention, enabled_meditation, enabled_blinks, enabled_galvanic; private int attentionArrayCounter, meditationArrayCounter, galvanicArrayCounter; //result for specified standard derivation double std_res_att, std_res_med, std_res_resis; double after_calib_att, after_calib_med, after_calib_resis, after_calib_blinks; //Status for handler public final int RECIEVE_MESSAGE = 1; //Bluetooth adapter private BluetoothAdapter galvanicAdapter; private BluetoothAdapter eegAdapter; //Bluetooth socket private BluetoothSocket galvanicBtSocket = null; //Use a stringbuilder for performance. private StringBuilder sb = new StringBuilder(); //Thread which handles the connections. private ConnectedThread mConnectedThread; //the well known UUID for Bluetooth Connections private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // Change this adress to your device mac - the mac from your arduino bt shield // linvor address 00:12:07:17:18:24 private static String ADDRESS = "00:12:07:17:18:24"; //BluetoothDevice galvanic skin BluetoothDevice galvanicBtDevice; //TGDevice is used for pairing to myndplay eeg TGDevice tgDevice; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.game_screen_layout); setUp(); Bundle extras = getIntent().getExtras(); if(extras != null && extras.containsKey(Constants.GAME_ID)){ gameId = UUID.fromString(extras.getString(Constants.GAME_ID)); } /* * neue Variablen fuer die Activity: * hierbei handelt es sich um die Arrays zur Berechnung der Standardabweichungen fuer * Attention, Meditation und Blinzler (alle EEG) und des Widerstands vom Galvanic * */ std_att = new int[ARRAYLENGTH]; arrayLeeren(std_att, ARRAYLENGTH); std_med = new int[ARRAYLENGTH]; arrayLeeren(std_med, ARRAYLENGTH); std_resis = new int[ARRAYLENGTH]; arrayLeeren(std_resis, ARRAYLENGTH); enabled_attention = false; enabled_meditation = false; enabled_blinks = false; enabled_galvanic = false; //Zaehler fr die Durchlaeufe durch die Wertearray attentionArrayCounter = 0; meditationArrayCounter = 0; galvanicArrayCounter = 0; //ein Zaehler fuer die Augenblinzler - wird auch verwendet blinkCounter = 0; /* * Die Resultate aus der Berechnung der Standardabweichung fuer: * std_res_att = Attention (EEG) * std_res_med = Meditation (EEG) * std_res_blinks = Blinks (EEG) * std_res_resis = Widerstand (Galvanic) */ std_res_att = 0.0; std_res_med = 0.0; std_res_resis = 0.0; /* * jetzt kommen ein paar Speicherobjekte fuer nach der Kalibrierung */ after_calib_att = 0.0; after_calib_med =0.0; after_calib_resis = 0.0; after_calib_blinks = 0; galvanicAdapter = BluetoothAdapter.getDefaultAdapter(); eegAdapter = BluetoothAdapter.getDefaultAdapter(); if(eegAdapter != null){ Log.d(TAG, "... the EEG Address is correct..."); //Check the bluetooth state. checkBTState(); } } @Override public void update(Observable observable, Object data) { if(!(data instanceof Game.Phase)){ throw new IllegalArgumentException("Observer received unknown data. Data is not of type Game.Phase."); } Game.Phase phase = (Game.Phase) data; switch (phase) { case ANSWER: showQuestion(); break; case GAME_END: mNextButton.setText(getString(R.string.go_to_score)); mNextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent nextActivity = new Intent(GameActivity.this, ScoreActivity.class); nextActivity.putExtra(Constants.GAME_ID, gameId.toString()); startActivity(nextActivity); } }); break; default: throw new IllegalStateException("No matching Phase found."); } } /** * Creates a new {@link CursorLoader}, when the loader is created. */ @Override public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) { String selection = ""; return new CursorLoader(getApplicationContext(), Questions.CONTENT_URI, projection, selection, null, null); } /** * Gets all Questions to Set up the game. Enables the yes and no button and starts the game. */ @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { List<String> questions = new ArrayList<String>(); while (cursor.moveToNext()) { final int index = cursor.getColumnIndexOrThrow(Questions.QUESTION); String question = cursor.getString(index); questions.add(question); } setUpGame(questions); mYesButton.setEnabled(true); mNoButton.setEnabled(true); game.next(); } /** * Does nothing. */ @Override public void onLoaderReset(Loader<Cursor> arg0) { //Noting to do here } /** * When back button is pressed asked if the game should be stopped. If so, * go back to the {@link StartActivity} an remove other Acivities from the stack. * If not, does nothing. */ @Override public void onBackPressed() { DialogUtil.showConfirmDialog(this, R.string.back_to_tile, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Intent intent = new Intent(GameActivity.this, StartActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); dialog.dismiss(); } }); } /** * Calls {@link #setUpDisplays()} and initializes the {@link LoaderManager}. */ private void setUp() { setUpDisplays(); LoaderManager lm = getLoaderManager(); lm.initLoader(Constants.QUESTION_LOADER_ID, null, this); } /** * Creates the {@link Game} objects for this class. Also adds this class as * {@link Observer} for the game. * * @param questions the list of questions to choose from in this game */ private void setUpGame(List<String> questions) { GameInfo info = (GameInfo) getIntent().getParcelableExtra(GameInfo.TYPE); game = new Game(info.getPlayers(), questions, info.getRounds(), getApplicationContext()); game.addObserver(this); } /** * Sets up all the {@link View}s and adds listeners to the button to processed. */ private void setUpDisplays() { mRoundsTextView = (TextView) findViewById(R.id.game_screen_rounds_label); mCurrentPlayerTextView = (TextView) findViewById(R.id.game_screen_current_player_display); mQuestionTextView = (TextView) findViewById(R.id.game_screen_question_text); mAnswerButtonContainer = findViewById(R.id.game_screen_answer_button_container); mNextButton = (Button) findViewById(R.id.game_screen_next_question_button); mNextButton.setVisibility(View.GONE); mNextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { game.next(); } }); mYesButton = findViewById(R.id.game_screen_yes_button); mYesButton.setEnabled(false); mYesButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { answerQuestion(true); } }); mNoButton = findViewById(R.id.game_screen_no_button); mNoButton.setEnabled(false); mNoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { answerQuestion(false); } }); } /** * Adds the question to the question view and also updates the other views, which * show the games state. */ private void showQuestion() { mAnswerButtonContainer.setVisibility(View.VISIBLE); mNextButton.setVisibility(View.GONE); mRoundsTextView.setText(getString(R.string.round)+ " " + game.getRound() + "/" + game.getMaxQuestions()); mCurrentPlayerTextView.setText(game.getPlayer().getName()); mQuestionTextView.setText(game.getQuestion()); }; /** * Called when answered a question with the yes or no button. * Forwards the answer to the game, gets the result and updates the views as informations for teh user. * The answer button container will be hidden and the next button will appear. * * @param answer */ private void answerQuestion(boolean answer){ mAnswerButtonContainer.setVisibility(View.GONE); mNextButton.setVisibility(View.VISIBLE); boolean result = game.answerQuestion(answer); String resultString = (result) ? getString(R.string.truth) : getString(R.string.lie); resultString = game.getPlayer().getName() + ", " + String.format(getString(R.string.result_text_for_question), resultString); mCurrentPlayerTextView.setText(resultString); } /** * simpliest way to empty an array * @param array the array * @param length the length ot the array */ private void arrayLeeren(int array[], int length){ for(int i = 0; i < length; i++){ array[i] = 0; } } /** * Methode baut eine Bluetooth-Verbindung zwischen dem EEG und dem Smartphone auf. Dazu wird auf * den globalen Bluetooth-Adapter zugegriffen und deren Inhalt ueberprueft. Zur Connection wird * ausserdem das TGdevice aus lib/ThinkGear.jar verwendet. Die Bibliothek ist ein Blackbox - daher * keine Ahnung was dadrin passiert! Good Luck ^^ */ private void setupEegBluetooth(){ eegAdapter.startDiscovery(); Toast.makeText(this, "Create new TGDevice...", Toast.LENGTH_LONG).show(); tgDevice = new TGDevice(eegAdapter, eegHandler); Log.d(TAG, "...TGDevice initialized:...");//+tgDevice.getConnectedDevice().toString()); tgDevice.connect(true); tgDevice.start(); eegAdapter.cancelDiscovery(); } /** * try to build a galvanic connection */ private void setupGalvanicBluetooth(){ galvanicBtDevice = galvanicAdapter.getRemoteDevice(ADDRESS); try { galvanicBtSocket = createBluetoothSocket(galvanicBtDevice); } catch (final IOException e) { Log.e(TAG, e.getMessage()); exitWithErrorMessage("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + "."); } //Cancel discovery because it need to much ressources galvanicAdapter.cancelDiscovery(); // Establish the connection. This will block until it connects. Log.d(TAG, "...Connecting..."); try { galvanicBtSocket.connect(); // debuggingText.setText("Galvanic Connected\n"+debuggingText.getText()); Log.d(TAG, "....Connection ok..."); } catch (final IOException e) { Log.e(TAG, e.getLocalizedMessage()); try { galvanicBtSocket.close(); } catch (final IOException e2) { Log.e(TAG, e2.getMessage()); exitWithErrorMessage("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + "."); } } // Create a data stream so we can talk to server. Log.d(TAG, "...Create Socket..."); if (galvanicBtSocket != null) { mConnectedThread = new ConnectedThread(galvanicBtSocket, gsHandler, RECIEVE_MESSAGE); mConnectedThread.start(); } } /** * on destroy disconnect all connection to any devices, e.g. bluetooth devices */ @Override public void onDestroy() { try { tgDevice.close(); galvanicBtSocket.close(); } catch (IOException e) { e.printStackTrace(); } super.onDestroy(); } /** * Check for Bluetooth support and then check to make sure it is turned on */ private void checkBTState() { if (eegAdapter == null) { Log.e(TAG, "Bluetooth adapter is null"); exitWithErrorMessage("Fatal Error", "Bluetooth not support"); } else { if (eegAdapter.isEnabled()) { Log.d(TAG, "...Bluetooth ON..."); //start the device connections Log.d(TAG, "...Start Galvanic Bluetooth..."); //setup galvanic connection setupGalvanicBluetooth(); Log.d(TAG, "...Start EEG Bluetooth..."); //setup bluetooth connection setupEegBluetooth(); } else { Log.d(TAG, "... Start Bluetooth ..."); // If bluetooth is not enabled start the activity final Intent enableBtIntent = new Intent( BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, BLUETOOTH_INTENT_CODE); } } } /** * Make a toast with a title and a message, e.g. for ERROR-Messages * @param title The title for the toast. * @param message The message for the toast. */ private void exitWithErrorMessage(String title, String message) { Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show(); finish(); } /** * Handles messages from arduino and for updating the ui by incomming bytes and computing * if the testing person is a liar or not! */ private final Handler gsHandler = new Handler() { public void handleMessage(android.os.Message msg) { //int counter = 0; switch (msg.what) { case RECIEVE_MESSAGE: // if receive massage byte[] readBuf = (byte[]) msg.obj; String strIncom = new String(readBuf, 0, msg.arg1); //create string from bytes //Log.d(TAG, "the incoming String: "+strIncom); sb.append(strIncom); // append string to stringbuilder sb int startOfValueIndex = sb.indexOf(";"); //Log.d(TAG, "my start of Value index: "+startOfValueIndex); int endOfValueIndex_1 = sb.indexOf("\r\n"); // determine the end-of-line //Log.d(TAG, "my end of Value index 1: "+endOfValueIndex_1); int endOfValueIndex_2 = sb.indexOf(" "); //Log.d(TAG, "my end of Value index 2: "+endOfValueIndex_2); if (endOfValueIndex_1 > startOfValueIndex) { // if end-of-line, sbprint = sb.substring(startOfValueIndex+1, endOfValueIndex_1);// extract string sb.delete(0, sb.length()); // and clear } else if(endOfValueIndex_2 > startOfValueIndex) { sbprint = sb.substring(startOfValueIndex+1, endOfValueIndex_2); sb.delete(0, sb.length()); // and clear } else { break; } /* * hier war eine Ueberpruefung durch die Standardabweichung erwuenscht * * nur solange wie der Counter < 10 (ARRAYLENGTH) ist, wird das Array mit den aktuellen Daten * versorgt, sonst wird die Standardabweichung fuer genau dieses Array berechnet und in der *_res_* * Variable gespeichert */ // if(enabled_galvanic){ // if(galvanicArrayCounter >=0 && galvanicArrayCounter < ARRAYLENGTH){ // MatheBerechnungen.werteSichern(galvanicArrayCounter, std_resis, Integer.valueOf(sbprint), TAG); // galvanicArrayCounter += 1; // } else { // galvanicArrayCounter = 0; // std_res_resis = MatheBerechnungen.standardAbweichung(std_resis); // enabled_galvanic = false; // Log.d(TAG, "End of enabled_galvanic"); // gs_std_resis.setText(""); // gs_std_resis.setText("Data from Arduino: " + sbprint); // update TextView sbprint = ""; Log.d(TAG, "...String:" + sb.toString() + "Byte:" + msg.arg1 + "..."); break; } }; }; /** * Handles messages from TGDevice * Es wird ein neuer Handler "eegHandler" erzeugt, der die reinkommenden Daten interpretiert und * entsprechend weitere Befehle ausfuehrt oder (zu fast 100% in unserem Fall) die Daten ausgibt bzw. * in ein Array schreibt */ private final Handler eegHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case TGDevice.MSG_STATE_CHANGE: switch (msg.arg1) { case TGDevice.STATE_IDLE: break; case TGDevice.STATE_CONNECTING: // eeg_std_att.setText("Connecting...\n"+eeg_std_att.getText()); break; case TGDevice.STATE_CONNECTED: // eeg_std_att.setText("Connected.\n" + eeg_std_att.getText()); tgDevice.start(); break; case TGDevice.STATE_NOT_FOUND: // eeg_std_att.setText("Can't find\n" + eeg_std_att.getText()); break; case TGDevice.STATE_NOT_PAIRED: // eeg_std_att.setText("not paired\n" + eeg_std_att.getText()); break; case TGDevice.STATE_DISCONNECTED: // eeg_std_att.setText("Disconnected ...\n" + eeg_std_att.getText()); } break; case TGDevice.MSG_ATTENTION: //Ausfuehrung der Sicherung der Attentionwerte im std_att-Array und ggf. STD-Berechnung //gleiches vorgehen wie bei den Galvanic Skin Werten if(enabled_attention){ if(attentionArrayCounter >=0 && attentionArrayCounter < ARRAYLENGTH){ MatheBerechnungen.werteSichern(attentionArrayCounter, std_att, Integer.valueOf(msg.arg1), TAG); //is msg.arg1 still an integer? attentionArrayCounter += 1; } else { attentionArrayCounter = 0; std_res_att = MatheBerechnungen.standardAbweichung(std_att); Log.d("STD Attention", "Der Wert: "+std_res_att); enabled_attention = false; Log.d(TAG, "End of enabled_attention"); } } // eeg_std_att.setText("Attention: " + msg.arg1 + "\n" + eeg_std_att.getText()); break; case TGDevice.MSG_MEDITATION: //Ausfuehrung der Sicherung der Attentionwerte im std_med-Array und ggf. STD-Berechnung //gleiches vorgehen wie bei den Galvanic Skin Werten if(enabled_meditation){ if(meditationArrayCounter >=0 && meditationArrayCounter < ARRAYLENGTH){ MatheBerechnungen.werteSichern(meditationArrayCounter, std_med, Integer.valueOf(msg.arg1),TAG); //is msg.arg1 still an integer? meditationArrayCounter += 1; } else { meditationArrayCounter = 0; std_res_med = MatheBerechnungen.standardAbweichung(std_med); Log.d("STD Meditation", "Der Wert: "+std_res_med); enabled_meditation = false; Log.d(TAG, "End of enabled_meditation"); } } // eeg_std_medit.setText("Meditation: " + msg.arg1 + "\n" + eeg_std_medit.getText()); break; case TGDevice.MSG_BLINK: // hier wird der Blinzel-Counter erhoeht, toll, was !? ^^ if(enabled_blinks){ blinkCounter += 1; if(!enabled_attention && !enabled_meditation){ enabled_blinks = false; } Log.d("Blinks", "Der Wert: "+blinkCounter); } // eeg_blink_counts.setText("Anzahl: " + blinkCounter); break; case TGDevice.MSG_LOW_BATTERY: Toast.makeText(getApplicationContext(), "Low battery!", Toast.LENGTH_SHORT).show(); break; default: break; } } }; /** * Create a bluetoothsocket from a given device * * @param device * @return Returns a bluetooth socket.. * @throws IOException */ private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException { if (Build.VERSION.SDK_INT >= 10) { try { final Method m = device.getClass().getMethod( "createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class }); return (BluetoothSocket) m.invoke(device, MY_UUID); } catch (Exception e) { Log.e(TAG, "Could not create Insecure RFComm Connection", e); } } return device.createRfcommSocketToServiceRecord(MY_UUID); } @Override protected void onActivityResult (int requestCode, int resultCode, Intent data){ super.onActivityResult(requestCode, resultCode, data); //setup bluetooth connection switch (requestCode) { case BLUETOOTH_INTENT_CODE: setupGalvanicBluetooth(); setupEegBluetooth(); break; default: break; } } /** * the method theHonestSkin checks all calculated standard derivation to the calibrated values and computes a result (truth or lie) * and checks whether three of the lies are true to give out a true (it's a liar) or false (no it's an hones player) * @return true (liar) or false (honest skin) */ private boolean theHonestSkin(){ boolean liar = false; boolean att_lie = false; if(std_res_att <= (after_calib_att += after_calib_att*LIE_FACTOR_0_1)){ att_lie = false; }else{ att_lie = true; } boolean med_lie = false; if(std_res_med <= (after_calib_med += after_calib_med*LIE_FACTOR_0_1)){ med_lie = false; }else{ med_lie = true; } boolean res_lie = false; if(std_res_resis <= (after_calib_resis += after_calib_resis*LIE_FACTOR_0_1)){ res_lie = false; }else{ res_lie = true; } boolean blinks_lie = false; if(blinkCounter <= after_calib_blinks){ blinks_lie = false; }else{ blinks_lie = true; } if((att_lie && med_lie && res_lie) || (att_lie && med_lie && blinks_lie) || (att_lie && res_lie && blinks_lie) || (med_lie && res_lie && blinks_lie)){ liar = true; } return liar; } }
package desutine.kismet.target; import com.google.common.collect.ImmutableList; import com.google.gson.*; import com.google.gson.reflect.TypeToken; import desutine.kismet.Kismet; import desutine.kismet.ModLogger; import desutine.kismet.server.WSDTargetDatabase; import desutine.kismet.util.StackHelper; import net.minecraft.block.Block; import net.minecraft.block.BlockEmptyDrops; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.FurnaceRecipes; import net.minecraft.nbt.JsonToNBT; import net.minecraft.nbt.NBTException; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.TextComponentString; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraft.world.storage.loot.*; import net.minecraft.world.storage.loot.conditions.LootCondition; import net.minecraft.world.storage.loot.conditions.LootConditionManager; import net.minecraft.world.storage.loot.functions.LootFunction; import net.minecraft.world.storage.loot.functions.LootFunctionManager; import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.common.util.FakePlayerFactory; import net.minecraftforge.oredict.OreDictionary; import java.util.*; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.IntStream; public class TargetDatabaseBuilder { // "based" on LootTableManager's Gson // note: using custom Serializer for LootEntry because of vanilla bug private static final Gson gson = (new GsonBuilder()) .registerTypeAdapter(RandomValueRange.class, new RandomValueRange.Serializer()) .registerTypeAdapter(LootPool.class, new LootPool.Serializer()) .registerTypeAdapter(LootTable.class, new LootTable.Serializer()) .registerTypeHierarchyAdapter(LootEntry.class, new LootEntrySerializerFix()) .registerTypeHierarchyAdapter(LootFunction.class, new LootFunctionManager.Serializer()) .registerTypeHierarchyAdapter(LootCondition.class, new LootConditionManager.Serializer()) .registerTypeHierarchyAdapter(LootContext.EntityTarget.class, new LootContext.EntityTarget.Serializer()) .create(); private WSDTargetDatabase WSDTargetDatabase; private Queue<List<InformedStack>> remainingPackets = new ArrayDeque<>(); public TargetDatabaseBuilder(WorldServer world) { WSDTargetDatabase = desutine.kismet.server.WSDTargetDatabase.get(world); } /** * Generates the target lists within the game. * * @param player The player entity to use to enrich the state */ public void generateStacks(EntityPlayerMP player) { player.addChatMessage(new TextComponentString("[Kismet] Starting target library reset...")); WSDTargetDatabase = desutine.kismet.server.WSDTargetDatabase.get(player.worldObj); WSDTargetDatabase.setStacks(new HashMap<>()); Map<String, InformedStack> stacks = getRegisteredItems(); identifyLoot(player.getServerForPlayer(), stacks); identifyBlockDrops(player.worldObj, stacks); // separate the stacks per mod, for smaller packets final HashMap<String, List<InformedStack>> modSortedStacks = new HashMap<>(); for (InformedStack wrapper : stacks.values()) { String mod = StackHelper.getMod(wrapper); if (!modSortedStacks.containsKey(mod)) { final ArrayList<InformedStack> wrappers = new ArrayList<>(); wrappers.add(wrapper); modSortedStacks.put(mod, wrappers); } else { modSortedStacks.get(mod).add(wrapper); } } remainingPackets.addAll(modSortedStacks.values()); sendNextPacket(player); } private static void identifyBlockDrops(World world, Map<String, InformedStack> stacks) { // let's now try to get worldgen in this VERY hackish way: final Set<String> drops = new HashSet<>(); final Set<String> silkDrops = new HashSet<>(); final FakePlayer fakePlayer = FakePlayerFactory.getMinecraft((WorldServer) world); Block.blockRegistry.forEach(block -> { // only deals with the bedrock edge case but alas if (block instanceof BlockEmptyDrops) return; final ImmutableList<IBlockState> validStates = block.getBlockState().getValidStates(); for (IBlockState state : validStates) { // check their drops (including if it is silk harvestable) drops.addAll(getDropsFromState(world, fakePlayer, block, state)); // test for silk touchness if (block.canSilkHarvest(world, BlockPos.ORIGIN, state, fakePlayer)) { silkDrops.addAll(getSilkDrops(block, state)); } } }); // set all of these as obtainable drops.forEach(addToStackMap(stacks, InformedStack.ObtainableTypes.Mineable)); silkDrops.forEach(addToStackMap(stacks, InformedStack.ObtainableTypes.Silkable)); } private static Set<String> getDropsFromState(World world, FakePlayer fakePlayer, Block block, IBlockState state) { Set<String> drops = new HashSet<>(); // if the block is unbreakable in this state, don't even bother if (block.getBlockHardness(state, world, BlockPos.ORIGIN) < 0) return drops; // a state machine that loops around while it adds new items to the drops int size = drops.size(); int chances = 20; do { // assuming fortune 5 to get the best drops // hoping the block doesn't do stuff diff with lesser fortunes... // fixme assume the worse described above and test for diff fortunes try { drops.addAll(block.getDrops(world, BlockPos.ORIGIN, state, 5).stream() .map(StackHelper::toUniqueKey) .collect(Collectors.toList())); } catch (Exception e) { ModLogger.error("Error while gathering blocks for " + StackHelper.toUniqueKey(new ItemStack(block)) + state, e); continue; } if (size != drops.size()) { size = drops.size(); chances = 20; } } while (--chances > 0); return drops; } /** * Gets the silk touch drop for this block, under state. * Note: function doesn't check if the block+state is actually silk touchable. * * @param block * @param state * @return A String set of the unique keys for the drops */ private static Set<String> getSilkDrops(Block block, IBlockState state) { Set<String> drops = new HashSet<>(); ItemStack silkDrop = block.createStackedBlock(state); // Class<?> currentClass = block.getClass(); // try while we don't have Block.class // while (currentClass != null && Block.class.isAssignableFrom(currentClass)) { // Method silkDrops = null; // try { // // as the method is protected, I'll "just" access it with reflection // silkDrops = currentClass.getDeclaredMethod("createStackedBlock", IBlockState.class); // } catch (SecurityException e) { // // no access to the class, abort // ModLogger.error("", e); // break; // } catch (NoSuchMethodException ignored) { // if (silkDrops != null) { // try { // silkDrops.setAccessible(true); // silkDrop = (ItemStack) silkDrops.invoke(block, state); // // if we reached here, the function was sucessfully invoked // // so we can break the loop and see what we got // break; // // no access to the method, or state is not correctly setup, abort // ModLogger.error("", e); // break; // // loop hasn't terminated, so let's go up one level and try again // currentClass = currentClass.getSuperclass(); if (silkDrop != null) drops.add(StackHelper.toUniqueKey(silkDrop)); return drops; } private static Map<String, InformedStack> getRegisteredItems() { final HashMap<String, InformedStack> stacks = new HashMap<>(); // add stacks from ItemRegistery for (ResourceLocation loc : Item.itemRegistry.getKeys()) { Item item = Item.itemRegistry.getObject(loc); ItemStack stack = new ItemStack(item); if (stack.getItem() == null) continue; stack.setItemDamage(OreDictionary.WILDCARD_VALUE); final InformedStack wrapper = new InformedStack(stack); stacks.put(wrapper.toString(), wrapper); } return stacks; } /** * @param world * @param stacks * @return Number of new items added from the loot system */ private static int identifyLoot(WorldServer world, Map<String, InformedStack> stacks) { final int oldSize = stacks.size(); final LootTableManager lootTableManager = world.getLootTableManager(); final List<LootTable> allTables = LootTableList.getAll().stream() .map(lootTableManager::getLootTableFromLocation) .collect(Collectors.toList()); // iterate down the JSON tree and fetch what items we can see final Set<String> loots = iterateLootJsonTree(allTables); // add them to the hashed map, trying to avoid replacing already existing stacks loots.forEach(addToStackMap(stacks, InformedStack.ObtainableTypes.Lootable)); return stacks.size() - oldSize; // FluidRegistry.getBucketFluids(); // UniversalBucket.getFilledBucket() } private static Consumer<String> addToStackMap(Map<String, InformedStack> stacks, InformedStack.ObtainableTypes type) { return key -> { ItemStack stack = TargetLibraryBuilder.getItemStack(key); if (stack != null && stack.getItem() != null) { InformedStack wrapper = new InformedStack(stack, type); wrapper.setHasSubtypes(true); if (stacks.containsKey(key)) { stacks.get(key).setObtainable(type, true); } else { stacks.put(key, wrapper); } } }; } private static Set<String> iterateLootJsonTree(List<LootTable> allTables) { Set<String> items = new HashSet<>(); // iterating down the JSON tree~ for (LootTable aTable : allTables) { final JsonObject table = gson.toJsonTree(aTable, new TypeToken<LootTable>() { }.getType()).getAsJsonObject(); JsonArray pools = table.getAsJsonArray("pools"); for (JsonElement aPool : pools) { JsonArray entries = aPool.getAsJsonObject().getAsJsonArray("entries"); for (JsonElement anEntry : entries) { JsonObject entry = anEntry.getAsJsonObject(); // we only want to deal with item-type entries if (!entry.get("type").getAsString().equals("item")) continue; getItemsFromLootEntry(items, entry); } } } return items; } private static void getItemsFromLootEntry(Set<String> items, JsonObject entry) { final String name = entry.get("name").getAsString(); Set<String> variants = new HashSet<>(); variants.add(name); List<Integer> metaValues = new ArrayList<>(); int maxCount = 1; int maxAddCount = 0; NBTTagCompound nbt = null; if (entry.has("functions")) { for (JsonElement aFunction : entry.get("functions").getAsJsonArray()) { JsonObject function = aFunction.getAsJsonObject(); switch (function.get("function").getAsString()) { case "minecraft:furnace_smelt": // change the item to be the smelted version ItemStack stack = TargetLibraryBuilder.getItemStack(name); final ItemStack smeltedStack = FurnaceRecipes.instance().getSmeltingResult(stack); variants.add(StackHelper.toUniqueKey(smeltedStack)); break; case "minecraft:looting_enchant": JsonElement count = function.get("count"); if (count.isJsonObject()) { JsonObject countRange = count.getAsJsonObject(); maxAddCount = countRange.get("max").getAsInt() * 3; } else { maxAddCount = count.getAsInt() * 3; } break; case "minecraft:set_count": count = function.get("count"); if (count.isJsonObject()) { JsonObject countRange = count.getAsJsonObject(); maxCount = countRange.get("max").getAsInt(); } else { maxCount = count.getAsInt(); } break; case "minecraft:set_data": JsonElement data = function.get("data"); if (data.isJsonObject()) { JsonObject dataRange = data.getAsJsonObject(); int min = dataRange.get("min").getAsInt(); int max = dataRange.get("max").getAsInt(); // max is inclusive IntStream.range(min, max + 1).forEach(metaValues::add); } else { int meta = data.getAsInt(); metaValues.add(meta); } break; case "minecraft:set_nbt": JsonElement tag = function.get("tag"); try { nbt = JsonToNBT.getTagFromJson(tag.getAsString()); } catch (NBTException e) { ModLogger.warning(e); } break; case "minecraft:enchant_randomly": case "minecraft:enchant_with_levels": case "minecraft:set_damage": // ignored break; default: ModLogger.warning("Loot tables: unknown function, " + function.get("function").getAsString()); break; } } } if (maxCount + maxAddCount <= 0) { ModLogger.warning("Loot tables: empty drop," + name + ":" + (maxCount + maxAddCount)); return; } // add meta=0 if we didn't get any data if (metaValues.isEmpty()) metaValues.add(0); // for each data values, add the item string (+nbt if any) for (String variant : variants) { for (int meta : metaValues) { items.add(String.format("%s:%d%s", variant, meta, nbt != null ? ":" + nbt.toString() : "")); } } } public boolean sendNextPacket(EntityPlayerMP player) { if (remainingPackets == null || remainingPackets.isEmpty()) return false; final List<InformedStack> toSend = remainingPackets.poll(); if (toSend == null) return false; Kismet.network.enrichStacks(toSend, player); return true; } public void recreateLibrary() { if (WSDTargetDatabase == null) return; TargetLibraryBuilder.recreateLibrary(WSDTargetDatabase.getStacks()); } }
package edu.stanford.prpl.junction.impl; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smackx.muc.MultiUserChat; import org.jivesoftware.smackx.muc.RoomInfo; import org.json.JSONException; import org.json.JSONObject; import edu.stanford.prpl.junction.api.activity.ActivityDescription; import edu.stanford.prpl.junction.api.activity.JunctionActor; import edu.stanford.prpl.junction.api.messaging.MessageHandler; import edu.stanford.prpl.junction.api.messaging.MessageHeader; public class JunctionMaker { private String mSwitchboard; public static JunctionMaker getInstance(String switchboard) { // todo: singleton per-URL? return new JunctionMaker(switchboard); } public static JunctionMaker getInstance() { return new JunctionMaker(); } protected JunctionMaker() { } protected JunctionMaker(String switchboard) { mSwitchboard=switchboard; } public Junction newJunction(URI uri, JunctionActor actor) { ActivityDescription desc = new ActivityDescription(); desc.setHost(uri.getHost()); if (uri.getPath() != null) { // TODO: check to make sure this works for URIs w/o path desc.setSessionID(uri.getPath().substring(1)); } return newJunction(desc,actor); } private String getURLParam(String query, String param) { int pos = query.indexOf(param+"="); if (pos < 0) return null; String val = query.substring(pos+1+param.length()); pos = val.indexOf("&"); if (pos > 0) val = val.substring(0,pos); return val; } public Junction newJunction(ActivityDescription desc, JunctionActor actor) { // this needs to be made more formal if (null == desc.getHost() && mSwitchboard != null) { desc.setHost(mSwitchboard); } Junction jx = new Junction(desc); jx.registerActor(actor); if (desc.isActivityCreator()) { String[] roles = desc.getRoles(); for (String role : roles) { JSONObject plat = desc.getRolePlatform(role, "jxservice"); if (plat != null) { // Auto-invite the service via the service factory System.out.println("Auto-requesting service for " + role); inviteActorService(jx,role); // TODO: add a method that takes in a Junction // so we don't have to do an extra lookup /* URI listenerURI = null; try { String listener = "junction://" + plat.getString("switchboard") + "/jxservice"; listenerURI = new URI(listener); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } inviteActorByListenerService(invitationURI, listenerURI); */ } } } // creating an activity is an activity using a JunctionService. // Invite the JunctionMaker service to the session. // This service will be bundled with all Junction servers. //activity.requestService("JunctionMaker", mHostURL, "edu.stanford.prpl.junction.impl.JunctionMakerService"); return jx; } public void inviteActorByListenerService(final URI invitationURI, URI listenerServiceURI) { JunctionActor actor = new JunctionActor("inviter") { @Override public void onActivityJoin() { JSONObject invitation = new JSONObject(); try { invitation.put("activity", invitationURI.toString()); } catch (Exception e) {} getJunction().sendMessageToSession(invitation); leave(); } }; JunctionMaker.getInstance().newJunction(listenerServiceURI, actor); } /** * Requests a listening service to join this activity as the prescribed role. Here, * the service must be detailed in the activity description's list of roles. * * An example platform in the role specification: * { role: "dealer", platforms: [ * { platform: "jxservice", * classname: "edu.stanford.prpl.poker.dealer", * switchboard: "my.foreign.switchboard" } ] } * * If switchboard is not present, it is assumed to be on the same switchboard * on which this activity is being run. * * @param role * @param host * @param serviceName */ // public void inviteActorService(final URI invitationURI) { public void inviteActorService(final Junction jx, final String role) { ActivityDescription desc = jx.getActivityDescription(); System.out.println("Desc: " + desc.getJSON().toString()); // find service platform spec System.out.println("inviting service for role " + role); JSONObject platform = desc.getRolePlatform(role, "jxservice"); System.out.println("got platform " + platform); if (platform == null) return; String switchboard = platform.optString("switchboard"); System.out.println("switchboard: " + switchboard); if (switchboard == null || switchboard.length() == 0) { switchboard = jx.getSwitchboard(); System.out.println("switchboard is null, new: " + switchboard); } final String serviceName = platform.optString("serviceName"); JunctionActor actor = new JunctionActor("inviter") { @Override public void onActivityJoin() { JSONObject invitation = new JSONObject(); try { invitation.put("activity", jx.getInvitationURI(role)); invitation.put("serviceName",serviceName); } catch (Exception e) {} getJunction().sendMessageToSession(invitation); leave(); } }; // remote jxservice activity: URI remoteServiceActivity=null; try { remoteServiceActivity = new URI("junction://"+switchboard+"/jxservice"); } catch (URISyntaxException e) { e.printStackTrace(); return; } System.out.println("Inviting service at uri " + remoteServiceActivity); JunctionMaker.getInstance().newJunction(remoteServiceActivity, actor); } public ActivityDescription getActivityDescription(URI uri) { // TODO: Move the XMPPConnection into the JunctionMaker // (out of Junction) /* JunctionMaker jm = null; String host = uri.getHost(); if (host.equals(mSwitchboard)) { jm = this; } else { jm = new JunctionMaker(host); } */ String host = uri.getHost(); String sessionID = uri.getPath().substring(1); XMPPConnection conn = getXMPPConnection(host); String room = sessionID+"@conference."+host; System.err.println("looking up info from xmpp room " + room); try { RoomInfo info = MultiUserChat.getRoomInfo(conn, room); System.err.println("room desc " + info.getDescription()); System.err.println("room subj " + info.getSubject()); System.err.println("part " + info.getOccupantsCount()); System.err.println("room " + info.getRoom()); String descString = info.getDescription(); if (descString == null || descString.trim().length()==0) return null; JSONObject descJSON = new JSONObject(descString); return new ActivityDescription(descJSON); } catch (XMPPException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; } private XMPPConnection getXMPPConnection(String host) { XMPPConnection mXMPPConnection= new XMPPConnection(host); try { mXMPPConnection.connect(); mXMPPConnection.loginAnonymously(); return mXMPPConnection; } catch (Exception e) { e.printStackTrace(); } return null; } }
package eu.amidst.core.header.statics; import eu.amidst.core.database.statics.readers.Kind; public final class VariableBuilder { private static String name; private static boolean observable; private static int numberOfStates; private static boolean isLeave = false; private static Kind stateSpaceKind; public static String getName() { return name; } public static void setName(String name) { VariableBuilder.name = name; } public static boolean isObservable() { return observable; } public static void setObservable(boolean observable) { VariableBuilder.observable = observable; } public static int getNumberOfStates() { return numberOfStates; } public static void setNumberOfStates(int numberOfStates) { VariableBuilder.numberOfStates = numberOfStates; } public static boolean isIsLeave() { return isLeave; } public static void setIsLeave(boolean isLeave) { VariableBuilder.isLeave = isLeave; } public static Kind getStateSpaceKind() { return stateSpaceKind; } public static void setStateSpaceKind(Kind stateSpaceKind) { VariableBuilder.stateSpaceKind = stateSpaceKind; } }
package fi.csc.microarray.description; import java.util.LinkedList; import java.util.List; import fi.csc.microarray.description.SADLSyntax.InputType; import fi.csc.microarray.description.SADLSyntax.ParameterType; /** * SADL description for one analysis tool. Describes analysis tools so * that they can be used in Chipster context. * * @author Aleksi Kallio * */ public class SADLDescription { private Name name; private String comment; private LinkedList<Input> inputs = new LinkedList<Input>(); private LinkedList<Output> outputs = new LinkedList<Output>(); private LinkedList<Input> metaInputs = new LinkedList<Input>(); private LinkedList<Output> metaOutputs = new LinkedList<Output>(); private LinkedList<Parameter> parameters = new LinkedList<Parameter>(); private String category; public static class Name { private String id = null; private String displayName = null; private String prefix; private String postfix; public static Name createEmptyName() { return new Name(null, null, null, null); } public static Name createName(String name, String displayName) { return new Name(name, null, null, displayName); } public static Name createName(String name) { return new Name(name, null, null, name); } public static Name createNameSet(String prefix, String postfix, String displayName) { return new Name(null, prefix, postfix, displayName); } public static Name createNameSet(String prefix, String postfix) { return new Name(null, prefix, postfix, prefix + SADLSyntax.INPUT_SET_DESIGNATOR + postfix); } private Name(String id, String prefix, String postfix, String displayName) { this.id = id; this.prefix = prefix; this.postfix = postfix; this.displayName = displayName; } public void setPrefix(String prefix) { this.prefix = prefix; } public void setPostfix(String postfix) { this.postfix = postfix; } public String getID() { return id; } public String getDisplayName() { return displayName; } public void setID(String id) { this.id = id; } public void setDisplayName(String displayName) { this.displayName = displayName; } /** * The prefix part of a spliced id of an input set. For a regular input * returns null. */ public String getPrefix() { return prefix; } /** * The postfix part of a spliced id of an input set. For a regular input * returns null. */ public String getPostfix() { return postfix; } /** * Return true iff this is an input set (not a regular input). */ public boolean isNameSet( ) { return id == null; } @Override public String toString() { String firstPart; if (isNameSet()) { firstPart = getPrefix() + "{...}" + getPostfix(); } else { firstPart = id; } return hyphenate(firstPart) + ": " + hyphenate(displayName); } private String hyphenate(String name) { if (name.contains(" ")) { return "\"" + name + "\""; } else { return name; } } } public static class Entity { private Name name; private boolean optional; public Entity(Name name, boolean optional) { this.optional = optional; this.name = name; } public boolean isOptional() { return optional; } public void setName(Name name) { this.name = name; } public Name getName() { return name; } public void setOptional(boolean optional) { this.optional = optional; } } /** * Input file description. */ public static class Input extends Entity { private InputType type; public Input(InputType type, Name name) { this(type, name, false); } public Input() { super(Name.createEmptyName(), false); } public Input(InputType type, Name name, boolean optional) { super(name, optional); this.type = type; } public void setType(InputType type) { this.type = type; } public InputType getType() { return type; } } /** * Output file description. */ public static class Output extends Entity { public Output(Name name) { super(name, false); } public Output() { super(Name.createEmptyName(), false); } } /** * Analysis tool parameter description. * */ public static class Parameter extends Entity { private ParameterType type; private Name[] selectionOptions; private String from; private String to; private String defaultValue; private String comment; public Parameter(Name name, ParameterType type, Name[] selectionOptions, String from, String to, String defaultValue, String comment) { super(name, false); this.type = type; this.selectionOptions = selectionOptions; this.from = from; this.to = to; this.defaultValue = defaultValue; this.comment = comment; } public ParameterType getType() { return type; } public Name[] getSelectionOptions() { return selectionOptions; } public String getFrom() { return from; } public String getTo() { return to; } public String getDefaultValue() { return defaultValue; } public String getComment() { return comment; } } /** * Returns a new (mostly empty) object presentation for parsed SADL. */ public SADLDescription(Name name, String category, String comment) { super(); this.name = name; this.comment = comment; this.category = category; } public void addInput(Input input) { inputs.add(input); } public void addMetaInput(Input input) { metaInputs.add(input); } public void addOutput(Output metaOutput) { outputs.add(metaOutput); } public void addMetaOutput(Output metaOutput) { metaOutputs.add(metaOutput); } public void addParameter(Parameter parameter) { parameters.add(parameter); } public Name getName() { return name; } public String getComment() { return comment; } public List<Input> inputs() { return inputs; } public List<Input> metaInputs() { return metaInputs; } public List<Output> outputs() { return outputs; } public List<Output> metaOutputs() { return metaOutputs; } public List<Parameter> parameters() { return parameters; } public void addInputs(List<Input> inputCollection) { inputs.addAll(inputCollection); } public void addMetaInputs(List<Input> inputCollection) { metaInputs.addAll(inputCollection); } public void addOutputs(List<Output> outputCollection) { outputs.addAll(outputCollection); } public void addMetaOutputs(List<Output> outputCollection) { metaOutputs.addAll(outputCollection); } public String getCategory() { return this.category; } /** * @see SADLGenerator#generate(SADLDescription) */ @Override public String toString() { return SADLGenerator.generate(this); } }
package edu.harvard.iq.dataverse; import edu.harvard.iq.dataverse.settings.SettingsServiceBean; import java.io.IOException; import java.io.Serializable; import java.util.*; import java.util.logging.Logger; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpServletRequest; import org.json.*; @Named @javax.enterprise.context.SessionScoped public class DataverseLocaleBean implements Serializable { private static final Logger logger = Logger.getLogger(DataverseLocaleBean.class.getCanonicalName()); @Inject SettingsWrapper settingsWrapper; { //Noticed that the NullPointerException was thrown from FacesContext.getCurrentInstance() while running the testcases(mvn:package). //Reason: the FacesContext is not initialized until the app starts. So, added the below if-condition if(FacesContext.getCurrentInstance() == null) { localeCode = "en"; } else { if (FacesContext.getCurrentInstance().getViewRoot().getLocale().getLanguage() == "en_US") { localeCode = "en"; } else { localeCode = FacesContext.getCurrentInstance().getViewRoot().getLocale().getLanguage(); } } } // Map from locale to display name eg en -> English private Map<String, String> dataverseLocales; private String localeCode; public void init() { dataverseLocales = new LinkedHashMap<>(); try { JSONArray entries = new JSONArray(settingsWrapper.getValueForKey(SettingsServiceBean.Key.Languages, "[]")); for (Object obj : entries) { JSONObject entry = (JSONObject) obj; String locale = entry.getString("locale"); String title = entry.getString("title"); dataverseLocales.put(locale, title); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } //localeCode = dataverseLocales.keySet().iterator().next(); /*if (FacesContext.getCurrentInstance().getViewRoot().getLocale().getLanguage() == "en_US") { localeCode = "en"; } else { localeCode = FacesContext.getCurrentInstance().getViewRoot().getLocale().getLanguage(); }*/ } public Map<String, String> getDataverseLocales(){ return dataverseLocales; } public boolean useLocale() { if (dataverseLocales == null) { init(); } return dataverseLocales.size() > 1; } public String getLocaleCode() { if (localeCode == null) { init(); } return localeCode; } public void setLocaleCode(String localeCode) { this.localeCode = localeCode; } public String getLocaleTitle() { if (dataverseLocales == null) { init(); } return dataverseLocales.get(localeCode); } public void countryLocaleCodeChanged(String code) { if (dataverseLocales == null) { init(); } localeCode = code; FacesContext.getCurrentInstance() .getViewRoot().setLocale(new Locale(dataverseLocales.get(code))); try { String url = ((HttpServletRequest) FacesContext.getCurrentInstance() .getExternalContext().getRequest()).getHeader("referer"); FacesContext.getCurrentInstance().getExternalContext().redirect(url); } catch (IOException ioe) { ioe.printStackTrace(); } } }
package uk.ac.ic.wlgitbridge.util; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.io.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; public class Util { private static String SERVICE_NAME; private static String HOSTNAME; private static int PORT; private static String POSTBACK_URL; private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS"); public static String entries(int entries) { if (entries == 1) { return "entry"; } else { return "entries"; } } public static int booleanToInt(boolean b) { if (b) { return 1; } else { return 0; } } public static boolean intToBoolean(int i) { return i != 0; } private static String removeAllSuffix(String str, String suffix) { int lastIndexOfSuffix; String result = str; while ((lastIndexOfSuffix = result.lastIndexOf(suffix)) > -1) { result = result.substring(0, lastIndexOfSuffix); } return result; } /* removeAllSuffixes("something.git///", "/", ".git") => "something" */ public static String removeAllSuffixes(String str, String... suffixes) { String result = str; for (String suffix : suffixes) { result = removeAllSuffix(result, suffix); } return result; } public static String getContentsOfReader(BufferedReader reader) throws IOException { StringBuilder sb = new StringBuilder(); for (String line; (line = reader.readLine()) != null; ) { sb.append(line); } return sb.toString(); } public static void setServiceName(String serviceName) { SERVICE_NAME = serviceName; } public static String getServiceName() { return SERVICE_NAME; } public static int getPort() { return PORT; } public static void setPort(int port) { PORT = port; } public static void setPostbackURL(String postbackURL) { POSTBACK_URL = postbackURL; } public static String getPostbackURL() { return POSTBACK_URL; } private static void println(PrintStream ps, String ln) { ps.println(getStringBuilder().append(ln)); } public static void sout(String ln) { println(System.out, ln); } public static void serr(String ln) { println(System.err, ln); } private static StringBuilder getStringBuilder() { StringBuilder sb = new StringBuilder("["); sb.append(dateFormat.format(new Date())); sb.append("] "); return sb; } public static void sout() { sout(""); } public static void serr() { serr(""); } public static void serr(Object obj) { serr(obj.toString()); } public static void printStackTrace(Throwable t) { serr(); t.printStackTrace(); } public static void deleteDirectory(File directory) { if (directory != null) { deleteInDirectory(directory); directory.delete(); } } public static void deleteInDirectory(File directory) { if (directory != null) { deleteInDirectoryApartFrom(directory); } } public static void deleteInDirectoryApartFrom(File directory, String... apartFrom) { if (directory != null) { Set<String> excluded = new HashSet<String>(Arrays.asList(apartFrom)); File [] files = directory.listFiles(); if (files != null) { for (File file : files) { if (!excluded.contains(file.getName())) { if (file.isDirectory()) { deleteInDirectory(file); } file.delete(); } } } } } public static List<String> linesFromStream(InputStream stream, int skip, String trimSuffix) throws IOException { List<String> lines = new ArrayList<String>(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String line; for (int i = 0; i < skip; i++) { reader.readLine(); } while ((line = reader.readLine()) != null) { String trim = line.trim(); trim = trim.replaceAll("\\p{C}", ""); int endIndex = trim.lastIndexOf(trimSuffix); if (endIndex >= 0) { trim = trim.substring(0, endIndex); } lines.add(trim); } return lines; } public static String fromStream(InputStream stream, int skip) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); StringBuilder out = new StringBuilder(); String newLine = System.getProperty("line.separator"); String line; for (int i = 0; i < skip; i++) { reader.readLine(); } while ((line = reader.readLine()) != null) { out.append(line); out.append(newLine); } return out.toString(); } public static String fromStream(InputStream stream) throws IOException { return fromStream(stream, 0); } public static String getCodeFromResponse(JsonObject json) { String code = "error"; JsonElement codeElement = json.get("code"); if (codeElement == null) { String error = "Unexpected error"; serr("Unexpected response from API:"); serr(json.toString()); serr("End of response"); JsonElement statusElement = json.get("status"); if (statusElement != null) { String status = statusElement.getAsString(); if (status.equals("422")) { error = "Unprocessable entity"; } else if (status.equals("404")) { error = "Not found"; } else if (status.equals("403")) { error = "Forbidden"; } } throw new RuntimeException(error); } else { code = codeElement.getAsString(); } return code; } }
package info.faceland.strife.listeners; import com.google.common.base.CharMatcher; import info.faceland.beast.BeastData; import info.faceland.strife.StrifePlugin; import info.faceland.strife.attributes.StrifeAttribute; import info.faceland.strife.data.Champion; import info.faceland.utils.StringConverter; import org.bukkit.ChatColor; import org.bukkit.Sound; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.ProjectileLaunchEvent; import java.util.Map; import java.util.Random; public class CombatListener implements Listener { private final StrifePlugin plugin; private final Random random; public CombatListener(StrifePlugin plugin) { this.plugin = plugin; random = new Random(System.currentTimeMillis()); } @EventHandler(priority = EventPriority.HIGHEST) public void onProjectileLaunch(ProjectileLaunchEvent event) { if (event.getEntity().getShooter() instanceof Entity) { event.getEntity().setVelocity(event.getEntity().getVelocity().add(((Entity) event.getEntity().getShooter()).getVelocity())); } } @EventHandler(priority = EventPriority.HIGHEST) public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { LivingEntity a; if (event.isCancelled() || !(event.getEntity() instanceof LivingEntity)) { return; } // LET THE DATA GATHERING COMMENCE boolean melee = true; if (event.getDamager() instanceof LivingEntity) { a = (LivingEntity) event.getDamager(); } else if (event.getDamager() instanceof Projectile && ((Projectile) event.getDamager()).getShooter() instanceof LivingEntity) { a = (LivingEntity) ((Projectile) event.getDamager()).getShooter(); melee = false; } else { return; } LivingEntity b = (LivingEntity) event.getEntity(); if (b instanceof Player) { double chance = plugin.getChampionManager().getChampion(b.getUniqueId()).getAttributeValues().get(StrifeAttribute.EVASION); if (random.nextDouble() < chance) { event.setCancelled(true); b.getWorld().playSound(a.getEyeLocation(), Sound.IRONGOLEM_THROW, 1f, 2f); return; } } double damage; double meleeDamageA = StrifeAttribute.MELEE_DAMAGE.getBaseValue(), attackSpeedA; double criticalDamageA = StrifeAttribute.CRITICAL_DAMAGE.getBaseValue(), armorPenA = StrifeAttribute.ARMOR_PENETRATION.getBaseValue(); double lifeStealA = StrifeAttribute.LIFE_STEAL.getBaseValue(), lifeStolenA = 0D, playerHealthA = b.getHealth(); double rangedDamageA = StrifeAttribute.RANGED_DAMAGE.getBaseValue(), criticalRateA = StrifeAttribute.CRITICAL_RATE.getBaseValue(); double attackSpeedMultA = 1D, fireDamageA = StrifeAttribute.FIRE_DAMAGE.getBaseValue(); double armorB = StrifeAttribute.ARMOR.getBaseValue(), reflectDamageB = StrifeAttribute.DAMAGE_REFLECT.getBaseValue(); double parryB, blockB = StrifeAttribute.BLOCK.getBaseValue(); boolean blocking = false; boolean parried = false; if (a instanceof Player) { for (EntityDamageEvent.DamageModifier modifier : EntityDamageEvent.DamageModifier.values()) { if (event.isApplicable(modifier)) { event.setDamage(modifier, 0D); } } Player p = (Player) a; Champion champ = plugin.getChampionManager().getChampion(p.getUniqueId()); Map<StrifeAttribute, Double> vals = champ.getAttributeValues(); meleeDamageA = vals.get(StrifeAttribute.MELEE_DAMAGE); attackSpeedA = (StrifeAttribute.ATTACK_SPEED.getBaseValue() * (1 / (1 + vals.get(StrifeAttribute.ATTACK_SPEED)))); criticalDamageA = vals.get(StrifeAttribute.CRITICAL_DAMAGE); armorPenA = vals.get(StrifeAttribute.ARMOR_PENETRATION); lifeStealA = vals.get(StrifeAttribute.LIFE_STEAL); playerHealthA = a.getHealth(); rangedDamageA = vals.get(StrifeAttribute.RANGED_DAMAGE); criticalRateA = vals.get(StrifeAttribute.CRITICAL_RATE); fireDamageA = vals.get(StrifeAttribute.FIRE_DAMAGE); long timeLeft = plugin.getAttackSpeedTask().getTimeLeft(a.getUniqueId()); long timeToSet = Math.round(Math.max(4.0 * attackSpeedA, 0.0)); if (timeLeft > 0) { attackSpeedMultA = Math.max(1.0 - 1.0 * timeLeft / timeToSet, 0.0); } plugin.getAttackSpeedTask().setTimeLeft(a.getUniqueId(), timeToSet); } else { BeastData data = plugin.getBeastPlugin().getData(a.getType()); if (data != null && a.getCustomName() != null) { int level = StringConverter.toInt(CharMatcher.DIGIT.retainFrom(ChatColor.stripColor(a.getCustomName()))); meleeDamageA = data.getDamageExpression().setVariable("LEVEL", level).evaluate(); rangedDamageA = meleeDamageA; } } if (b instanceof Player) { Player p = (Player) b; Champion champ = plugin.getChampionManager().getChampion(p.getUniqueId()); Map<StrifeAttribute, Double> vals = champ.getAttributeValues(); armorB = vals.get(StrifeAttribute.ARMOR); reflectDamageB = vals.get(StrifeAttribute.DAMAGE_REFLECT); parryB = vals.get(StrifeAttribute.PARRY); blockB = vals.get(StrifeAttribute.BLOCK); if (((Player) b).isBlocking()) { blocking = true; if (random.nextDouble() < parryB) { parried = true; } } } // LET THE DAMAGE CALCULATION COMMENCE for (EntityDamageEvent.DamageModifier modifier : EntityDamageEvent.DamageModifier.values()) { if (event.isApplicable(modifier)) { event.setDamage(modifier, 0); } } if (melee) { if (blocking) { if (parried) { damage = meleeDamageA * attackSpeedMultA; a.damage(damage * 0.25); event.setCancelled(true); b.getWorld().playSound(b.getEyeLocation(), Sound.ANVIL_LAND, 1f, 2f); return; } damage = meleeDamageA * attackSpeedMultA; if (random.nextDouble() < criticalRateA) { damage = damage * criticalDamageA; b.getWorld().playSound(b.getEyeLocation(), Sound.FALL_BIG, 2f, 1f); } double damageReducer = (1 - (armorB * (1 - armorPenA))); damage = damage * damageReducer; damage = damage * (1 - blockB); lifeStolenA = damage * lifeStealA; event.setDamage(EntityDamageEvent.DamageModifier.BASE, damage); a.setHealth(Math.min(playerHealthA + lifeStolenA, a.getMaxHealth())); if (reflectDamageB > 0) { a.damage(damage * reflectDamageB); a.getWorld().playSound(a.getEyeLocation(), Sound.GLASS, 1f, 2f); } b.setFireTicks((int) Math.round(fireDamageA * 20)); return; } damage = meleeDamageA * attackSpeedMultA; if (random.nextDouble() < criticalRateA) { damage = damage * criticalDamageA; b.getWorld().playSound(b.getEyeLocation(), Sound.FALL_BIG, 2f, 1f); } double damageReducer = (1 - (armorB * (1 - armorPenA))); damage = damage * damageReducer; lifeStolenA = damage * lifeStealA; event.setDamage(EntityDamageEvent.DamageModifier.BASE, damage); a.setHealth(Math.min(playerHealthA + lifeStolenA, a.getMaxHealth())); if (reflectDamageB > 0) { a.damage(damage * reflectDamageB); a.getWorld().playSound(a.getEyeLocation(), Sound.GLASS, 1f, 2f); } b.setFireTicks((int) Math.round(fireDamageA * 20)); return; } if (blocking) { if (parried) { event.setCancelled(true); b.getWorld().playSound(b.getEyeLocation(), Sound.ANVIL_LAND, 1f, 2f); return; } damage = rangedDamageA * (event.getDamager().getVelocity().length() / Math.pow(3, 2)); if (random.nextDouble() < criticalRateA) { damage = damage * criticalDamageA; b.getWorld().playSound(b.getEyeLocation(), Sound.FALL_BIG, 2f, 1f); } double damageReducer = (1 - (armorB * (1 - armorPenA))); damage = damage * damageReducer; damage = damage * (1 - blockB); lifeStolenA = damage * lifeStealA; event.setDamage(EntityDamageEvent.DamageModifier.BASE, damage); a.setHealth(Math.min(a.getHealth() + lifeStolenA, a.getMaxHealth())); if (reflectDamageB > 0) { a.damage(damage * reflectDamageB); a.getWorld().playSound(a.getEyeLocation(), Sound.GLASS, 1f, 2f); } b.setFireTicks((int) Math.round(fireDamageA * 20)); return; } damage = rangedDamageA * (event.getDamager().getVelocity().lengthSquared() / Math.pow(3, 2)); if (random.nextDouble() < criticalRateA) { damage = damage * criticalDamageA; b.getWorld().playSound(b.getEyeLocation(), Sound.FALL_BIG, 2f, 1f); } double damageReducer = (1 - (armorB * (1 - armorPenA))); damage = damage * damageReducer; lifeStolenA = damage * lifeStealA; event.setDamage(EntityDamageEvent.DamageModifier.BASE, damage); a.setHealth(Math.min(a.getHealth() + lifeStolenA, a.getMaxHealth())); if (reflectDamageB > 0) { a.damage(damage * reflectDamageB); a.getWorld().playSound(a.getEyeLocation(), Sound.GLASS, 1f, 2f); } b.setFireTicks((int) Math.round(fireDamageA * 20)); } }
package io.domisum.lib.auxiliumlib.util; import io.domisum.lib.auxiliumlib.annotations.API; import lombok.AccessLevel; import lombok.NoArgsConstructor; import java.time.Duration; import java.time.Instant; import java.time.temporal.Temporal; @API @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class DurationUtil { // MATH @API public static Duration getDelta(Duration duration1, Duration duration2) { return duration1.minus(duration2).abs(); } @API public static Duration min(Duration a, Duration b) { return (a.compareTo(b) < 0) ? a : b; } @API public static Duration max(Duration a, Duration b) { return (a.compareTo(b) > 0) ? a : b; } // FLOATING COMMA CONVERSION @API public static double getMinutesDecimal(Duration duration) { return duration.getSeconds()/(double) Duration.ofMinutes(1).getSeconds(); } @API public static double getSecondsDecimal(Duration duration) { return duration.toMillis()/(double) Duration.ofSeconds(1).toMillis(); } @API public static double getMillisecondsDecimal(Duration duration) { return duration.getSeconds()*1000+(duration.toNanosPart()/(double) (1000*1000)); } @API public static Duration fromSecondsDecimal(double seconds) { return Duration.ofMillis(Math.round(seconds*1000)); } // DISPLAY @API public static String displayMinutesSeconds(Duration duration) { final int secondsInMinute = 60; long totalSeconds = (int) Math.ceil(duration.toMillis()/(double) 1000); long displayMinutes = totalSeconds/secondsInMinute; long displaySeconds = totalSeconds%secondsInMinute; String secondsString = displaySeconds+""; if(secondsString.length() == 1) secondsString = "0"+secondsString; return displayMinutes+":"+secondsString; } // NOW @API public static Duration toNow(Temporal from) { return Duration.between(from, Instant.now()); } @API public static Duration until(Temporal until) { return Duration.between(Instant.now(), until); } @API public static boolean isOlderThan(Instant instant, Duration duration) { var age = toNow(instant); return age.compareTo(duration) > 0; } @API public static boolean hasPassed(Instant instant) { return instant.isBefore(Instant.now()); } }
package edu.umd.cs.daveho.ba; import java.util.List; import java.util.LinkedHashMap; import java.util.Map; import org.apache.bcel.classfile.JavaClass; /** * A context for analysis of a complete project. * This serves as the repository for whole-program information * and data structures. * @author David Hovemeyer */ public class AnalysisContext { private RepositoryLookupFailureCallback lookupFailureCallback; private SourceFinder sourceFinder; private ClassContextCache classContextCache; /** * The maximum number of ClassContext objects to cache. * FIXME: need to evaluate this parameter. Need to keep stats * about accesses. */ private static final int MAX_SIZE = 60; private static class ClassContextCache extends LinkedHashMap<JavaClass, ClassContext> { public boolean removeEldestEntry(Map.Entry<JavaClass, ClassContext> entry) { return size() > MAX_SIZE; } } private static AnalysisContext instance; /** Constructor. */ private AnalysisContext() { this.sourceFinder = new SourceFinder(); this.classContextCache = new ClassContextCache(); } /** Get the single AnalysisContext instance. */ public static AnalysisContext instance() { if (instance == null) { instance = new AnalysisContext(); } return instance; } /** Set the repository lookup failure callback for created ClassContexts. */ public void setLookupFailureCallback(RepositoryLookupFailureCallback lookupFailureCallback) { this.lookupFailureCallback = lookupFailureCallback; } /** Set the source path. */ public void setSourcePath(List<String> sourcePath) { sourceFinder.setSourceBaseList(sourcePath); } /** Get the SourceFinder, for finding source files. */ public SourceFinder getSourceFinder() { return sourceFinder; } /** * Get the ClassContext for a class. * @param javaClass the class * @return the ClassContext for that class */ public ClassContext getClassContext(JavaClass javaClass) { ClassContext classContext = classContextCache.get(javaClass); if (classContext == null) { classContext = new ClassContext(javaClass, lookupFailureCallback); classContextCache.put(javaClass, classContext); } return classContext; } } // vim:ts=4
package com.kii.thingif.command; public interface Action { }
package com.winterwell.maths.timeseries; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.logging.Level; import com.winterwell.json.JSONArray; import com.winterwell.json.JSONObject; import com.winterwell.maths.matrix.MatrixUtils; import com.winterwell.maths.stats.KScore; import com.winterwell.maths.stats.StatsUtils; import com.winterwell.maths.stats.algorithms.IPredictor; import com.winterwell.maths.stats.algorithms.ITimeSeriesFilter; import com.winterwell.maths.stats.distributions.IDistribution; import com.winterwell.maths.stats.distributions.d1.IDistribution1D; import com.winterwell.maths.stats.distributions.discrete.ObjectDistribution; import com.winterwell.maths.timeseries.ExtraDimensionsDataStream.KMatchPolicy; import com.winterwell.maths.vector.X; import com.winterwell.maths.vector.XY; import com.winterwell.maths.vector.XYZ; import com.winterwell.utils.FailureException; import com.winterwell.utils.MathUtils; import com.winterwell.utils.Printer; import com.winterwell.utils.StrUtils; import com.winterwell.utils.TodoException; import com.winterwell.utils.Utils; import com.winterwell.utils.WrappedException; import com.winterwell.utils.containers.AbstractIterator; import com.winterwell.utils.containers.Pair; import com.winterwell.utils.containers.TopNList; import com.winterwell.utils.io.FileUtils; import com.winterwell.utils.io.LineReader; import com.winterwell.utils.log.Log; import com.winterwell.utils.time.Dt; import com.winterwell.utils.time.Time; import com.winterwell.utils.time.TimeUtils; import com.winterwell.utils.web.SimpleJson; import com.winterwell.utils.web.XStreamUtils; import no.uib.cipr.matrix.DenseMatrix; import no.uib.cipr.matrix.DenseVector; import no.uib.cipr.matrix.Matrix; import no.uib.cipr.matrix.MatrixEntry; import no.uib.cipr.matrix.Vector; import no.uib.cipr.matrix.Vector.Norm; import no.uib.cipr.matrix.VectorEntry; import no.uib.cipr.matrix.sparse.SparseVector; class CSVDataStream extends ADataStream { private static final long serialVersionUID = 1L; private final File file; private final LineReader lreader; transient Time prev = TimeUtils.ANCIENT; public CSVDataStream(File file, LineReader lreader, int dim) { super(dim); this.file = file; this.lreader = lreader; } @Override public void close() { lreader.close(); } @Override public AbstractIterator<Datum> iterator() { return new AbstractIterator<Datum>() { @Override protected Datum next2() { if (!lreader.hasNext()) return null; String line = lreader.next(); if (Utils.isBlank(line) || line.charAt(0) == ' return next2(); // this is redundant - the header is already // gone String[] bits = line.split("\t"); assert bits.length == (getDim() + 2) : "(exp:" + getDim() + "found:" + (bits.length - 2) + ") " + file + ":" + lreader.getLineNum() + " dimension error " + Printer.toString(bits); // time Time t = new Time(Long.valueOf(bits[0])); // check correct ordering assert !prev.isAfter(t) : prev + " vs " + t + " in " + file + " line " + lreader.getLineNum(); prev = t; double[] vec = new double[bits.length - 2]; for (int i = 1, n = bits.length - 1; i < n; i++) { double vi = Double.valueOf(bits[i]); assert MathUtils.isFinite(vi) : file + " line " + lreader.getLineNum() + ": " + vi; vec[i - 1] = vi; } // deseralise label Object label = null; String lastBit = bits[bits.length - 1]; if (Utils.isBlank(lastBit)) { label = null; } else if (lastBit.charAt(0) == '<') { // XML? label = XStreamUtils.serialiseFromXml(lastBit); } else { // JSON? label = DataUtils.simpleJson.fromJson(lastBit); } return new Datum(t, vec, label); } }; } @Override public String toString() { return "CSVDataStream:" + file; } } /** * Utility methods for working with time-series data. * * merge with {@link VectorUtils}?? * * NB: Probably no merge with {@link MatrixUtils}, which is extra-methods for matrices like getColumn(). * * @testedby {@link DataUtilsTest} * * @author daniel * */ public class DataUtils extends StatsUtils { private DataUtils() { } /** * Renders Datums as {time:Java-time-stamp, label:"", data:[]} * @param data * @return */ public static String toJson(IDataStream data) { JSONArray highchartsData = new JSONArray(); for (Datum datum : data) { JSONObject point = new JSONObject(); if (datum.isTimeStamped()) { point.put("x", datum.time.getTime()); } point.put("y", datum.x()); highchartsData.put(point); } return highchartsData.toString(); } static final SimpleJson simpleJson = new SimpleJson(); /** * Apply the matrix to elements of the base data stream * * @param transform * @param data * @return a filtered data stream that transforms points as it reads them. * It preservs any time and label info. */ public static IDataStream applyMatrix(final Matrix transform, Iterable<? extends Vector> baseData) { assert transform != null; IDataStream ds; if (baseData instanceof IDataStream) { ds = (IDataStream) baseData; } else { ds = new ListDataStream(baseData); } return new FilteredDataStream(ds) { @Override protected Datum filter(Datum datum) { assert datum!=null; Datum y = new Datum(datum.time, new double[transform.numRows()], datum.getLabel()); y.setModifiable(true); transform.mult(datum, y); return y; } }; } /** * Pull one dimension out of a vector data stream. * * @param base * @param dim * The dimension to keep * @see #getColumns(IDataStream, int...) */ public static IDataStream get1D(final IDataStream baseData, final int dimIndex) { assert baseData != null; assert dimIndex < baseData.getDim() : String.format("Request for dimension %d of %dD stream", dimIndex,baseData.getDim()); return new ADataStream(1) { private static final long serialVersionUID = 1L; @Override public Dt getSampleFrequency() { return baseData.getSampleFrequency(); } @Override public AbstractIterator<Datum> iterator() { return new AbstractIterator<Datum>() { AbstractIterator<Datum> base = baseData.iterator(); @Override public final double[] getProgress() { return base.getProgress(); } @Override protected Datum next2() { if (!base.hasNext()) return null; Datum d = base.next(); assert d != null : "Base: " + base; assert d.getData() != null : d + " from base: " + base; assert d.time != null : d + " from: " + base; return new Datum(d.time, d.getData()[dimIndex], d.getLabel()); } }; } @Override public String toString() { return "ADataStream1D:" + dimIndex + baseData; } }; } /** * Multi-dim variant of {@link #get1D(IDataStream, int)} * @param base * @param outputColumns * @return */ public static IDataStream getColumns(IDataStream base, int... outputColumns) { DenseMatrix dm = new DenseMatrix(outputColumns.length, base.getDim()); for (int i = 0; i < outputColumns.length; i++) { dm.set(i, outputColumns[i], 1); } return new MatrixStream(dm, base); } // /** // * Switches on some extra (not always appropriate) sanity checks // */ // private static final boolean PARANOID_DEBUG = false; /** * Extract the nth dimension * * @param sample * @param nth * @return an array of the values for dimension n from the samples */ public static double[] get1DArr(Iterable<? extends Vector> sample, int n) { if (sample instanceof Collection) { // fastest copy double[] xs = new double[((Collection) sample).size()]; int i = 0; for (Vector v : sample) { xs[i] = v.get(n); i++; } return xs; } // copy out ArrayList<Double> list = new ArrayList(); for (Vector v : sample) { double vn = v.get(n); list.add(vn); } return MathUtils.toArray(list); } /** * Convert into a data stream by taking the Euclidean length of vectors. * * @param rawDataStream * @return */ public static ADataStream getEuclidean(final ADataStream base) { return new ADataStream(1) { private static final long serialVersionUID = 1L; @Override public AbstractIterator<Datum> iterator() { return new AbstractIterator<Datum>() { final AbstractIterator<Datum> baseIt = base.iterator(); @Override protected Datum next2() throws Exception { if (!baseIt.hasNext()) return null; Datum d = baseIt.next(); double x = MathUtils.euclideanLength(d.getData()); return new Datum(d.time, x, d.getLabel()); } }; } @Override public String toString() { return "||" + base + "||"; } }; } /** * Create a mixture sampling from two distributions. COnvenient for some * tests. * * @param labelA * @param distA * @param labelB * @param distB * @param dt * @return */ public static IDataStream mix(Object labelA, IDistribution distA, Object labelB, IDistribution distB, Dt dt) { RandomDataStream a = new RandomDataStream(distA, null, dt); a.setLabel(labelA); RandomDataStream b = new RandomDataStream(distB, null, dt); b.setLabel(labelB); return new MixedDataStream(a, b); } public static IDataStream read(final File streamData) { // Find out the dimensions int dim = 0; LineReader lreader = new LineReader(streamData); while (lreader.hasNext()) { String line = lreader.peekNext(); if (Utils.isBlank(line) || line.charAt(0) == ' lreader.next(); // throw away header continue; } String[] bits = line.split("\t"); dim = bits.length - 2; break; } return new CSVDataStream(streamData, lreader, dim); } /** * Load a data stream, adding in a factory method * * @param f * @param factory * @return */ public static IDataStream read(File f, final IDataStream factory) { final IDataStream s = read(f); return new ADataStream(s.getDim()) { private static final long serialVersionUID = 1L; @Override public IDataStream factory(Object source) { return factory.factory(source); } @Override public AbstractIterator<Datum> iterator() { return s.iterator(); } }; } /** * Attempt to equalise the labels by creating more data from the rare * labels. * * @param data * @return */ public static ListDataStream resampleEqualLabels(IDataStream data) { // count 'em ListDataStream ldata = data.list(); ObjectDistribution dist = new ObjectDistribution(); for (Datum object : ldata) { if (object.getLabel() == null) { continue; } dist.count(object.getLabel()); } dist.normalise(); // try to avoid dropping data points (we prefer duplicating to maake up // numbers) double maxP = dist.prob(dist.getMostLikely()); HashMap<Object, Double> boost = new HashMap<Object, Double>(); for (Object label : dist) { double p = dist.prob(label); assert p != 0; double b = maxP / p; // limit how much resampling we will do b = Math.max(b, 1000); boost.put(label, b); } ResampledDataStream rds = new ResampledDataStream(ldata.clone(), boost); return rds.list(); } /** * Synonym for {@link #toList(ADataStream, int)}. */ public static ArrayList<Datum> sample(IDataStream stream, int maxValues) { return toList(stream, maxValues); } /** * Convenience for generating labelled samples from a distribution * * @param dist * @param numSamples * @param label * @return */ public static ListDataStream sample(IDistribution dist, int numSamples, Object label) { ListDataStream samples = new ListDataStream(dist.getDim()); for (int i = 0; i < numSamples; i++) { Vector sample = dist.sample(); Datum d = new Datum(sample, label); samples.add(d); } return samples; } /** * Sort a data stream by the labels. * * @param data * @return one data stream per label. null-labelled data is included (but * you can remove it afterwards) */ public static Map<Object, ListDataStream> sortByLabel(IDataStream data) { Map<Object, ListDataStream> sorted = new HashMap<Object, ListDataStream>(); for (Datum datum : data) { ListDataStream stream = sorted.get(datum.getLabel()); if (stream == null) { stream = new ListDataStream(data.getDim()); sorted.put(datum.getLabel(), stream); } stream.add(datum); } return sorted; } /** * Get a filtered view of the datastream from start (inclusive) to end * (exclusive). * * @param stream * This must be properly ordered. * @param start * Earliest data point (inclusive). Can be null for no start * filtering * @param end * Latest data point (exclusive). Can be null for no end * filtering * @return slice-of-stream. Uses lazy-filtering * @testedyb {@link DataUtilsTest#testSubStream} */ // name is for similarity with List.subList public static IDataStream subStream(IDataStream stream, final Time start, final Time end) { assert stream != null; if (start == null && end == null) return stream; assert !Utils.equals(start, end) : start; return new SubStream(stream, start, end); } /** * Sum all the entries in data. * * @param data * Must be a finite stream. Cannot have zero dimension. */ public static Vector sum(IDataStream data) { assert data.getDim() != 0 : data; Vector sum = DataUtils.newVector(data.getDim()); for (Datum datum : data) { // if ( ! datum.isZero()) { // HACK debugging // assert true; sum.add(datum); } return sum; } /** * Extract one dimension from a stream, and copy into an array. * * @param stream * @param dim * @return the dim dimension values from stream * @see #get1D(IDataStream, int) * @see #toList(IDataStream, int) */ public static double[] toArray(Iterable<Datum> stream, int dim) { ArrayList<Double> list = new ArrayList(); for (Datum datum : stream) { list.add(datum.get(dim)); } return MathUtils.toArray(list); } /** * Convert a stream into an array. Can only be called once on a stream! * * @param stream * Must not be empty * @param maxValues * Will pull up to this many values. Needed as s(stream)ome data streams * are unending. -1 for unlimited * @return contents of the stream as an array */ public static ArrayList<Datum> toList(IDataStream stream, int maxValues) { int capacity = maxValues == -1 ? 2000 : maxValues; ArrayList<Datum> list = new ArrayList<Datum>(capacity); for (Datum d : stream) { assert DataUtils.isFinite(d) : d; list.add(d); if (list.size() == maxValues) { break; } } return list; } /** * Save contents of the stream as a list of * <code>time-code value label</code> lines in a a file. Label objects are * saved using toString() for primitives and String, or converted using * XStream for other objects. Tabs and line-endings will be discarded * * @param stream * @param out * @param maxValues * Will save up to this many values. Needed as some data streams * are unending. -1 for unlimited * @param headerComment * Can be null. If set, a description is added to the start of * the file. Each line must begin with a # * * <p> * The output file is only written to on success. Should * something go wrong this method shouldn't leave a partially * saved file. C.f. append which will leave partial files. */ public static void write(IDataStream stream, File out, int maxValues, String headerComment) { File temp = FileUtils.createTempFile("data", ".csv"); BufferedWriter writer = FileUtils.getWriter(temp); try { write2(stream, writer, maxValues, headerComment); assert temp.exists() : temp; FileUtils.move(temp, out); assert out.exists() : out; } catch (Exception e) { // Something went wrong - don't leave a partially saved file // c.f. append which will leave partial files FileUtils.delete(temp); throw Utils.runtime(e); } } static void write2(IDataStream stream, BufferedWriter writer, int maxValues, String headerComment) { try { Time prev = TimeUtils.ANCIENT; int cnt = 0; // Header? if (!Utils.isBlank(headerComment)) { for (String h : StrUtils.splitLines(headerComment)) { // assert h.startsWith("#") : headerComment; This isn't // really essential or part of csv standard writer.write(h + StrUtils.LINEEND); } } // Data int dim = stream.getDim(); for (Datum d : stream) { assert dim == d.size() : dim + " vs " + d.size() + ": " + d + "\t" + stream; if (cnt == maxValues) { break; } if (cnt == Integer.MAX_VALUE) { Log.report("Data stream exceeded max-int values!", Level.SEVERE); } cnt++; // time stamp writer.append(Long.toString(d.time.longValue())); // check correct ordering assert !prev.isAfter(d.time) : prev + " vs " + d.time + " in " + stream + " count " + cnt; prev = d.time; // vector double[] array = d.getData(); for (int i = 0; i < array.length; i++) { writer.append('\t'); double vi = array[i]; assert MathUtils.isFinite(vi) : stream + ": " + d; writer.append(Double.toString(vi)); } writer.append('\t'); // label Object lbl = d.getLabel(); String xml; try { xml = simpleJson.toJson(lbl); } catch (Exception e) { xml = XStreamUtils.serialiseToXml(lbl); } xml = xml.replace('\t', ' '); xml = xml.replace('\r', ' '); xml = xml.replace('\n', ' '); writer.append(xml); writer.append('\n'); } writer.close(); } catch (IOException e) { throw new WrappedException(e); } } public static void writeAppend(IDataStream stream, File out, int maxValues) { try { BufferedWriter w = FileUtils.getWriter(new FileOutputStream(out, true)); write2(stream, w, maxValues, null); } catch (FileNotFoundException e) { throw new WrappedException(e); } } /** * @param data * @return all the labels used, converted by toString * (including "null" if there is unlabelled data) */ public static List<String> getLabels(IDataStream data) { HashSet labels = new HashSet(); for (Datum datum : data) { Object l = datum.getLabel(); labels.add(l==null? "null" : l.toString()); } return new ArrayList(labels); } /** * @param timeSeries * @return Remove leading and trailing 0s */ public static ListDataStream trim(IDataStream timeSeries) { int dim = timeSeries.getDim(); ArrayList trimmed = new ArrayList(); AbstractIterator<Datum> it = timeSeries.iterator(); // burn-in while(it.hasNext()) { Datum d = it.next(); if (d.norm(Norm.Infinity) != 0) { trimmed.add(d); break; } } if (trimmed.isEmpty()) { return new ListDataStream(dim); } // burn through int last = trimmed.size(); while(it.hasNext()) { Datum d = it.next(); trimmed.add(d); if (d.norm(Norm.Infinity) != 0) { last = trimmed.size(); } } // burn-out if (last == trimmed.size()) { return new ListDataStream(trimmed); } List trimmed2 = trimmed.subList(0, last); return new ListDataStream(trimmed2); } /** * Just a wrapper for {@link DeltaDataStream} * @param iDataStream * @return the datastream measuring the difference between points. I.e. the discrete/stepping 1st derivative. * The first bucket is zero. The timestamps are for the later buckets. */ public static IDataStream diff(IDataStream iDataStream) { return new DeltaDataStream(iDataStream); } public static ListDataStream max(IDataStream a, IDataStream b) { // TODO refactor to be a 2-arg fun-datat-stream int dim = Math.min(a.getDim(), b.getDim()); ListDataStream max = new ListDataStream(dim); AbstractIterator<Datum> bit = b.iterator(); AbstractIterator<Datum> ait = a.iterator(); while(true) { Datum ad = ait.hasNext()? ait.next() : null; Datum bd = bit.hasNext()? bit.next() : null; if (ad==null && bd==null) break; if (ad==null) { max.add(bd); continue; } if (bd==null) { max.add(ad); continue; } if (dim==1) { if (ad.x() > bd.x()) { max.add(ad); } else { max.add(bd); } } else { Vector vector = DataUtils.elementWiseMax(ad, bd); Datum md = new Datum(ad.time, vector, Utils.or(ad.getLabel(),bd.getLabel())); max.add(md); } } return max; } public static double[] getResiduals(double[] targets, IPredictor regression, List<? extends Vector> expRows) { assert expRows.size()==targets.length; double[] predictions = getPredictions(regression, expRows); double[] residuals = new double[expRows.size()]; for(int i=0; i<targets.length; i++) { double ti = targets[i]; double pti = predictions[i]; residuals[i] = ti - pti; } return residuals; } public static double[] getPredictions(IPredictor regression, List<? extends Vector> expRows) { double[] predictions = new double[expRows.size()]; for(int i=0; i<predictions.length; i++) { double pti = regression.predict(expRows.get(i)); predictions[i] = pti; } return predictions; } /** * Just a convenience for {@link #getScore(KScore, double[], double[], int)} * @param targets * @param residuals * @return */ public static double getR2(double[] targets, double[] residuals) { return getScore(KScore.R2, targets, residuals, 1); } public static double getScore(KScore score, double[] targets, double[] residuals, int numExpVars) { switch(score) { case R2: double mean = mean(filterFinite(targets)); double sumressq=0,sumsq=0; for(int i=0; i<residuals.length; i++) { double ti = targets[i]; if (Double.isNaN(ti)) { // target was missing -- skip from calculation continue; } sumsq += MathUtils.sq(ti - mean); // yes this is n*variance sumressq += MathUtils.sq(residuals[i]); } // no variance in the targets?? if (MathUtils.isTooSmall(sumsq)) { if (MathUtils.isTooSmall(sumressq)) { return 1; } return 0; } double r2 = 1 - sumressq/sumsq; assert MathUtils.isFinite(r2) && r2<=1 : r2; return r2; case ADJUSTED_R2: int n = targets.length, k = numExpVars; double r2score = getScore(KScore.R2, targets, residuals, numExpVars); double ar2 = 1 - ((1- r2score)*(n-1)*1.0/(n-k-1)); return ar2; case CHI2: // ChiSquaredDistribution d; // ChiSquaredTest t; throw new TodoException(); case RMSE: double se = 0; for (double d : residuals) { se +=d*d; } double mse = se / residuals.length; return Math.sqrt(mse); case NRMSE: double rmse = getScore(KScore.RMSE, targets, residuals, numExpVars); mean = StatsUtils.mean(targets); return rmse / Math.abs(mean); case MAPE: double sae = 0; for (int j = 0; j < residuals.length; j++) { double tj = targets[j]; // skip 0 to avoid nan?? // if (tj==0) continue; sae += Math.abs(residuals[j] / tj); } return sae / residuals.length; } throw new TodoException(score); } /** * The vector-valued version of getScore() * @param score * @param testtargets * @param residuals * @param numExpVars * @return */ public static double getScore(KScore score, List<? extends Vector> testtargets, final List<? extends Vector> residuals, int numExpVars) { switch(score) { case R2: // the r2 for each dimension Vector targetVar = StatsUtils.var(testtargets); Vector residualVar = StatsUtils.var(residuals); Vector r2 = newVector(targetVar.size()); for(int d=0; d<targetVar.size(); d++) { double rvard = residualVar.get(d); double tvard = targetVar.get(d); // Robustness: no variance in the targets?? if (MathUtils.isTooSmall(tvard)) { if (MathUtils.isTooSmall(rvard)) { r2.set(d, 1); } else { r2.set(d, 0); } } else { r2.set(d, 1 - rvard / tvard); } } // average them return r2.norm(Norm.One) / r2.size(); case ADJUSTED_R2: double r2score = getScore(KScore.R2, testtargets, residuals, numExpVars); int n = residuals.size(); int k = numExpVars; // how many explanatory variables does this filter use? // This isn't really valid, cos it potentially has the full history trace. double ar2 = 1 - ((1-r2score)*(n-1)*1.0/(n-k-1)); return ar2; case RMSE: double se = 0; for (Vector r : residuals) { se += r.dot(r); } double mse = se / residuals.size(); return Math.sqrt(mse); case NRMSE: double rmse = getScore(KScore.RMSE, testtargets, residuals, numExpVars); Vector mean = StatsUtils.mean(testtargets); return rmse / mean.norm(Norm.Two); case MAPE: // HACK -- MAPE for vectors? How should we define that?? double sae = 0; int dims = residuals.get(0).size(); for (int j = 0; j < residuals.size(); j++) { Vector tj = testtargets.get(j); // skip 0 to avoid nan?? // if (tj==0) continue; Vector rj = residuals.get(j); for(int d=0; d<dims; d++) { sae += Math.abs(rj.get(d) / tj.get(d)); } } return sae / (residuals.size()*dims); } throw new TodoException(score); } /** * * @param targets Possibly the same as inputs! * @param filter * @param inputs * @return */ public static List<Vector> getResiduals(List<? extends Vector> targets, ITimeSeriesFilter filter, List<? extends Vector> inputs) { List<IDistribution> smoothed = filter.smooth(null, new ListDataStream(inputs)); List<Vector> residuals = new ArrayList(); for(int i=0; i<targets.size(); i++) { Vector ti = targets.get(i); Vector ri = ti.copy(); Vector si = smoothed.get(i).getMean(); ri.add(-1, si); residuals.add(ri); } return residuals; } /** * * @param filter * @param inputs * @return */ public static List<Vector> getPredictions(ITimeSeriesFilter filter, List<? extends Vector> inputs) { List<IDistribution> smoothed = filter.smooth(null, new ListDataStream(inputs)); List<Vector> residuals = new ArrayList(); for(int i=0; i<inputs.size(); i++) { Vector si = smoothed.get(i).getMean(); residuals.add(si); } return residuals; } /** * Convert all values to absolute values * * @param v This will be modified! * @return * @return v */ public static Vector abs(Vector v) { for (VectorEntry ve : v) { double x = ve.get(); double ax = Math.abs(x); ve.set(ax); } return v; } /** * The angle between a and b. * <p> * For sort order, you could use a.b and skip the inverse cos step. * * @param a * Must have non-zero length * @param b * Must have non-zero length * @return 0 to pi * @throws FailureException * if a or b have zero length */ public static double angle(Vector a, Vector b) throws FailureException { double ab = a.norm(Norm.Two) * b.norm(Norm.Two); if (ab == 0) throw new FailureException("zero length vector"); double aDotB = a.dot(b); assert MathUtils.isFinite(aDotB); double angle = Math.acos(aDotB / ab); assert angle >= 0 && angle <= Math.PI; return angle; } /** * Create a new vector consisting of x followed by y * * @param x * @param y * @return x append y, which has dimennsions dim(x)+dimm(y) * @testedby {@link VectorUtilsTest#testAppend()} */ public static Vector append(Vector x, Vector y) { // if (x instanceof DenseVector && y instanceof DenseVector) { // double[] arr = Arrays.copyOf(((DenseVector)x).getData(), // x.size()+y.size()); // double[] yd = ((DenseVector)y).getData(); // for(int i=0; i<yd.length; i++) { // arr[i+x.size()]=yd[i]; // DenseVector xy = new DenseVector(arr, false); // return xy; Vector xy = DataUtils.newVector(x.size() + y.size()); for (VectorEntry ve : x) { xy.set(ve.index(), ve.get()); } for (VectorEntry ve : y) { xy.set(x.size() + ve.index(), ve.get()); } return xy; } /** * Is x approximately equal to y? x and y must have the same dimension * * @see MathUtils.approx() */ public static boolean approx(Vector x, Vector y) { assert x.size() == y.size(); // Or return false? for (int i = 0; i < x.size(); i++) { if (!MathUtils.approx(x.get(i), y.get(i))) return false; } return true; } public static Vector asVector(double x) { return new X(x); } /** * @param a * @param b * @return Euclidean distance between a and b TODO how to handle the case * where a is sparse & basically infinite (but empty), and b is * dense? */ public static double dist(Vector a, Vector b) { Vector a2 = a.copy(); a2.add(-1, b); return a2.norm(Norm.Two); } /** * @param a * @param b * @return Each element of a, divided by the corresponding element of b, in * order */ public static Vector elementWiseDivide(Vector a, Vector b) { if (a.size() != b.size()) throw new IllegalArgumentException("Vectors must be of same size"); Vector result = DataUtils.newVector(a.size()); for (Integer idx = 0; idx < a.size(); idx++) { result.set(idx, a.get(idx) / b.get(idx)); } return result; } /** * For each *element* (i.e. entry), get the max of the two vectors (so * result is (max(a0,b0),max(a1,b1) ....) * * @param a * @param b * @return max for each entry */ public static Vector elementWiseMax(Vector a, Vector b) { if (a.size() != b.size()) throw new IllegalArgumentException("Vectors must be of same size"); Vector result = DataUtils.newVector(a.size()); for (Integer idx = 0; idx < a.size(); idx++) { result.set(idx, MathUtils.max(a.get(idx), b.get(idx))); } return result; } /** * For each *element* (i.e. entry), get the min of the two vectors (so * result is (min(a0,b0),min(a1,b1) ....) * * @param a * @param b * @return min for each entry */ public static Vector elementWiseMin(Vector a, Vector b) { if (a.size() != b.size()) throw new IllegalArgumentException("Vectors must be of same size"); Vector result = DataUtils.newVector(a.size()); for (Integer idx = 0; idx < a.size(); idx++) { result.set(idx, MathUtils.min(a.get(idx), b.get(idx))); } return result; } /** * @param a * @param b * @return Each element of a, multiplied by the corresponding element of b, * in order */ public static Vector elementWiseMultiply(Vector a, Vector b) { if (a.size() != b.size()) throw new IllegalArgumentException("Vectors must be of same size"); Vector result = DataUtils.newVector(a.size()); for (Integer idx = 0; idx < a.size(); idx++) { result.set(idx, a.get(idx) * b.get(idx)); } return result; } /** * Like {@link #equals(Object)} but allows some leeway for rounding errors. * uses {@link MathUtils#equalish(double, double)} on the distance between * the two vectors added to the average length. * * @param a * @param b * @return */ public static boolean equalish(Vector a, Vector b) { double d = dist(a, b); double len = DataUtils.len(a) + DataUtils.len(b); return MathUtils.equalish(len, len + d); } /** * * @param a * @param b * @param tolerance * @return false if the difference in any dimension exceeds tolerance. true * otherwise */ public static boolean equalish(Vector a, Vector b, double tolerance) { // dense cases if (a instanceof DenseVector || a instanceof XY || a instanceof XYZ) { for (int i = 0, n = a.size(); i < n; i++) { if (Math.abs(a.get(i) - b.get(i)) > tolerance) return false; } return true; } // Check both ways - inefficient for dense, efficient for sparse for (VectorEntry e : a) { if (Math.abs(e.get() - b.get(e.index())) > tolerance) return false; } for (VectorEntry eb : b) { if (Math.abs(eb.get() - a.get(eb.index())) > tolerance) return false; } return true; } /** * Convenience for testing! * * @param x * @param xi * @return true if x has the values given by xi */ public static boolean equals(Vector x, double... xi) { return DataUtils.equals(x, DataUtils.newVector(xi)); } /** * Ignores class * * @see equalish which allows for rounding errors */ public static boolean equals(Vector a, Vector b) { // lenient size comparison (doesn't check for sparse vectors) if (a.size() != -1 && b.size() != -1 && a.size() < Integer.MAX_VALUE / 2 && b.size() < Integer.MAX_VALUE / 2) { if (a.size() != b.size()) return false; } // dense cases if (a instanceof DenseVector || a instanceof XY || a instanceof XYZ) { for (int i = 0, n = a.size(); i < n; i++) { if (a.get(i) != b.get(i)) return false; } return true; } // Check both ways - inefficient for dense, efficient for sparse for (VectorEntry e : a) { if (e.get() != b.get(e.index())) return false; } for (VectorEntry eb : b) { if (eb.get() != a.get(eb.index())) return false; } return true; } public static Vector filledVector(int dim, double value) { Vector v = new DenseVector(dim); for (int i = 0; i < dim; i++) { v.set(i, value); } return v; } /** * The "top-left"(min) and "bottom-right"(max) corners of a bounding * hyper-box for these data points. * * @param data * @return min, max */ public static Pair<Vector> getBounds(Iterable<? extends Vector> data) { assert data != null; assert data.iterator().hasNext() : "no data"; Vector first = data.iterator().next(); Vector min = first.copy(); Vector max = first.copy(); for (Vector vector : data) { for (VectorEntry ve : vector) { double v = ve.get(); assert MathUtils.isFinite(v) : vector; if (ve.get() > max.get(ve.index())) { max.set(ve.index(), v); } else if (ve.get() < min.get(ve.index())) { min.set(ve.index(), v); } } } return new Pair<Vector>(min, max); } /** * Create a box around a point. Useful for working with * {@link IDistribution}s which need a box to give a probability. * * @param x * @param dx * @return a top-left, bottom-right box, with x in the middle and width 2*dx * (i.e. we take a +/- dx step in each axes to reach a corner). * <p> * Note: It is probably a mistake to use this with high-dimensional * vectors - or at least, it suggests something strange. */ public static Pair<Vector> getBoxAround(Vector x, double dx) { int dim = x.size(); double[] a = new double[dim]; double[] b = new double[dim]; for (int i = 0; i < x.size(); i++) { a[i] = x.get(i) - dx; b[i] = x.get(i) + dx; } Vector av = DataUtils.newVector(a); Vector bv = DataUtils.newVector(b); return new Pair<Vector>(av, bv); } /** * Get the top num dimensions with the highest values. Note: you quite * probably want to call {@link abs} first! Otherwise large * negative numbers will be bottom of the list. * * @param vector * @param num * @return Can return less than n if the vector is small. * @testedby {@link VectorUtilsTest#testGetSortedIndices()} */ public static List<Integer> getSortedIndices(final Vector vector, int num) { TopNList<Integer> topn = new TopNList<Integer>(num, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { if (o1 == o2) return 0; double v1 = vector.get(o1); double v2 = vector.get(o2); if (v1 == v2) // arbitrary: order lowest index first return o1 < o2 ? -1 : 1; return -Double.compare(v1, v2); } }); for (VectorEntry ve : vector) { int i = ve.index(); topn.maybeAdd(i); } return topn; } public static double getVolume(Vector minCorner, Vector maxCorner) { assert minCorner.size() == maxCorner.size(); double volume = 1; for (int i = 0; i < minCorner.size(); i++) { double w = maxCorner.get(i) - minCorner.get(i); assert w >= 0 : minCorner + " " + maxCorner; volume *= w; } return volume; } /** * Check that each element is a finite number. * * @param x * @return true if finite, false if any element is infinite or NaN */ public static boolean isFinite(Vector x) { for (VectorEntry e : x) { if (!MathUtils.isFinite(e.get())) return false; } return true; } public static boolean isSafe(Vector x) { for (VectorEntry e : x) { if (!MathUtils.isSafe(e.get())) return false; } return true; } /** * Check that each element is a finite number. * * @param x * @return true if finite, false if any element is infinite or NaN */ public static boolean isFinite(Matrix x) { for (MatrixEntry e : x) { if ( ! MathUtils.isFinite(e.get())) return false; } return true; } public static boolean isSafe(Matrix x) { for (MatrixEntry e : x) { if ( ! MathUtils.isSafe(e.get())) return false; } return true; } public static boolean isNormalised(Vector normal) { double len = normal.norm(Norm.Two); return MathUtils.equalish(len, 1.0); } /** * @param x * @return true if x is zero */ public static boolean isZero(Vector x) { for (VectorEntry ve : x) { if (ve.get() != 0) return false; } return true; } /** * @param vectorValues * @return a new vector based on this array. This should copy the input * array. */ public static Vector newVector(double[] vectorValues) { int dim = vectorValues.length; if (dim == 1) return new X(vectorValues[0]); if (dim == 2) return new XY(vectorValues[0], vectorValues[1]); if (dim == 3) return new XYZ(vectorValues[0], vectorValues[1], vectorValues[2]); if (dim < 2000) return new DenseVector(vectorValues); return new SparseVector(new DenseVector(vectorValues, false)); } /** * Create a new vector of the given dimension. Selects an appropriate class, * switching from specialised-low-dim, to dense, to sparse. * * @param dim * @return zero in dim dimensions */ public static Vector newVector(int dim) { if (dim == 1) return new X(0); if (dim == 2) return new XY(0, 0); if (dim == 3) return new XYZ(0, 0, 0); if (dim < 2000) return new DenseVector(dim); return new SparseVector(dim); } /** * Create a zero vector of the same dimension as x * @param x * @return */ public static Vector newVector(Vector x) { if (x instanceof DenseVector) { return new DenseVector(x.size()); } return newVector(x.size()); } /** * Note: includes an assert check for NaN * * @param v * @return minimum value in v (note: negative numbers win) */ public static double min(Vector v) { double min = Double.POSITIVE_INFINITY; for (VectorEntry ve : v) { assert !Double.isNaN(ve.get()); if (ve.get() < min) { min = ve.get(); } } return min; } /** * @param x * @return mean of values in x (including zeroes) */ public static double mean(Vector x) { return StatsUtils.mean(DataUtils.toArray(x)); } /** * @param v * @return maximum value in v */ public static double max(Vector v) { double max = Double.NEGATIVE_INFINITY; for (VectorEntry ve : v) { if (ve.get() > max) { max = ve.get(); } } return max; } /** * Convenience method for the Euclidean norm */ public static double len(Vector x) { return x.norm(Norm.Two); } /** * Normalise a vector in place, v = v / |v| * * @param v * the vector to be normalised. Can be null (returns null). * @return v for convenience * @see StatsUtils#normaliseProbVector(double[]) */ public static Vector normalise(Vector v) throws FailureException { if (v==null) return null; double size = v.norm(Norm.Two); if (size == 0) throw new FailureException("Vector has no non-zero values"); v.scale(1.0 / size); return v; } /** * @param a * a vector * @param b * a scalar * @return Each element of a, to the power of scalar b */ public static Vector power(Vector a, Double b) { Vector result = newVector(a.size()); for (Integer idx = 0; idx < a.size(); idx++) { result.set(idx, Math.pow(a.get(idx), b)); } return result; } /** * Project a vector down into a subspace (as defined by a set of basis * vectors). * * @param vector * This is not edited directly. * @param basis * These should have length 1 * @return A copy of vector as projected onto the basis vectors. Dimensions * come from the basis vectors (e.g. 2 basis vectors = 2 * dimensions). */ public static Vector projectInto(Vector vector, Vector[] basis) { Vector projected = newVector(basis.length); for (int i = 0; i < basis.length; i++) { Vector e = basis[i]; assert isNormalised(e) : e; double ve = vector.dot(e); projected.set(i, ve); } return projected; } /** * @param var * @return copy of var with each entry square rooted. Convenient in * statistics to convert from variance to standard deviation. */ public static Vector sqrt(Vector var) { var = var.copy(); for (VectorEntry ve : var) { ve.set(Math.sqrt(ve.get())); } return var; } /** * @param dim * @return random vector, uniform over the [-0.5, 0.5]^n cuboid */ public static Vector randomVector(int dim) { Random r = Utils.getRandom(); Vector v = newVector(dim); for (int i = 0; i < dim; i++) { v.set(i, r.nextDouble() - 0.5); } return v; } /** * Subtract one vector from another, a = a - b; * * @param a * This will be edited! * @param b */ public static Vector subtract(Vector a, Vector b) { a.add(-1, b); return a; } /** * TODO should this be a copy? or can it be "possibly shared structure"? If * you want an array its probably for fast work * * @param v * @return array copy of v */ public static double[] toArray(Vector v) { assert v.size() < Integer.MAX_VALUE; // if (v instanceof DenseVector) { avoid the copy?? // return ((DenseVector) v).getData(); return new DenseVector(v).getData(); } /** * Project a vector down onto a sub-space which is one dimension less than * the space, but still in the same space. I.e. get the component of vector * which is orthogonal to the normal. * * @param vector * This is not edited directly. * @param normal * This should have length 1 * @return A copy of vector projected onto the (hyper)plane defined by the * given normal vector. Has the same dimensions as the input vector. */ public static Vector projectOrthogonal(Vector vector, Vector normal) { assert isNormalised(normal); vector = vector.copy(); // v - (v.n)n double vn = vector.dot(normal); vector.add(-vn, normal); return vector; } /** * Project a vector down onto a target line. I.e. get the component of * vector which is in the same direction to the normal. * * @param vector * This is not edited directly. * @param normal * This should have length 1 * @return A copy of vector projected onto the given normal vector. Has the * same dimensions as the input vector. */ public static Vector projectOnto(Vector vector, Vector normal) { assert isNormalised(normal); Vector proj = normal.copy(); // v - (v.n)n double vn = vector.dot(normal); proj.scale(vn); return proj; } /** * * @param m * @return [row][column] */ public static double[][] toArray(Matrix m) { double[][] vs = new double[m.numRows()][m.numColumns()]; for (MatrixEntry me : m) { vs[me.row()][me.column()] = me.get(); } return vs; } /** * * @param columns * @return */ public static ListDataStream combineColumns(List<double[]> columns) { KMatchPolicy policy = KMatchPolicy.IGNORE_TIMESTAMPS; List<IDataStream> dataStreams = new ArrayList(); for (double[] col : columns) { ListDataStream ds = new ListDataStream(col); dataStreams.add(ds); } ExtraDimensionsDataStream ds = new ExtraDimensionsDataStream(policy, dataStreams); return ds.list(); } public static Vector slice(Vector x, int start, int end) { if (start<0) start = x.size()+start; if (end<0) end = x.size()+end; double[] xs = Arrays.copyOfRange(toArray(x), start, end); return new DenseVector(xs); } /** * Sum the log of the likelihood. * Use logs because a product would likely run to zero * @param dist * @param data * @return */ public static double logLikelihood(IDistribution1D dist, double[] data) { double sum = 0; for (double d : data) { double ld = Math.log(dist.density(d)); sum += ld; } return sum; } } final class SubStream extends FilteredDataStream { private static final long serialVersionUID = 1L; private Time start; private Time end; public String toString() { return "SubStream["+base+"]["+start+" to "+end+"]"; } SubStream(IDataStream base, Time start, Time end) { super(base); this.start = start; this.end = end; } @Override protected Datum filter(Datum datum) { Time t = datum.getTime(); if (start != null && t.isBefore(start)) return null; if (end == null || t.isBefore(end)) return datum; // we've hit the end throw new EnoughAlreadyException(); } }
package io.fabric8.maven.docker.service; import com.google.common.collect.ImmutableMap; import io.fabric8.maven.docker.access.DockerAccess; import io.fabric8.maven.docker.access.DockerAccessException; import io.fabric8.maven.docker.config.BuildImageConfiguration; import io.fabric8.maven.docker.config.CleanupMode; import io.fabric8.maven.docker.config.ImageConfiguration; import io.fabric8.maven.docker.util.EnvUtil; import io.fabric8.maven.docker.util.ImageName; import io.fabric8.maven.docker.util.Logger; import io.fabric8.maven.docker.util.MojoParameters; import org.apache.maven.plugin.MojoExecutionException; import java.io.File; import java.util.Map; public class BuildService { private final DockerAccess docker; private final QueryService queryService; public final ArchiveService archiveService; private final Logger log; BuildService(DockerAccess docker, QueryService queryService, ArchiveService archiveService, Logger log) { this.docker = docker; this.queryService = queryService; this.archiveService = archiveService; this.log = log; } /** * Build an image * * @param imageConfig the image configuration * @param params mojo params for the project * @param noCache if not null, dictate the caching behaviour. Otherwise its taken from the build configuration * @param buildArgs * @throws DockerAccessException * @throws MojoExecutionException */ public void buildImage(ImageConfiguration imageConfig, MojoParameters params, boolean noCache, Map<String, String> buildArgs) throws DockerAccessException, MojoExecutionException { String imageName = imageConfig.getName(); ImageName.validate(imageName); BuildImageConfiguration buildConfig = imageConfig.getBuildConfiguration(); String oldImageId = null; CleanupMode cleanupMode = buildConfig.cleanupMode(); if (cleanupMode.isRemove()) { oldImageId = queryService.getImageId(imageName); } long time = System.currentTimeMillis(); File dockerArchive = archiveService.createArchive(imageName, buildConfig, params, log); log.info("%s: Created %s in %s", dockerArchive.getName(), imageConfig.getDescription(), EnvUtil.formatDurationTill(time)); Map<String, String> mergedBuildMap = prepareBuildArgs(buildArgs, buildConfig); // auto is now supported by docker, consider switching? String newImageId = doBuildImage(imageName, dockerArchive, getDockerfileName(buildConfig), cleanupMode.isRemove(), noCache, mergedBuildMap); log.info("%s: Built image %s",imageConfig.getDescription(), newImageId); if (oldImageId != null && !oldImageId.equals(newImageId)) { try { docker.removeImage(oldImageId, true); log.info("%s: Removed old image %s", imageConfig.getDescription(), oldImageId); } catch (DockerAccessException exp) { if (cleanupMode == CleanupMode.TRY_TO_REMOVE) { log.warn("%s: %s (old image)%s", imageConfig.getDescription(), exp.getMessage(), (exp.getCause() != null ? " [" + exp.getCause().getMessage() + "]" : "")); } else { throw exp; } } } } private Map<String, String> prepareBuildArgs(Map<String, String> buildArgs, BuildImageConfiguration buildConfig) { ImmutableMap.Builder<String, String> builder = ImmutableMap.<String, String>builder(). putAll(buildArgs); if(buildConfig.getArgs() != null){ builder.putAll(buildConfig.getArgs()); } return builder.build(); } private String getDockerfileName(BuildImageConfiguration buildConfig) { if (buildConfig.isDockerFileMode()) { return buildConfig.getDockerFile().getName(); } else { return null; } } private String doBuildImage(String imageName, File dockerArchive, String dockerfileName, boolean cleanUp, boolean noCache, Map<String, String> buildArgs) throws DockerAccessException, MojoExecutionException { docker.buildImage(imageName, dockerArchive, dockerfileName, cleanUp, noCache, buildArgs); return queryService.getImageId(imageName); } }
package edu.umd.cs.findbugs.ba.npe; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.ba.Debug; import edu.umd.cs.findbugs.ba.Location; import edu.umd.cs.findbugs.ba.XField; import edu.umd.cs.findbugs.ba.XMethod; import edu.umd.cs.findbugs.ba.XMethodParameter; /** * A class to abstractly represent values in stack slots, * indicating whether thoses values can be null, non-null, * null on some incoming path, or unknown. * * @author David Hovemeyer * @see IsNullValueFrame * @see IsNullValueAnalysis */ public class IsNullValue implements IsNullValueAnalysisFeatures, Debug { private static final boolean DEBUG_EXCEPTION = SystemProperties.getBoolean("inv.debugException"); private static final boolean DEBUG_KABOOM = SystemProperties.getBoolean("inv.debugKaboom"); /** Definitely null. */ private static final int NULL = 0; /** Definitely null because of a comparison to a known null value. */ private static final int CHECKED_NULL = 1; /** Definitely not null. */ private static final int NN = 2; /** Definitely not null because of a comparison to a known null value. */ private static final int CHECKED_NN = 3; /** Definitely not null an NPE would have occurred and we would not be here if it were null. */ private static final int NO_KABOOM_NN = 4; /** Null on some simple path (at most one branch) to current location. */ private static final int NSP = 5; /** Unknown value (method param, value read from heap, etc.), assumed not null. */ private static final int NN_UNKNOWN = 6; /** Null on some complex path (at least two branches) to current location. */ private static final int NCP2 = 7; /** Null on some complex path (at least three branches) to current location. */ private static final int NCP3 = 8; private static final int FLAG_SHIFT = 8; /** Value was propagated along an exception path. */ private static final int EXCEPTION = 1 << FLAG_SHIFT; /** Value is (potentially) null because of a parameter passed to the method. */ private static final int PARAM = 2 << FLAG_SHIFT; /** Value is (potentially) null because of a value returned from a called method. */ private static final int RETURN_VAL = 4 << FLAG_SHIFT; private static final int FIELD_VAL = 8 << FLAG_SHIFT; /** Value is (potentially) null because of a value returned from readline. */ private static final int READLINE_VAL = (16 << FLAG_SHIFT) | RETURN_VAL; private static final int FLAG_MASK = EXCEPTION | PARAM | RETURN_VAL | FIELD_VAL | READLINE_VAL; private static final int[][] mergeMatrix = { // NULL, CHECKED_NULL, NN, CHECKED_NN, NO_KABOOM_NN, NSP, NN_UNKNOWN, NCP2, NCP3 {NULL}, // NULL {NULL, CHECKED_NULL, }, // CHECKED_NULL {NSP, NSP, NN}, {NSP, NSP, NN, CHECKED_NN, }, // CHECKED_NN {NSP, NSP, NN, NN, NO_KABOOM_NN}, // NO_KABOOM_NN {NSP, NSP, NSP, NSP, NSP, NSP}, // NSP {NSP, NSP, NN_UNKNOWN, NN_UNKNOWN, NN_UNKNOWN, NSP, NN_UNKNOWN, }, // NN_UNKNOWN {NSP, NSP, NCP2, NCP2, NCP2, NSP, NCP2, NCP2,}, // NCP2 {NSP, NSP, NCP3, NCP3, NCP3, NSP, NCP3, NCP3, NCP3}// NCP3 }; private static final IsNullValue[][] instanceByFlagsList = createInstanceByFlagList(); private static IsNullValue[][] createInstanceByFlagList() { final int max = FLAG_MASK >>> FLAG_SHIFT; IsNullValue[][] result = new IsNullValue[max + 1][]; for (int i = 0; i <= max; ++i) { final int flags = i << FLAG_SHIFT; result[i] = new IsNullValue[]{ new IsNullValue(NULL | flags), new IsNullValue(CHECKED_NULL | flags), new IsNullValue(NN | flags), new IsNullValue(CHECKED_NN | flags), null, // NO_KABOOM_NN values must be allocated dynamically new IsNullValue(NSP | flags), new IsNullValue(NN_UNKNOWN | flags), new IsNullValue(NCP2 | flags), new IsNullValue(NCP3 | flags), }; } return result; } // Fields private final int kind; private final Location locationOfKaBoom; private IsNullValue(int kind) { this.kind = kind; locationOfKaBoom = null; if (VERIFY_INTEGRITY) checkNoKaboomNNLocation(); } private IsNullValue(int kind, Location ins) { this.kind = kind; locationOfKaBoom = ins; if (VERIFY_INTEGRITY) checkNoKaboomNNLocation(); } private void checkNoKaboomNNLocation() { if (getBaseKind() == NO_KABOOM_NN && locationOfKaBoom == null) { throw new IllegalStateException("construction of no-KaBoom NN without Location"); } } @Override public boolean equals(Object o) { if (o == null || this.getClass() != o.getClass()) return false; IsNullValue other = (IsNullValue) o; if ( kind != other.kind) return false; if (locationOfKaBoom == other.locationOfKaBoom) return true; if (locationOfKaBoom == null || other.locationOfKaBoom == null) return false; return locationOfKaBoom.equals(other.locationOfKaBoom); } @Override public int hashCode() { int hashCode = kind; if (locationOfKaBoom != null) hashCode += locationOfKaBoom.hashCode(); return hashCode; } private int getBaseKind() { return kind & ~FLAG_MASK; } private int getFlags() { return kind & FLAG_MASK; } private boolean hasFlag(int flag) { return (kind & flag) == flag; } /** * Was this value propagated on an exception path? */ public boolean isException() { return hasFlag(EXCEPTION); } /** * Was this value marked as a possibly null return value? */ public boolean isReturnValue() { return hasFlag(RETURN_VAL); } public boolean isReadlineValue() { return hasFlag(READLINE_VAL); } public boolean isFieldValue() { return hasFlag(FIELD_VAL); } /** * Was this value marked as a possibly null parameter? */ public boolean isParamValue() { return (kind & PARAM) != 0; } /** * Is this value known because of an explicit null check? */ public boolean isChecked() { return getBaseKind() == CHECKED_NULL || getBaseKind() == CHECKED_NN; } /** * Is this value known to be non null because a NPE would have occurred otherwise? */ public boolean wouldHaveBeenAKaboom() { return getBaseKind() == NO_KABOOM_NN; } private IsNullValue toBaseValue() { return instanceByFlagsList[0][getBaseKind()]; } /** * Convert to an exception path value. */ public IsNullValue toExceptionValue() { if (getBaseKind() == NO_KABOOM_NN) return new IsNullValue(kind | EXCEPTION, locationOfKaBoom); return instanceByFlagsList[(getFlags() | EXCEPTION) >> FLAG_SHIFT][getBaseKind()]; } /** * Convert to a value known because it was returned from a method * in a method property database. * @param methodInvoked TODO */ public IsNullValue markInformationAsComingFromReturnValueOfMethod(XMethod methodInvoked) { int flag = RETURN_VAL; if (methodInvoked.getName().equals("readLine") && methodInvoked.getSignature().equals("()Ljava/lang/String;")) flag = READLINE_VAL; if (getBaseKind() == NO_KABOOM_NN) return new IsNullValue(kind | flag, locationOfKaBoom); return instanceByFlagsList[(getFlags() | flag) >> FLAG_SHIFT][getBaseKind()]; } /** * Convert to a value known because it was returned from a method * in a method property database. * @param field TODO */ public IsNullValue markInformationAsComingFromFieldValue(XField field) { if (getBaseKind() == NO_KABOOM_NN) return new IsNullValue(kind | FIELD_VAL, locationOfKaBoom); return instanceByFlagsList[(getFlags() | FIELD_VAL) >> FLAG_SHIFT][getBaseKind()]; } /** * Get the instance representing values that are definitely null. */ public static IsNullValue nullValue() { return instanceByFlagsList[0][NULL]; } /** * Get the instance representing a value known to be null * because it was compared against null value, or because * we saw that it was assigned the null constant. */ public static IsNullValue checkedNullValue() { return instanceByFlagsList[0][CHECKED_NULL]; } /** * Get the instance representing values that are definitely not null. */ public static IsNullValue nonNullValue() { return instanceByFlagsList[0][NN]; } /** * Get the instance representing a value known to be non-null * because it was compared against null value, or because * we saw the object creation. */ public static IsNullValue checkedNonNullValue() { return instanceByFlagsList[0][CHECKED_NN]; } /** * Get the instance representing a value known to be non-null * because a NPE would have occurred if it were null. */ public static IsNullValue noKaboomNonNullValue(@NonNull Location ins) { if (ins == null) throw new NullPointerException("ins cannot be null"); return new IsNullValue(NO_KABOOM_NN, ins); } /** * Get the instance representing values that are definitely null * on some simple (no branches) incoming path. */ public static IsNullValue nullOnSimplePathValue() { return instanceByFlagsList[0][NSP]; } /** * Get instance representing a parameter marked as MightBeNull */ public static IsNullValue parameterMarkedAsMightBeNull(XMethodParameter mp) { return instanceByFlagsList[PARAM >> FLAG_SHIFT][NSP]; } /** * Get non-reporting non-null value. * This is what we use for unknown values. */ public static IsNullValue nonReportingNotNullValue() { return instanceByFlagsList[0][NN_UNKNOWN]; } /** * Get null on complex path value. * This is like null on simple path value, but there * are at least two branches between the explicit null value * and the current location. If the conditions are correlated, * then the path on which the value is null may be infeasible. */ public static IsNullValue nullOnComplexPathValue() { return instanceByFlagsList[0][NCP2]; } /** * Like "null on complex path" except that there are at least * <em>three</em> branches between the explicit null value * and the current location. */ public static IsNullValue nullOnComplexPathValue3() { return instanceByFlagsList[0][NCP3]; } /** * Get null value resulting from comparison to explicit null. */ public static IsNullValue pathSensitiveNullValue() { return instanceByFlagsList[0][CHECKED_NULL]; } /** * Get non-null value resulting from comparison to explicit null. */ public static IsNullValue pathSensitiveNonNullValue() { return instanceByFlagsList[0][CHECKED_NN]; } /** * Merge two values. */ public static IsNullValue merge(IsNullValue a, IsNullValue b) { if (a == b) return a; if (a.equals(b)) return a; int aKind = a.kind & 0xff; int bKind = b.kind & 0xff; int aFlags = a.getFlags(); int bFlags = b.getFlags(); int combinedFlags = aFlags & bFlags; if (!(a.isNullOnSomePath() || a.isDefinitelyNull()) && b.isException()) combinedFlags |= EXCEPTION; else if (!(b.isNullOnSomePath() || b.isDefinitelyNull()) && a.isException()) combinedFlags |= EXCEPTION; // Left hand value should be >=, since it is used // as the first dimension of the matrix to index. if (aKind < bKind) { int tmp = aKind; aKind = bKind; bKind = tmp; } assert aKind >= bKind; int result = mergeMatrix[aKind][bKind]; IsNullValue resultValue = (result == NO_KABOOM_NN) ? noKaboomNonNullValue(a.locationOfKaBoom) : instanceByFlagsList[combinedFlags >> FLAG_SHIFT][result]; return resultValue; } /** * Is this value definitely null? */ public boolean isDefinitelyNull() { int baseKind = getBaseKind(); return baseKind == NULL || baseKind == CHECKED_NULL; } /** * Is this value null on some path? */ public boolean isNullOnSomePath() { int baseKind = getBaseKind(); if (NCP_EXTRA_BRANCH) { // Note: NCP_EXTRA_BRANCH is an experimental feature // to see how many false warnings we get when we allow // two branches between an explicit null and a // a dereference. return baseKind == NSP || baseKind == NCP2; } else { return baseKind == NSP; } } /** * Is this value null on a complicated path? */ public boolean isNullOnComplicatedPath() { int baseKind = getBaseKind(); return baseKind == NN_UNKNOWN || baseKind == NCP2 || baseKind == NCP3; } /** * Return true if this value is either definitely null, * or might be null on a simple path. * * @return true if this value is either definitely null, * or might be null on a simple path, false otherwise */ public boolean mightBeNull() { return isDefinitelyNull() || isNullOnSomePath(); } /** * Is this value definitely not null? */ public boolean isDefinitelyNotNull() { int baseKind = getBaseKind(); return baseKind == NN || baseKind == CHECKED_NN || baseKind == NO_KABOOM_NN; } @Override public String toString() { String pfx = ""; if (DEBUG_EXCEPTION) { int flags = getFlags(); if (flags == 0) pfx = "_"; else { if ((flags & EXCEPTION) != 0) pfx += "e"; if ((flags & PARAM) != 0) pfx += "p"; if ((flags & RETURN_VAL) != 0) pfx += "r"; if ((flags & FIELD_VAL) != 0) pfx += "f"; } } if (DEBUG_KABOOM && locationOfKaBoom == null) { pfx += "[?]"; } switch (getBaseKind()) { case NULL: return pfx + "n" + ","; case CHECKED_NULL: return pfx + "w" + ","; case NN: return pfx + "N" + ","; case CHECKED_NN: return pfx + "W" + ","; case NO_KABOOM_NN: return pfx + "K" + ","; case NSP: return pfx + "s" + ","; case NN_UNKNOWN: return pfx + "-" + ","; case NCP2: return pfx + "/" + ","; default: throw new IllegalStateException("unknown kind of IsNullValue: " + kind); } } public Location getLocationOfKaBoom() { return locationOfKaBoom; } /** * Control split: move given value down in the lattice * if it is a conditionally-null value. * * @return another value (equal or further down in the lattice) */ public IsNullValue downgradeOnControlSplit() { IsNullValue value = this; if (NCP_EXTRA_BRANCH) { // Experimental: track two distinct kinds of "null on complex path" values. if (value.isNullOnSomePath()) value = nullOnComplexPathValue(); else if (value.equals(nullOnComplexPathValue())) value = nullOnComplexPathValue3(); } else { // Downgrade "null on simple path" values to // "null on complex path". if (value.isNullOnSomePath()) value = nullOnComplexPathValue(); } return value; } } // vim:ts=4
package edu.umd.cs.findbugs.detect; import java.util.HashSet; import java.util.Iterator; import org.apache.bcel.classfile.Attribute; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.CodeException; import org.apache.bcel.classfile.Constant; import org.apache.bcel.classfile.ConstantClass; import org.apache.bcel.classfile.ConstantPool; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import org.apache.bcel.classfile.Synthetic; import org.apache.bcel.generic.ObjectType; import org.apache.bcel.generic.ReferenceType; import org.apache.bcel.generic.Type; import edu.umd.cs.findbugs.BugAccumulator; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.ClassAnnotation; import edu.umd.cs.findbugs.IntAnnotation; import edu.umd.cs.findbugs.JavaVersion; import edu.umd.cs.findbugs.LocalVariableAnnotation; import edu.umd.cs.findbugs.MethodAnnotation; import edu.umd.cs.findbugs.OpcodeStack; import edu.umd.cs.findbugs.Priorities; import edu.umd.cs.findbugs.SourceLineAnnotation; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.CFGBuilderException; import edu.umd.cs.findbugs.ba.DataflowAnalysisException; import edu.umd.cs.findbugs.ba.Hierarchy; import edu.umd.cs.findbugs.ba.ObjectTypeFactory; import edu.umd.cs.findbugs.ba.SignatureParser; import edu.umd.cs.findbugs.ba.XMethod; import edu.umd.cs.findbugs.ba.type.TypeDataflow; import edu.umd.cs.findbugs.bcel.OpcodeStackDetector; import edu.umd.cs.findbugs.classfile.ClassDescriptor; import edu.umd.cs.findbugs.classfile.DescriptorFactory; public class DumbMethods extends OpcodeStackDetector { private static final ObjectType CONDITION_TYPE = ObjectTypeFactory.getInstance("java.util.concurrent.locks.Condition"); private final BugReporter bugReporter; private boolean sawCurrentTimeMillis; private BugInstance gcInvocationBugReport; private int gcInvocationPC; private CodeException[] exceptionTable; /* private boolean sawLDCEmptyString; */ private String primitiveObjCtorSeen; private boolean ctorSeen; private boolean prevOpcodeWasReadLine; private int prevOpcode; private boolean isPublicStaticVoidMain; private boolean isEqualsObject; private boolean sawInstanceofCheck; private boolean reportedBadCastInEquals; private int sawCheckForNonNegativeSignedByte; private int sinceBufferedInputStreamReady; private int randomNextIntState; private boolean checkForBitIorofSignedByte; private final boolean jdk15ChecksEnabled; private final BugAccumulator accumulator; public DumbMethods(BugReporter bugReporter) { this.bugReporter = bugReporter; accumulator = new BugAccumulator(bugReporter); jdk15ChecksEnabled = JavaVersion.getRuntimeVersion().isSameOrNewerThan(JavaVersion.JAVA_1_5); } boolean isSynthetic; @Override public void visit(JavaClass obj) { String superclassName = obj.getSuperclassName(); isSynthetic = superclassName.equals("java.rmi.server.RemoteStub"); Attribute[] attributes = obj.getAttributes(); if (attributes != null) { for(Attribute a : attributes) { if (a instanceof Synthetic) { isSynthetic = true; } } } } @Override public void visitAfter(JavaClass obj) { accumulator.reportAccumulatedBugs(); } public static boolean isTestMethod(Method method) { return method.getName().startsWith("test"); } @Override public void visit(Method method) { String cName = getDottedClassName(); // System.out.println(getFullyQualifiedMethodName()); isPublicStaticVoidMain = method.isPublic() && method.isStatic() && getMethodName().equals("main") || cName.toLowerCase().indexOf("benchmark") >= 0; prevOpcodeWasReadLine = false; Code code = method.getCode(); if (code != null) { this.exceptionTable = code.getExceptionTable(); } if (this.exceptionTable == null) { this.exceptionTable = new CodeException[0]; } primitiveObjCtorSeen = null; ctorSeen = false; randomNextIntState = 0; checkForBitIorofSignedByte = false; isEqualsObject = getMethodName().equals("equals") && getMethodSig().equals("(Ljava/lang/Object;)Z") && !method.isStatic(); sawInstanceofCheck = false; reportedBadCastInEquals = false; freshRandomOnTos = false; sinceBufferedInputStreamReady = 100000; sawCheckForNonNegativeSignedByte = -1000; } int opcodesSincePendingAbsoluteValueBug; BugInstance pendingAbsoluteValueBug; SourceLineAnnotation pendingAbsoluteValueBugSourceLine; boolean freshRandomOnTos = false; boolean freshRandomOneBelowTos = false; static boolean isPowerOfTwo(int i) { if (i <= 0) { return false; } if ((i | (i-1))+1 == 2*i) { return true; } return false; } @Override public void sawOpcode(int seen) { if (stack.getStackDepth() >= 2) switch(seen) { case IF_ICMPEQ: case IF_ICMPNE: case IF_ICMPLE: case IF_ICMPGE: case IF_ICMPLT: case IF_ICMPGT: OpcodeStack.Item item0 = stack.getStackItem(0); OpcodeStack.Item item1 = stack.getStackItem(1); if (item0.getConstant() instanceof Integer) { OpcodeStack.Item tmp = item0; item0 = item1; item1 = tmp; } Object constant1 = item1.getConstant(); XMethod returnValueOf = item0.getReturnValueOf(); if (constant1 instanceof Integer && returnValueOf != null && returnValueOf.getName().equals("getYear") && (returnValueOf.getClassName().equals("java.util.Date") || returnValueOf.getClassName().equals("java.sql.Date"))) { int year = (Integer) constant1; if (year > 1900) accumulator.accumulateBug(new BugInstance(this, "UNKNOWN", HIGH_PRIORITY) .addClassAndMethod(this) .addMethod(returnValueOf).describe(MethodAnnotation.METHOD_CALLED) .addInt(year).describe(IntAnnotation.INT_VALUE), this); } } // System.out.printf("%4d %10s: %s\n", getPC(), OPCODE_NAMES[seen], stack); if (seen == IFLT && stack.getStackDepth() > 0 && stack.getStackItem(0).getSpecialKind() == OpcodeStack.Item.SIGNED_BYTE) { sawCheckForNonNegativeSignedByte = getPC(); } if (pendingAbsoluteValueBug != null) { if (opcodesSincePendingAbsoluteValueBug == 0) { opcodesSincePendingAbsoluteValueBug++; } else { if (seen == IREM) { OpcodeStack.Item top = stack.getStackItem(0); Object constantValue = top.getConstant(); if (constantValue instanceof Number && isPowerOfTwo(((Number) constantValue).intValue())) { pendingAbsoluteValueBug.setPriority(Priorities.LOW_PRIORITY); } } accumulator.accumulateBug(pendingAbsoluteValueBug, pendingAbsoluteValueBugSourceLine); pendingAbsoluteValueBug = null; pendingAbsoluteValueBugSourceLine = null; } } if (seen == INVOKESTATIC && getClassConstantOperand().equals("org/easymock/EasyMock") && (getNameConstantOperand().equals("replay") || getNameConstantOperand().equals("verify") || getNameConstantOperand().startsWith("reset")) && getSigConstantOperand().equals("([Ljava/lang/Object;)V") && getPrevOpcode(1) == ANEWARRAY && getPrevOpcode(2) == ICONST_0) accumulator.accumulateBug(new BugInstance(this, "DMI_VACUOUS_CALL_TO_EASYMOCK_METHOD", NORMAL_PRIORITY) .addClassAndMethod(this) .addCalledMethod(this),this); if ((seen == INVOKESTATIC || seen == INVOKEVIRTUAL || seen == INVOKESPECIAL || seen == INVOKEINTERFACE) && getSigConstantOperand().indexOf("Ljava/lang/Runnable;") >= 0) { SignatureParser parser = new SignatureParser(getSigConstantOperand()); int count = 0; for(Iterator<String> i = parser.parameterSignatureIterator(); i.hasNext(); count++) { String parameter = i.next(); if (parameter.equals("Ljava/lang/Runnable;")) { OpcodeStack.Item item = stack.getStackItem(parser.getNumParameters() - 1 - count); if ("Ljava/lang/Thread;".equals(item.getSignature())) { accumulator.accumulateBug(new BugInstance(this, "DMI_THREAD_PASSED_WHERE_RUNNABLE_EXPECTED", NORMAL_PRIORITY) .addClassAndMethod(this) .addCalledMethod(this),this); } } } } if (prevOpcode == I2L && seen == INVOKESTATIC && getClassConstantOperand().equals("java/lang/Double") && getNameConstantOperand() .equals("longBitsToDouble")) { accumulator.accumulateBug(new BugInstance(this, "DMI_LONG_BITS_TO_DOUBLE_INVOKED_ON_INT", HIGH_PRIORITY) .addClassAndMethod(this) .addCalledMethod(this), this); } if (freshRandomOnTos && seen == INVOKEVIRTUAL || freshRandomOneBelowTos && seen == INVOKEVIRTUAL && getClassConstantOperand().equals("java/util/Random") ) { accumulator.accumulateBug(new BugInstance(this, "DMI_RANDOM_USED_ONLY_ONCE", HIGH_PRIORITY) .addClassAndMethod(this) .addCalledMethod(this), this); } freshRandomOneBelowTos = freshRandomOnTos && isRegisterLoad(); freshRandomOnTos = seen == INVOKESPECIAL && getClassConstantOperand().equals("java/util/Random") && getNameConstantOperand().equals("<init>"); if ((seen == INVOKEVIRTUAL && getClassConstantOperand().equals("java/util/HashMap") && getNameConstantOperand() .equals("get")) || (seen == INVOKEINTERFACE && getClassConstantOperand().equals("java/util/Map") && getNameConstantOperand() .equals("get")) || (seen == INVOKEVIRTUAL && getClassConstantOperand() .equals("java/util/HashSet") && getNameConstantOperand() .equals("contains")) || (seen == INVOKEINTERFACE && getClassConstantOperand().equals("java/util/Set") && getNameConstantOperand() .equals("contains"))) { OpcodeStack.Item top = stack.getStackItem(0); if (top.getSignature().equals("Ljava/net/URL;")) { accumulator.accumulateBug(new BugInstance(this, "DMI_COLLECTION_OF_URLS", HIGH_PRIORITY) .addClassAndMethod(this), this); } } /** Since you can change the number of core threads for a scheduled thread pool executor, disabling this for now */ if (false && seen == INVOKESPECIAL && getClassConstantOperand().equals("java/util/concurrent/ScheduledThreadPoolExecutor") && getNameConstantOperand().equals("<init>")) { int arguments = getNumberArguments(getSigConstantOperand()); OpcodeStack.Item item = stack.getStackItem(arguments - 1); Object value = item.getConstant(); if (value instanceof Integer && ((Integer) value).intValue() == 0) accumulator.accumulateBug(new BugInstance(this, "DMI_SCHEDULED_THREAD_POOL_EXECUTOR_WITH_ZERO_CORE_THREADS", HIGH_PRIORITY).addClassAndMethod(this), this); } if (seen == INVOKEVIRTUAL && getClassConstantOperand().equals("java/util/concurrent/ScheduledThreadPoolExecutor") && getNameConstantOperand().equals("setMaximumPoolSize")) { accumulator.accumulateBug(new BugInstance(this, "DMI_FUTILE_ATTEMPT_TO_CHANGE_MAXPOOL_SIZE_OF_SCHEDULED_THREAD_POOL_EXECUTOR", HIGH_PRIORITY).addClassAndMethod(this), this); } if (isEqualsObject && !reportedBadCastInEquals) { if (seen == INSTANCEOF || seen == INVOKEVIRTUAL && getNameConstantOperand().equals("getClass") && getSigConstantOperand().equals("()Ljava/lang/Class;") ) { OpcodeStack.Item item = stack.getStackItem(0); if (item.getRegisterNumber() == 1) { sawInstanceofCheck = true; } } else if (seen == INVOKESPECIAL && getNameConstantOperand().equals("equals") && getSigConstantOperand().equals("(Ljava/lang/Object;)Z")) { OpcodeStack.Item item0 = stack.getStackItem(0); OpcodeStack.Item item1 = stack.getStackItem(1); if (item1.getRegisterNumber() + item0.getRegisterNumber() == 1) { sawInstanceofCheck = true; } } else if (seen == CHECKCAST && !sawInstanceofCheck) { OpcodeStack.Item item = stack.getStackItem(0); if (item.getRegisterNumber() == 1) { if (getSizeOfSurroundingTryBlock(getPC()) == Integer.MAX_VALUE) { accumulator.accumulateBug(new BugInstance(this, "BC_EQUALS_METHOD_SHOULD_WORK_FOR_ALL_OBJECTS", NORMAL_PRIORITY) .addClassAndMethod(this), this); } reportedBadCastInEquals = true; } } } { boolean foundVacuousComparison = false; if (seen == IF_ICMPGT || seen == IF_ICMPLE) { OpcodeStack.Item rhs = stack.getStackItem(0); Object rhsConstant = rhs.getConstant(); if (rhsConstant instanceof Integer && ((Integer)rhsConstant).intValue() == Integer.MAX_VALUE) { foundVacuousComparison = true; } OpcodeStack.Item lhs = stack.getStackItem(1); Object lhsConstant = lhs.getConstant(); if (lhsConstant instanceof Integer && ((Integer)lhsConstant).intValue() == Integer.MIN_VALUE) { foundVacuousComparison = true; } } if (seen == IF_ICMPLT || seen == IF_ICMPGE) { OpcodeStack.Item rhs = stack.getStackItem(0); Object rhsConstant = rhs.getConstant(); if (rhsConstant instanceof Integer && ((Integer)rhsConstant).intValue() == Integer.MIN_VALUE) { foundVacuousComparison = true; } OpcodeStack.Item lhs = stack.getStackItem(1); Object lhsConstant = lhs.getConstant(); if (lhsConstant instanceof Integer && ((Integer)lhsConstant).intValue() == Integer.MAX_VALUE) { foundVacuousComparison = true; } } if (foundVacuousComparison) { accumulator.accumulateBug(new BugInstance(this, "INT_VACUOUS_COMPARISON", getBranchOffset() < 0 ? HIGH_PRIORITY : NORMAL_PRIORITY) .addClassAndMethod(this), this); } } if (seen == INVOKESTATIC && ( getClassConstantOperand().equals("java/lang/Math") || getClassConstantOperand().equals("java/lang/StrictMath")) && getNameConstantOperand().equals("abs") && getSigConstantOperand().equals("(I)I")) { OpcodeStack.Item item0 = stack.getStackItem(0); int special = item0.getSpecialKind(); if (special == OpcodeStack.Item.RANDOM_INT) { pendingAbsoluteValueBug = new BugInstance(this, "RV_ABSOLUTE_VALUE_OF_RANDOM_INT", HIGH_PRIORITY) .addClassAndMethod(this); pendingAbsoluteValueBugSourceLine = SourceLineAnnotation.fromVisitedInstruction(this); opcodesSincePendingAbsoluteValueBug = 0; } else if (special == OpcodeStack.Item.HASHCODE_INT) { pendingAbsoluteValueBug = new BugInstance(this, "RV_ABSOLUTE_VALUE_OF_HASHCODE", HIGH_PRIORITY) .addClassAndMethod(this); pendingAbsoluteValueBugSourceLine = SourceLineAnnotation.fromVisitedInstruction(this); opcodesSincePendingAbsoluteValueBug = 0; } } try { int stackLoc = stackEntryThatMustBeNonnegative(seen); if (stackLoc >= 0) { OpcodeStack.Item tos = stack.getStackItem(stackLoc); switch (tos.getSpecialKind()) { case OpcodeStack.Item.HASHCODE_INT_REMAINDER: accumulator.accumulateBug(new BugInstance(this, "RV_REM_OF_HASHCODE", HIGH_PRIORITY) .addClassAndMethod(this), this); break; case OpcodeStack.Item.RANDOM_INT: case OpcodeStack.Item.RANDOM_INT_REMAINDER: accumulator.accumulateBug(new BugInstance(this, "RV_REM_OF_RANDOM_INT", HIGH_PRIORITY) .addClassAndMethod(this), this); break; } } if (seen == IREM) { OpcodeStack.Item item0 = stack.getStackItem(0); Object constant0 = item0.getConstant(); if (constant0 instanceof Integer && ((Integer)constant0).intValue() == 1) { accumulator.accumulateBug(new BugInstance(this, "INT_BAD_REM_BY_1", HIGH_PRIORITY) .addClassAndMethod(this), this); } } if (stack.getStackDepth() >= 1 && (seen == LOOKUPSWITCH || seen == TABLESWITCH)) { OpcodeStack.Item item0 = stack.getStackItem(0); if (item0.getSpecialKind() == OpcodeStack.Item.SIGNED_BYTE) { int[] switchLabels = getSwitchLabels(); int [] switchOffsets = getSwitchOffsets(); for(int i = 0; i < switchLabels.length; i++) { int v = switchLabels[i]; if (v <= -129 || v >= 128) { accumulator.accumulateBug(new BugInstance(this, "INT_BAD_COMPARISON_WITH_SIGNED_BYTE", HIGH_PRIORITY) .addClassAndMethod(this) .addInt(v).describe(IntAnnotation.INT_VALUE), SourceLineAnnotation.fromVisitedInstruction(this, getPC() + switchOffsets[i])); } } } } // check for use of signed byte where is it assumed it can be out of the -128...127 range if (stack.getStackDepth() >= 2) { switch (seen) { case IF_ICMPEQ: case IF_ICMPNE: case IF_ICMPLT: case IF_ICMPLE: case IF_ICMPGE: case IF_ICMPGT: OpcodeStack.Item item0 = stack.getStackItem(0); OpcodeStack.Item item1 = stack.getStackItem(1); int seen2 = seen; if (item0.getConstant() != null) { OpcodeStack.Item tmp = item0; item0 = item1; item1 = tmp; switch(seen) { case IF_ICMPLT: seen2 = IF_ICMPGT; break; case IF_ICMPGE: seen2 = IF_ICMPLE; break; case IF_ICMPGT: seen2 = IF_ICMPLT; break; case IF_ICMPLE: seen2 = IF_ICMPGE; break; } } Object constant1 = item1.getConstant(); if (item0.getSpecialKind() == OpcodeStack.Item.SIGNED_BYTE && constant1 instanceof Number) { int v1 = ((Number)constant1).intValue(); if (v1 <= -129 || v1 >= 128 || v1 == 127 && !(seen2 == IF_ICMPEQ || seen2 == IF_ICMPNE )) { int priority = HIGH_PRIORITY; if (v1 == 127) { switch(seen2) { case IF_ICMPGT: // 127 > x priority = LOW_PRIORITY; break; case IF_ICMPGE: // 127 >= x : always true priority = HIGH_PRIORITY; break; case IF_ICMPLT: // 127 < x : never true priority = HIGH_PRIORITY; break; case IF_ICMPLE: // 127 <= x priority = LOW_PRIORITY; break; } } else if (v1 == 128) { switch(seen2) { case IF_ICMPGT: // 128 > x priority = NORMAL_PRIORITY; break; case IF_ICMPGE: // 128 >= x priority = HIGH_PRIORITY; break; case IF_ICMPLT: // 128 < x priority = HIGH_PRIORITY; break; case IF_ICMPLE: // 128 <= x priority = HIGH_PRIORITY; break; } } else if (v1 <= -129) { priority = NORMAL_PRIORITY; } if (getPC() - sawCheckForNonNegativeSignedByte < 10) priority++; accumulator.accumulateBug(new BugInstance(this, "INT_BAD_COMPARISON_WITH_SIGNED_BYTE", priority) .addClassAndMethod(this) .addInt(v1).describe(IntAnnotation.INT_VALUE), this); } } else if (item0.getSpecialKind() == OpcodeStack.Item.NON_NEGATIVE && constant1 instanceof Number) { int v1 = ((Number)constant1).intValue(); if (v1 < 0) { accumulator.accumulateBug(new BugInstance(this, "INT_BAD_COMPARISON_WITH_NONNEGATIVE_VALUE", HIGH_PRIORITY) .addClassAndMethod(this) .addInt(v1).describe(IntAnnotation.INT_VALUE), this); } } } } switch(seen) { case IAND: case LAND: case IOR: case LOR: case IXOR: case LXOR: long badValue = (seen == IAND || seen == LAND) ? -1 : 0; OpcodeStack.Item rhs = stack.getStackItem(0); OpcodeStack.Item lhs = stack.getStackItem(1); int prevOpcode = getPrevOpcode(1); int prevPrevOpcode = getPrevOpcode(2); if (rhs.hasConstantValue(badValue) && (prevOpcode == LDC || prevOpcode == ICONST_0 || prevOpcode == ICONST_M1 || prevOpcode == LCONST_0) && prevPrevOpcode != GOTO) reportVacuousBitOperation(seen, lhs); } if (checkForBitIorofSignedByte && seen != I2B) { String pattern = (prevOpcode == LOR || prevOpcode == IOR) ? "BIT_IOR_OF_SIGNED_BYTE" : "BIT_ADD_OF_SIGNED_BYTE"; int priority = (prevOpcode == LOR || prevOpcode == LADD) ? HIGH_PRIORITY : NORMAL_PRIORITY; accumulator.accumulateBug(new BugInstance(this, pattern , priority) .addClassAndMethod(this), this); checkForBitIorofSignedByte = false; } else if ((seen == IOR || seen == LOR || seen == IADD || seen == LADD) && stack.getStackDepth() >= 2) { OpcodeStack.Item item0 = stack.getStackItem(0); OpcodeStack.Item item1 = stack.getStackItem(1); int special0 = item0.getSpecialKind(); int special1 = item1.getSpecialKind(); if (special0 == OpcodeStack.Item.SIGNED_BYTE && special1 == OpcodeStack.Item.LOW_8_BITS_CLEAR && !item1.hasConstantValue(256) || special0 == OpcodeStack.Item.LOW_8_BITS_CLEAR && !item0.hasConstantValue(256) && special1 == OpcodeStack.Item.SIGNED_BYTE ) { checkForBitIorofSignedByte = true; } else { checkForBitIorofSignedByte = false; } } else { checkForBitIorofSignedByte = false; } if (prevOpcodeWasReadLine && sinceBufferedInputStreamReady >= 100 && seen == INVOKEVIRTUAL && getClassConstantOperand().equals("java/lang/String") && getSigConstantOperand().startsWith("()")) { accumulator.accumulateBug(new BugInstance(this, "NP_IMMEDIATE_DEREFERENCE_OF_READLINE", NORMAL_PRIORITY) .addClassAndMethod(this), this); } if (seen == INVOKEVIRTUAL && getClassConstantOperand().equals("java/io/BufferedReader") && getNameConstantOperand().equals("ready") && getSigConstantOperand().equals("()Z")) { sinceBufferedInputStreamReady = 0; } else { sinceBufferedInputStreamReady++; } prevOpcodeWasReadLine = (seen == INVOKEVIRTUAL||seen == INVOKEINTERFACE) && getNameConstantOperand().equals("readLine") && getSigConstantOperand().equals("()Ljava/lang/String;"); // System.out.println(randomNextIntState + " " + OPCODE_NAMES[seen] + " " + getMethodName()); switch(randomNextIntState) { case 0: if (seen == INVOKEVIRTUAL && getClassConstantOperand().equals("java/util/Random") && getNameConstantOperand().equals("nextDouble") || seen == INVOKESTATIC && getClassConstantOperand().equals("java/lang/Math") && getNameConstantOperand().equals("random")) { randomNextIntState = 1; } break; case 1: if (seen == D2I) { accumulator.accumulateBug(new BugInstance(this, "RV_01_TO_INT", HIGH_PRIORITY) .addClassAndMethod(this), this); randomNextIntState = 0; } else if (seen == DMUL) { randomNextIntState = 4; } else { randomNextIntState = 2; } break; case 2: if (seen == I2D) { randomNextIntState = 3; } else if (seen == DMUL) { randomNextIntState = 4; } else { randomNextIntState = 0; } break; case 3: if (seen == DMUL) { randomNextIntState = 4; } else { randomNextIntState = 0; } break; case 4: if (seen == D2I) { accumulator.accumulateBug(new BugInstance(this, "DM_NEXTINT_VIA_NEXTDOUBLE", NORMAL_PRIORITY) .addClassAndMethod(this), this); } randomNextIntState = 0; break; default: throw new IllegalStateException(); } if (isPublicStaticVoidMain && seen == INVOKEVIRTUAL && getClassConstantOperand().startsWith("javax/swing/") && (getNameConstantOperand().equals("show") && getSigConstantOperand().equals("()V") || getNameConstantOperand().equals("pack") && getSigConstantOperand().equals("()V") || getNameConstantOperand().equals("setVisible") && getSigConstantOperand().equals("(Z)V"))) { accumulator.accumulateBug(new BugInstance(this, "SW_SWING_METHODS_INVOKED_IN_SWING_THREAD", LOW_PRIORITY) .addClassAndMethod(this), this); } // if ((seen == INVOKEVIRTUAL) // && getClassConstantOperand().equals("java/lang/String") // && getNameConstantOperand().equals("substring") // && getSigConstantOperand().equals("(I)Ljava/lang/String;") // && stack.getStackDepth() > 1) { // OpcodeStack.Item item = stack.getStackItem(0); // Object o = item.getConstant(); // if (o != null && o instanceof Integer) { // int v = ((Integer) o).intValue(); // if (v == 0) // accumulator.accumulateBug(new BugInstance(this, "DMI_USELESS_SUBSTRING", NORMAL_PRIORITY) // .addClassAndMethod(this) // .addSourceLine(this)); if ((seen == INVOKEVIRTUAL) && getNameConstantOperand().equals("isAnnotationPresent") && getSigConstantOperand().equals("(Ljava/lang/Class;)Z") && stack.getStackDepth() > 0) { OpcodeStack.Item item = stack.getStackItem(0); Object value = item.getConstant(); if (value instanceof String) { String annotationClassName = (String) value; boolean lacksClassfileRetention = AnalysisContext.currentAnalysisContext().getAnnotationRetentionDatabase().lacksRuntimeRetention( annotationClassName.replace('/','.')); if (lacksClassfileRetention) { ClassDescriptor annotationClass = DescriptorFactory.createClassDescriptor(annotationClassName); accumulator.accumulateBug(new BugInstance(this, "DMI_ANNOTATION_IS_NOT_VISIBLE_TO_REFLECTION", HIGH_PRIORITY) .addClassAndMethod(this).addCalledMethod(this).addClass(annotationClass).describe(ClassAnnotation.ANNOTATION_ROLE), this); } } } if ((seen == INVOKEVIRTUAL) && getNameConstantOperand().equals("next") && getSigConstantOperand().equals("()Ljava/lang/Object;") && getMethodName().equals("hasNext") && getMethodSig().equals("()Z") && stack.getStackDepth() > 0) { OpcodeStack.Item item = stack.getStackItem(0); accumulator.accumulateBug(new BugInstance(this, "DMI_CALLING_NEXT_FROM_HASNEXT", item.isInitialParameter() && item.getRegisterNumber() == 0 ? NORMAL_PRIORITY : LOW_PRIORITY) .addClassAndMethod(this) .addCalledMethod(this), this); } if ((seen == INVOKESPECIAL) && getClassConstantOperand().equals("java/lang/String") && getNameConstantOperand().equals("<init>") && getSigConstantOperand().equals("(Ljava/lang/String;)V")) { accumulator.accumulateBug(new BugInstance(this, "DM_STRING_CTOR", NORMAL_PRIORITY) .addClassAndMethod(this), this); } if (seen == INVOKESTATIC && getClassConstantOperand().equals("java/lang/System") && getNameConstantOperand().equals("runFinalizersOnExit") || seen == INVOKEVIRTUAL && getClassConstantOperand().equals("java/lang/Runtime") && getNameConstantOperand().equals("runFinalizersOnExit")) { accumulator.accumulateBug(new BugInstance(this, "DM_RUN_FINALIZERS_ON_EXIT", HIGH_PRIORITY) .addClassAndMethod(this), this); } if ((seen == INVOKESPECIAL) && getClassConstantOperand().equals("java/lang/String") && getNameConstantOperand().equals("<init>") && getSigConstantOperand().equals("()V")) { accumulator.accumulateBug(new BugInstance(this, "DM_STRING_VOID_CTOR", NORMAL_PRIORITY) .addClassAndMethod(this), this); } if (!isPublicStaticVoidMain && seen == INVOKESTATIC && getClassConstantOperand().equals("java/lang/System") && getNameConstantOperand().equals("exit") && !getMethodName().equals("processWindowEvent") && !getMethodName().startsWith("windowClos") && getMethodName().indexOf("exit") == -1 && getMethodName().indexOf("Exit") == -1 && getMethodName().indexOf("crash") == -1 && getMethodName().indexOf("Crash") == -1 && getMethodName().indexOf("die") == -1 && getMethodName().indexOf("Die") == -1 && getMethodName().indexOf("main") == -1) { accumulator.accumulateBug(new BugInstance(this, "DM_EXIT", getMethod().isStatic() ? LOW_PRIORITY : NORMAL_PRIORITY) .addClassAndMethod(this), SourceLineAnnotation.fromVisitedInstruction(this)); } if (((seen == INVOKESTATIC && getClassConstantOperand().equals("java/lang/System")) || (seen == INVOKEVIRTUAL && getClassConstantOperand().equals("java/lang/Runtime"))) && getNameConstantOperand().equals("gc") && getSigConstantOperand().equals("()V") && !getDottedClassName().startsWith("java.lang") && !getMethodName().startsWith("gc") && !getMethodName().endsWith("gc")) { if (gcInvocationBugReport == null) { // System.out.println("Saw call to GC"); if (isPublicStaticVoidMain) { // System.out.println("Skipping GC complaint in main method"); return; } if (isTestMethod(getMethod())) { return; } // Just save this report in a field; it will be flushed // IFF there were no calls to System.currentTimeMillis(); // in the method. gcInvocationBugReport = new BugInstance(this, "DM_GC", HIGH_PRIORITY) .addClassAndMethod(this) .addSourceLine(this); gcInvocationPC = getPC(); //System.out.println("GC invocation at pc " + PC); } } if (!isSynthetic && (seen == INVOKESPECIAL) && getClassConstantOperand().equals("java/lang/Boolean") && getNameConstantOperand().equals("<init>") && !getClassName().equals("java/lang/Boolean")) { int majorVersion = getThisClass().getMajor(); if (majorVersion >= MAJOR_1_4) { accumulator.accumulateBug(new BugInstance(this, "DM_BOOLEAN_CTOR", NORMAL_PRIORITY) .addClassAndMethod(this), this); } } if ((seen == INVOKESTATIC) && getClassConstantOperand().equals("java/lang/System") && (getNameConstantOperand().equals("currentTimeMillis") || getNameConstantOperand().equals("nanoTime"))) { sawCurrentTimeMillis = true; } if ((seen == INVOKEVIRTUAL) && getClassConstantOperand().equals("java/lang/String") && getNameConstantOperand().equals("toString") && getSigConstantOperand().equals("()Ljava/lang/String;")) { accumulator.accumulateBug(new BugInstance(this, "DM_STRING_TOSTRING", LOW_PRIORITY) .addClassAndMethod(this), this); } if ((seen == INVOKEVIRTUAL) && getClassConstantOperand().equals("java/lang/String") && (getNameConstantOperand().equals("toUpperCase") || getNameConstantOperand().equals("toLowerCase")) && getSigConstantOperand().equals("()Ljava/lang/String;")) { accumulator.accumulateBug(new BugInstance(this, "DM_CONVERT_CASE", LOW_PRIORITY) .addClassAndMethod(this), this); } if ((seen == INVOKESPECIAL) && getNameConstantOperand().equals("<init>")) { String cls = getClassConstantOperand(); String sig = getSigConstantOperand(); if ((cls.equals("java/lang/Integer") && sig.equals("(I)V")) || (cls.equals("java/lang/Float") && sig.equals("(F)V")) || (cls.equals("java/lang/Double") && sig.equals("(D)V")) || (cls.equals("java/lang/Long") && sig.equals("(J)V")) || (cls.equals("java/lang/Byte") && sig.equals("(B)V")) || (cls.equals("java/lang/Character") && sig.equals("(C)V")) || (cls.equals("java/lang/Short") && sig.equals("(S)V")) || (cls.equals("java/lang/Boolean") && sig.equals("(Z)V"))) { primitiveObjCtorSeen = cls; } else { primitiveObjCtorSeen = null; } } else if ((primitiveObjCtorSeen != null) && (seen == INVOKEVIRTUAL) && getNameConstantOperand().equals("toString") && getClassConstantOperand().equals(primitiveObjCtorSeen) && getSigConstantOperand().equals("()Ljava/lang/String;")) { accumulator.accumulateBug(new BugInstance(this, "DM_BOXED_PRIMITIVE_TOSTRING", LOW_PRIORITY) .addClassAndMethod(this), this); primitiveObjCtorSeen = null; } else { primitiveObjCtorSeen = null; } if ((seen == INVOKESPECIAL) && getNameConstantOperand().equals("<init>")) { ctorSeen = true; } else if (ctorSeen && (seen == INVOKEVIRTUAL) && getClassConstantOperand().equals("java/lang/Object") && getNameConstantOperand().equals("getClass") && getSigConstantOperand().equals("()Ljava/lang/Class;")) { accumulator.accumulateBug(new BugInstance(this, "DM_NEW_FOR_GETCLASS", LOW_PRIORITY) .addClassAndMethod(this), this); ctorSeen = false; } else { ctorSeen = false; } if (jdk15ChecksEnabled && (seen == INVOKEVIRTUAL) && isMonitorWait(getNameConstantOperand(), getSigConstantOperand())) { checkMonitorWait(); } if ((seen == INVOKESPECIAL) && getNameConstantOperand().equals("<init>") && getClassConstantOperand().equals("java/lang/Thread")) { String sig = getSigConstantOperand(); if (sig.equals("()V") || sig.equals("(Ljava/lang/String;)V") || sig.equals("(Ljava/lang/ThreadGroup;Ljava/lang/String;)V")) { if (!getMethodName().equals("<init>") || (getPC() > 20)) { accumulator.accumulateBug(new BugInstance(this, "DM_USELESS_THREAD", LOW_PRIORITY) .addClassAndMethod(this), this); } } } } finally { prevOpcode = seen; } } /** * @param seen * @param item */ private void reportVacuousBitOperation(int seen, OpcodeStack.Item item) { if (item.getConstant() == null) accumulator.accumulateBug(new BugInstance(this, "INT_VACUOUS_BIT_OPERATION" , NORMAL_PRIORITY) .addClassAndMethod(this).addString(OPCODE_NAMES[seen]).addOptionalAnnotation(LocalVariableAnnotation.getLocalVariableAnnotation(getMethod(), item, getPC())), this); } /** * Return index of stack entry that must be nonnegative. * * Return -1 if no stack entry is required to be nonnegative. * @param seen * @return */ private int stackEntryThatMustBeNonnegative(int seen) { switch(seen) { case INVOKEINTERFACE: if (getClassConstantOperand().equals("java/util/List")) { return getStackEntryOfListCallThatMustBeNonnegative(); } break; case INVOKEVIRTUAL: if (getClassConstantOperand().equals("java/util/LinkedList") || getClassConstantOperand().equals("java/util/ArrayList")) { return getStackEntryOfListCallThatMustBeNonnegative(); } break; case IALOAD: case AALOAD: case SALOAD: case CALOAD: case BALOAD: case LALOAD: case DALOAD: case FALOAD: return 0; case IASTORE: case AASTORE: case SASTORE: case CASTORE: case BASTORE: case LASTORE: case DASTORE: case FASTORE: return 1; } return -1; } private int getStackEntryOfListCallThatMustBeNonnegative() { String name = getNameConstantOperand(); if ((name.equals("add") || name.equals("set")) && getSigConstantOperand().startsWith("(I")) { return 1; } if ((name.equals("get") || name.equals("remove")) && getSigConstantOperand().startsWith("(I)")) { return 0; } return -1; } private void checkMonitorWait() { try { TypeDataflow typeDataflow = getClassContext().getTypeDataflow(getMethod()); TypeDataflow.LocationAndFactPair pair = typeDataflow.getLocationAndFactForInstruction(getPC()); if (pair == null) { return; } Type receiver = pair.frame.getInstance( pair.location.getHandle().getInstruction(), getClassContext().getConstantPoolGen() ); if (!(receiver instanceof ReferenceType)) { return; } if (Hierarchy.isSubtype((ReferenceType) receiver, CONDITION_TYPE)) { accumulator.accumulateBug(new BugInstance(this, "DM_MONITOR_WAIT_ON_CONDITION", HIGH_PRIORITY) .addClassAndMethod(this), this); } } catch (ClassNotFoundException e) { bugReporter.reportMissingClass(e); } catch (DataflowAnalysisException e) { bugReporter.logError("Exception caught by DumbMethods", e); } catch (CFGBuilderException e) { bugReporter.logError("Exception caught by DumbMethods", e); } } private boolean isMonitorWait(String name, String sig) { // System.out.println("Check call " + name + "," + sig); return name.equals("wait") && (sig.equals("()V") || sig.equals("(J)V") || sig.equals("(JI)V")); } @Override public void visit(Code obj) { super.visit(obj); flush(); } /** * A heuristic - how long a catch block for OutOfMemoryError might be. */ private static final int OOM_CATCH_LEN = 20; /** * Flush out cached state at the end of a method. */ private void flush() { if (pendingAbsoluteValueBug != null) { accumulator.accumulateBug(pendingAbsoluteValueBug, pendingAbsoluteValueBugSourceLine); pendingAbsoluteValueBug = null; pendingAbsoluteValueBugSourceLine = null; } if (gcInvocationBugReport != null && !sawCurrentTimeMillis) { // Make sure the GC invocation is not in an exception handler // for OutOfMemoryError. boolean outOfMemoryHandler = false; for (CodeException handler : exceptionTable) { if (gcInvocationPC < handler.getHandlerPC() || gcInvocationPC > handler.getHandlerPC() + OOM_CATCH_LEN) { continue; } int catchTypeIndex = handler.getCatchType(); if (catchTypeIndex > 0) { ConstantPool cp = getThisClass().getConstantPool(); Constant constant = cp.getConstant(catchTypeIndex); if (constant instanceof ConstantClass) { String exClassName = (String) ((ConstantClass) constant).getConstantValue(cp); if (exClassName.equals("java/lang/OutOfMemoryError")) { outOfMemoryHandler = true; break; } } } } if (!outOfMemoryHandler) { bugReporter.reportBug(gcInvocationBugReport); } } sawCurrentTimeMillis = false; gcInvocationBugReport = null; exceptionTable = null; } }
package com.autonomy.abc.topnavbar.notifications; import com.autonomy.abc.config.ABCTestBase; import com.autonomy.abc.config.TestConfig; import com.autonomy.abc.selenium.actions.PromotionActionFactory; import com.autonomy.abc.selenium.config.ApplicationType; import com.autonomy.abc.selenium.element.GritterNotice; import com.autonomy.abc.selenium.menu.NavBarTabId; import com.autonomy.abc.selenium.menu.NotificationsDropDown; import com.autonomy.abc.selenium.menu.SideNavBar; import com.autonomy.abc.selenium.menu.TopNavBar; import com.autonomy.abc.selenium.page.AppBody; import com.autonomy.abc.selenium.page.HSOElementFactory; import com.autonomy.abc.selenium.page.analytics.AnalyticsPage; import com.autonomy.abc.selenium.page.keywords.CreateNewKeywordsPage; import com.autonomy.abc.selenium.page.keywords.KeywordsPage; import com.autonomy.abc.selenium.promotions.PromotionService; import com.autonomy.abc.selenium.promotions.SpotlightPromotion; import com.autonomy.abc.selenium.search.SearchActionFactory; import javafx.geometry.Side; import org.apache.xpath.compiler.Keywords; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.Platform; import org.openqa.selenium.support.ui.WebDriverWait; import org.slf4j.LoggerFactory; import java.util.List; import static com.autonomy.abc.framework.ABCAssert.assertThat; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.Matchers.contains; import static org.hamcrest.core.Is.is; public class NotificationsDropDownITCase extends ABCTestBase{ public NotificationsDropDownITCase(final TestConfig config, final String browser, final ApplicationType appType, final Platform platform) { super(config, browser, appType, platform); } private NotificationsDropDown notifications; private KeywordsPage keywordsPage; private CreateNewKeywordsPage createNewKeywordsPage; private TopNavBar topNavBar; private SideNavBar sideNavBar; @Before public void setUp() { topNavBar = body.getTopNavBar(); sideNavBar = body.getSideNavBar(); notifications = topNavBar.getNotifications(); } @Test public void testCountNotifications() throws InterruptedException { sideNavBar.switchPage(NavBarTabId.KEYWORDS); keywordsPage = getElementFactory().getKeywordsPage(); keywordsPage.createNewKeywordsButton().click(); createNewKeywordsPage = getElementFactory().getCreateNewKeywordsPage(); createNewKeywordsPage.createSynonymGroup("john juan jO", "English"); topNavBar.notificationsDropdown(); notifications = topNavBar.getNotifications(); assertThat("There should be 1 notification in the drop down", notifications.countNotifications(), is(1)); sideNavBar.switchPage(NavBarTabId.KEYWORDS); keywordsPage = getElementFactory().getKeywordsPage(); keywordsPage.deleteSynonym("john", "john"); topNavBar.notificationsDropdown(); notifications = topNavBar.getNotifications(); assertThat("There should be 2 notifications in the drop down", notifications.countNotifications(), is(2)); sideNavBar.switchPage(NavBarTabId.KEYWORDS); keywordsPage = getElementFactory().getKeywordsPage(); keywordsPage.deleteSynonym("juan", "juan"); topNavBar.notificationsDropdown(); notifications = topNavBar.getNotifications(); assertThat("There should be 3 notifications in the drop down", notifications.countNotifications(), is(3)); } @Test public void testNotificationsRemainAfterPageRefresh() throws InterruptedException { sideNavBar.switchPage(NavBarTabId.KEYWORDS); keywordsPage = getElementFactory().getKeywordsPage(); keywordsPage.deleteAllBlacklistedTerms(); keywordsPage.createNewKeywordsButton().click(); createNewKeywordsPage = getElementFactory().getCreateNewKeywordsPage(); createNewKeywordsPage.createBlacklistedTerm("one two three four five", "English"); topNavBar.notificationsDropdown(); notifications = topNavBar.getNotifications(); assertThat("There should be 5 notifications in the drop down", notifications.countNotifications(), is(5)); getDriver().navigate().refresh(); newBody(); body.getTopNavBar().notificationsDropdown(); notifications = topNavBar.getNotifications(); assertThat("After page refresh there should still be 5 notifications in the drop down", notifications.countNotifications(), is(5)); } //Fails because of CSA-1542 @Test public void testNotificationsOverTwoWindows() throws InterruptedException { sideNavBar.switchPage(NavBarTabId.KEYWORDS); topNavBar.notificationsDropdown(); notifications = topNavBar.getNotifications(); assertThat(notifications.countNotifications(), is(0)); keywordsPage = getElementFactory().getKeywordsPage(); List<String> browserHandles = keywordsPage.createAndListWindowHandles(); getDriver().switchTo().window(browserHandles.get(1)); getDriver().navigate().to(getConfig().getWebappUrl()); AppBody bodyWindowTwo = getBody(); TopNavBar topNavBarWindowTwo = bodyWindowTwo.getTopNavBar(); SideNavBar sideNavBarWindowTwo = bodyWindowTwo.getSideNavBar(); getDriver().manage().window().maximize(); sideNavBarWindowTwo.switchPage(NavBarTabId.KEYWORDS); topNavBarWindowTwo.notificationsDropdown(); NotificationsDropDown notificationsDropDownWindowTwo = topNavBarWindowTwo.getNotifications(); assertThat(notificationsDropDownWindowTwo.countNotifications(), is(0)); try { getDriver().switchTo().window(browserHandles.get(0)); keywordsPage.createNewKeywordsButton().click(); getElementFactory().getCreateNewKeywordsPage().createSynonymGroup("Animal Beast", "English"); getElementFactory().getSearchPage(); sideNavBar.switchPage(NavBarTabId.KEYWORDS); keywordsPage = getElementFactory().getKeywordsPage(); new WebDriverWait(getDriver(), 5).until(GritterNotice.notificationAppears()); topNavBar.notificationsDropdown(); notifications = topNavBar.getNotifications(); assertThat(notifications.countNotifications(), is(1)); String windowOneNotificationText = notifications.notificationNumber(1).getText(); getDriver().switchTo().window(browserHandles.get(1)); assertThat(notificationsDropDownWindowTwo.countNotifications(), is(1)); assertThat(notificationsDropDownWindowTwo.notificationNumber(1).getText(), is(windowOneNotificationText)); topNavBarWindowTwo.notificationsDropdown(); KeywordsPage keywordsPageWindowTwo = getElementFactory().getKeywordsPage(); keywordsPageWindowTwo.deleteSynonym("Animal", "Animal"); topNavBarWindowTwo.notificationsDropdown(); assertThat(notificationsDropDownWindowTwo.countNotifications(), is(2)); List<String> notificationMessages = notificationsDropDownWindowTwo.getAllNotificationMessages(); getDriver().switchTo().window(browserHandles.get(0)); assertThat(notifications.countNotifications(), is(2)); assertThat(notifications.getAllNotificationMessages(), contains(notificationMessages.toArray())); if (getConfig().getType().equals(ApplicationType.HOSTED)) { sideNavBar.switchPage(NavBarTabId.ANALYTICS); newBody(); ((HSOElementFactory) getElementFactory()).getAnalyticsPage(); topNavBar.notificationsDropdown(); notifications = topNavBar.getNotifications(); assertThat(notifications.countNotifications(), is(2)); assertThat(notifications.getAllNotificationMessages(), contains(notificationMessages.toArray())); } getDriver().switchTo().window(browserHandles.get(1)); PromotionService promotionService = getApplication().createPromotionService(getElementFactory()); promotionService.setUpPromotion(new SpotlightPromotion("wheels"), new SearchActionFactory(getApplication(), getElementFactory()).makeSearch("cars"), 3); new WebDriverWait(getDriver(), 5).until(GritterNotice.notificationAppears()); topNavBarWindowTwo.notificationsDropdown(); notificationsDropDownWindowTwo = topNavBarWindowTwo.getNotifications(); assertThat(notificationsDropDownWindowTwo.countNotifications(), is(3)); assertThat(notificationsDropDownWindowTwo.notificationNumber(1).getText(), containsString("promotion")); notificationMessages = notificationsDropDownWindowTwo.getAllNotificationMessages(); getDriver().switchTo().window(browserHandles.get(0)); notifications = topNavBar.getNotifications(); assertThat(notifications.countNotifications(), is(3)); assertThat(notifications.getAllNotificationMessages(), contains(notificationMessages.toArray())); int notificationsCount = 3; for(int i = 0; i < 6; i += 2) { getDriver().switchTo().window(browserHandles.get(1)); body.getSideNavBar().switchPage(NavBarTabId.KEYWORDS); getElementFactory().getKeywordsPage().createNewKeywordsButton().click(); getElementFactory().getCreateNewKeywordsPage().createSynonymGroup(i + " " + (i + 1), "English"); getElementFactory().getSearchPage(); new WebDriverWait(getDriver(), 30).until(GritterNotice.notificationAppears()); bodyWindowTwo.getTopNavBar().notificationsDropdown(); assertThat(notificationsDropDownWindowTwo.countNotifications(), is(Math.min(++notificationsCount, 5))); notificationMessages = notificationsDropDownWindowTwo.getAllNotificationMessages(); getDriver().switchTo().window(browserHandles.get(0)); assertThat(notifications.countNotifications(), is(Math.min(notificationsCount, 5))); assertThat(notifications.getAllNotificationMessages(), contains(notificationMessages.toArray())); } } finally { getDriver().switchTo().window(browserHandles.get(1)); body.getSideNavBar().switchPage(NavBarTabId.KEYWORDS); getElementFactory().getKeywordsPage().deleteKeywords(); body.getSideNavBar().switchPage(NavBarTabId.PROMOTIONS); getElementFactory().getPromotionsPage().deleteAllPromotions(); } } private void newBody(){ body = getBody(); topNavBar = body.getTopNavBar(); sideNavBar = body.getSideNavBar(); } }
package jenkins.plugins.play.extensions; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import hudson.Extension; import hudson.util.FormValidation; /** * @author rafaelrezende * */ public class PlayTestOnly extends PlayExtension { private final static String command = "test-only"; private final String parameter; @DataBoundConstructor public PlayTestOnly(String parameter) { this.parameter = parameter; } /** * @return the command */ public String getCommand() { return command; } /** * @return the testOnlyName */ public final String getParameter() { return parameter; } @Extension public static class DescriptorImpl extends PlayExtensionDescriptor { @Override public String getDisplayName() { return "Execute single test case"; } public FormValidation doCheckParameter (@QueryParameter String parameter) { return FormValidation.validateRequired(parameter); } } }
package io.domisum.lib.auxiliumlib.util.math; import io.domisum.lib.auxiliumlib.PHR; import io.domisum.lib.auxiliumlib.annotations.API; import lombok.AccessLevel; import lombok.NoArgsConstructor; import org.apache.commons.lang3.Validate; @API @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class MathUtil { // NUMBERS @API public static double getDelta(double a, double b) { return Math.abs(a-b); } @API public static double mix(double firstNumber, double firstPart, double secondNumber, double secondPart) { double firstPercentage = firstPart/(firstPart+secondPart); double secondPercentage = 1-firstPercentage; return (firstPercentage*firstNumber)+(secondPercentage*secondNumber); } @API public static double mix(double firstNumber, double firstPart, double secondNumber) { double secondPercentage = 1-firstPart; return (firstPart*firstNumber)+(secondPercentage*secondNumber); } @API public static double clampAbs(double number, double maximumAbs) { return ((number < 0) ? -1 : 1)*Math.min(Math.abs(number), maximumAbs); } @API public static double clamp(double min, double max, double value) { if(min > max) throw new IllegalArgumentException(PHR.r("min ({}) was bigger than max ({})", min, max)); if(value < min) return min; if(value > max) return max; return value; } @API public static int clamp(int min, int max, int value) { if(min > max) throw new IllegalArgumentException(PHR.r("min ({}) was bigger than max ({})", min, max)); if(value < min) return min; if(value > max) return max; return value; } @API public static double clampUpper(double max, double value) { if(value > max) return max; return value; } @API public static double clampUpper(int max, int value) { if(value > max) return max; return value; } @API public static double avg(double... values) { if(values.length == 0) throw new IllegalArgumentException("can't average calculate average of no numbers"); double sum = 0; for(double value : values) sum += value; return sum/values.length; } @API public static double remapLinear(double baseStart, double baseEnd, double targetStart, double targetEnd, double valueToRemap) { Validate.isTrue(baseStart != baseEnd, "baseStart can't be equal to baseEnd ("+baseStart+")"); Validate.isTrue(targetStart != targetEnd, "targetStart can't be equal to targetEnd ("+targetStart+")"); double proportionFrom1To2 = (valueToRemap-baseStart)/(baseEnd-baseStart); return targetStart+((targetEnd-targetStart)*proportionFrom1To2); } // ANGLE @API public static boolean isAngleNearRad(double a, double b, double maxD) { return isAngleNearDeg(Math.toDegrees(a), Math.toDegrees(b), maxD); } @API public static boolean isAngleNearDeg(double a, double b, double maxD) { return getAngleDistanceDeg(a, b) < maxD; } @API public static double getAngleDistanceDeg(double a, double b) { double delta = Math.abs(a-b)%360; if(delta > 180) delta = 360-delta; return delta; } /** * Rounds a double to the specified number of decimal places. * <p> * Rounds values equal to or above .5 up (towards positive infinity), values below down (towards negative infinity). <br/> * Example: Rounds 7.45 with 1 decimal place to 7.5; rounds -7.45 with 1 decimal place to -7.4 * * @param numberToRound number to be rounded * @param decimalPlaces the number of decimal places to round to * @return the rounded number */ @API public static double round(double numberToRound, int decimalPlaces) { if(Double.isNaN(numberToRound)) return Double.NaN; double factor = 1; for(int i = 0; i < Math.abs(decimalPlaces); i++) if(decimalPlaces > 0) factor *= 10; else factor /= 10; return (double) Math.round(numberToRound*factor)/factor; } @API public static String percentage(double fraction, int decimalPlaces) { return round(fraction*100, decimalPlaces)+"%"; } // FUNCTION @API public static double smoothStep(double input) { if(input <= 0) return 0; if(input >= 1) return 1; // 3*x^2 - 2*x^3 double a = 3*(input*input); double b = 2*(input*input*input); return a-b; } @API public static double smootherStep(double input) { // https://en.wikipedia.org/wiki/Smoothstep#Variations if(input <= 0) return 0; if(input >= 1) return 1; // 6*x^5 - 15*x^4 + 10*x^3 double a = 6*(input*input*input*input*input); double b = 15*(input*input*input*input); double c = 10*(input*input*input); return a-b+c; } }
package io.fabric8.jenkins.openshiftsync; import static io.fabric8.jenkins.openshiftsync.Annotations.DISABLE_SYNC_CREATE; import static io.fabric8.jenkins.openshiftsync.BuildConfigToJobMap.getJobFromBuildConfig; import static io.fabric8.jenkins.openshiftsync.BuildConfigToJobMap.putJobWithBuildConfig; import static io.fabric8.jenkins.openshiftsync.BuildConfigToJobMapper.mapBuildConfigToFlow; import static io.fabric8.jenkins.openshiftsync.BuildRunPolicy.SERIAL; import static io.fabric8.jenkins.openshiftsync.BuildRunPolicy.SERIAL_LATEST_ONLY; import static io.fabric8.jenkins.openshiftsync.JenkinsUtils.updateJob; import static io.fabric8.jenkins.openshiftsync.OpenShiftUtils.getAnnotation; import static io.fabric8.jenkins.openshiftsync.OpenShiftUtils.getFullNameParent; import static io.fabric8.jenkins.openshiftsync.OpenShiftUtils.getName; import static io.fabric8.jenkins.openshiftsync.OpenShiftUtils.getNamespace; import static io.fabric8.jenkins.openshiftsync.OpenShiftUtils.jenkinsJobDisplayName; import static io.fabric8.jenkins.openshiftsync.OpenShiftUtils.jenkinsJobFullName; import static io.fabric8.jenkins.openshiftsync.OpenShiftUtils.jenkinsJobName; import static io.fabric8.jenkins.openshiftsync.OpenShiftUtils.parseResourceVersion; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.logging.Logger; import org.apache.tools.ant.filters.StringInputStream; import org.jenkinsci.plugins.workflow.flow.FlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import com.cloudbees.hudson.plugins.folder.Folder; import hudson.BulkChange; import hudson.model.ItemGroup; import hudson.model.ParameterDefinition; import hudson.util.XStream2; import io.fabric8.openshift.api.model.BuildConfig; import jenkins.model.Jenkins; import jenkins.security.NotReallyRoleSensitiveCallable; public class JobProcessor extends NotReallyRoleSensitiveCallable<Void, Exception> { private final BuildConfigWatcher jobProcessor; private final BuildConfig buildConfig; private final static Logger logger = Logger.getLogger(BuildConfigToJobMap.class.getName()); public JobProcessor(BuildConfigWatcher buildConfigWatcher, BuildConfig buildConfig) { jobProcessor = buildConfigWatcher; this.buildConfig = buildConfig; } @Override public Void call() throws Exception { String jobName = jenkinsJobName(buildConfig); String jobFullName = jenkinsJobFullName(buildConfig); WorkflowJob job = getJobFromBuildConfig(buildConfig); Jenkins activeInstance = Jenkins.getActiveInstance(); ItemGroup parent = activeInstance; if (job == null) { job = (WorkflowJob) activeInstance.getItemByFullName(jobFullName); } boolean newJob = job == null; if (newJob) { String disableOn = getAnnotation(buildConfig, DISABLE_SYNC_CREATE); if (disableOn != null && disableOn.length() > 0) { logger.fine("Not creating missing jenkins job " + jobFullName + " due to annotation: " + DISABLE_SYNC_CREATE); return null; } parent = getFullNameParent(activeInstance, jobFullName, getNamespace(buildConfig)); job = new WorkflowJob(parent, jobName); } BulkChange bulkJob = new BulkChange(job); job.setDisplayName(jenkinsJobDisplayName(buildConfig)); FlowDefinition flowFromBuildConfig = mapBuildConfigToFlow(buildConfig); if (flowFromBuildConfig == null) { return null; } job.setDefinition(flowFromBuildConfig); String existingBuildRunPolicy = null; BuildConfigProjectProperty buildConfigProjectProperty = job.getProperty(BuildConfigProjectProperty.class); existingBuildRunPolicy = populateBCProjectProperty(job, existingBuildRunPolicy, buildConfigProjectProperty); // (re)populate job param list with any envs // from the build config Map<String, ParameterDefinition> paramMap = JenkinsUtils.addJobParamForBuildEnvs(job, buildConfig.getSpec().getStrategy().getJenkinsPipelineStrategy(), true); job.setConcurrentBuild(!(buildConfig.getSpec().getRunPolicy().equals(SERIAL) || buildConfig.getSpec().getRunPolicy().equals(SERIAL_LATEST_ONLY))); InputStream jobStream = new StringInputStream(new XStream2().toXML(job)); if (newJob) { try { if (parent instanceof Folder) { Folder folder = (Folder) parent; folder.createProjectFromXML(jobName, jobStream).save(); } else { activeInstance.createProjectFromXML(jobName, jobStream).save(); } logger.info("Created job " + jobName + " from BuildConfig " + NamespaceName.create(buildConfig) + " with revision: " + buildConfig.getMetadata().getResourceVersion()); } catch (IllegalArgumentException e) { // see // jenkins might reload existing jobs on // startup between the // newJob check above and when we make // the createProjectFromXML call; if so, // retry as an update updateJob(job, jobStream, existingBuildRunPolicy, buildConfigProjectProperty); logger.info("Updated job " + jobName + " from BuildConfig " + NamespaceName.create(buildConfig) + " with revision: " + buildConfig.getMetadata().getResourceVersion()); } } else { updateJob(job, jobStream, existingBuildRunPolicy, buildConfigProjectProperty); logger.info("Updated job " + jobName + " from BuildConfig " + NamespaceName.create(buildConfig) + " with revision: " + buildConfig.getMetadata().getResourceVersion()); } bulkJob.commit(); String fullName = job.getFullName(); WorkflowJob workflowJob = activeInstance.getItemByFullName(fullName, WorkflowJob.class); if (workflowJob == null && parent instanceof Folder) { // we should never need this but just in // case there's an // odd timing issue or something... Folder folder = (Folder) parent; folder.add(job, jobName); workflowJob = activeInstance.getItemByFullName(fullName, WorkflowJob.class); } if (workflowJob == null) { logger.warning("Could not find created job " + fullName + " for BuildConfig: " + getNamespace(buildConfig) + "/" + getName(buildConfig)); } else { JenkinsUtils.verifyEnvVars(paramMap, workflowJob, buildConfig); putJobWithBuildConfig(workflowJob, buildConfig); } return null; } private String populateBCProjectProperty(WorkflowJob job, String existingBuildRunPolicy, BuildConfigProjectProperty buildConfigProjectProperty) throws IOException { if (buildConfigProjectProperty != null) { existingBuildRunPolicy = buildConfigProjectProperty.getBuildRunPolicy(); long updatedBCResourceVersion = parseResourceVersion(buildConfig); long oldBCResourceVersion = parseResourceVersion(buildConfigProjectProperty.getResourceVersion()); BuildConfigProjectProperty newProperty = new BuildConfigProjectProperty(buildConfig); if (updatedBCResourceVersion <= oldBCResourceVersion && newProperty.getUid().equals(buildConfigProjectProperty.getUid()) && newProperty.getNamespace().equals(buildConfigProjectProperty.getNamespace()) && newProperty.getName().equals(buildConfigProjectProperty.getName()) && newProperty.getBuildRunPolicy().equals(buildConfigProjectProperty.getBuildRunPolicy())) { return null; } buildConfigProjectProperty.setUid(newProperty.getUid()); buildConfigProjectProperty.setNamespace(newProperty.getNamespace()); buildConfigProjectProperty.setName(newProperty.getName()); buildConfigProjectProperty.setResourceVersion(newProperty.getResourceVersion()); buildConfigProjectProperty.setBuildRunPolicy(newProperty.getBuildRunPolicy()); } else { job.addProperty(new BuildConfigProjectProperty(buildConfig)); } return existingBuildRunPolicy; } }
package lk.grp.synergy.control.impl; import lk.grp.synergy.control.SampleControllerInterface; public class SampleController implements SampleControllerInterface{ /** * Use this package to create controller classes * Please remove this class once you begin actual development work */ public void sampleMethod() { //This is just a sample } }
package ml.duncte123.skybot.commands.fun; import me.duncte123.botcommons.messaging.EmbedUtils; import ml.duncte123.skybot.Settings; import ml.duncte123.skybot.objects.command.Command; import ml.duncte123.skybot.objects.command.CommandCategory; import ml.duncte123.skybot.objects.command.CommandContext; import ml.duncte123.skybot.utils.AirUtils; import net.dv8tion.jda.core.EmbedBuilder; import net.dv8tion.jda.core.Permission; import net.dv8tion.jda.core.entities.Member; import net.dv8tion.jda.core.entities.TextChannel; import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent; import org.jetbrains.annotations.NotNull; import org.json.JSONObject; import java.util.List; import static me.duncte123.botcommons.messaging.MessageUtils.sendEmbed; import static me.duncte123.botcommons.messaging.MessageUtils.sendMsg; public class LoveCommand extends Command { public LoveCommand() { this.category = CommandCategory.FUN; } @Override public void executeCommand(@NotNull CommandContext ctx) { final List<String> args = ctx.getArgs(); final GuildMessageReceivedEvent event = ctx.getEvent(); if (args.isEmpty()) { sendMsg(event, "Correct usage: `" + Settings.PREFIX + getName() + " <user 1> [user 2]`"); return; } String name1 = ctx.getMember().getEffectiveName(); String name2 = args.get(0); if (args.size() > 1) { name1 = args.get(0); name2 = args.get(1); } final Member target1 = AirUtils.getMentionedUser(name1, ctx.getGuild()); final Member target2 = AirUtils.getMentionedUser(name2, ctx.getGuild()); final JSONObject response = ctx.getApis().getLove(target1.getEffectiveName(), target2.getEffectiveName()); final EmbedBuilder embed = EmbedUtils.defaultEmbed() .setTitle(response.getString("names"), "https://patreon.com/DuncteBot") .addField(response.getString("score"), response.getString("message"), false); final TextChannel channel = ctx.getChannel(); if (ctx.getSelfMember().hasPermission(channel, Permission.MESSAGE_ATTACH_FILES, Permission.MESSAGE_EMBED_LINKS) && channel.canTalk()) { ctx.getWeebApi().generateLoveship( target1.getUser().getEffectiveAvatarUrl().replaceFirst("gif", "png"), target2.getUser().getEffectiveAvatarUrl().replaceFirst("gif", "png") ).async((image) -> { final String message = String.format("Shipping **%s** and **%s**", target1.getEffectiveName(), target2.getEffectiveName()); channel.sendMessage(message) .addFile(image, "love.png") .embed(embed.setImage("attachment://love.png").build()) .queue(); }); } else { sendEmbed(event, embed); } } @Override public String getName() { return "ship"; } @Override public String[] getAliases() { return new String[]{"love", "loveship"}; } @Override public String help() { return null; } }
package io.pivotal.poc.bac.authrouteservice; import netegrity.siteminder.javaagent.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpMethod; import org.springframework.stereotype.Controller; import java.net.URI; @Controller public class SMService implements InitializingBean { Logger LOG = LoggerFactory.getLogger(SMService.class); private final AgentAPI _api = new AgentAPI(); @Value("${sm.ip}") private String _policyIp; @Value("${sm.agent.hostname}") private String _agentHostName; @Value("${sm.agent.sharedSecret}") private String _sharedSecret; public void afterPropertiesSet() throws Exception { ServerDef sd = new ServerDef(); sd.serverIpAddress = _policyIp; sd.connectionMax = 10; sd.connectionMin = 1; sd.timeout = 10; _api.init(new InitDef( _agentHostName, _sharedSecret, false, sd)); LOG.info("SM Agent initialized: " + _api.toString()); LOG.info("\tSM Agent hostname: " + _agentHostName); LOG.info("\tSM Agent Policy Server IP: " + _policyIp); LOG.info("\tSM Agent shared secret: " + _sharedSecret); } public boolean isValid(String authCokie) { LOG.debug("Validating cookie [" + authCokie + "]"); int rc = _api.decodeSSOToken(authCokie, new TokenDescriptor(0,true), new AttributeList(), false, new StringBuffer()); LOG.debug("Decode return code: "+ rc); switch (rc) { case AgentAPI.SUCCESS: return true; case AgentAPI.FAILURE: return false; default: throw new RuntimeException("Error Occurred Checking if decoding cookie; ReturnCode: " + rc); } } public boolean isProtected(URI uri, HttpMethod method) { LOG.debug("Checking if URI [" + uri + "] is protected"); int rc = _api.isProtected(_agentHostName, new ResourceContextDef( _agentHostName, "Cloudfoundry", uri.getPath(), method.name()), new RealmDef()); LOG.debug("IsProtected return code: "+ rc); switch (rc) { case AgentAPI.YES: return true; case AgentAPI.NO: return false; default: throw new RuntimeException("Error Occurred Checking if resource is protected; ReturnCode: " + rc); } } }
package org.workcraft.gui; import org.mozilla.javascript.Context; import org.workcraft.Framework; import org.workcraft.utils.DesktopApi; import org.workcraft.utils.GuiUtils; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; @SuppressWarnings("serial") public class JavaScriptWindow extends JPanel { private static final String SCRIPT_SUBMIT = "script-submit"; private static final KeyStroke ctrlEnter = KeyStroke.getKeyStroke("ctrl ENTER"); private final JTextPane txtScript; private boolean isInitState; @SuppressWarnings("serial") private final class ScriptSubmitAction extends AbstractAction { private final class ThreadExtension extends Thread { @Override public void run() { try { final Framework framework = Framework.getInstance(); Object result = framework.execJavaScript(txtScript.getText()); Context.enter(); String out = Context.toString(result); Context.exit(); if (!"undefined".equals(out)) { System.out.println(out); } txtScript.setText(""); } catch (org.mozilla.javascript.WrappedException e) { Throwable we = e.getWrappedException(); System.err.println(we.getClass().getName() + " " + we.getMessage()); } catch (org.mozilla.javascript.RhinoException e) { System.err.println(e.getMessage()); } } } @Override public void actionPerformed(ActionEvent action) { if (txtScript.getText().length() > 0) { new ThreadExtension().start(); } } } public JavaScriptWindow() { txtScript = new JTextPane(); txtScript.setBorder(GuiUtils.getEmptyBorder()); txtScript.addFocusListener(new FocusListener() { @Override public void focusLost(FocusEvent e) { String text = txtScript.getText().trim(); if (text.isEmpty()) { resetScript(); } } @Override public void focusGained(FocusEvent e) { if (isInitState) { isInitState = false; txtScript.setText(""); } } }); // Set action for Ctrl-Enter -- submit script InputMap input = txtScript.getInputMap(); ActionMap actions = txtScript.getActionMap(); input.put(ctrlEnter, SCRIPT_SUBMIT); actions.put(SCRIPT_SUBMIT, new ScriptSubmitAction()); JPanel panelInput = new JPanel(); panelInput.setLayout(new BorderLayout()); panelInput.add(txtScript, BorderLayout.CENTER); panelInput.setMinimumSize(new Dimension(100, 100)); setLayout(new BorderLayout()); add(panelInput, BorderLayout.CENTER); resetScript(); } private void resetScript() { isInitState = true; txtScript.setText("// Write a script and press " + DesktopApi.getMenuKeyName() + "-Enter to execute it."); } }
package org.knopflerfish.framework; import java.io.*; import java.net.*; import java.security.*; import java.util.Set; import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.HashSet; import java.util.Iterator; import java.util.Locale; import java.util.Dictionary; import java.util.Enumeration; import java.util.Hashtable; import org.osgi.framework.*; import org.osgi.service.packageadmin.PackageAdmin; import org.osgi.service.startlevel.StartLevel; /** * This class contains references to all common data structures * inside the framework. * * @author Jan Stein, Erik Wistrand, Philippe Laporte, * Mats-Ola Persson, Gunnar Ekolin */ public class Framework { /** * The "System" properties for this framework instance. Allways use * <tt>Framework.setProperty(String,String)</tt> to add values to * this map. */ protected static Map/*<String, String>*/ props = new HashMap/*<String, String>*/(); /** * The set of properties that must not be present in props, since a * bundle is allowed to update them and such updates are required to * be visible when calling <tt>BundleContext.getProperty(String)</tt>. */ private static Set volatileProperties = new HashSet(); static { // See last paragraph of section 3.3.1 in the R4.0.1 and R4.1 core spec. volatileProperties.add(Constants.FRAMEWORK_EXECUTIONENVIRONMENT); } /** * Specification version for this framework. */ static final String SPEC_VERSION = "1.3"; /** * Boolean indicating that framework is running. */ boolean active; /** * Set during shutdown process. */ boolean shuttingdown /*= false*/; /** * All bundle in this framework. */ public Bundles bundles; /** * All listeners in this framework. */ Listeners listeners; /** * All exported and imported packages in this framework. */ Packages packages; /** * All registered services in this framework. */ Services services; PermissionOps perm; /** * System bundle */ SystemBundle systemBundle; BundleContextImpl systemBC; /** * Bundle Storage */ BundleStorage storage; /** * Private Bundle Data Storage */ FileTree dataStorage /*= null*/; /** * Main handle so that main doesn't get GCed. */ Object mainHandle; /** * The start level service. */ StartLevelImpl startLevelService; /** * Factory for handling service-based URLs */ ServiceURLStreamHandlerFactory urlStreamHandlerFactory; /** * Factory for handling service-based URL contents */ ServiceContentHandlerFactory contentHandlerFactory; /** * Property constants for the framework. */ final static String TRUE = "true"; final static String FALSE = "false"; // EXIT_ON_SHUTDOWN and USING_WRAPPER_SCRIPT must be initialized // before initProperties(). Thus, they are *not* possible // to set on a per-framework basis (which wouldn't make sense anyway). final static boolean EXIT_ON_SHUTDOWN = TRUE.equals(Framework.getProperty(Main.EXITONSHUTDOWN_PROP, TRUE)); final static boolean USING_WRAPPER_SCRIPT = TRUE.equals(Framework.getProperty(Main.USINGWRAPPERSCRIPT_PROP, FALSE)); static { initProperties(); } final static String osArch = Framework.getProperty("os.arch"); final static String osName = Framework.getProperty("os.name"); static String osVersion; // If set to true, then during the UNREGISTERING event the Listener // can use the ServiceReference to receive an instance of the service. public final static boolean UNREGISTERSERVICE_VALID_DURING_UNREGISTERING = TRUE.equals(Framework.getProperty("org.knopflerfish.servicereference.valid.during.unregistering", TRUE)); // If set to true, set the bundle startup thread's context class // loader to the bundle class loader. This is useful for tests // but shouldn't really be used in production. final static boolean SETCONTEXTCLASSLOADER = TRUE.equals(Framework.getProperty("org.knopflerfish.osgi.setcontextclassloader", FALSE)); final static boolean REGISTERSERVICEURLHANDLER = TRUE.equals(Framework.getProperty("org.knopflerfish.osgi.registerserviceurlhandler", TRUE)); static boolean bIsMemoryStorage /*= false*/; static String whichStorageImpl; private static final String USESTARTLEVEL_PROP = "org.knopflerfish.startlevel.use"; /** * The file where we store the class path */ private final static String CLASSPATH_DIR = "classpath"; private final static String BOOT_CLASSPATH_FILE = "boot"; private final static String FRAMEWORK_CLASSPATH_FILE = "framework"; /** Cached value of * Framework.getProperty(Constants.FRAMEWORK_EXECUTIONENVIRONMENT) * Used and updated by isValidEE() */ private Set eeCacheSet = new HashSet(); private String eeCache = null; /** * Whether the framework supports extension bundles or not. * This will be false if bIsMemoryStorage is false. */ static boolean SUPPORTS_EXTENSION_BUNDLES; final static int EXIT_CODE_NORMAL = 0; final static int EXIT_CODE_RESTART = 200; public static int javaVersionMajor = -1; public static int javaVersionMinor = -1; public static int javaVersionMicro = -1; static { String javaVersion = Framework.getProperty("java.version"); // Value is on the form M.N.U_P[-xxx] where M,N,U,P are decimal integers if (null!=javaVersion) { int startPos = 0; int endPos = 0; int max = javaVersion.length(); while (endPos<max && Character.isDigit(javaVersion.charAt(endPos))) { endPos++; } if (startPos<endPos) { try { javaVersionMajor = Integer.parseInt(javaVersion.substring(startPos,endPos)); startPos = endPos +1; endPos = startPos; while (endPos<max && Character.isDigit(javaVersion.charAt(endPos))) { endPos++; } if (startPos<endPos) { javaVersionMinor = Integer.parseInt(javaVersion.substring(startPos,endPos)); startPos = endPos +1; endPos = startPos; while (endPos<max && Character.isDigit(javaVersion.charAt(endPos))){ endPos++; } if (startPos<endPos) { javaVersionMicro = Integer.parseInt(javaVersion.substring(startPos,endPos)); } } } catch (NumberFormatException _nfe) { } } } } /** * Is it safe to use double-checked locking or not. * It is safe if JSR 133 is included in the running JRE. * I.e., for Java SE if version is 1.5 or higher. */ public final static boolean isDoubleCheckedLockingSafe = "true".equals(Framework.getProperty ("org.knopflerfish.framework.is_doublechecked_locking_safe", (javaVersionMajor>=1 && javaVersionMinor>=5 ? "true" : "false"))); /** * Contruct a framework. * */ public Framework(Object m) throws Exception { ProtectionDomain pd = null; if (System.getSecurityManager() != null) { try { pd = getClass().getProtectionDomain(); } catch (Throwable t) { if(Debug.classLoader) { Debug.println("Failed to get protection domain: " + t); } } perm = new SecurePermissionOps(this); } else { perm = new PermissionOps(); } Class storageImpl = Class.forName(whichStorageImpl); storage = (BundleStorage)storageImpl.newInstance(); dataStorage = Util.getFileStorage("data"); packages = new Packages(this); listeners = new Listeners(perm); services = new Services(perm); systemBundle = new SystemBundle(this, pd); systemBC = new BundleContextImpl(systemBundle); bundles = new Bundles(this); systemBundle.setBundleContext(systemBC); perm.registerService(); String[] classes = new String [] { PackageAdmin.class.getName() }; services.register(systemBundle, classes, new PackageAdminImpl(this), null); registerStartLevel(); urlStreamHandlerFactory = new ServiceURLStreamHandlerFactory(this); contentHandlerFactory = new ServiceContentHandlerFactory(this); urlStreamHandlerFactory .setURLStreamHandler(BundleURLStreamHandler.PROTOCOL, new BundleURLStreamHandler(bundles, perm)); urlStreamHandlerFactory .setURLStreamHandler(ReferenceURLStreamHandler.PROTOCOL, new ReferenceURLStreamHandler()); // Install service based URL stream handler. This can be turned // off if there is need if(REGISTERSERVICEURLHANDLER) { try { URL.setURLStreamHandlerFactory(urlStreamHandlerFactory); URLConnection.setContentHandlerFactory(contentHandlerFactory); } catch (Throwable e) { Debug.println("Cannot set global URL handlers, continuing without OSGi service URL handler (" + e + ")"); e.printStackTrace(); } } bundles.load(); mainHandle = m; } private void registerStartLevel(){ String useStartLevel = Framework.getProperty(USESTARTLEVEL_PROP, TRUE); if(TRUE.equals(useStartLevel)) { if(Debug.startlevel) { Debug.println("[using startlevel service]"); } startLevelService = new StartLevelImpl(this); // restoreState just reads from persistent storage // open() needs to be called to actually do the work // This is done after framework has been launched. startLevelService.restoreState(); services.register(systemBundle, new String [] { StartLevel.class.getName() }, startLevelService, null); } } /** * Start this Framework. * This method starts all the bundles that were started at * the time of the last shutdown. * * <p>If the Framework is already started, this method does nothing. * If the Framework is not started, this method will: * <ol> * <li>Enable event handling. At this point, events can be delivered to * listeners.</li> * <li>Attempt to start all bundles marked for starting as described in the * {@link Bundle#start} method. * Reports any exceptions that occur during startup using * <code>FrameworkErrorEvents</code>.</li> * <li>Set the state of the Framework to <i>active</i>.</li> * <li>Broadcasting a <code>FrameworkEvent</code> through the * <code>FrameworkListener.frameworkStarted</code> method.</li> * </ol></p> * * <p>If this Framework is not launched, it can still install, * uninstall, start and stop bundles. (It does these tasks without * broadcasting events, however.) Using Framework without launching * it allows for off-line debugging of the Framework.</p> * * @param startBundle If it is specified with a value larger than 0, * then the bundle with that id is started. * Otherwise start all suspended bundles. */ public void launch(long startBundle) throws BundleException { if (!active) { active = true; if (startBundle > 0) { startBundle(startBundle); } else { for (Iterator i = storage.getStartOnLaunchBundles().iterator(); i.hasNext(); ) { Bundle b = bundles.getBundle((String)i.next()); try { b.start(); } catch (BundleException be) { listeners.frameworkError(b, be); } } } systemBundle.systemActive(); // start level open is delayed to this point to // correctly work at restart if (startLevelService != null) { startLevelService.open(); } listeners.frameworkEvent(new FrameworkEvent(FrameworkEvent.STARTED, systemBundle, null)); } } /** * Stop this Framework, suspending all started contexts. * This method suspends all started contexts so that they can be * automatically restarted when this Framework is next launched. * * <p>If the framework is not started, this method does nothing. * If the framework is started, this method will: * <ol> * <li>Set the state of the Framework to <i>inactive</i>.</li> * <li>Suspended all started bundles as described in the * {@link Bundle#stop} method except that the persistent * state of the bundle will continue to be started. * Reports any exceptions that occur during stopping using * <code>FrameworkErrorEvents</code>.</li> * <li>Disable event handling.</li> * </ol></p> * */ public void shutdown() { if (active) { // No shuttingdown event specified // listeners.frameworkChanged(new FrameworkEvent(FrameworkEvent.SHUTTING_DOWN)); active = false; List slist = storage.getStartOnLaunchBundles(); shuttingdown = true; systemBundle.systemShuttingdown(); if (startLevelService != null) { startLevelService.shutdown(); } // Stop bundles, in reverse start order for (int i = slist.size()-1; i >= 0; i Bundle b = bundles.getBundle((String)slist.get(i)); try { if(b != null) { synchronized (b) { if (b.getState() == Bundle.ACTIVE) { b.stop(); } } } } catch (BundleException be) { listeners.frameworkEvent(new FrameworkEvent(FrameworkEvent.ERROR, b, be)); } } shuttingdown = false; // Purge any unrefreshed bundles List all = bundles.getBundles(); for (Iterator i = all.iterator(); i.hasNext(); ) { ((BundleImpl)i.next()).purge(); } } StringBuffer bootClasspath = new StringBuffer(); StringBuffer frameworkClasspath = new StringBuffer(); for (Iterator i = bundles.getFragmentBundles(systemBundle).iterator(); i.hasNext(); ) { BundleImpl eb = (BundleImpl)i.next(); String path = eb.archive.getJarLocation(); StringBuffer sb = eb.isBootClassPathExtension() ? bootClasspath : frameworkClasspath; sb.append(path); if (i.hasNext()) { sb.append(File.pathSeparator); } } try { FileTree storage = Util.getFileStorage(CLASSPATH_DIR); File bcpf = new File(storage, BOOT_CLASSPATH_FILE); File fcpf = new File(storage, FRAMEWORK_CLASSPATH_FILE); if (bootClasspath.length() > 0) { saveStringBuffer(bcpf, bootClasspath); } else { bcpf.delete(); } if (frameworkClasspath.length() > 0) { saveStringBuffer(fcpf, frameworkClasspath); } else { fcpf.delete(); } } catch (IOException e) { System.err.println("Could not save classpath " + e); } } private void saveStringBuffer(File f, StringBuffer content) throws IOException { PrintStream out = null; try { out = new PrintStream(new FileOutputStream(f)); out.println(content.toString()); } finally { if (out != null) { out.close(); } } } /** * Install a bundle from the given location. * * @param location The location identifier of the bundle to install. * @param in The InputStream from which the bundle will be read. * @return The BundleImpl object of the installed bundle. * @exception BundleException If the install failed. */ public long installBundle(String location, InputStream in) throws BundleException { return bundles.install(location, in).id; } /** * Start a bundle. * * @param id Id of bundle to start. * @exception BundleException If start failed. */ public void startBundle(long id) throws BundleException { Bundle b = bundles.getBundle(id); if (b != null) { b.start(); } else { throw new BundleException("No such bundle: " + id); } } /** * Stop a bundle. * * @param id Id of bundle to stop. * @exception BundleException If stop failed. */ public void stopBundle(long id) throws BundleException { Bundle b = bundles.getBundle(id); if (b != null) { b.stop(); } else { throw new BundleException("No such bundle: " + id); } } /** * Uninstall a bundle. * * @param id Id of bundle to stop. * @exception BundleException If uninstall failed. */ public void uninstallBundle(long id) throws BundleException { Bundle b = bundles.getBundle(id); if (b != null) { b.uninstall(); } else { throw new BundleException("No such bundle: " + id); } } /** * Update a bundle. * * @param id Id of bundle to update. * @exception BundleException If update failed. */ public void updateBundle(long id) throws BundleException { Bundle b = bundles.getBundle(id); if (b != null) { b.update(); } else { throw new BundleException("No such bundle: " + id); } } /** * Retrieve location of the bundle that has the given * unique identifier. * * @param id The identifier of the bundle to retrieve. * @return A location as a string, or <code>null</code> * if the identifier doesn't match any installed bundle. */ public String getBundleLocation(long id) { Bundle b = bundles.getBundle(id); if (b != null) { return b.getLocation(); } else { return null; } } /** * Retrieve bundle id of the bundle that has the given * unique location. * * @param location The location of the bundle to retrieve. * @return The unique identifier of the bundle, or <code>-1</code> * if the location doesn't match any installed bundle. */ public long getBundleId(String location) { Bundle b = bundles.getBundle(location); if (b != null) { return b.getBundleId(); } else { return -1; } } /** * Get private bundle data storage file handle. */ public FileTree getDataStorage(long id) { if (dataStorage != null) { return new FileTree(dataStorage, Long.toString(id)); } return null; } /** * Check if an execution environment string is accepted */ boolean isValidEE(String ee) { ee = ee.trim(); if(ee == null || "".equals(ee)) { return true; } String fwEE = Framework.getProperty(Constants.FRAMEWORK_EXECUTIONENVIRONMENT); if(fwEE == null) { // If EE is not set, allow everything return true; } else if (!fwEE.equals(eeCache)) { eeCacheSet.clear(); String[] l = Util.splitwords(fwEE, ","); for(int i = 0 ; i < l.length; i++) { eeCacheSet.add(l[i]); } eeCache = fwEE; } String[] eel = Util.splitwords(ee, ","); for(int i = 0 ; i < eel.length; i++) { if(eeCacheSet.contains(eel[i])) { return true; } } return false; } // Static package methods /** * Retrieve the value of the named framework property. * */ public static String getProperty(String key) { return getProperty(key, null); } /** * Retrieve the value of the named framework property, with a default value. * */ public static String getProperty(String key, String def) { String v = (String)props.get(key); if(v != null) { return v; } else { // default to system property return System.getProperty(key, def); } } public static void setProperty(String key, String val) { if (volatileProperties.contains(key)) { System.setProperty(key,val); } else { props.put(key, val); } } public static void setProperties(Dictionary newProps) { for(Enumeration it = newProps.keys(); it.hasMoreElements(); ) { String key = (String)it.nextElement(); setProperty(key, (String)newProps.get(key)); } } public static Dictionary getProperties(){ Hashtable p = new Hashtable(); p.putAll(System.getProperties()); p.putAll(props); return p; } /** * Get a copy of the current system properties. */ public static java.util.Properties getSystemProperties() { return (java.util.Properties)System.getProperties().clone(); } protected static void initProperties() { props = new HashMap(); whichStorageImpl = "org.knopflerfish.framework.bundlestorage." + Framework.getProperty("org.knopflerfish.framework.bundlestorage", "file") + ".BundleStorageImpl"; bIsMemoryStorage = whichStorageImpl.equals("org.knopflerfish.framework.bundlestorage.memory.BundleStorageImpl"); if (bIsMemoryStorage || !EXIT_ON_SHUTDOWN || !USING_WRAPPER_SCRIPT) { SUPPORTS_EXTENSION_BUNDLES = false; // we can not support this in this mode. } else { SUPPORTS_EXTENSION_BUNDLES = true; } // The name of the operating system of the hosting computer. setProperty(Constants.FRAMEWORK_OS_NAME, System.getProperty("os.name")); // The name of the processor of the hosting computer. setProperty(Constants.FRAMEWORK_PROCESSOR, System.getProperty("os.arch")); String ver = System.getProperty("os.version"); if (ver != null) { int dots = 0; int i = 0; for ( ; i < ver.length(); i++) { char c = ver.charAt(i); if (Character.isDigit(c)) { continue; } else if (c == '.') { if (++dots < 3) { continue; } } break; } osVersion = ver.substring(0, i); } setProperty(Constants.FRAMEWORK_OS_VERSION, osVersion); setProperty(Constants.FRAMEWORK_VERSION, SPEC_VERSION); setProperty(Constants.FRAMEWORK_VENDOR, "Knopflerfish"); setProperty(Constants.FRAMEWORK_LANGUAGE, Locale.getDefault().getLanguage()); // Various framework properties setProperty(Constants.SUPPORTS_FRAMEWORK_REQUIREBUNDLE, TRUE); setProperty(Constants.SUPPORTS_FRAMEWORK_FRAGMENT, TRUE); setProperty(Constants.SUPPORTS_FRAMEWORK_EXTENSION, SUPPORTS_EXTENSION_BUNDLES ? TRUE : FALSE); setProperty(Constants.SUPPORTS_BOOTCLASSPATH_EXTENSION, SUPPORTS_EXTENSION_BUNDLES ? TRUE : FALSE); Dictionary sysProps = getSystemProperties(); setProperties(sysProps); } /** * Get the bundle context used by the system bundle. */ public BundleContext getSystemBundleContext() { return systemBC; } }
package li.tengfei.apng.opt.optimizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.awt.*; import java.util.*; /** * K-Means++ Color Reducer * * @author ltf * @since 16/12/14, 9:52 */ public class KMeansPpReducer implements ColorReducer { private static final Logger log = LoggerFactory.getLogger(KMeansPpReducer.class); private static final int MAX_CACHE_DISTS = 1024 * 10; // 200M private Random rand = new Random(); private int mPixels; private int[][] mDists; private Color[] mColors; /** * reduce color use k-means++ algorithm */ @Override public Map<Color, Color> reduce(Color[] pixels, int target) { // count color appearance mPixels = pixels.length; HashMap<Color, Integer> countMap = new HashMap<Color, Integer>(); for (Color p : pixels) { if (countMap.containsKey(p)) { countMap.put(p, countMap.get(p) + 1); } else { countMap.put(p, 1); } } // set colors [ sorted by count ] ArrayList<ColorCount> colorCounts = new ArrayList<>(countMap.size()); Color[] colors = new Color[countMap.size()]; int[] counts = new int[countMap.size()]; for (Map.Entry<Color, Integer> e : countMap.entrySet()) { colorCounts.add(new ColorCount(e.getKey(), e.getValue())); } Collections.sort(colorCounts); for (int i = 0; i < colorCounts.size(); i++) { colors[i] = colorCounts.get(i).color; counts[i] = colorCounts.get(i).count; } int[] indexes = new int[countMap.size()]; Color[] outcolors = new Color[target]; reduce(colors, counts, indexes, outcolors); HashSet<Color> distinctOut = new HashSet<>(); distinctOut.addAll(Arrays.asList(outcolors)); log.debug("finally output colors count: " + distinctOut.size()); HashMap<Color, Color> mapping = new HashMap<>(colors.length); for (int j = 0; j < colors.length; j++) { mapping.put(colors[j], outcolors[indexes[j]]); } return mapping; } /** * reduce colors to centers(outColors) * * @param colors input colors * @param counts input colors' count * @param indexes output colors' mapping * @param centers output reduced colors */ private void reduce(Color[] colors, int[] counts, int[] indexes, Color[] centers) { // init centers initCenters(colors, counts, indexes, centers); int lastMinChanged = Integer.MAX_VALUE; int countOverLastMin = 0; long lastMillis = System.currentTimeMillis(); while (cluster(colors, centers, indexes) > 0) { //splitMaxCenters(colors, counts, centers, indexes, 0.000005f); int changed = refreshCenters(colors, centers, counts, indexes); long millis = System.currentTimeMillis(); log.debug("rounds millis: " + (millis - lastMillis)); lastMillis = millis; // if current changed <= minChanged appeared N times ago, then stop if (countOverLastMin > 50 && changed <= lastMinChanged) { cluster(colors, centers, indexes); break; } if (changed < lastMinChanged) { lastMinChanged = changed; countOverLastMin = 0; log.debug("new min changed: " + changed); } else countOverLastMin++; } } /** * Random init center points (colors) */ private void initCenters(Color[] colors, int[] counts, int[] indexes, Color[] centers) { int pixels = 0; // random init centers for (int i = 0; i < centers.length; i++) { Color candidate = null; while (candidate == null) { candidate = randomPickColor(colors, counts); // remove exists Color for (int j = 0; j < i; j++) { if (candidate.equals(centers[i])) candidate = null; } } centers[i] = candidate; } cluster(colors, centers, indexes); splitMaxCenters(colors, counts, centers, indexes, 0.033f); } private Color randomPickColor(Color[] colors, int[] counts) { int candidateCount = mPixels; int candidateIndex = 0; while (candidateCount > 0) { candidateIndex = rand.nextInt(counts.length); candidateCount -= counts[candidateIndex]; } return colors[candidateIndex]; } /** * split max center * * @param splitRate split if the max * splitRate > min */ private void splitMaxCenters(Color[] colors, int[] counts, Color[] centers, int[] indexes, float splitRate) { int[] centerCounts = new int[centers.length]; for (int i = 0; i < indexes.length; i++) { centerCounts[indexes[i]] += counts[i]; } ArrayList<IndexCount> indexCounts = new ArrayList<>(centerCounts.length); for (int i = 0; i < centerCounts.length; i++) { indexCounts.add(new IndexCount(i, centerCounts[i])); } Collections.sort(indexCounts); for (int maxPos = 0, minPos = indexCounts.size() - 1; maxPos < minPos; maxPos++) { // split previous max count center, to replace last min count center, until max * splitRate < min if (indexCounts.get(maxPos).count * splitRate < indexCounts.get(minPos).count) break; if (splitMaxCenter( colors, counts, centers, indexes, indexCounts.get(maxPos).index, indexCounts.get(minPos).index)) { minPos } } } /** * split MAX CENTER centers[maxIdx] INTO centers[maxIdx], centers[minIdx] * * @return split success or not */ private boolean splitMaxCenter(Color[] colors, int[] counts, Color[] centers, final int[] indexes, final int maxIdx, int minIdx) { // generate sub colors/counts/centers/indexes for split int count = 0; for (int idx : indexes) if (idx == maxIdx) count++; Color[] subColors = new Color[count]; int[] subCounts = new int[count]; int[] subIndexes = new int[count]; Color[] subCenters = new Color[2]; int idx = 0; for (int i = 0; i < indexes.length; i++) { if (indexes[i] != maxIdx) continue; subColors[idx] = colors[i]; subCounts[idx++] = counts[i]; } // get the longest distance two color int maxDist = 0, maxX = 0, maxY = 0; for (int x = 0; x < subColors.length; x++) { for (int y = x + 1; y < subColors.length; y++) { int dist = distance(subColors[x], subColors[y]); if (dist > maxDist) { maxDist = dist; maxX = x; maxY = y; } } } // use the longest distance color as two center subCenters[0] = subColors[maxX]; subCenters[1] = subColors[maxY]; // do cluster and refresh centers cluster(subColors, subCenters, subIndexes); refreshCenters(subColors, subCenters, subCounts, subIndexes); boolean splitSucc = !subCenters[0].equals(subCenters[1]); if (splitSucc) { centers[minIdx] = subCenters[0]; centers[maxIdx] = subCenters[1]; } return splitSucc; } /** * recompute centers * * @param colors distinct colors * @param centers centers * @param counts color appear count * @param indexes color mapping to indexes * @return color center changed counts */ private int refreshCenters(Color[] colors, Color[] centers, int[] counts, int[] indexes) { int changed = 0; for (int i = 0; i < centers.length; i++) { long R = 0, G = 0, B = 0, A = 0, W = 0; // compute center a,r,g,b for (int j = 0; j < colors.length; j++) { if (indexes[j] != i) continue; long count = counts[j]; R += colors[j].getRed() * count; G += colors[j].getGreen() * count; B += colors[j].getBlue() * count; A += colors[j].getAlpha() * count; W += count; } Color vCenter = new Color( Math.round(R / W), Math.round(G / W), Math.round(B / W), Math.round(A / W)); Color center = centers[i]; int minDist = Integer.MAX_VALUE; for (int j = 0; j < colors.length; j++) { if (indexes[j] != i) continue; int dist = distance(vCenter, colors[j]); if (dist < minDist) { minDist = dist; center = colors[j]; } } if (!center.equals(centers[i])) { changed++; centers[i] = center; } } return changed; } /** * cluster colors to nearby centers * * @param colors distinct colors * @param centers centers * @param indexes color mapping to indexes * @return color mapping changed counts */ private int cluster(Color[] colors, Color[] centers, int[] indexes) { int changed = 0; for (int i = 0; i < colors.length; i++) { int minDist = Integer.MAX_VALUE; int minIdx = 0; for (int j = 0; j < centers.length; j++) { int dist = distance(colors[i], centers[j]); if (dist < minDist) { minDist = dist; minIdx = j; } } if (indexes[i] != minIdx) { indexes[i] = minIdx; changed++; } } return changed; } public int distance(Color a, Color b) { int dist = 0; int delta = a.getRed() - b.getRed(); dist += delta * delta; delta = a.getGreen() - b.getGreen(); dist += delta * delta; delta = a.getBlue() - b.getBlue(); dist += delta * delta; delta = a.getAlpha() - b.getAlpha(); dist += delta * delta; return dist; } /** * @param colors * @param a * @param b * @return */ private int distance(Color[] colors, int a, int b) { if (a == b) return 0; else if (a > b) return distance(colors, b, a); return 0; } private void initDistCache(Color[] colors, int[] counts) { int maxCount = colors.length < MAX_CACHE_DISTS ? colors.length : MAX_CACHE_DISTS; for (int x = 0; x < maxCount; x++) { //for(int y=) } } private static class IndexCount implements Comparable<IndexCount> { int index; int count; public IndexCount(int index, int count) { this.index = index; this.count = count; } @Override public int compareTo(IndexCount o) { return o.count - this.count; } } private static class ColorCount implements Comparable<ColorCount> { Color color; int count; public ColorCount(Color color, int count) { this.color = color; this.count = count; } @Override public int compareTo(ColorCount o) { return o.count - this.count; } } }
package com.xeiam.xchange.btce; import com.xeiam.xchange.btce.dto.account.BTCEAccountInfo; import com.xeiam.xchange.btce.dto.marketdata.BTCETicker; import com.xeiam.xchange.btce.dto.marketdata.BTCETrade; import com.xeiam.xchange.btce.dto.trade.BTCEOrder; import com.xeiam.xchange.currency.MoneyUtils; import com.xeiam.xchange.dto.Order.OrderType; import com.xeiam.xchange.dto.account.AccountInfo; import com.xeiam.xchange.dto.marketdata.Ticker; import com.xeiam.xchange.dto.marketdata.Ticker.TickerBuilder; import com.xeiam.xchange.dto.marketdata.Trade; import com.xeiam.xchange.dto.marketdata.Trades; import com.xeiam.xchange.dto.trade.LimitOrder; import com.xeiam.xchange.dto.trade.OpenOrders; import com.xeiam.xchange.dto.trade.Wallet; import com.xeiam.xchange.utils.DateUtils; import org.joda.money.BigMoney; import org.joda.money.CurrencyUnit; import org.joda.money.IllegalCurrencyException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; /** * Various adapters for converting from BTCE DTOs to XChange DTOs */ public final class BTCEAdapters { private static final Logger log = LoggerFactory.getLogger(BTCEAdapters.class); /** * private Constructor */ private BTCEAdapters() { } /** * Adapts a BTCEOrder to a LimitOrder * * @param amount * @param price * @param currency * @param orderTypeString * @param id * @return */ public static LimitOrder adaptOrder(BigDecimal amount, BigDecimal price, String tradableIdentifier, String currency, String orderTypeString, String id) { // place a limit order OrderType orderType = orderTypeString.equalsIgnoreCase("bid") ? OrderType.BID : OrderType.ASK; BigMoney limitPrice; limitPrice = MoneyUtils.parse(currency + " " + price); return new LimitOrder(orderType, amount, tradableIdentifier, currency, limitPrice); } /** * Adapts a List of BTCEOrders to a List of LimitOrders * * @param BTCEOrders * @param currency * @param orderType * @param id * @return */ public static List<LimitOrder> adaptOrders(List<BigDecimal[]> BTCEOrders, String tradableIdentifier, String currency, String orderType, String id) { List<LimitOrder> limitOrders = new ArrayList<LimitOrder>(); for (BigDecimal[] btceOrder : BTCEOrders) { // Bid orderbook is reversed order. Insert at index 0 instead of // appending if (orderType.equalsIgnoreCase("bid")) { limitOrders.add(0, adaptOrder(btceOrder[1], btceOrder[0], tradableIdentifier, currency, orderType, id)); } else { limitOrders.add(adaptOrder(btceOrder[1], btceOrder[0], tradableIdentifier, currency, orderType, id)); } } return limitOrders; } /** * Adapts a BTCETrade to a Trade Object * * @param BTCETrade A BTCE trade * @return The XChange Trade */ public static Trade adaptTrade(BTCETrade BTCETrade) { OrderType orderType = BTCETrade.equals("bid") ? OrderType.BID : OrderType.ASK; BigDecimal amount = BTCETrade.getAmount(); String currency = BTCETrade.getPriceCurrency(); BigMoney price = MoneyUtils.parse(currency + " " + BTCETrade.getPrice()); String tradableIdentifier = BTCETrade.getItem(); Date date = DateUtils.fromMillisUtc(BTCETrade.getDate() * 1000L); return new Trade(orderType, amount, tradableIdentifier, currency, price, date); } /** * Adapts a BTCETrade[] to a Trades Object * * @param BTCETrades The BTCE trade data * @return The trades */ public static Trades adaptTrades(BTCETrade[] BTCETrades) { List<Trade> tradesList = new ArrayList<Trade>(); for (BTCETrade BTCETrade : BTCETrades) { // Date is reversed order. Insert at index 0 instead of appending tradesList.add(0, adaptTrade(BTCETrade)); } return new Trades(tradesList); } /** * Adapts a BTCETicker to a Ticker Object * * @param bTCETicker * @return */ public static Ticker adaptTicker(BTCETicker bTCETicker, String tradableIdentifier, String currency) { BigMoney last = MoneyUtils.parse(currency + " " + bTCETicker.getTicker().getLast()); BigMoney bid = MoneyUtils.parse(currency + " " + bTCETicker.getTicker().getSell()); BigMoney ask = MoneyUtils.parse(currency + " " + bTCETicker.getTicker().getBuy()); BigMoney high = MoneyUtils.parse(currency + " " + bTCETicker.getTicker().getHigh()); BigMoney low = MoneyUtils.parse(currency + " " + bTCETicker.getTicker().getLow()); BigDecimal volume = bTCETicker.getTicker().getVol(); return TickerBuilder.newInstance().withTradableIdentifier(tradableIdentifier).withLast(last).withBid(bid).withAsk(ask).withHigh(high).withLow(low).withVolume(volume).build(); } public static AccountInfo adaptAccountInfo(BTCEAccountInfo btceAccountInfo) { List<Wallet> wallets = new ArrayList<Wallet>(); Map<String, BigDecimal> funds = btceAccountInfo.getFunds(); for (String lcCurrency : funds.keySet()) { String currency = lcCurrency.toUpperCase(); try { CurrencyUnit.of(currency); } catch (IllegalCurrencyException e) { log.warn("Ignoring unknown currency {}",currency); continue; } wallets.add(Wallet.createInstance(currency, funds.get(lcCurrency))); } return new AccountInfo(null, wallets); } public static OpenOrders adaptOrders(Map<Long, BTCEOrder> btceOrderMap) { List<LimitOrder> os = new ArrayList<LimitOrder>(); for (Long id : btceOrderMap.keySet()) { BTCEOrder o = btceOrderMap.get(id); OrderType orderType = o.getType() == BTCEOrder.Type.buy ? OrderType.BID : OrderType.ASK; String[] pair = o.getPair().split("_"); String currency = pair[1].toUpperCase(); BigMoney price = BigMoney.of(CurrencyUnit.of(currency), o.getAmount()); os.add(new LimitOrder(orderType, o.getAmount(), pair[0].toUpperCase(), currency, Long.toString(id), price)); } return new OpenOrders(os); } }
package org.reldb.rel.v0.storage; import java.io.*; import java.util.*; import java.util.concurrent.TimeUnit; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Files; import org.reldb.rel.exceptions.*; import org.reldb.rel.v0.external.DirClassLoader; import org.reldb.rel.v0.generator.*; import org.reldb.rel.v0.interpreter.Interpreter; import org.reldb.rel.v0.languages.tutoriald.parser.*; import org.reldb.rel.v0.storage.catalog.*; import org.reldb.rel.v0.storage.relvars.RelvarDefinition; import org.reldb.rel.v0.storage.relvars.RelvarGlobal; import org.reldb.rel.v0.storage.relvars.RelvarHeading; import org.reldb.rel.v0.storage.relvars.RelvarMetadata; import org.reldb.rel.v0.storage.relvars.RelvarPrivate; import org.reldb.rel.v0.storage.relvars.RelvarPrivateCell; import org.reldb.rel.v0.storage.relvars.RelvarReal; import org.reldb.rel.v0.storage.relvars.RelvarRealMetadata; import org.reldb.rel.v0.storage.tables.KeyTableNames; import org.reldb.rel.v0.storage.tables.KeyTables; import org.reldb.rel.v0.storage.tables.RegisteredTupleIterator; import org.reldb.rel.v0.storage.tables.Table; import org.reldb.rel.v0.storage.tables.TablePrivate; import org.reldb.rel.v0.types.Heading; import org.reldb.rel.v0.types.Type; import org.reldb.rel.v0.types.TypeAlpha; import org.reldb.rel.v0.types.builtin.*; import org.reldb.rel.v0.values.*; import org.reldb.rel.v0.version.Version; import org.reldb.rel.v0.vm.Context; import org.reldb.rel.v0.vm.Operator; import org.reldb.rel.v0.vm.VirtualMachine; import com.sleepycat.bind.EntryBinding; import com.sleepycat.bind.serial.SerialBinding; import com.sleepycat.bind.serial.StoredClassCatalog; import com.sleepycat.bind.tuple.StringBinding; import com.sleepycat.je.*; public class RelDatabase { public final static String systemOwner = "Rel"; private Environment environment; private DatabaseConfig dbConfigurationNormal; private DatabaseConfig dbConfigurationAllowCreate; private DatabaseConfig dbConfigurationTemporary; private DatabaseConfig dbConfigurationTemporaryWithDuplicatesNoComparator; private DatabaseConfig dbConfigurationMetadataAllowCreateNoComparator; // Metadata private ClassCatalog classCatalog; private StringBinding stringDataBinding; private DatabaseEntry keyTableEntry = new DatabaseEntry(); private Database relvarDb; // open real relvar tables private Hashtable<String, Database> openTables = new Hashtable<String, Database>(); // temporary private relvar table names private HashSet<String> tempTables = new HashSet<String>(); // active transaction per thread private Hashtable<Long, RelTransaction> transactions = new Hashtable<Long, RelTransaction>(); // database constraints private Hashtable<String, Operator> constraints = new Hashtable<String, Operator>(); // built-in operators private HashMap<String, OperatorDefinition> builtinops = new HashMap<String, OperatorDefinition>(); // Permanent cached operator definitions. private HashMap<OperatorSignature, OperatorDefinition> operatorCachePermanent = new HashMap<OperatorSignature, OperatorDefinition>(); // Cached operator definitions private HashMap<OperatorSignature, OperatorDefinition> operatorCache = new HashMap<OperatorSignature, OperatorDefinition>(); // Cached type definitions private HashMap<String, org.reldb.rel.v0.types.Type> typeCache = new HashMap<String, org.reldb.rel.v0.types.Type>(); // Active registered tuple iterators private HashSet<RegisteredTupleIterator> registeredTupleIterators = new HashSet<RegisteredTupleIterator>(); // class loader for external Java-based operators and types private DirClassLoader dirClassLoader; // Relative database directory name private static final String databaseHomeRelative = "Reldb"; // Relative user code directory name private static final String userCodeHomeRelative = "RelUserCode"; // Rel user Java code package private static final String relUserCodePackage = databaseHomeRelative + "." + userCodeHomeRelative; // User code home dir private String userCodeHome; // Database home dir private String databaseHome = databaseHomeRelative; // Rel home dir private String homeDir; // Special mode for caching permanent operators and types private boolean specialCacheMode = true; // Custom types folder private String customRelvarsDatabase; private String customRelvarsHome; private ArrayList<String> customRelvars; // Additional JAR files for the Java compiler to include in the classpath when compiling. private String[] additionalJarsForJavaCompilerClasspath = null; public void setAdditionalJarsForJavaCompilerClasspath(String[] additionalJarsForClasspath) { this.additionalJarsForJavaCompilerClasspath = additionalJarsForClasspath; } public String[] getAdditionalJarsForJavaCompilerClasspath() { return additionalJarsForJavaCompilerClasspath; } /* * This class is used to set up custom Comparator used by the Berkeley DB for data (not needed for metadata). */ private static class ComparisonHandler implements Serializable, Comparator<byte[]> { private static final long serialVersionUID = 1L; private static volatile SerialBinding<ValueTuple> tupleBinding; public ComparisonHandler(SerialBinding<ValueTuple> tupleBinding) { ComparisonHandler.tupleBinding = tupleBinding; } @Override public int compare(byte[] o1, byte[] o2) { ValueTuple v1 = tupleBinding.entryToObject(new DatabaseEntry(o1)); ValueTuple v2 = tupleBinding.entryToObject(new DatabaseEntry(o2)); return v1.compareTo(v2); } } private static void applyComparatorTo(Comparator<byte[]> comparator, DatabaseConfig config) { config.setBtreeComparator(comparator); config.setOverrideBtreeComparator(true); config.setDuplicateComparator(comparator); config.setOverrideDuplicateComparator(true); } private String getBerkeleyJavaDBVersion() { return JEVersion.CURRENT_VERSION.getVersionString(); } public static void mkdir(String dir) { File dirf = new File(dir); if (!dirf.exists()) { if (!dirf.mkdirs()) { String msg = "Unable to create directory: " + dirf; throw new ExceptionFatal("RS0324: " + msg); } } } private String getClickerFileName() { return homeDir + File.separator + "ClickToOpen.rdb"; } private void writeClicker() { FileWriter writer = null; try { writer = new FileWriter(getClickerFileName(), false); if (writer != null) writer.close(); } catch (Exception e) { System.out.println("WARNING: Unable to create " + getClickerFileName()); } } private String getVersionFileName() { return databaseHome + File.separator + "version"; } private void writeVersion() throws IOException { FileWriter writer = null; try { writer = new FileWriter(getVersionFileName(), false); writer.write(Integer.toString(Version.getDatabaseVersion())); } finally { if (writer != null) writer.close(); } } private int readVersion() { List<String> lines = null; try { lines = Files.readAllLines(new File(getVersionFileName()).toPath()); } catch (IOException e1) { return -1; } if (lines.isEmpty()) return -1; try { return Integer.parseInt(lines.get(0)); } catch (NumberFormatException nfe) { return -1; } } public void open(File envHome, boolean canCreateDb, PrintStream outputStream) throws DatabaseFormatVersionException { System.out.println("Opening database in " + envHome + "\nIf it doesn't exist, we'll " + ((canCreateDb) ? "try to create it" : "cause an error") + "."); String usingBerkeleyJavaDBVersion = getBerkeleyJavaDBVersion(); if (!usingBerkeleyJavaDBVersion.equals(Version.expectedBerkeleyDBVersion)) throw new ExceptionFatal("RS0323: Expected to find Berkeley Java DB version " + Version.expectedBerkeleyDBVersion + " but found version " + usingBerkeleyJavaDBVersion + ".\nAn attempted update or re-installation has probably failed.\nPlease make sure " + Version.getBerkeleyDbJarFilename() + " is not read-only, then try the update or re-installation again."); homeDir = envHome.getAbsolutePath(); if (homeDir.endsWith(".")) homeDir = homeDir.substring(0, homeDir.length() - 1); if (!homeDir.endsWith(java.io.File.separator)) homeDir += java.io.File.separator; databaseHome = homeDir + databaseHomeRelative; if (!(new File(databaseHome)).exists()) if (!canCreateDb) throw new ExceptionSemantic("RS0406: Database " + homeDir + " either doesn't exist or isn't a Rel database."); else { mkdir(databaseHome); try { writeVersion(); } catch (IOException ioe) { throw new ExceptionSemantic("RS0408: Can't write version file in database in " + homeDir + "."); } } else { int detectedVersion = readVersion(); if (detectedVersion < 0) { throw new ExceptionSemantic("RS0407: Database in " + homeDir + " has no version information, or it's invalid. The database must be upgraded manually.\nBack it up with the version of Rel used to create it and load the backup into a new database."); } else if (detectedVersion < Version.getDatabaseVersion()) { String msg = "RS0410: Database requires conversion from format v" + detectedVersion + " to format v" + Version.getDatabaseVersion(); throw new DatabaseFormatVersionException(msg, detectedVersion); } else if (detectedVersion > Version.getDatabaseVersion()) { throw new ExceptionSemantic("RS0409: Database in " + homeDir + " appears to have been created by a newer version of Rel than this one.\nOpen it with the latest version of Rel."); } } writeClicker(); userCodeHome = databaseHome + java.io.File.separator + userCodeHomeRelative; dirClassLoader = new DirClassLoader(homeDir); try { EnvironmentConfig environmentConfig = new EnvironmentConfig(); environmentConfig.setReadOnly(false); environmentConfig.setAllowCreate(true); environmentConfig.setTransactional(true); environmentConfig.setTxnSerializableIsolation(true); dbConfigurationNormal = new DatabaseConfig(); dbConfigurationNormal.setReadOnly(false); dbConfigurationNormal.setAllowCreate(false); dbConfigurationNormal.setTransactional(true); dbConfigurationNormal.setSortedDuplicates(false); dbConfigurationAllowCreate = new DatabaseConfig(); dbConfigurationAllowCreate.setReadOnly(false); dbConfigurationAllowCreate.setAllowCreate(true); dbConfigurationAllowCreate.setTransactional(true); dbConfigurationAllowCreate.setSortedDuplicates(false); dbConfigurationTemporary = new DatabaseConfig(); dbConfigurationTemporary.setReadOnly(false); dbConfigurationTemporary.setAllowCreate(true); dbConfigurationTemporary.setTransactional(false); dbConfigurationTemporary.setSortedDuplicates(false); dbConfigurationTemporary.setTemporary(true); dbConfigurationTemporaryWithDuplicatesNoComparator = new DatabaseConfig(); dbConfigurationTemporaryWithDuplicatesNoComparator.setReadOnly(false); dbConfigurationTemporaryWithDuplicatesNoComparator.setAllowCreate(true); dbConfigurationTemporaryWithDuplicatesNoComparator.setTransactional(false); dbConfigurationTemporaryWithDuplicatesNoComparator.setSortedDuplicates(true); dbConfigurationTemporaryWithDuplicatesNoComparator.setTemporary(true); dbConfigurationMetadataAllowCreateNoComparator = new DatabaseConfig(); dbConfigurationMetadataAllowCreateNoComparator.setReadOnly(false); dbConfigurationMetadataAllowCreateNoComparator.setAllowCreate(true); dbConfigurationMetadataAllowCreateNoComparator.setTransactional(true); dbConfigurationMetadataAllowCreateNoComparator.setSortedDuplicates(false); // Open the class catalog classCatalog = new ClassCatalog(databaseHome, environmentConfig, dbConfigurationMetadataAllowCreateNoComparator); // Set up database BTREE and duplicate comparators. Comparator<byte[]> comparator = new ComparisonHandler(classCatalog.getTupleBinding()); applyComparatorTo(comparator, dbConfigurationNormal); applyComparatorTo(comparator, dbConfigurationAllowCreate); applyComparatorTo(comparator, dbConfigurationTemporary); // Open the main database environment environment = new Environment(new File(databaseHome), environmentConfig); // Get a code generator Generator generator = new Generator(this, System.out); // Data for key table entries stringDataBinding = new StringBinding(); stringDataBinding.objectToEntry("", keyTableEntry); // Open the metadata db. relvarDb = environment.openDatabase(null, "_Relvars", dbConfigurationMetadataAllowCreateNoComparator); // Declare the Catalog Catalog catalog = new Catalog(this); // Catalog build phase 0 catalog.generatePhase0(generator); // Construct builtin-in primitive types and operators specialCacheMode = true; BuiltinOperators.buildOperators(this); BuiltinTypeBuilder.buildTypes(this); operatorCachePermanent = operatorCache; specialCacheMode = false; // Construct built-in type types. if (!isTypeExists(generator, "TypeInfo")) { try { Interpreter.executeStatementPrivileged(this, "TYPE TypeInfo UNION;", "Rel", System.out); Interpreter.executeStatementPrivileged(this, "TYPE Scalar IS {TypeInfo POSSREP {TypeName CHAR}};", "Rel", System.out); Interpreter.executeStatementPrivileged(this, "TYPE NonScalar IS {TypeInfo POSSREP {Kind CHAR, Attributes RELATION {AttrName CHAR, AttrType TypeInfo}}};", "Rel", System.out); } catch (ParseException e) { e.printStackTrace(); } } // Catalog build phase 1 catalog.generatePhase1(generator); // Prepare for battle. reset(); // Set up plugin directories File homePlugins = new File(System.getProperty("user.home") + java.io.File.separator + "Relplugins"); File databasePlugins = new File(homeDir + java.io.File.separator + "Relplugins"); if (!homePlugins.exists()) homePlugins.mkdir(); if (!databasePlugins.exists()) databasePlugins.mkdir(); customRelvarsHome = homePlugins.getAbsolutePath() + java.io.File.separator + "relvars"; customRelvarsDatabase = databasePlugins.getAbsolutePath() + java.io.File.separator + "relvars"; customRelvars = new ArrayList<String>(); loadPaths(new File(customRelvarsDatabase), new File(customRelvarsHome)); loadConstraints(outputStream); System.out.println("Database " + envHome + " is open."); } catch (DatabaseException db) { String msg = "Unable to open database: " + db.getMessage(); outputStream.println(msg); db.printStackTrace(System.out); throw new ExceptionFatal("RS0325: " + msg); } } /** Return the directory that contains the database. */ public String getHomeDir() { return homeDir; } public void registerTupleIterator(RegisteredTupleIterator registeredTupleIterator) { registeredTupleIterators.add(registeredTupleIterator); } public void unregisterTupleIterator(RegisteredTupleIterator registeredTupleIterator) { registeredTupleIterators.remove(registeredTupleIterator); } public boolean isOpen() { return environment != null; } // Close the environment public void close() { if (environment == null) { System.out.println("WARNING: Attempting to re-close a closed database!"); System.out.println("It's not a problem, but we'll tell you where it's coming from so maybe you can fix it:"); (new Throwable()).printStackTrace(); return; } System.out.println("Closing database in " + homeDir); System.out.println("\tClosing active tuple iterators in " + homeDir); int activeTupleIterators = 0; try { for (RegisteredTupleIterator tupleIterator: registeredTupleIterators) if (tupleIterator.forceClose()) activeTupleIterators++; } catch (Exception e) { System.err.println("\tError closing active tuple iterators: " + homeDir + ": " + e.toString()); } if (activeTupleIterators == 1) System.err.println("\t" + activeTupleIterators + " active tuple iterator was closed."); else if (activeTupleIterators > 1) System.err.println("\t" + activeTupleIterators + " active tuple iterators were closed."); System.out.println("\tCommitting open transactions in " + homeDir); int openTransactions = 0; for (RelTransaction transaction: transactions.values()) while (transaction.getReferenceCount() > 0) try { commitTransaction(transaction); openTransactions++; } catch(DatabaseException dbe) { System.err.println("\tError committing active transactions " + homeDir + ": " + dbe.toString()); } catch (Exception e) { System.err.println("\tUnknown shutdown error 1: " + e); } if (openTransactions == 1) System.err.println("\t" + openTransactions + " open transaction was closed."); else if (openTransactions > 1) System.err.println("\t" + openTransactions + " open transactions were closed."); System.out.println("\tClosing relvars in " + homeDir); try { for (Database table: openTables.values()) table.close(); } catch(DatabaseException dbe) { System.err.println("\tError closing internal tables " + homeDir + ": " + dbe.toString()); } catch (Exception e) { System.err.println("\tUnknown shutdown error 2: " + e); } System.out.println("\tPurging temporary data in " + homeDir); try { for (String tableName: tempTables) environment.removeDatabase(null, tableName); } catch(DatabaseException dbe) { System.err.println("\tError removing temporary data storage " + homeDir + ": " + dbe.toString()); } catch (Exception e) { System.err.println("\tUnknown shutdown error 3: " + e); } System.out.println("\tTemporary data purged in " + homeDir); try { relvarDb.close(); } catch(DatabaseException dbe) { System.err.println("\tError closing the relvarDb " + homeDir + ": " + dbe.toString()); } catch (Exception e) { System.err.println("\tUnknown shutdown error 4: " + e); } System.out.println("\tClosing environment in " + homeDir); try { environment.close(); } catch(DatabaseException dbe) { System.err.println("\tError closing the environment " + homeDir + ": " + dbe.toString()); } catch (Exception e) { System.err.println("\tUnknown shutdown error 5: " + e); } environment = null; try { classCatalog.close(); } catch(DatabaseException dbe) { System.err.println("\tError closing the ClassCatalog in " + homeDir + ": " + dbe.toString()); } catch (Exception e) { System.err.println("\tUnknown shutdown error 6: " + e); } System.out.println("Database " + homeDir + " is closed."); } public void reset() { operatorCache = new HashMap<OperatorSignature, OperatorDefinition>(); typeCache.clear(); } /** Get the user Java code definition directory. */ public String getJavaUserSourcePath() { return userCodeHome; } public static String getRelUserCodePackage() { return relUserCodePackage; } private Database openDatabaseRaw(Transaction txn, String tabName, DatabaseConfig configuration) throws DatabaseException { Database db = environment.openDatabase(txn, tabName, configuration); openTables.put(tabName, db); return db; } // This gnarly bit of code ensures a Berkeley Database is open and valid. If it was opened in a transaction // that was rolled back, it will throw an exception when an attempt is made to open a cursor. In that // case, it needs to be re-opened in the current transaction. private Database openDatabase(Transaction txn, String tabName, DatabaseConfig configuration) { Database db = openTables.get(tabName); try { if (db == null) db = openDatabaseRaw(txn, tabName, configuration); else db.openCursor(txn, null).close(); } catch (IllegalStateException de) { try { db.close(); db = openDatabaseRaw(txn, tabName, configuration); } catch (IllegalStateException de2) { de2.printStackTrace(); throw new ExceptionFatal("RS0326: openDatabase: re-open failed: " + de2); } } return db; } private void closeDatabase(String tabName) throws DatabaseException { Database table = openTables.get(tabName); if (table != null) { table.close(); openTables.remove(tabName); } } public ValueOperator compileAnonymousOperator(String source, PrintStream outputStream) { Interpreter interpreter = new Interpreter(RelDatabase.this, outputStream); try { return interpreter.compileAnonymousOperator(source); } catch (ParseException pe) { throw new ExceptionSemantic("RS0288: Failed compiling anonymous operator " + source + ": " + pe.toString()); } } private void loadConstraints(final PrintStream outputStream) { try { (new TransactionRunner() { public Object run(Transaction txn) throws Throwable { Interpreter interpreter = new Interpreter(RelDatabase.this, outputStream); RelvarSystem constraintsRelvar = (RelvarSystem)openGlobalRelvar(Catalog.relvarConstraints); TupleIterator ti = constraintsRelvar.iterator(interpreter.getGenerator()); try { while (ti.hasNext()) { ValueTuple constraintEntry = ti.next(); String constraintName = constraintEntry.getValues()[0].toString(); String source = constraintEntry.getValues()[1].toString(); try { Operator constraintCheckOperator = interpreter.getGenerator().beginConstraintDefinition(); interpreter.compileStatement("RETURN " + source + ";"); interpreter.getGenerator().endConstraintDefinition(); constraints.put(constraintName, constraintCheckOperator); } catch (ParseException pe) { pe.printStackTrace(); throw new ExceptionFatal("RS0327: Failed loading constraint " + constraintName + ": " + pe.toString()); } } } finally { ti.close(); } return null; } }).execute(this); } catch (ExceptionSemantic es) { throw es; } catch (Throwable t) { t.printStackTrace(); throw new ExceptionFatal("RS0328: loadConstraints failed: " + t); } } private boolean checkConstraint(VirtualMachine vm, Operator constraintCheck) { vm.execute(constraintCheck); return ((ValueBoolean)vm.pop()).booleanValue(); } /** Check the known constraints for validity. If a constraint fails, return its name. If all constraints succeed, return null. */ public synchronized String checkConstraints(final PrintStream outputStream) { try { return (String)((new TransactionRunner() { public Object run(Transaction txn) throws Throwable { VirtualMachine vm = new VirtualMachine(new Generator(RelDatabase.this, System.out), RelDatabase.this, outputStream); for (Map.Entry<String, Operator> entry: constraints.entrySet()) { String constraintName = entry.getKey(); try { if (!checkConstraint(vm, entry.getValue())) return constraintName; } catch (ExceptionSemantic es) { throw new ExceptionSemantic("RS0393: error in CONSTRAINT " + constraintName + ": " + es.getMessage(), es); } catch (Throwable t) { t.printStackTrace(); throw new ExceptionFatal("RS0329: checkConstraints failed: " + t); } } return null; } }).execute(this)); } catch (ExceptionSemantic es) { throw es; } catch (Throwable e) { e.printStackTrace(); throw new ExceptionFatal("RS0392: checkConstraints failed: " + e); } } public String getNativeDBVersion() { return "Oracle Berkeley DB Java Edition version " + getBerkeleyJavaDBVersion(); } // Store a Relvar name and associated metadata. public void putRelvarMetadata(Transaction txn, String relvarName, RelvarMetadata metadata) throws DatabaseException { if (metadata.getCreationSequence() == -1) metadata.setCreationSequence(getUniqueID()); DatabaseEntry theKey = new DatabaseEntry(); stringDataBinding.objectToEntry(relvarName, theKey); DatabaseEntry theData = new DatabaseEntry(); classCatalog.getRelvarMetadataBinding().objectToEntry(metadata, theData); relvarDb.put(txn, theKey, theData); } // Retrieve a Relvar's metadata. Return null if not found. public synchronized RelvarMetadata getRelvarMetadata(Transaction txn, String relvarName) throws DatabaseException { DatabaseEntry theKey = new DatabaseEntry(); DatabaseEntry foundData = new DatabaseEntry(); stringDataBinding.objectToEntry(relvarName, theKey); if (relvarDb.get(txn, theKey, foundData, LockMode.DEFAULT) == OperationStatus.SUCCESS) return classCatalog.getRelvarMetadataBinding().entryToObject(foundData); return null; } // Remove a Relvar's metadata. private void dropRelvarMetadata(Transaction txn, String relvarName) throws DatabaseException { DatabaseEntry theKey = new DatabaseEntry(); stringDataBinding.objectToEntry(relvarName, theKey); if (relvarDb.delete(txn, theKey) != OperationStatus.SUCCESS) throw new ExceptionFatal("RS0330: unable to drop relvar metadata for " + relvarName); } // Obtain a unique ID public synchronized long getUniqueID() { File uniquidFile = new File(databaseHome + java.io.File.separatorChar + "unique.id"); long id = 0, nextid = 1; try { DataInputStream dis = new DataInputStream(new FileInputStream(uniquidFile)); id = dis.readLong(); nextid = id + 1; dis.close(); } catch (Throwable t) { System.out.println("Creating new ID file."); } try { DataOutputStream dos = new DataOutputStream(new FileOutputStream(uniquidFile)); dos.writeLong(nextid); dos.close(); return id; } catch (Throwable t) { t.printStackTrace(); throw new ExceptionFatal("RS0331: " + t.toString()); } } // Obtain the current thread ID private Long getThreadID() { return new Long(Thread.currentThread().getId()); } /** Return true if a relvar exists. */ private boolean isRelvarExists(Transaction txn, String name) throws DatabaseException { return (getRelvarMetadata(txn, name) != null); } public EntryBinding<ValueTuple> getTupleBinding() { return classCatalog.getTupleBinding(); } public DatabaseEntry getKeyTableEntry() { return keyTableEntry; } StoredClassCatalog getClassCatalog() { return classCatalog.getStoredClassCatalog(); } /** Begin transaction. */ public synchronized RelTransaction beginTransaction() { Long threadID = getThreadID(); RelTransaction currentTransaction = transactions.get(threadID); if (currentTransaction == null) { try { Transaction txn = environment.beginTransaction(null, null); // TODO - parameterise setLockTimeout value somewhere txn.setLockTimeout(10, TimeUnit.SECONDS); currentTransaction = new RelTransaction(txn); transactions.put(threadID, currentTransaction); } catch (DatabaseException dbe) { dbe.printStackTrace(); throw new ExceptionFatal("RS0332: unable to begin new transaction: " + dbe); } } else currentTransaction.addReference(); return currentTransaction; } // Get current transaction in this thread. Return null if there isn't one. private RelTransaction getCurrentTransaction() { Long threadID = getThreadID(); return transactions.get(threadID); } /** Commit specified transaction */ private void commitTransactionUnsynchronized(RelTransaction txn) { txn.commit(); if (txn.getReferenceCount() == 0) transactions.remove(getThreadID()); } /** Commit specified transaction. */ public synchronized void commitTransaction(RelTransaction txn) { commitTransactionUnsynchronized(txn); } /** Commit current transaction. */ public synchronized void commitTransaction() { RelTransaction currentTransaction = getCurrentTransaction(); if (currentTransaction == null) throw new ExceptionSemantic("RS0208: No transaction is active."); commitTransactionUnsynchronized(currentTransaction); } /** Roll back specified transaction. */ private void rollbackTransactionUnsynchronized(RelTransaction txn) { txn.abort(); if (txn.getReferenceCount() == 0) transactions.remove(getThreadID()); } /** Roll back specified transaction. */ synchronized void rollbackTransaction(RelTransaction txn) { rollbackTransactionUnsynchronized(txn); } /** Roll back current transaction if there is one. Silently return if there isn't one. */ public synchronized void rollbackTransactionIfThereIsOne() { reset(); RelTransaction currentTransaction = getCurrentTransaction(); if (currentTransaction == null) return; while (currentTransaction.getReferenceCount() > 0) rollbackTransactionUnsynchronized(currentTransaction); } /** Roll back current transaction. Throw an exception if there isn't one. */ public synchronized void rollbackTransaction() { RelTransaction currentTransaction = getCurrentTransaction(); if (currentTransaction == null) throw new ExceptionSemantic("RS0209: No transaction is active."); rollbackTransactionUnsynchronized(currentTransaction); } private ArrayList<String> getFoldersAt(File f) { ArrayList<String> list = new ArrayList<String>(); for(File file : f.listFiles()) if(file.isDirectory()) list.add(file.getName().trim()); return list; } private ArrayList<File> getFilesAt(File f) { ArrayList<File> list = new ArrayList<File>(); for(File file : f.listFiles()) if(!file.isDirectory()) list.add(file); return list; } public ArrayList<String> getAllCustomTypes() { return customRelvars; } private void loadSinglePath(File file) throws MalformedURLException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { URL u = file.toURI().toURL(); URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); Class<?> urlClass = URLClassLoader.class; Method method = urlClass.getDeclaredMethod("addURL", new Class[]{URL.class}); method.setAccessible(true); method.invoke(urlClassLoader, new Object[]{u}); } private void loadLibFolderContents(String folder, File libFolder) { if(!libFolder.exists() || libFolder.list().length == 0 || !libFolder.isDirectory()) { System.out.println("\t" + folder.toUpperCase() + ": " + "lib folder not found or empty."); return; } for(File file : getFilesAt(libFolder)) try { if(file.getName().endsWith("jar")) { loadSinglePath(file); System.out.println("\t" + folder.toUpperCase() + ": " + file.getName() + " was loaded succesfully."); } else System.out.println("\t" + folder.toUpperCase() + ": " + "Ignored: " + file.getName()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } private void loadPaths(File database, File home) { try { if(!database.exists() && !home.exists()) { database.mkdir(); home.mkdir(); return; } if(!database.exists()) { database.mkdir(); } if(!home.exists()) { home.mkdir(); return; } ArrayList<String> homeTypes = getFoldersAt(home); if(homeTypes.isEmpty()) System.out.println("No custom relvars were found in " + home); for(String folder : homeTypes) { File typeFolder = new File(home.getAbsolutePath() + java.io.File.separator + folder); if(typeFolder.list().length > 0) { customRelvars.add(folder); System.out.println("Custom relvar " + folder + " was succesfully loaded"); File libFolder = new File(typeFolder.getAbsolutePath() + java.io.File.separator + "lib"); loadLibFolderContents(folder, libFolder); } else System.out.println("Custom relvar " + folder + " was not loaded. Folder is empty."); } ArrayList<String> databaseTypes = getFoldersAt(database); if(databaseTypes.isEmpty()) System.out.println("No custom relvars were found in " + database); for(String folder : databaseTypes) if(!homeTypes.contains(folder)) { File typeFolder = new File(database.getAbsolutePath() + java.io.File.separator + folder); if(typeFolder.list().length > 0) { customRelvars.add(folder); System.out.println("Custom relvar " + folder + "was succesfully loaded"); File libFolder = new File(typeFolder.getAbsolutePath() + java.io.File.separator + "lib"); loadLibFolderContents(folder, libFolder); } else System.out.println("Custom relvar " + folder + " was not loaded. Folder is empty."); } else System.out.println("Duplicate custom relvar " + folder + " found!"); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } } /** Obtain Catalog as a TupleIterator */ public synchronized TupleIterator getCatalogTupleIterator(final Generator generator) { return new RegisteredTupleIterator(generator.getDatabase()) { DatabaseEntry foundKey = new DatabaseEntry(); DatabaseEntry foundData = new DatabaseEntry(); RelvarMetadata current = null; String currentKey = null; public boolean hasNext() { if (current != null) return true; try { if (cursor == null) { txn = beginTransaction(); cursor = relvarDb.openCursor(txn.getTransaction(), null); } if (cursor.getNext(foundKey, foundData, LockMode.DEFAULT) == OperationStatus.SUCCESS) { current = classCatalog.getRelvarMetadataBinding().entryToObject(foundData); currentKey = stringDataBinding.entryToObject(foundKey); return true; } } catch (DatabaseException exp) { exp.printStackTrace(); throw new ExceptionFatal("RS0333: Unable to get next Catalog entry: " + exp); } return false; } public ValueTuple next() { if (hasNext()) try { RelvarHeading relvarHeading = current.getHeadingDefinition(RelDatabase.this); Heading heading = relvarHeading.getHeading(); Value typeInfo = generator.getTypeOf(heading, "RELATION"); int keyCount = relvarHeading.getKeyCount(); ValueRelation keysRelation = new ValueRelation(generator) { private static final long serialVersionUID = 1L; @Override public TupleIterator newIterator() { return new TupleIterator() { int keyNumber = 0; @Override public boolean hasNext() { return keyNumber < keyCount; } @Override public ValueTuple next() { ValueRelationLiteral keyDef = new ValueRelationLiteral(generator); for (String attributeName: relvarHeading.getKey(keyNumber).getNames()) { ValueCharacter attributeNameChar = ValueCharacter.select(generator, attributeName); keyDef.insert(new ValueTuple(generator, new Value[] {attributeNameChar})); } keyNumber++; return new ValueTuple(generator, new Value[] {keyDef}); } @Override public void close() { } }; } @Override public int hashCode() { return 0; } }; // This must parallel the Heading defined by getNewHeading() in RelvarCatalogMetadata Value[] values = new Value[] { ValueCharacter.select(generator, currentKey), ValueCharacter.select(generator, current.getSourceDefinition()), ValueCharacter.select(generator, current.getOwner()), ValueInteger.select(generator, current.getCreationSequence()), ValueBoolean.select(generator, current.isVirtual()), typeInfo, keysRelation }; return new ValueTuple(generator, values); } finally { current = null; } throw new NoSuchElementException(); } }; } /** Record dependencies */ private void addDependencies(Generator generator, String object, String dependencyRelvarName, Collection<String> uses) { RelvarSystemDependencies dependencyRelvar = (RelvarSystemDependencies)openGlobalRelvar(dependencyRelvarName); for (String usesname: uses) dependencyRelvar.insertInternal(generator, object, usesname); } /** Remove object dependencies */ private void removeDependencies(Generator generator, final String object, String dependencyRelvarName) { RelvarSystemDependencies dependencyRelvar = (RelvarSystemDependencies)openGlobalRelvar(dependencyRelvarName); dependencyRelvar.delete(generator, new TupleFilter() { public boolean filter(ValueTuple tuple) { // index 0 is 'Object' attribute return (((ValueCharacter)tuple.getValues()[0]).stringValue().equals(object)); } }); } /** Append dependency descriptions to output StringBuffer. */ private void obtainDependencies(Generator generator, final StringBuffer output, final String object, String dependencyRelvarName, final String usedBy) { RelvarSystemDependencies dependencyRelvar = (RelvarSystemDependencies)openGlobalRelvar(dependencyRelvarName); TupleIterator dependencies = dependencyRelvar.getValue(generator).select(new TupleFilter() { public boolean filter(ValueTuple tuple) { // index 1 is 'Uses' attribute return (((ValueCharacter)tuple.getValues()[1]).stringValue().equals(object)); } }).iterator(); try { int referenceCount = 0; while (dependencies.hasNext()) { if (referenceCount++ < 5) { // index 0 is 'Object' attribute output.append("\n\tused by " + usedBy + " " + dependencies.next().getValues()[0]); } else { output.append(" and more..."); break; } } } finally { dependencies.close(); } } /** Return true if a type of the given name has been loaded. Return null if it can't be found. */ public synchronized org.reldb.rel.v0.types.Type loadType(Generator generator, String typeName) { if (typeName.equalsIgnoreCase("CHARACTER") || typeName.equalsIgnoreCase("CHAR")) return TypeCharacter.getInstance(); else if (typeName.equalsIgnoreCase("INTEGER") || typeName.equalsIgnoreCase("INT")) return TypeInteger.getInstance(); else if (typeName.equalsIgnoreCase("BOOLEAN") || typeName.equalsIgnoreCase("BOOL")) return TypeBoolean.getInstance(); else if (typeName.equalsIgnoreCase("RATIONAL") || typeName.equalsIgnoreCase("RAT")) return TypeRational.getInstance(); org.reldb.rel.v0.types.Type type = typeCache.get(typeName); if (type == null) { try { RelvarTypes typesRelvar = (RelvarTypes)openGlobalRelvar(Catalog.relvarTypes); ValueTuple typeTuple = typesRelvar.getTupleForKey(generator, typeName); if (typeTuple == null) return null; Interpreter interpreter = new Interpreter(RelDatabase.this, System.out); // Make sure immediate supertypes are loaded first ValueRelation superTypeNames = (ValueRelation)typeTuple.getValues()[6]; if (superTypeNames.getCardinality() > 0) { for (TupleIterator it = superTypeNames.iterator(); it.hasNext();) loadType(generator, it.next().getValues()[0].stringValue()); // this type should now be cached, because all subtypes of a loaded type will be loaded, // so if we load the immediate supertype of this type, this type should already be loaded type = typeCache.get(typeName); if (type != null) return type; } String language = typeTuple.getValues()[4].toString(); if (language.equals("Rel")) { String source = typeTuple.getValues()[1].toString(); try { interpreter.getGenerator().beginTypeRetrieval(); interpreter.compileStatement(source); type = interpreter.getGenerator().endTypeRetrieval(); } catch (ParseException pe) { pe.printStackTrace(); throw new ExceptionFatal("RS0335: Failed loading type " + typeName + ": " + pe.toString()); } } else if (language.equals("Java")) { try { Class<?>typeClass = (Class<?>) loadClass(typeName); if (typeClass == null) throw new ExceptionSemantic("RS0210: Unable to load class " + typeName); Constructor<?> ctor = typeClass.getConstructor(new Class[] {org.reldb.rel.v0.generator.Generator.class}); if (ctor == null) throw new ExceptionSemantic("RS0211: Unable to find a constructor of the form " + typeName + "(Generator generator)"); type = (org.reldb.rel.v0.types.Type)(ctor.newInstance(generator)); } catch (InstantiationException ie) { ie.printStackTrace(); throw new ExceptionFatal("RS0336: Unable to load TYPE " + typeName + " [1]: " + ie.getMessage()); } catch (IllegalAccessException iae) { iae.printStackTrace(); throw new ExceptionFatal("RS0337: Unable to load TYPE " + typeName + " [2]: " + iae.getMessage()); } } else throw new ExceptionFatal("RS0338: Unrecognised language '" + language + "' in TYPE " + typeName); typeCache.put(typeName, type); // load subtypes ValueRelation subTypeNames = (ValueRelation)typeTuple.getValues()[5]; for (TupleIterator it = subTypeNames.iterator(); it.hasNext();) loadType(generator, it.next().getValues()[0].stringValue()); } catch (Throwable t) { t.printStackTrace(); throw new ExceptionFatal("RS0339: loadType failed: " + t); } } return type; } /** Return true if type exists */ public synchronized boolean isTypeExists(Generator generator, String typeName) { if (typeCache.containsKey(typeName)) return true; RelvarTypes typesRelvar = (RelvarTypes)openGlobalRelvar(Catalog.relvarTypes); return (typesRelvar.getTupleForKey(generator, typeName) != null); } /** Create type */ public synchronized void createType(final Generator generator, final String typeName, final String src, final String owner, final String language, final References references, final String superTypeName) { if (isTypeExists(generator, typeName)) throw new ExceptionSemantic("RS0212: TYPE " + typeName + " is already in the database."); try { (new TransactionRunner() { public Object run(Transaction txn) throws Throwable { RelvarTypes typesRelvar = (RelvarTypes)openGlobalRelvar(Catalog.relvarTypes); Vector<String> superTypeNames = new Vector<String>(); if (superTypeName != null) superTypeNames.add(superTypeName); typesRelvar.insertInternal(generator, typeName, src, owner, language, superTypeNames); // Remove any self-reference references.removeReferenceToType(typeName); // Add dependencies addDependencies(generator, typeName, Catalog.relvarDependenciesTypeOperator, references.getReferencedOperators()); addDependencies(generator, typeName, Catalog.relvarDependenciesTypeRelvar, references.getReferencedRelvars()); addDependencies(generator, typeName, Catalog.relvarDependenciesTypeType, references.getReferencedTypes()); // if this is a subtype, update the immediate supertype if (superTypeName != null) { // TODO - maybe force reload of supertype here? typesRelvar.addSubtype(generator, superTypeName, typeName); } return null; } }).execute(this); if (!specialCacheMode) reset(); } catch (ExceptionSemantic es) { throw es; } catch (Throwable t) { t.printStackTrace(); throw new ExceptionFatal("RS0340: createType failed: " + t); } } private void removeGeneratedOperators(Generator generator, final String typeName) { ArrayList<String> dropOps = new ArrayList<String>(); RelvarOperators operatorsRelvar = (RelvarOperators)openGlobalRelvar(Catalog.relvarOperators); TupleIterator operatorsIterator = operatorsRelvar.getValue(generator).iterator(); try { while (operatorsIterator.hasNext()) { ValueTuple operatorTuple = operatorsIterator.next(); ValueRelation implementations = (ValueRelation)operatorTuple.getValues()[1]; // attribute 1 of operator tuple is implementations TupleIterator implementationsIterator = implementations.iterator(); try { while (implementationsIterator.hasNext()) { ValueTuple implementationTuple = implementationsIterator.next(); if (((ValueCharacter)implementationTuple.getValues()[4]).stringValue().equals(typeName)) { // attribute 4 of implementation tuple is generation type String opSignatureText = ((ValueCharacter)implementationTuple.getValues()[0]).stringValue(); // attr 0 of implementation tuple is signature dropOps.add(opSignatureText); } } } finally { implementationsIterator.close(); } } } finally { operatorsIterator.close(); } for (String opSignatureText: dropOps) { Interpreter interpreter = new Interpreter(RelDatabase.this, System.out); OperatorSignature signature; try { signature = interpreter.getOperatorSignature(opSignatureText); } catch (ParseException pe) { pe.printStackTrace(); throw new ExceptionFatal("RS0341: Unable to retrieve operator signature for '" + opSignatureText + "': " + pe.toString()); } dropOperatorInternal(generator, signature); } } /** Drop type */ public synchronized void dropType(final Generator generator, final String typeName) { final org.reldb.rel.v0.types.Type type = loadType(generator, typeName); try { (new TransactionRunner() { public Object run(Transaction txn) throws Throwable { Generator generator = new Generator(RelDatabase.this, System.out); removeGeneratedOperators(generator, typeName); StringBuffer dependencies = new StringBuffer(); obtainDependencies(generator, dependencies, typeName, Catalog.relvarDependenciesOperatorType, "OPERATOR"); obtainDependencies(generator, dependencies, typeName, Catalog.relvarDependenciesRelvarType, "VAR"); obtainDependencies(generator, dependencies, typeName, Catalog.relvarDependenciesTypeType, "TYPE"); if (dependencies.length() > 0) throw new ExceptionSemantic("RS0213: Type " + typeName + " may not be dropped due to dependencies:" + dependencies); RelvarTypes typesRelvar = (RelvarTypes)openGlobalRelvar(Catalog.relvarTypes); typesRelvar.deleteInternal(generator, typeName); removeDependencies(generator, typeName, Catalog.relvarDependenciesTypeOperator); removeDependencies(generator, typeName, Catalog.relvarDependenciesTypeRelvar); removeDependencies(generator, typeName, Catalog.relvarDependenciesTypeType); dirClassLoader.unload(getRelUserCodePackage() + "." + typeName); // if this is a subtype, update the immediate supertype if (type instanceof TypeAlpha) { TypeAlpha udt = (TypeAlpha)type; if (udt.isSubtype()) { // TODO - maybe force reload of supertype here? String superTypeName = udt.getSupertype().getSignature(); typesRelvar.removeSubtype(generator, superTypeName, typeName); } } typeCache.remove(typeName); return null; } }).execute(this); reset(); } catch (ExceptionSemantic es) { throw es; } catch (Throwable t) { t.printStackTrace(); throw new ExceptionFatal("RS0342: dropType failed: " + t); } } /** Return true if constraint exists */ public synchronized boolean isConstraintExists(String constraintName) { return constraints.containsKey(constraintName); } /** Create constraint. */ public synchronized void createConstraint(final Generator generator, final VirtualMachine vm, final String constraintName, final String sourceCode, final Operator operator, final String owner, final References references) { try { (new TransactionRunner() { public Object run(Transaction txn) throws Throwable { if (isConstraintExists(constraintName)) throw new ExceptionSemantic("RS0214: Constraint " + constraintName + " already exists."); if (!checkConstraint(vm, operator)) throw new ExceptionSemantic("RS0215: Constraint " + constraintName + " returns false."); RelvarSystem constraintsRelvar = (RelvarSystem)openGlobalRelvar(Catalog.relvarConstraints); constraintsRelvar.insertInternal(generator, constraintName, sourceCode, owner); addDependencies(generator, constraintName, Catalog.relvarDependenciesConstraintOperator, references.getReferencedOperators()); addDependencies(generator, constraintName, Catalog.relvarDependenciesConstraintRelvar, references.getReferencedRelvars()); addDependencies(generator, constraintName, Catalog.relvarDependenciesConstraintType, references.getReferencedTypes()); constraints.put(constraintName, operator); return null; } }).execute(this); } catch (ExceptionSemantic es) { throw es; } catch (Throwable t) { t.printStackTrace(); throw new ExceptionFatal("RS0343: createConstraint failed: " + t); } } /** Drop constraint. */ public synchronized void dropConstraint(final Generator generator, final String constraintName) { try { (new TransactionRunner() { public Object run(Transaction txn) throws Throwable { RelvarSystem constraintsRelvar = (RelvarSystem)openGlobalRelvar(Catalog.relvarConstraints); constraintsRelvar.deleteInternal(generator, constraintName); removeDependencies(generator, constraintName, Catalog.relvarDependenciesConstraintOperator); removeDependencies(generator, constraintName, Catalog.relvarDependenciesConstraintRelvar); removeDependencies(generator, constraintName, Catalog.relvarDependenciesConstraintType); constraints.remove(constraintName); return null; } }).execute(this); } catch (ExceptionSemantic es) { throw es; } catch (Throwable t) { t.printStackTrace(); throw new ExceptionFatal("RS0344: dropConstraint failed: " + t); } } /** Return true if operator exists */ public synchronized boolean isOperatorExists(OperatorSignature signature) { RelvarOperators operatorsRelvar = (RelvarOperators)openGlobalRelvar(Catalog.relvarOperators); return (operatorsRelvar.isOperatorExists(new Generator(RelDatabase.this, System.out), signature)); } /** Return the name of the TYPE that created the given operator. Return NULL if the operator is not found. */ public synchronized String getOperatorGenerationTypeName(OperatorSignature signature) { RelvarOperators operatorsRelvar = (RelvarOperators)openGlobalRelvar(Catalog.relvarOperators); return (operatorsRelvar.getOperatorGenerationTypeName(new Generator(RelDatabase.this, System.out), signature)); } /** Create operator. */ public synchronized void createOperator(final Generator generator, final OperatorDefinition operator) { if (isOperatorExists(operator.getSignature())) throw new ExceptionSemantic("RS0216: OPERATOR " + operator.getSignature() + " is already in the database."); try { (new TransactionRunner() { public Object run(Transaction txn) throws Throwable { RelvarOperators operatorsRelvar = (RelvarOperators)openGlobalRelvar(Catalog.relvarOperators); String opsig = operator.getSignature().toRelLookupString(); String returnType = (operator.getDeclaredReturnType() != null) ? operator.getDeclaredReturnType().getSignature() : ""; operatorsRelvar.insertInternal(new Generator(RelDatabase.this, System.out), operator.getSignature().getName(), returnType, opsig, operator.getSourceCode(), operator.getLanguage(), operator.getCreatedByType(), operator.getOwner()); References references = operator.getReferences(); // Remove self-reference references.removeReferenceToOperator(opsig); addDependencies(generator, opsig, Catalog.relvarDependenciesOperatorOperator, references.getReferencedOperators()); addDependencies(generator, opsig, Catalog.relvarDependenciesOperatorRelvar, references.getReferencedRelvars()); addDependencies(generator, opsig, Catalog.relvarDependenciesOperatorType, references.getReferencedTypes()); return null; } }).execute(this); } catch (ExceptionSemantic es) { throw es; } catch (Throwable t) { t.printStackTrace(); throw new ExceptionFatal("RS0345: createOperator failed: " + t); } } private void dropOperatorInternal(Generator generator, OperatorSignature signature) { if (operatorCache.containsKey(signature)) operatorCache.remove(signature); String opsig = signature.toRelLookupString(); StringBuffer dependencies = new StringBuffer(); obtainDependencies(generator, dependencies, opsig, Catalog.relvarDependenciesConstraintOperator, "CONSTRAINT"); obtainDependencies(generator, dependencies, opsig, Catalog.relvarDependenciesOperatorOperator, "OPERATOR"); obtainDependencies(generator, dependencies, opsig, Catalog.relvarDependenciesRelvarOperator, "VAR"); obtainDependencies(generator, dependencies, opsig, Catalog.relvarDependenciesTypeOperator, "TYPE"); if (dependencies.length() > 0) throw new ExceptionSemantic("RS0217: Operator " + signature + " may not be dropped due to dependencies:" + dependencies); RelvarOperators operatorsRelvar = (RelvarOperators)openGlobalRelvar(Catalog.relvarOperators); operatorsRelvar.deleteInternal(generator, signature); dirClassLoader.unload(getRelUserCodePackage() + "." + signature.getClassSignature()); removeDependencies(generator, opsig, Catalog.relvarDependenciesOperatorOperator); removeDependencies(generator, opsig, Catalog.relvarDependenciesOperatorRelvar); removeDependencies(generator, opsig, Catalog.relvarDependenciesOperatorType); } /** Drop operator. */ public synchronized void dropOperator(final OperatorSignature signature) { try { (new TransactionRunner() { public Object run(Transaction txn) throws Throwable { dropOperatorInternal(new Generator(RelDatabase.this, System.out), signature); return null; } }).execute(this); } catch (ExceptionSemantic es) { throw es; } catch (Throwable t) { t.printStackTrace(); throw new ExceptionFatal("RS0346: dropOperator failed: " + t); } } public Class<?> loadClass(String classSignature) { try { return dirClassLoader.forName(getRelUserCodePackage() + "." + classSignature); } catch (ClassNotFoundException t) { t.printStackTrace(); throw new ExceptionFatal("RS0347: Failed loading class " + classSignature + ": " + t.toString()); } } public Method getMethod(OperatorSignature signature) { // Target class must have a 'static void execute(Context context)' method. String classSignature = signature.getClassSignature(); try { return loadClass(classSignature).getDeclaredMethod("execute", new Class[] {Context.class}); } catch (NoSuchMethodException m) { m.printStackTrace(); throw new ExceptionFatal("RS0348: Failed loading operator " + signature + " from class " + classSignature + ": " + m.toString()); } } public void cacheOperator(OperatorDefinition op) { operatorCache.put(op.getSignature(), op); } private OperatorDefinition getOperatorFromCache(OperatorSignature signature) { OperatorDefinition definition = operatorCachePermanent.get(signature); if (definition != null) return definition; return operatorCache.get(signature); } /** Return true if an operator of the given signature has been loaded. Return null if it can't be found. */ public synchronized OperatorDefinition loadOperator(Generator generator, OperatorSignature signature) { OperatorDefinition definition = getOperatorFromCache(signature); if (definition != null) return definition; definition = builtinops.get(signature.toNativeLookupString()); if (definition != null) return definition; RelvarOperators operatorsRelvar = (RelvarOperators)openGlobalRelvar(Catalog.relvarOperators); ValueTuple operatorTuple = operatorsRelvar.getTupleForKey(generator, signature.getName()); if (operatorTuple == null) return null; Interpreter interpreter = new Interpreter(RelDatabase.this, System.out); ValueRelationLiteral existingImplementations = (ValueRelationLiteral)operatorTuple.getValues()[1]; TupleIterator implementationIterator = existingImplementations.iterator(); try { while (implementationIterator.hasNext()) { ValueTuple implementationTuple = implementationIterator.next(); String existingImplementationSignature = ((ValueCharacter)implementationTuple.getValues()[0]).stringValue(); if (existingImplementationSignature.equalsIgnoreCase(signature.toRelLookupString())) { String sourceCode = implementationTuple.getValues()[2].toString(); String language = implementationTuple.getValues()[3].toString(); if (language.equals("Rel") || language.equals("System")) { try { if (sourceCode.length() == 0) { String createdByType = implementationTuple.getValues()[4].toString(); loadType(generator, createdByType); return getOperatorFromCache(signature); } else return interpreter.compileOperator(sourceCode); } catch (ParseException pe) { pe.printStackTrace(); throw new ExceptionFatal("RS0349: Failed loading operator " + signature + ": " + pe.toString()); } } else if (language.equals("JavaP")) { return new OperatorDefinitionNativeProcedureExternal(signature, getMethod(signature)); } else if (language.equals("JavaF")) { OperatorDefinitionNativeFunctionExternal opdef = new OperatorDefinitionNativeFunctionExternal(signature, getMethod(signature)); org.reldb.rel.v0.types.Type returnType; try { returnType = interpreter.getOperatorReturnType(sourceCode); } catch (ParseException pe) { pe.printStackTrace(); throw new ExceptionFatal("RS0350: Failed loading operator " + signature + ": " + pe.toString()); } opdef.setDeclaredReturnType(returnType); return opdef; } else throw new ExceptionFatal("RS0351: Unrecognised language '" + language + "' in operator " + signature); } } } finally { implementationIterator.close(); } return null; } public synchronized void getPossibleTargetSignatures(HashSet<OperatorSignature> targets, Generator generator, OperatorSignature signature) { RelvarOperators operatorsRelvar = (RelvarOperators)openGlobalRelvar(Catalog.relvarOperators); ValueTuple operatorTuple = operatorsRelvar.getTupleForKey(generator, signature.getName()); if (operatorTuple != null) { ValueRelationLiteral existingImplementations = (ValueRelationLiteral)operatorTuple.getValues()[1]; TupleIterator implementationIterator = existingImplementations.iterator(); try { Interpreter interpreter = new Interpreter(RelDatabase.this, System.out); while (implementationIterator.hasNext()) { ValueTuple implementationTuple = implementationIterator.next(); String parmSignature = ((ValueCharacter)implementationTuple.getValues()[0]).stringValue(); String returnStr = ((ValueCharacter)implementationTuple.getValues()[1]).stringValue(); String existingImplementationSignatureText = parmSignature + ((returnStr.length() > 0) ? " RETURNS " + returnStr : ""); OperatorSignature storedSignature; try { storedSignature = interpreter.getOperatorSignature(existingImplementationSignatureText); } catch (ParseException pe) { pe.printStackTrace(); throw new ExceptionFatal("RS0352: Unable to retrieve operator signature for '" + existingImplementationSignatureText + "': " + pe.toString()); } if (storedSignature.canBeInvokedBy(signature)) targets.add(storedSignature); } } finally { implementationIterator.close(); } } for (OperatorDefinition op: operatorCache.values()) { OperatorSignature storedSignature = op.getSignature(); if (storedSignature.canBeInvokedBy(signature)) targets.add(storedSignature); } OperatorDefinition definition = builtinops.get(signature.toNativeLookupString()); if (definition != null) targets.add(definition.getSignature()); } synchronized void defineBuiltinOperator(OperatorDefinition operator) { builtinops.put(operator.getSignature().toNativeLookupString(), operator); } // Return list of built-in operators as RELATION {signature CHAR} public synchronized ValueRelation getBuiltinOperators(Generator generator) { return new ValueRelation(generator) { private static final long serialVersionUID = 1L; public int hashCode() { return 0; } public TupleIterator newIterator() { return new TupleIterator() { Iterator<OperatorDefinition> i = builtinops.values().iterator(); public boolean hasNext() { return i.hasNext(); } public ValueTuple next() { Generator generator = getGenerator(); return new ValueTuple(generator, new Value[] {ValueCharacter.select(generator, i.next().toString())}); } public void close() {} }; } }; } /** Return true if a relvar exists. */ public synchronized boolean isRelvarExists(final String name) { try { return ((Boolean)(new TransactionRunner() { public Object run(Transaction txn) throws Throwable { return new Boolean(isRelvarExists(txn, name)); } }).execute(this)).booleanValue(); } catch (ExceptionSemantic es) { throw es; } catch (Throwable t) { t.printStackTrace(); throw new ExceptionFatal("RS0353: isRelvarExists failed: " + t); } } /** Get the table for a given real relvar name. */ public synchronized KeyTables getTable(Transaction txn, String name) throws DatabaseException { RelvarMetadata metadata = getRelvarMetadata(txn, name); if (metadata == null) return null; if (!(metadata instanceof RelvarRealMetadata)) throw new ExceptionFatal("RS0354: VAR " + name + " is not a REAL relvar."); KeyTableNames tableName = ((RelvarRealMetadata)metadata).getTableName(); KeyTables table = new KeyTables(tableName.size()); for (int i=0; i<tableName.size(); i++) { String tabName = tableName.getName(i); Database db = openDatabase(txn, tabName, dbConfigurationNormal); table.setDatabase(i, db); } return table; } // Retrieve a global Relvar's metadata. Return null if not found. public RelvarMetadata getRelvarMetadata(final String relvarName) { try { return ((RelvarMetadata)(new TransactionRunner() { public Object run(Transaction txn) throws Throwable { return getRelvarMetadata(txn, relvarName); } }).execute(this)); } catch (ExceptionSemantic es) { throw es; } catch (Throwable t) { t.printStackTrace(); throw new ExceptionFatal("RS0355: getRelvarMetadata failed: " + t); } } String getUniqueTableName() { return "relvar_" + getUniqueID(); } /** Create a real relvar with specified metadata. */ public synchronized void createRealRelvar(final Generator generator, final RelvarDefinition relvarInfo) { try { (new TransactionRunner() { public Object run(Transaction txn) throws Throwable { if (isRelvarExists(txn, relvarInfo.getName())) throw new ExceptionSemantic("RS0218: VAR " + relvarInfo.getName() + " already exists."); RelvarMetadata metadata = getRelvarMetadata(txn, relvarInfo.getName()); if (metadata != null && metadata instanceof RelvarRealMetadata) { KeyTableNames tableName = ((RelvarRealMetadata)metadata).getTableName(); for (int i=0; i<tableName.size(); i++) { String tabName = tableName.getName(i); closeDatabase(tabName); try { environment.removeDatabase(txn, tabName); } catch (DatabaseException dbe) { dbe.printStackTrace(); throw new ExceptionFatal("RS0356: unable to remove table " + tableName); } } } RelvarRealMetadata newMetadata = (RelvarRealMetadata)relvarInfo.getRelvarMetadata(); KeyTableNames tableName = new KeyTableNames(newMetadata.getHeadingDefinition(RelDatabase.this).getKeyCount()); for (int i=0; i<tableName.size(); i++) { String tabName = getUniqueTableName(); tableName.setName(i, tabName); openDatabase(txn, tabName, dbConfigurationAllowCreate).close(); openTables.remove(tabName); } newMetadata.setTableName(tableName); putRelvarMetadata(txn, relvarInfo.getName(), newMetadata); addDependencies(generator, relvarInfo.getName(), Catalog.relvarDependenciesRelvarType, relvarInfo.getReferences().getReferencedTypes()); return null; } }).execute(this); } catch (ExceptionSemantic es) { throw es; } catch (Throwable t) { t.printStackTrace(); throw new ExceptionFatal("RS0357: createRealRelvar failed: " + t); } } /** Create a VIRTUAL relvar. */ public synchronized void createVirtualRelvar(final Generator generator, final RelvarDefinition information) { try { (new TransactionRunner() { public Object run(Transaction txn) throws Throwable { if (isRelvarExists(txn, information.getName())) throw new ExceptionSemantic("RS0219: VAR " + information.getName() + " already exists."); putRelvarMetadata(txn, information.getName(), information.getRelvarMetadata()); addDependencies(generator, information.getName(), Catalog.relvarDependenciesRelvarOperator, information.getReferences().getReferencedOperators()); addDependencies(generator, information.getName(), Catalog.relvarDependenciesRelvarRelvar, information.getReferences().getReferencedRelvars()); addDependencies(generator, information.getName(), Catalog.relvarDependenciesRelvarType, information.getReferences().getReferencedTypes()); return null; } }).execute(this); } catch (ExceptionSemantic es) { throw es; } catch (Throwable t) { t.printStackTrace(); throw new ExceptionFatal("RS0358: createVirtualRelvar failed: " + t); } } public void createExternalRelvar(final Generator generator, final RelvarDefinition relvarInfo) { try { (new TransactionRunner() { public Object run(Transaction txn) throws Throwable { if (isRelvarExists(txn, relvarInfo.getName())) throw new ExceptionSemantic("RS0220: VAR " + relvarInfo.getName() + " already exists."); putRelvarMetadata(txn, relvarInfo.getName(), relvarInfo.getRelvarMetadata()); addDependencies(generator, relvarInfo.getName(), Catalog.relvarDependenciesRelvarType, relvarInfo.getReferences().getReferencedTypes()); return null; } }).execute(this); } catch (ExceptionSemantic es) { throw es; } catch (Throwable t) { t.printStackTrace(); throw new ExceptionFatal("RS0359: createExternalRelvar failed: " + t); } } /** Get new temporary storage area. */ private synchronized Database createTempStorage(final DatabaseConfig config) { String newTableName = getUniqueTableName(); Transaction txn = null; Database database = openDatabase(txn, newTableName, config); tempTables.add(newTableName); return database; } /** Get new temporary storage area. */ public Database createTempStorage() { return createTempStorage(dbConfigurationTemporary); } /** Get new temporary storage area. Does not use custom comparator. */ public Database createTempStorageWithDuplicatesNoComparator() { return createTempStorage(dbConfigurationTemporaryWithDuplicatesNoComparator); } /** Close temp storage */ public synchronized void destroyTempStorage(Database temp) { String tableName = temp.getDatabaseName(); closeDatabase(tableName); tempTables.remove(tableName); } /** Get new 'private' (temporary) Table. */ public synchronized TablePrivate getTempTable(final RelvarHeading keyDefinition) { try { return (TablePrivate)((new TransactionRunner() { public Object run(Transaction txn) throws Throwable { KeyTables tables = new KeyTables(keyDefinition.getKeyCount()); for (int i=0; i<tables.size(); i++) { String newTableName = getUniqueTableName(); Database db = openDatabase(txn, newTableName, dbConfigurationAllowCreate); tempTables.add(newTableName); tables.setDatabase(i, db); } return new TablePrivate(RelDatabase.this, tables, keyDefinition); } }).execute(this)); } catch (ExceptionSemantic es) { throw es; } catch (Throwable t) { t.printStackTrace(); throw new ExceptionFatal("RS0360: getTempTable failed: " + t); } } /** Create a PRIVATE relvar. */ public synchronized SlotScoped createPrivateRelvar(final int depth, final int offset, final RelvarHeading keydef) { return new RelvarPrivate(depth, offset, this, keydef); } /** Open a global relvar. Return null if it doesn't exist. */ public synchronized RelvarGlobal openGlobalRelvar(final String name) { try { return ((RelvarGlobal)(new TransactionRunner() { public Object run(Transaction txn) throws Throwable { RelvarMetadata metadata = getRelvarMetadata(txn, name); if (metadata == null) return null; return metadata.getRelvar(name, RelDatabase.this); } }).execute(this)); } catch (ExceptionSemantic es) { throw es; } catch (Throwable t) { t.printStackTrace(); throw new ExceptionFatal("RS0361: openRelvar failed: " + t); } } /** Drop a relvar. Throw an exception if it doesn't exist. */ public synchronized void dropRelvar(final String name) { try { (new TransactionRunner() { public Object run(Transaction txn) throws Throwable { RelvarMetadata metadata = getRelvarMetadata(txn, name); if (metadata == null) throw new ExceptionSemantic("RS0221: VAR " + name + " does not exist."); Generator generator = new Generator(RelDatabase.this, System.out); StringBuffer dependencies = new StringBuffer(); obtainDependencies(generator, dependencies, name, Catalog.relvarDependenciesRelvarRelvar, "VAR"); obtainDependencies(generator, dependencies, name, Catalog.relvarDependenciesOperatorRelvar, "OPERATOR"); obtainDependencies(generator, dependencies, name, Catalog.relvarDependenciesConstraintRelvar, "CONSTRAINT"); obtainDependencies(generator, dependencies, name, Catalog.relvarDependenciesTypeRelvar, "TYPE"); if (dependencies.length() > 0) throw new ExceptionSemantic("RS0222: VAR " + name + " may not be dropped due to dependencies:" + dependencies); metadata.dropRelvar(RelDatabase.this); if (metadata instanceof RelvarRealMetadata) { KeyTableNames tableName = ((RelvarRealMetadata)metadata).getTableName(); for (int i=0; i<tableName.size(); i++) { String tabName = tableName.getName(i); closeDatabase(tabName); environment.removeDatabase(txn, tabName); } } dropRelvarMetadata(txn, name); removeDependencies(generator, name, Catalog.relvarDependenciesRelvarOperator); removeDependencies(generator, name, Catalog.relvarDependenciesRelvarRelvar); removeDependencies(generator, name, Catalog.relvarDependenciesRelvarType); return null; } }).execute(this); } catch (ExceptionSemantic es) { throw es; } catch (Throwable t) { t.printStackTrace(); throw new ExceptionFatal("RS0362: dropRelvar failed: " + t); } } // Copy tuples from a ValueRelation to a Table private void copy(Generator generator, Transaction txn, Table table, KeyTables db, ValueRelation source) throws DatabaseException { TupleIterator iterator = ((ValueRelation)source.getSerializableClone()).iterator(); try { while (iterator.hasNext()) table.insertTupleNoDuplicates(generator, db, txn, iterator.next(), "Assigning"); } finally { iterator.close(); } } // Set the value of a given Relvar public synchronized void setValue(final RelvarPrivateCell target, final ValueRelation source) { try { (new TransactionRunner() { public Object run(Transaction txn) throws Throwable { KeyTableNames newTableName = new KeyTableNames(target.getTable().getHeadingDefinition().getKeyCount()); KeyTables newDb = new KeyTables(newTableName.size()); for (int i=0; i<newTableName.size(); i++) { String tabName = getUniqueTableName(); newTableName.setName(i, tabName); Database db = openDatabase(txn, tabName, dbConfigurationAllowCreate); tempTables.add(tabName); newDb.setDatabase(i, db); } copy(new Generator(RelDatabase.this, System.out), txn, target.getTable(), newDb, source); KeyTables oldDb = target.getTable().getTable(txn); for (int i=0; i<oldDb.size(); i++) { Database olddb = oldDb.getDatabase(i); String tabName = olddb.getDatabaseName(); openTables.remove(tabName); tempTables.remove(tabName); olddb.close(); environment.removeDatabase(txn, tabName); } target.setTable(newDb); return null; } }).execute(this); } catch (ExceptionSemantic es) { throw es; } catch (Throwable t) { t.printStackTrace(); throw new ExceptionFatal("RS0363: RelvarPrivate setValue failed: " + t); } } // Set the value of a given Relvar public synchronized void setValue(final RelvarReal target, final ValueRelation source) { try { (new TransactionRunner() { public Object run(Transaction txn) throws Throwable { KeyTables oldDb = getTable(txn, target.getName()); KeyTableNames newTableName = new KeyTableNames(oldDb.size()); KeyTables db = new KeyTables(oldDb.size()); for (int i=0; i<newTableName.size(); i++) { String tabName = getUniqueTableName(); newTableName.setName(i, tabName); Database dbase = openDatabase(txn, tabName, dbConfigurationAllowCreate); db.setDatabase(i, dbase); } copy(new Generator(RelDatabase.this, System.out), txn, target.getTable(), db, source); KeyTableNames oldTableName = oldDb.getDatabaseName(); for (int i=0; i<oldTableName.size(); i++) { String tabName = oldTableName.getName(i); openTables.remove(tabName); oldDb.getDatabase(i).close(); environment.removeDatabase(txn, tabName); } RelvarRealMetadata metadata = (RelvarRealMetadata)getRelvarMetadata(txn, target.getName()); metadata.setTableName(newTableName); putRelvarMetadata(txn, target.getName(), metadata); return null; } }).execute(this); } catch (ExceptionSemantic es) { throw es; } catch (Throwable t) { t.printStackTrace(); throw new ExceptionFatal("RS0364: RelvarReal setValue failed: " + t); } } public synchronized void alterVarRealAlterKey(Generator generator, String varname, Object keydefs) { // TODO - alter System.out.println("alterVarRealAlterKey: ALTER VAR " + varname + " ALTER " + keydefs.toString()); } public synchronized void alterVarRealChangeAttributeType(Generator generator, String varname, String attributeName, Type newType) { // TODO - alter System.out.println("alterVarRealChangeAttributeType: ALTER VAR " + varname + " REAL TYPE_OF " + attributeName + " TO " + newType.getSignature()); } public synchronized void alterVarRealDropAttribute(Generator generator, String varname, String attributeName) { // TODO - alter System.out.println("alterVarRealDropAttribute: ALTER VAR " + varname + " REAL DROP " + attributeName); } public synchronized void alterVarRealInsertAttributes(Generator generator, String varname, Object heading) { // TODO - alter System.out.println("alterVarRealInsertAttributes: ALTER VAR " + varname + " REAL INSERT " + heading.toString()); } public synchronized void alterVarRealRenameAttribute(Generator generator, String varname, String oldAttributeName, String newAttributeName) { // TODO - alter System.out.println("alterVarRealRename: ALTER VAR " + varname + " REAL RENAME " + oldAttributeName + " TO " + newAttributeName); } }
package net.glowstone.block.blocktype; import net.glowstone.block.GlowBlock; import net.glowstone.block.entity.TEContainer; import net.glowstone.block.entity.TileEntity; import net.glowstone.entity.GlowPlayer; import org.bukkit.block.BlockFace; import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; import java.util.Collection; import java.util.LinkedList; /** * Base BlockType for containers. */ public class BlockContainer extends BlockType { @Override public boolean blockInteract(GlowPlayer player, GlowBlock block, BlockFace face, Vector clickedLoc) { TileEntity te = block.getTileEntity(); if (te instanceof TEContainer) { // todo: animation? player.openInventory(((TEContainer) te).getInventory()); return true; } return false; } @Override public Collection<ItemStack> getDrops(GlowBlock block) { LinkedList<ItemStack> list = new LinkedList<ItemStack>(); list.add(new ItemStack(block.getType(), 1)); for (ItemStack i : ((TEContainer) block.getTileEntity()).getInventory().getContents()) { if (i != null) { list.add(i); } } return list; } }
package me.dmillerw.remoteio.tile; import me.dmillerw.remoteio.block.BlockRemoteInterface; import me.dmillerw.remoteio.block.ModBlocks; import me.dmillerw.remoteio.core.frequency.DeviceRegistry; import me.dmillerw.remoteio.core.frequency.IFrequencyProvider; import me.dmillerw.remoteio.lib.property.RenderState; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.ITickable; import net.minecraft.util.math.BlockPos; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.property.IExtendedBlockState; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class TileRemoteInterface extends TileCore implements ITickable, IFrequencyProvider { private BlockPos remotePosition; private int frequency = 0; @Override public void writeToDisk(NBTTagCompound compound) { compound.setInteger("_frequency", frequency); } @Override public void readFromDisk(NBTTagCompound compound) { frequency = compound.getInteger("_frequency"); } @Override public void writeDescription(NBTTagCompound compound) { if (remotePosition != null) compound.setLong("_remote_position", remotePosition.toLong()); compound.setInteger("_frequency", frequency); } @Override public void readDescription(NBTTagCompound compound) { if (compound.hasKey("_remote_position")) remotePosition = BlockPos.fromLong(compound.getLong("_remote_position")); else remotePosition = null; frequency = compound.getInteger("_frequency"); } @Override public void onLoad() { if (!worldObj.isRemote) { remotePosition = DeviceRegistry.getWatchedBlock(worldObj.provider.getDimension(), getFrequency()); } } @Override public void update() { if (!worldObj.isRemote) { BlockPos pos = DeviceRegistry.getWatchedBlock(worldObj.provider.getDimension(), getFrequency()); if (pos == null) { if (remotePosition != null) { this.remotePosition = null; notifyNeighbors(); markDirtyAndNotify(); } } else if (!pos.equals(remotePosition)) { this.remotePosition = pos; notifyNeighbors(); markDirtyAndNotify(); } } } @Override public boolean hasFastRenderer() { TileEntity remote = getRemoteTile(); if (remote != null) return remote.hasFastRenderer(); else return false; } @Override public int getFrequency() { return frequency; } @Override public void setFrequency(int frequency) { this.frequency = frequency; notifyNeighbors(); markDirtyAndNotify(); } @Override public BlockPos getPosition() { return pos; } public BlockPos getRemotePosition() { return remotePosition; } public IBlockState getRemoteState() { if (remotePosition != null) { IBlockState state = worldObj.getBlockState(remotePosition); if (state.getBlock().isAir(state, worldObj, remotePosition)) return null; if (state.getBlock() == ModBlocks.analyzer || state.getBlock() == ModBlocks.remote_interface) return null; return state; } else return null; } private TileEntity getRemoteTile() { return getRemoteState() == null ? null : worldObj.getTileEntity(getRemotePosition()); } @SideOnly(Side.CLIENT) public IExtendedBlockState getExtendedBlockState(IBlockState state) { IBlockState connected = getRemoteState(); if (connected == null) { return ((IExtendedBlockState) state) .withProperty(BlockRemoteInterface.RENDER_STATE, RenderState.BLANK); } TileEntity tile = worldObj.getTileEntity(getRemotePosition()); boolean tileRender = false; if (tile != null) { tileRender = TileEntityRendererDispatcher.instance.getSpecialRenderer(tile) != null; } RenderState renderState = new RenderState(); renderState.blockState = connected.getActualState(worldObj, getRemotePosition()); renderState.extendedBlockState = connected.getBlock().getExtendedState(renderState.blockState, worldObj, getRemotePosition()); renderState.camouflage = true; renderState.tileRender = tileRender; return ((IExtendedBlockState) state) .withProperty(BlockRemoteInterface.RENDER_STATE, renderState); } /* START CAPABILITY HANDLING */ @Override public boolean hasCapability(Capability<?> capability, EnumFacing facing) { TileEntity remoteTile = getRemoteTile(); return remoteTile != null && remoteTile.hasCapability(capability, facing); } @Override public <T> T getCapability(Capability<T> capability, EnumFacing facing) { return getRemoteTile().getCapability(capability, facing); } }
package net.kyori.membrane.facet.internal; import net.kyori.lunar.exception.Exceptions; import net.kyori.membrane.facet.Connectable; import net.kyori.membrane.facet.Enableable; import net.kyori.membrane.facet.Facet; import java.util.Set; import java.util.stream.Stream; import javax.annotation.Nonnull; import javax.inject.Inject; public class FacetsImpl implements Facets { private final Set<Facet> facets; @Inject protected FacetsImpl(final Set<Facet> facets) { this.facets = facets; } @Override public void enable() { this.of(Connectable.class).forEach(Exceptions.rethrowConsumer(Connectable::connect)); this.of(Enableable.class).forEach(Enableable::enable); } @Override public void disable() { this.of(Enableable.class).forEach(Enableable::disable); this.of(Connectable.class).forEach(Exceptions.rethrowConsumer(Connectable::disconnect)); } @Nonnull @Override public Stream<? extends Facet> all() { return this.facets.stream(); } }
package me.rkfg.xmpp.bot.plugins; import java.util.LinkedList; import java.util.List; import java.util.Random; import java.util.concurrent.LinkedBlockingDeque; import java.util.regex.Matcher; import java.util.regex.Pattern; import me.rkfg.xmpp.bot.Main; import me.rkfg.xmpp.bot.domain.Markov; import me.rkfg.xmpp.bot.domain.MarkovFirstWord; import me.rkfg.xmpp.bot.domain.MarkovFirstWordCount; import org.hibernate.NonUniqueResultException; import org.hibernate.Session; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.util.StringUtils; import ru.ppsrk.gwt.client.ClientAuthException; import ru.ppsrk.gwt.client.LogicException; import ru.ppsrk.gwt.server.HibernateCallback; import ru.ppsrk.gwt.server.HibernateUtil; public class MarkovResponsePlugin extends MessagePluginImpl { Random random = new Random(); private static final int answersLimit = 30; private LinkedBlockingDeque<Long> answersTimes = new LinkedBlockingDeque<Long>(answersLimit + 1); private boolean cooldown = false; private String[] excuses = { "отстань, голова болит.", "устала я, потом поговорим.", "у меня ТЕ САМЫЕ часы, не видишь, что ли?", "Т___Т", "._.", ":[" }; private final static int cooldownHoursMin = 3; private final static int cooldownHoursMax = 5; private final static int minSegments = 2; private final static int softSegmentLimit = 7; private final static int hardSegmentLimit = 12; private final static int minLastWordLength = 5; private static final int answersLimitTime = 5 * 60 * 1000; // 5 minutes in ms @Override public void init() { new Thread(new Runnable() { @Override public void run() { while (true) { try { if (answersTimes.size() > answersLimit) { answersTimes.poll(); Long first = answersTimes.peekFirst(); Long last = answersTimes.peekLast(); if (first != null && last != null) { if (last - first < answersLimitTime) { cooldown = true; Thread.sleep(random.nextInt(1000) + 1000); Main.sendMUCMessage("Устала вам отвечать. Отдохну."); Thread.sleep(random.nextInt((cooldownHoursMax - cooldownHoursMin) * 3600000) + cooldownHoursMin * 3600000); cooldown = false; Main.sendMUCMessage("Отдохнула."); } } } else { Thread.sleep(1000); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }, "Cooldown thread").start(); } @Override public Pattern getPattern() { return Pattern.compile("^" + Main.getNick() + "[,: ] ?(.*)"); } @Override public String process(final Message message, final Matcher matcher) { try { return StringUtils.parseResource(message.getFrom()) + ", " + HibernateUtil.exec(new HibernateCallback<String>() { @Override public String run(Session session) throws LogicException, ClientAuthException { if (cooldown) { return excuse(); } int hash = 0; int off = 0; char val[] = matcher.group(1).toCharArray(); for (int i = 0; i < val.length; i++) { hash = 31 * hash + val[off++]; } hash = (int) (hash * (System.currentTimeMillis() / 3600000)); random.setSeed(hash); Object minmax[] = (Object[]) session.createQuery("select MIN(id), MAX(id) from Markov").uniqueResult(); Long min = (Long) minmax[0]; Long max = (Long) minmax[1]; Markov segment = null; List<String> result = new LinkedList<String>(); String[] userWords = org.apache.commons.lang3.StringUtils.split(matcher.group(1)); for (int i = 0; i < 5; i++) { String word = MarkovCollectorPlugin.purify(userWords[random.nextInt(userWords.length)]); if (!word.isEmpty() && word.length() >= minLastWordLength) { segment = (Markov) session.createQuery("from Markov m where m.firstWord = :mfw").setString("mfw", word) .setMaxResults(1).uniqueResult(); if (segment != null && !segment.getText().isEmpty()) { result.add(segment.getText()); break; } } } if (segment == null) { segment = getFirstSegment(session, min, max, result); } int len = random.nextInt(softSegmentLimit - minSegments) + minSegments; int leftToHard = hardSegmentLimit - len; while (len MarkovFirstWordCount segmentsCount = (MarkovFirstWordCount) session .createQuery("from MarkovFirstWordCount where word = :fw").setString("fw", segment.getLastWord()) .uniqueResult(); if (segmentsCount == null) { break; } int n = random.nextInt(segmentsCount.getCount().intValue()); try { MarkovFirstWord markovFirstWord = (MarkovFirstWord) session .createQuery("from MarkovFirstWord where word = :fw and number = :n").setEntity("fw", segmentsCount) .setInteger("n", n).uniqueResult(); segment = markovFirstWord.getMarkov(); if (!segment.getText().isEmpty()) { result.add(segment.getText()); } } catch (NonUniqueResultException e) { log.warn("Non-unique word in the index found: {}/{}.", segmentsCount.getWord(), n); } if (len == 0 && segment.getLastWord().length() < minLastWordLength && leftToHard len = 1; } } if (result.isEmpty()) { getFirstSegment(session, min, max, result); } answersTimes.offer(System.currentTimeMillis()); return org.apache.commons.lang3.StringUtils.join(result, " "); } }); } catch (ClientAuthException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (LogicException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "что-то пошло не так."; } protected String excuse() { return excuses[random.nextInt(excuses.length)]; } private Markov getFirstSegment(Session session, Long min, Long max, List<String> result) { Markov segment; do { segment = (Markov) session.createQuery("from Markov m where m.id = :mid") .setLong("mid", random.nextInt(max.intValue() - min.intValue()) + min).uniqueResult(); } while (segment == null); result.add(segment.getFirstWord()); result.add(segment.getText()); return segment; } }
package com.thoughtworks.xstream.mapper; import com.thoughtworks.xstream.alias.ClassMapper; import java.lang.ref.WeakReference; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Mapper that caches which names map to which classes. Prevents repetitive searching and class loading. * * @author Joe Walnes */ public class CachingMapper extends MapperWrapper { private transient Map realClassCache; public CachingMapper(Mapper wrapped) { super(wrapped); readResolve(); } /** * @deprecated As of 1.2, use {@link #CachingMapper(Mapper)} */ public CachingMapper(ClassMapper wrapped) { this((Mapper)wrapped); readResolve(); } public Class realClass(String elementName) { WeakReference reference = (WeakReference) realClassCache.get(elementName); if (reference != null) { Object cached = reference.get(); if (cached instanceof CannotResolveClassException) throw (CannotResolveClassException) cached; if (cached != null) { return (Class)cached; } } try { Class result = super.realClass(elementName); realClassCache.put(elementName, new WeakReference(result)); return result; } catch (CannotResolveClassException e) { realClassCache.put(elementName,e); throw e; } } private Object readResolve() { realClassCache = new ConcurrentHashMap(); return this; } }
package mil.nga.geopackage.features.user; import java.util.List; import mil.nga.geopackage.GeoPackageException; import mil.nga.geopackage.core.contents.Contents; import mil.nga.geopackage.core.contents.ContentsDataType; import mil.nga.geopackage.features.columns.GeometryColumns; import mil.nga.geopackage.user.UserTable; /** * Represents a user feature table * * @author osbornb */ public class FeatureTable extends UserTable<FeatureColumn> { /** * Constructor * * @param geometryColumns * geometry columns * @param columns * feature columns * @since 3.3.0 */ public FeatureTable(GeometryColumns geometryColumns, List<FeatureColumn> columns) { this(geometryColumns.getTableName(), geometryColumns.getColumnName(), columns); } /** * Constructor * * @param tableName * table name * @param columns * feature columns */ public FeatureTable(String tableName, List<FeatureColumn> columns) { this(tableName, null, columns); } /** * Constructor * * @param tableName * table name * @param geometryColumn * geometry column * @param columns * feature columns * @since 3.3.0 */ public FeatureTable(String tableName, String geometryColumn, List<FeatureColumn> columns) { super(new FeatureColumns(tableName, geometryColumn, columns)); } /** * Copy Constructor * * @param featureTable * feature table * @since 3.3.0 */ public FeatureTable(FeatureTable featureTable) { super(featureTable); } /** * {@inheritDoc} */ @Override public FeatureTable copy() { return new FeatureTable(this); } /** * {@inheritDoc} */ @Override public String getDataType() { return ContentsDataType.FEATURES.getName(); } /** * {@inheritDoc} */ @Override public FeatureColumns getUserColumns() { return (FeatureColumns) super.getUserColumns(); } /** * {@inheritDoc} */ @Override public FeatureColumns createUserColumns(List<FeatureColumn> columns) { return new FeatureColumns(getTableName(), getGeometryColumnName(), columns, true); } /** * Get the geometry column index * * @return geometry column index */ public int getGeometryColumnIndex() { return getUserColumns().getGeometryIndex(); } /** * Get the geometry feature column * * @return geometry feature column */ public FeatureColumn getGeometryColumn() { return getUserColumns().getGeometryColumn(); } /** * Get the geometry column name * * @return geometry column name * @since 3.5.0 */ public String getGeometryColumnName() { return getUserColumns().getGeometryColumnName(); } /** * Get the Id and Geometry Column names * * @return column names * @since 3.5.0 */ public String[] getIdAndGeometryColumnNames() { return new String[] { getPkColumnName(), getGeometryColumnName() }; } /** * {@inheritDoc} */ @Override protected void validateContents(Contents contents) { // Verify the Contents have a features data type ContentsDataType dataType = contents.getDataType(); if (dataType == null || dataType != ContentsDataType.FEATURES) { throw new GeoPackageException( "The " + Contents.class.getSimpleName() + " of a " + FeatureTable.class.getSimpleName() + " must have a data type of " + ContentsDataType.FEATURES.getName()); } } }
package net.openhft.chronicle.core.cooler; import net.openhft.affinity.Affinity; import net.openhft.chronicle.core.Jvm; import java.beans.XMLDecoder; import java.beans.XMLEncoder; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.concurrent.locks.LockSupport; public enum CpuCoolers implements CpuCooler { PARK { @Override public void disturb() { LockSupport.parkNanos(200_000); } }, PAUSE1 { @Override public void disturb() { Jvm.pause(1); } }, PAUSE3 { @Override public void disturb() { Jvm.pause(3); } }, PAUSE6 { @Override public void disturb() { Jvm.pause(6); } }, PAUSE10 { @Override public void disturb() { Jvm.pause(10); } }, PAUSE100 { @Override public void disturb() { Jvm.pause(100); } }, PAUSE1000 { @Override public void disturb() { Jvm.pause(1000); } }, YIELD { @Override public void disturb() { Thread.yield(); } }, BUSY { @Override public void disturb() { busyWait(0.1e6); } }, BUSY_3 { @Override public void disturb() { busyWait(0.3e6); } }, BUSY1 { @Override public void disturb() { busyWait(1e6); } }, BUSY3 { @Override public void disturb() { busyWait(3e6); } }, BUSY10 { @Override public void disturb() { busyWait(10e6); } }, BUSY30 { @Override public void disturb() { busyWait(30e6); } }, BUSY100 { @Override public void disturb() { busyWait(100e6); } }, BUSY300 { @Override public void disturb() { busyWait(300e6); } }, BUSY1000 { @Override public void disturb() { busyWait(1000e6); } }, AFFINITY { boolean toogle; @Override public void disturb() { Affinity.setAffinity(toogle ? 3 : 4); toogle = !toogle; } }, SERIALIZATION { @Override public void disturb() { ByteArrayOutputStream out = new ByteArrayOutputStream(); XMLEncoder oos = new XMLEncoder(out); oos.writeObject(System.getProperties()); oos.close(); XMLDecoder ois = new XMLDecoder(new ByteArrayInputStream(out.toByteArray())); blackhole = ois.readObject(); } }, MEMORY_COPY { long[] from = new long[8 << 20]; long[] to = new long[8 << 20]; @Override public void disturb() { System.arraycopy(from, 0, to, 0, from.length); } }, ALL { @Override public void disturb() { SERIALIZATION.disturb(); MEMORY_COPY.disturb(); PAUSE10.disturb(); } }; static volatile Object blackhole; public static void busyWait(double nanos) { long start = System.nanoTime(); if (Jvm.isJava9Plus()) { while (System.nanoTime() - start < nanos) { Thread.holdsLock(""); } } else { while (System.nanoTime() - start < nanos) { Compiler.enable(); } } } }
package mpicbg.spim.data.generic.sequence; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.scijava.Priority; import org.scijava.annotations.Indexable; /** * Annotation for a class that creates a {@link BasicImgLoader} for a specific * format (the format is specified in the XML "ImageLoader" element). * * @author Tobias Pietzsch &lt;tobias.pietzsch@gmail.com&gt; */ @Retention( RetentionPolicy.RUNTIME ) @Target( ElementType.TYPE ) @Indexable public @interface ImgLoaderIo { /** * Name for the format handled by the {@link BasicImgLoader}. */ String format(); /** * The concrete class of the {@link BasicImgLoader} that is loaded by the annotated class. */ Class< ? extends BasicImgLoader > type(); double priority() default Priority.NORMAL; }
package net.MCAds.advertisements; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; public class DependencyDownloader { public static void download() { boolean holoAPI = false; boolean barAPI = false; String[] pluginsList = new File("plugins").list(); for (String file : pluginsList) { // HoloAPI is most likely installed if (file.contains("HoloAPI")) { holoAPI = true; } // BarAPI is most likely installed if (file.contains("BarAPI")) { barAPI = true; } } // Download HoloAPI if (holoAPI == false) { try { downloadFile("http://dev.bukkit.org/media/files/787/363/HoloAPI-v1.2.3.jar", "plugins/HoloAPI.jar"); Main.server().getPluginManager().loadPlugin(new File("plugins/HoloAPI.jar")); Main.server().reload(); } catch (Exception e) { System.out.println("Downloading the dependency \"HoloAPI\" failed. please download it manually."); } } // Download BarAPI if (barAPI == false) { try { downloadFile("http://dev.bukkit.org/media/files/785/999/BarAPI.jar", "plugins/BarAPI.jar"); Main.server().getPluginManager().loadPlugin(new File("plugins/BarAPI.jar")); Main.server().reload(); } catch (Exception e) { System.out.println("Downloading the dependency \"BarAPI\" failed. please download it manually."); } } } public static void downloadFile(String link, String directory) throws IOException { URL url = new URL(link); InputStream is = url.openStream(); OutputStream os = new FileOutputStream(directory); byte[] b = new byte[2048]; int length; while ((length = is.read(b)) != -1) { os.write(b, 0, length); } is.close(); os.close(); } }
package org.sagebionetworks.repo.web.controller; import org.sagebionetworks.repo.model.AuthorizationConstants; import org.sagebionetworks.repo.model.MembershipRequest; import org.sagebionetworks.repo.model.MembershipRqstSubmission; import org.sagebionetworks.repo.model.PaginatedResults; import org.sagebionetworks.repo.model.ServiceConstants; import org.sagebionetworks.repo.web.NotFoundException; import org.sagebionetworks.repo.web.UrlHelpers; import org.sagebionetworks.repo.web.rest.doc.ControllerInfo; import org.sagebionetworks.repo.web.service.ServiceProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; @ControllerInfo(displayName="Membeship Request Services", path="repo/v1") @Controller public class MembershipRequestController extends BaseController { @Autowired ServiceProvider serviceProvider; /** * Create a membership request. The Team must be specified. Optionally, * the creator may include a message and/or expiration date for the request. * If no expiration date is specified then the request never expires. * * @param userId * @param request * @return * @throws NotFoundException */ @ResponseStatus(HttpStatus.CREATED) @RequestMapping(value = UrlHelpers.MEMBERSHIP_REQUEST, method = RequestMethod.POST) public @ResponseBody MembershipRqstSubmission createRequest( @RequestParam(value = AuthorizationConstants.USER_ID_PARAM, required = false) String userId, @RequestBody MembershipRqstSubmission request ) throws NotFoundException { return serviceProvider.getMembershipRequestService().create(userId, request); } /** * Retrieve the open requests submitted to a Team, optionally filtering by the requester. * An request is only open if it has not expired and if the requester has not been added the Team. * * @param id Team ID * @param userId * @param requestorId the ID of the user requesting admission to the Team * @param limit the maximum number of requests to return (default 10) * @param offset the starting index of the returned results (default 0) * @return * @throws NotFoundException */ @ResponseStatus(HttpStatus.OK) @RequestMapping(value = UrlHelpers.OPEN_MEMBERSHIP_REQUEST, method = RequestMethod.GET) public @ResponseBody PaginatedResults<MembershipRequest> getOpenRequests( @PathVariable String id, @RequestParam(value = AuthorizationConstants.USER_ID_PARAM, required = false) String userId, @RequestParam(value = UrlHelpers.REQUESTOR_ID_REQUEST_PARAMETER, required = false) String requestorId, @RequestParam(value = ServiceConstants.PAGINATION_LIMIT_PARAM, required = false, defaultValue = ServiceConstants.DEFAULT_PAGINATION_LIMIT_PARAM) Integer limit, @RequestParam(value = ServiceConstants.PAGINATION_OFFSET_PARAM, required = false, defaultValue = ServiceConstants.DEFAULT_PAGINATION_OFFSET_PARAM_NEW) Integer offset ) throws NotFoundException { return serviceProvider.getMembershipRequestService().getOpenRequests(userId, requestorId, id, limit, offset); } /** * Retrieve an request by ID * Note: The client must be the creator of the membership request to make this request. * @param id the Team ID * @param userId * @return * @throws NotFoundException */ @ResponseStatus(HttpStatus.OK) @RequestMapping(value = UrlHelpers.MEMBERSHIP_REQUEST_ID, method = RequestMethod.GET) public @ResponseBody MembershipRqstSubmission getRequest( @PathVariable String id, @RequestParam(value = AuthorizationConstants.USER_ID_PARAM, required = false) String userId ) throws NotFoundException { return serviceProvider.getMembershipRequestService().get(userId, id); } /** * Delete a request * Note: The client must be the creator of the membership request to make this request. * * @param id * @param userId * @throws NotFoundException */ @ResponseStatus(HttpStatus.NO_CONTENT) @RequestMapping(value = UrlHelpers.MEMBERSHIP_REQUEST_ID, method = RequestMethod.DELETE) public void deleteRequest( @PathVariable String id, @RequestParam(value = AuthorizationConstants.USER_ID_PARAM, required = false) String userId ) throws NotFoundException { serviceProvider.getMembershipRequestService().delete(userId, id); } }
package net.darkhax.bookshelf.registry; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.function.Function; import java.util.function.Supplier; import javax.annotation.Nullable; import org.apache.logging.log4j.Logger; import com.google.common.collect.ImmutableList; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.arguments.ArgumentType; import com.mojang.brigadier.builder.LiteralArgumentBuilder; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import net.darkhax.bookshelf.loot.modifier.SerializerFactory; import net.darkhax.bookshelf.util.LootUtils; import net.darkhax.bookshelf.util.MCJsonUtils; import net.minecraft.block.Block; import net.minecraft.command.CommandSource; import net.minecraft.command.arguments.ArgumentTypes; import net.minecraft.command.arguments.IArgumentSerializer; import net.minecraft.enchantment.Enchantment; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityClassification; import net.minecraft.entity.EntityType; import net.minecraft.entity.item.PaintingType; import net.minecraft.entity.merchant.villager.VillagerProfession; import net.minecraft.entity.merchant.villager.VillagerTrades.ITrade; import net.minecraft.inventory.container.Container; import net.minecraft.inventory.container.ContainerType; import net.minecraft.item.BlockItem; import net.minecraft.item.Item; import net.minecraft.item.ItemGroup; import net.minecraft.item.SpawnEggItem; import net.minecraft.item.crafting.IRecipe; import net.minecraft.item.crafting.IRecipeSerializer; import net.minecraft.item.crafting.IRecipeType; import net.minecraft.potion.Potion; import net.minecraft.server.MinecraftServer; import net.minecraft.stats.IStatFormatter; import net.minecraft.stats.Stats; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityType; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.util.Tuple; import net.minecraft.util.registry.Registry; import net.minecraft.world.biome.provider.BiomeProvider; import net.minecraft.world.biome.provider.BiomeProviderType; import net.minecraft.world.biome.provider.IBiomeProviderSettings; import net.minecraft.world.gen.ChunkGenerator; import net.minecraft.world.gen.ChunkGeneratorType; import net.minecraft.world.gen.GenerationSettings; import net.minecraft.world.storage.loot.LootPool; import net.minecraft.world.storage.loot.LootTable; import net.minecraft.world.storage.loot.conditions.ILootCondition; import net.minecraft.world.storage.loot.conditions.ILootCondition.AbstractSerializer; import net.minecraft.world.storage.loot.conditions.LootConditionManager; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.crafting.CraftingHelper; import net.minecraftforge.common.crafting.IIngredientSerializer; import net.minecraftforge.common.loot.GlobalLootModifierSerializer; import net.minecraftforge.common.loot.IGlobalLootModifier; import net.minecraftforge.event.LootTableLoadEvent; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.event.RegistryEvent.Register; import net.minecraftforge.event.village.VillagerTradesEvent; import net.minecraftforge.event.village.WandererTradesEvent; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.DistExecutor; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraftforge.fml.event.server.FMLServerStartingEvent; import net.minecraftforge.fml.server.ServerLifecycleHooks; import net.minecraftforge.registries.IForgeRegistry; public class RegistryHelper { protected final String modid; protected final Logger logger; @Nullable protected final ItemGroup group; /** * Creates a new registry helper for the given side the mod is running on. * * @param modid The mod id. * @param logger A logger for the mod. * @param group The item group if you have one. * @return A registry helper that has been created for the given side. */ public static RegistryHelper create (String modid, Logger logger, @Nullable ItemGroup group) { return DistExecutor.runForDist( () -> () -> new RegistryHelperClient(modid, logger, group), () -> () -> new RegistryHelper(modid, logger, group)); } public RegistryHelper(String modid, Logger logger, @Nullable ItemGroup group) { this.modid = modid; this.logger = logger; this.group = group; } public void initialize (IEventBus modBus) { if (!this.blocks.isEmpty()) { modBus.addGenericListener(Block.class, this::registerBlocks); } if (!this.items.isEmpty()) { modBus.addGenericListener(Item.class, this::registerItems); } if (!this.tileEntityTypes.isEmpty()) { modBus.addGenericListener(TileEntityType.class, this::registerTileEntities); } if (!this.recipeSerializers.isEmpty() || !this.recipeTypes.isEmpty()) { modBus.addGenericListener(IRecipeSerializer.class, this::registerRecipeTypes); } if (!this.containers.isEmpty()) { modBus.addGenericListener(ContainerType.class, this::registerContainerTypes); } if (!this.commands.isEmpty()) { MinecraftForge.EVENT_BUS.addListener(this::registerCommands); } if (!this.entityTypes.isEmpty()) { modBus.addGenericListener(EntityType.class, this::registerEntityTypes); } if (!this.biomeProviderTypes.isEmpty()) { modBus.addGenericListener(BiomeProviderType.class, this::registerBiomeProviders); } if (!this.chunkGeneratorTypes.isEmpty()) { modBus.addGenericListener(ChunkGeneratorType.class, this::registerChunkGeneratorTypes); } if (!this.potions.isEmpty()) { modBus.addGenericListener(Potion.class, this::registerPotionTypes); } if (!this.trades.isEmpty()) { MinecraftForge.EVENT_BUS.addListener(this::registerVillagerTrades); } if (!this.basicTrades.isEmpty() || !this.rareTrades.isEmpty()) { MinecraftForge.EVENT_BUS.addListener(this::registerWanderingTrades); } if (!this.commandArguments.isEmpty()) { modBus.addListener(this::registerCommandArguments); } if (!this.lootConditions.isEmpty()) { modBus.addListener(this::registerLootConditions); } if (!this.injectionTables.isEmpty()) { MinecraftForge.EVENT_BUS.addListener(this::loadTableInjections); } if (!this.globalModifierSerializers.isEmpty()) { modBus.addGenericListener(GlobalLootModifierSerializer.class, this::registerGlobalLootModifierSerializers); } if (!this.enchantments.isEmpty()) { modBus.addGenericListener(Enchantment.class, this::registerEnchantments); } if (!this.paintings.isEmpty()) { modBus.addGenericListener(PaintingType.class, this::registerPaintings); } if (!this.ingredients.isEmpty()) { modBus.addGenericListener(IRecipeSerializer.class, this::registerIngredientTypes); } } /** * BLOCKS */ private final List<Block> blocks = NonNullList.create(); private void registerBlocks (Register<Block> event) { if (!this.blocks.isEmpty()) { this.logger.info("Registering {} blocks.", this.blocks.size()); final IForgeRegistry<Block> registry = event.getRegistry(); for (final Block block : this.blocks) { registry.register(block); } } } public Block registerBlock (Block block, String id) { return this.registerBlock(block, new BlockItem(block, new Item.Properties().group(this.group)), id); } public Block registerBlock (Block block, BlockItem item, String id) { block.setRegistryName(new ResourceLocation(this.modid, id)); this.blocks.add(block); this.registerItem(item, id); return block; } public List<Block> getBlocks () { return ImmutableList.copyOf(this.blocks); } /** * ITEMS */ private final List<Item> items = NonNullList.create(); private void registerItems (Register<Item> event) { if (!this.items.isEmpty()) { this.logger.info("Registering {} items.", this.items.size()); final IForgeRegistry<Item> registry = event.getRegistry(); for (final Item item : this.items) { registry.register(item); } } } public Item registerItem (Item item, String id) { item.setRegistryName(new ResourceLocation(this.modid, id)); item.group = this.group; this.items.add(item); return item; } public List<Item> getItems () { return ImmutableList.copyOf(this.items); } /** * TILE ENTITIES */ private final List<TileEntityType<?>> tileEntityTypes = NonNullList.create(); public <T extends TileEntity> TileEntityType<T> registerTileEntity (Supplier<T> factory, String id, Block... blocks) { final TileEntityType<T> tileEntityType = TileEntityType.Builder.create(factory, blocks).build(null); tileEntityType.setRegistryName(this.modid, id); this.tileEntityTypes.add(tileEntityType); return tileEntityType; } private void registerTileEntities (Register<TileEntityType<?>> event) { if (!this.tileEntityTypes.isEmpty()) { this.logger.info("Registering {} tile entity types.", this.tileEntityTypes.size()); final IForgeRegistry<TileEntityType<?>> registry = event.getRegistry(); for (final TileEntityType<?> tileEntityType : this.tileEntityTypes) { registry.register(tileEntityType); } } } public List<TileEntityType<?>> getTileEntities () { return ImmutableList.copyOf(this.tileEntityTypes); } /** * RECIPE TYPES */ private final List<IRecipeType<?>> recipeTypes = NonNullList.create(); private final List<IRecipeSerializer<?>> recipeSerializers = NonNullList.create(); public <T extends IRecipe<?>> IRecipeType<T> registerRecipeType (String typeId) { final IRecipeType<T> type = IRecipeType.register(typeId); this.recipeTypes.add(type); return type; } public <T extends IRecipe<?>> IRecipeSerializer<T> registerRecipeSerializer (IRecipeSerializer<T> serializer, String id) { this.recipeSerializers.add(serializer); serializer.setRegistryName(new ResourceLocation(this.modid, id)); return serializer; } private void registerRecipeTypes (Register<IRecipeSerializer<?>> event) { if (!this.recipeTypes.isEmpty()) { this.logger.info("Registering {} recipe types.", this.recipeTypes.size()); for (final IRecipeType<?> recipeType : this.recipeTypes) { Registry.register(Registry.RECIPE_TYPE, new ResourceLocation(recipeType.toString()), recipeType); } } if (!this.recipeSerializers.isEmpty()) { this.logger.info("Registering {} recipe serializers.", this.recipeSerializers.size()); final IForgeRegistry<IRecipeSerializer<?>> registry = event.getRegistry(); for (final IRecipeSerializer<?> serializer : this.recipeSerializers) { registry.register(serializer); } } } public List<IRecipeType<?>> getRecipeTypes () { return ImmutableList.copyOf(this.recipeTypes); } public List<IRecipeSerializer<?>> getRecipeSerializers () { return ImmutableList.copyOf(this.recipeSerializers); } /** * CONTAINERS */ private final List<ContainerType<?>> containers = NonNullList.create(); public <T extends Container> ContainerType<T> registerContainer (ContainerType.IFactory<T> factory, String id) { return this.registerContainer(new ContainerType<>(factory), id); } public <T extends Container> ContainerType<T> registerContainer (ContainerType<T> type, String id) { type.setRegistryName(this.modid, id); this.containers.add(type); return type; } protected void registerContainerTypes (Register<ContainerType<?>> event) { if (!this.containers.isEmpty()) { this.logger.info("Registering {} containers.", this.containers.size()); final IForgeRegistry<ContainerType<?>> registry = event.getRegistry(); for (final ContainerType<?> containerType : this.containers) { registry.register(containerType); } } } public List<ContainerType<?>> getContainers () { return ImmutableList.copyOf(this.containers); } /** * COMMANDS */ private final List<LiteralArgumentBuilder<CommandSource>> commands = NonNullList.create(); public LiteralArgumentBuilder<CommandSource> registerCommand (LiteralArgumentBuilder<CommandSource> command) { this.commands.add(command); return command; } private void registerCommands (FMLServerStartingEvent event) { if (!this.commands.isEmpty()) { this.logger.info("Registering {} commands.", this.commands.size()); final CommandDispatcher<CommandSource> dispatcher = event.getCommandDispatcher(); for (final LiteralArgumentBuilder<CommandSource> command : this.commands) { dispatcher.register(command); } } } public List<LiteralArgumentBuilder<CommandSource>> getCommands () { return ImmutableList.copyOf(this.commands); } /** * ENTITIES */ private final List<EntityType<?>> entityTypes = NonNullList.create(); private final List<Item> spawnEggs = NonNullList.create(); public <T extends Entity> EntityType<T> registerMob (Class<T> entityClass, EntityType.IFactory<T> factory, EntityClassification classification, String id, float width, float height, int primary, int secondary) { return this.registerMob(entityClass, factory, classification, id, width, height, 64, 1, primary, secondary); } public <T extends Entity> EntityType<T> registerMob (Class<T> entityClass, EntityType.IFactory<T> factory, EntityClassification classification, String id, float width, float height, int trackingRange, int updateInterval, int primary, int secondary) { final EntityType<T> type = this.registerEntityType(entityClass, factory, classification, id, width, height, trackingRange, updateInterval); final Item spawnEgg = new SpawnEggItem(type, primary, secondary, new Item.Properties().group(ItemGroup.MISC)); spawnEgg.setRegistryName(this.modid, id + "_spawn_egg"); this.items.add(spawnEgg); this.spawnEggs.add(spawnEgg); return type; } public <T extends Entity> EntityType<T> registerEntityType (Class<T> entityClass, EntityType.IFactory<T> factory, EntityClassification classification, String id, float width, float height) { return this.registerEntityType(entityClass, factory, classification, id, width, height, 64, 1); } public <T extends Entity> EntityType<T> registerEntityType (Class<T> entityClass, EntityType.IFactory<T> factory, EntityClassification classification, String id, float width, float height, int trackingRange, int updateInterval) { final EntityType.Builder<T> builder = EntityType.Builder.create(factory, classification); builder.size(width, height); builder.setTrackingRange(trackingRange); builder.setUpdateInterval(updateInterval); return this.registerEntityType(builder.build(this.modid + ":" + id), id); } public <T extends Entity> EntityType<T> registerEntityType (EntityType<T> type, String id) { this.entityTypes.add(type); type.setRegistryName(this.modid, id); return type; } public List<EntityType<?>> getEntityTypes () { return ImmutableList.copyOf(this.entityTypes); } public List<Item> getSpawnEggs () { return ImmutableList.copyOf(this.spawnEggs); } protected void registerEntityTypes (Register<EntityType<?>> event) { if (!this.entityTypes.isEmpty()) { this.logger.info("Registering {} entity types.", this.entityTypes.size()); final IForgeRegistry<EntityType<?>> registry = event.getRegistry(); for (final EntityType<?> entityType : this.entityTypes) { registry.register(entityType); } } } /** * CHUNK GENERATOR TYPES */ private final List<ChunkGeneratorType<?, ?>> chunkGeneratorTypes = NonNullList.create(); public <C extends GenerationSettings, T extends ChunkGenerator<C>> ChunkGeneratorType<C, T> registerChunkGeneratorType (ChunkGeneratorType<C, T> type, String id) { this.chunkGeneratorTypes.add(type); type.setRegistryName(this.modid, id); return type; } private void registerChunkGeneratorTypes (Register<ChunkGeneratorType<?, ?>> event) { if (!this.chunkGeneratorTypes.isEmpty()) { this.logger.info("Registering {} chunk generator types.", this.chunkGeneratorTypes.size()); final IForgeRegistry<ChunkGeneratorType<?, ?>> registry = event.getRegistry(); for (final ChunkGeneratorType<?, ?> containerType : this.chunkGeneratorTypes) { registry.register(containerType); } } } /** * BIOME PROVIDER TYPES */ private final List<BiomeProviderType<?, ?>> biomeProviderTypes = NonNullList.create(); public <C extends IBiomeProviderSettings, T extends BiomeProvider> BiomeProviderType<C, T> registerBiomeProvider (BiomeProviderType<C, T> type, String id) { this.biomeProviderTypes.add(type); type.setRegistryName(this.modid, id); return type; } private void registerBiomeProviders (Register<BiomeProviderType<?, ?>> event) { if (!this.biomeProviderTypes.isEmpty()) { this.logger.info("Registering {} biome provider types.", this.biomeProviderTypes.size()); final IForgeRegistry<BiomeProviderType<?, ?>> registry = event.getRegistry(); for (final BiomeProviderType<?, ?> containerType : this.biomeProviderTypes) { registry.register(containerType); } } } /** * STATS */ private final List<ResourceLocation> stats = NonNullList.create(); public ResourceLocation registerStat (String key) { return this.registerStat(key, IStatFormatter.DEFAULT); } public ResourceLocation registerStat (String key, IStatFormatter formatter) { final ResourceLocation statIdentifier = new ResourceLocation(this.modid, key); Registry.register(Registry.CUSTOM_STAT, key, statIdentifier); Stats.CUSTOM.get(statIdentifier, formatter); this.stats.add(statIdentifier); return statIdentifier; } public List<ResourceLocation> getStatIdentifiers () { return ImmutableList.copyOf(this.stats); } /** * POTIONS */ private final List<Potion> potions = NonNullList.create(); public Potion registerPotion (Potion potion, String id) { this.potions.add(potion); potion.setRegistryName(this.modid, id); return potion; } private void registerPotionTypes (Register<Potion> event) { final IForgeRegistry<Potion> registry = event.getRegistry(); this.logger.info("Registering {} potion types.", this.potions.size()); for (final Potion potion : this.potions) { registry.register(potion); } } public List<Potion> getPotions () { return ImmutableList.copyOf(this.potions); } /** * VILLAGER TRADES */ private final Map<VillagerProfession, Int2ObjectMap<List<ITrade>>> trades = new HashMap<>(); public ITrade registerVillagerTrade (VillagerProfession profession, int level, ITrade trade) { // Get or create a new int map final Int2ObjectMap<List<ITrade>> tradesByLevel = this.trades.getOrDefault(profession, new Int2ObjectOpenHashMap<>()); // Get or create a new list of trades for the level. final List<ITrade> tradesForLevel = tradesByLevel.getOrDefault(level, new ArrayList<>()); // Add the trades. tradesForLevel.add(trade); // Add the various maps and lists to their parent collection. tradesByLevel.put(level, tradesForLevel); this.trades.put(profession, tradesByLevel); return trade; } private void registerVillagerTrades (VillagerTradesEvent event) { // Ensure type isn't null, because mods. if (event.getType() != null) { // Get all trades for the current profession final Int2ObjectMap<List<ITrade>> tradesByLevel = this.trades.get(event.getType()); // Check to make sure a trade has been registered. if (tradesByLevel != null && !tradesByLevel.isEmpty()) { // Iterate for the various profession levels for (final int level : tradesByLevel.keySet()) { final List<ITrade> tradeRegistry = event.getTrades().get(level); // If the trade pool exists add all trades for that tier. if (tradeRegistry != null) { tradeRegistry.addAll(tradesByLevel.get(level)); } else { // Level 1 through 5 should always exist, but this is modded so people // will inevitably mess this up. this.logger.error("The mod {} tried to register a trade at profession level {} for villager type {}. This profession level does not exist!", this.modid, level, event.getType().getRegistryName().toString()); } } } } } /** * WANDERER TRADES */ private final List<ITrade> basicTrades = new ArrayList<>(); private final List<ITrade> rareTrades = new ArrayList<>(); public ITrade addBasicWanderingTrade (ITrade trade) { this.basicTrades.add(trade); return trade; } public ITrade addRareWanderingTrade (ITrade trade) { this.rareTrades.add(trade); return trade; } private void registerWanderingTrades (WandererTradesEvent event) { event.getGenericTrades().addAll(this.basicTrades); event.getRareTrades().addAll(this.rareTrades); } /** * COMMAND ARGUMENT TYPES */ private final Map<String, Tuple<Class, IArgumentSerializer>> commandArguments = new HashMap<>(); public <T extends ArgumentType<?>> void registerCommandArgument (String name, Class<T> clazz, IArgumentSerializer<T> serializer) { this.commandArguments.put(name, new Tuple<>(clazz, serializer)); } private void registerCommandArguments (FMLCommonSetupEvent event) { this.logger.info("Registering {} command argument types.", this.commandArguments.size()); for (final Entry<String, Tuple<Class, IArgumentSerializer>> entry : this.commandArguments.entrySet()) { ArgumentTypes.register(entry.getKey(), entry.getValue().getA(), entry.getValue().getB()); } } /** * LOOT CONDITION */ private final List<AbstractSerializer<?>> lootConditions = NonNullList.create(); public void registerLootCondition (AbstractSerializer<?> condition) { this.lootConditions.add(condition); } private void registerLootConditions (FMLCommonSetupEvent event) { this.logger.info("Registering {} loot condition types.", this.lootConditions.size()); for (final AbstractSerializer<?> entry : this.lootConditions) { LootConditionManager.registerCondition(entry); } } /** * LOOT TABLE INJECTION */ private final Map<ResourceLocation, ResourceLocation> injectionTables = new HashMap<>(); public ResourceLocation injectTable (ResourceLocation toInject) { final ResourceLocation injectId = new ResourceLocation(this.modid, "inject/" + toInject.getNamespace() + "/" + toInject.getPath()); this.injectionTables.put(toInject, injectId); return injectId; } private void loadTableInjections (LootTableLoadEvent event) { final ResourceLocation injectTableName = this.injectionTables.get(event.getName()); // Checks if the table being loaded has a known injection table if (injectTableName != null) { final LootTable originalTable = event.getTable(); final MinecraftServer server = ServerLifecycleHooks.getCurrentServer(); if (server != null) { try { // Force load the injection table as it likely isn't loaded yet. final LootTable inject = MCJsonUtils.loadLootTable(event.getLootTableManager(), server.getResourceManager(), injectTableName); if (inject != null) { this.logger.info("Injecting loot table {} with {}.", event.getName(), injectTableName); this.mergeTables(originalTable, event.getName(), inject, injectTableName); } } catch (final IOException e) { this.logger.error("Failed to load {} as a loot table.", injectTableName, e); } } } } /** * Merges all the loot pools of one table into another table. Pools with the same name will * have their entries and conditions merged. Pools not present in the original will be * injected in their entirety. * * @param original The original loot table. * @param originalName The name of the original loot table. * @param mergeWith The table to merge into the original table. * @param mergeWithName The name of the table to merge. */ private void mergeTables (LootTable original, ResourceLocation originalName, LootTable mergeWith, ResourceLocation mergeWithName) { final List<LootPool> pools = LootUtils.getPools(original); final Map<String, LootPool> mappedPools = LootUtils.mapPools(pools); for (final LootPool poolToInject : LootUtils.getPools(mergeWith)) { final String poolName = poolToInject.getName(); if (mappedPools.containsKey(poolToInject.getName())) { final LootPool originalPool = mappedPools.get(poolName); this.logger.info("Merged pool {} into {} from {}.", originalPool.getName(), originalName, mergeWithName); LootUtils.getEntries(originalPool).addAll(LootUtils.getEntries(poolToInject)); LootUtils.getConditions(originalPool).addAll(LootUtils.getConditions(poolToInject)); } else { pools.add(poolToInject); this.logger.info("Injected new pool {} into table {}.", poolName, originalName); } } } /** * LOOT MODIFIERS */ private final List<GlobalLootModifierSerializer<?>> globalModifierSerializers = NonNullList.create(); public <T extends IGlobalLootModifier> GlobalLootModifierSerializer<T> registerGlobalModifier (Function<ILootCondition[], T> factory, String id) { return this.registerGlobalModifier(new SerializerFactory<>(factory), id); } public <T extends IGlobalLootModifier> GlobalLootModifierSerializer<T> registerGlobalModifier (GlobalLootModifierSerializer<T> serializer, String id) { serializer.setRegistryName(this.modid, id); this.globalModifierSerializers.add(serializer); return serializer; } private void registerGlobalLootModifierSerializers (Register<GlobalLootModifierSerializer<?>> event) { this.logger.info("Registering {} global loot modifier serializers.", this.globalModifierSerializers.size()); final IForgeRegistry<GlobalLootModifierSerializer<?>> registry = event.getRegistry(); for (final GlobalLootModifierSerializer<?> entry : this.globalModifierSerializers) { registry.register(entry); } } /** * ENCHANTMENTS */ private final List<Enchantment> enchantments = NonNullList.create(); public <T extends Enchantment> T registerEnchantment (T enchantment, String id) { enchantment.setRegistryName(this.modid, id); this.enchantments.add(enchantment); return enchantment; } public List<Enchantment> getEnchantments () { return ImmutableList.copyOf(this.enchantments); } private void registerEnchantments (Register<Enchantment> event) { this.logger.info("Registering {} enchantments.", this.enchantments.size()); final IForgeRegistry<Enchantment> registry = event.getRegistry(); for (final Enchantment entry : this.enchantments) { registry.register(entry); } } /** * PAINTINGS */ private final List<PaintingType> paintings = NonNullList.create(); public PaintingType registerPainting (String id, int width, int height) { return this.registerPainting(new PaintingType(width, height), id); } public <T extends PaintingType> T registerPainting (T painting, String id) { painting.setRegistryName(this.modid, id); this.paintings.add(painting); return painting; } public List<PaintingType> getPaintings () { return ImmutableList.copyOf(this.paintings); } private void registerPaintings (Register<PaintingType> event) { this.logger.info("Registering {} paintings.", this.paintings.size()); final IForgeRegistry<PaintingType> registry = event.getRegistry(); for (final PaintingType entry : this.paintings) { registry.register(entry); } } /** * INGREDIENTS */ private final Map<ResourceLocation, IIngredientSerializer<?>> ingredients = new HashMap<>(); public void registerIngredientType (IIngredientSerializer<?> serializer, String id) { this.ingredients.put(new ResourceLocation(this.modid, id), serializer); } private void registerIngredientTypes (RegistryEvent.Register<IRecipeSerializer<?>> event) { this.logger.info("Registering {} ingredient serializers.", this.ingredients.size()); for (final Entry<ResourceLocation, IIngredientSerializer<?>> entry : this.ingredients.entrySet()) { CraftingHelper.register(entry.getKey(), entry.getValue()); } } }
package net.spy.memcached.vbucket; import net.spy.memcached.MemcachedNode; import net.spy.memcached.NodeLocator; import net.spy.memcached.vbucket.config.Config; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.HashMap; import java.util.List; import java.net.InetSocketAddress; /** * Implementation of the {@link NodeLocator} interface that contains vbucket hashing methods */ public class VBucketNodeLocator implements NodeLocator { private Map<String, MemcachedNode> nodesMap; private Config config; /** * Construct a VBucketNodeLocator over the given JSON configuration string. * * @param nodes * @param jsonConfig */ public VBucketNodeLocator(List<MemcachedNode> nodes, Config jsonConfig) { super(); setNodes(nodes); setConfig(jsonConfig); } /** * {@inheritDoc} */ public MemcachedNode getPrimary(String k) { int vbucket = config.getVbucketByKey(k); int serverNumber = config.getMaster(vbucket); String server = config.getServer(serverNumber); // choose appropriate MemecachedNode according to config data return nodesMap.get(server); } /** * {@inheritDoc} */ public Iterator<MemcachedNode> getSequence(String k) { return nodesMap.values().iterator(); } /** * {@inheritDoc} */ public Collection<MemcachedNode> getAll() { return this.nodesMap.values(); } /** * {@inheritDoc} */ public NodeLocator getReadonlyCopy() { return this; } public void updateLocator(final List<MemcachedNode> nodes, final Config config) { setNodes(nodes); setConfig(config); } /** * Returns a vbucket index for the given key * @param key the key * @return vbucket index */ public int getVBucketIndex(String key) { return config.getVbucketByKey(key); } private void setNodes(Collection<MemcachedNode> nodes) { HashMap<String, MemcachedNode> vbnodesMap = new HashMap<String, MemcachedNode>(); for (MemcachedNode node : nodes) { InetSocketAddress addr = (InetSocketAddress) node.getSocketAddress(); String address = addr.getAddress().getHostName() + ":" + addr.getPort(); String hostname = addr.getAddress().getHostAddress() + ":" + addr.getPort(); vbnodesMap.put(address, node); vbnodesMap.put(hostname, node); } this.nodesMap = vbnodesMap; } private void setConfig(final Config config) { this.config = config; } /** * Method returns the node that is not contained in the specified collection of the failed nodes * @param k the key * @param notMyVbucketNodes a collection of the nodes are excluded * @return The first MemcachedNode which mets requirements */ public MemcachedNode getAlternative(String k, Collection<MemcachedNode> notMyVbucketNodes) { Collection<MemcachedNode> nodes = nodesMap.values(); nodes.removeAll(notMyVbucketNodes); if (nodes.isEmpty()) { return null; } else { return nodes.iterator().next(); } } }
package net.darkhax.darkutils.blocks; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyDirection; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItem; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public class BlockVectorPlate extends BlockTrapBase { public static final PropertyDirection FACING = PropertyDirection.create("facing", EnumFacing.Plane.HORIZONTAL); private final double speed; public BlockVectorPlate(double speed) { super(); this.setUnlocalizedName("darkutils.trap.movement"); this.setDefaultState(this.blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH)); this.speed = speed; } @Override public void onEntityCollidedWithBlock (World world, BlockPos pos, IBlockState state, Entity entity) { final EnumFacing direction = state.getValue(FACING).getOpposite(); if (!entity.isSneaking()) { entity.motionX += this.speed * direction.getFrontOffsetX(); entity.motionZ += this.speed * direction.getFrontOffsetZ(); if (entity instanceof EntityItem) { final EntityItem item = (EntityItem) entity; item.setAgeToCreativeDespawnTime(); // TODO } } } @Override protected BlockStateContainer createBlockState () { return new BlockStateContainer(this, new IProperty[] { FACING }); } @Override public IBlockState onBlockPlaced (World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer) { return this.getDefaultState().withProperty(FACING, placer.getHorizontalFacing().getOpposite()); } @Override public IBlockState getStateFromMeta (int meta) { return this.getDefaultState().withProperty(FACING, EnumFacing.getHorizontal(meta)); } @Override public int getMetaFromState (IBlockState state) { return state.getValue(FACING).getHorizontalIndex(); } }
package net.wouterdanes.docker.remoteapi; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.ws.rs.client.Entity; import javax.ws.rs.core.MediaType; import net.wouterdanes.docker.remoteapi.exception.DockerException; import net.wouterdanes.docker.remoteapi.model.DockerVersionInfo; /** * The class act as an interface to the "root" Remote Docker API with some "misc" service end points. */ public class MiscService extends BaseService { private static final Pattern BUILD_IMAGE_ID_EXTRACTION_PATTERN = Pattern.compile(".*Successfully built ([0-9a-f]+).*", Pattern.DOTALL); private static final Pattern BUILD_IMAGE_INTERMEDIATE_IDS_EXTRACTION_PATTERN = Pattern.compile(".*?Running in ([0-9a-f]+).*?", Pattern.DOTALL); private final ContainersService containersService; public MiscService(final String dockerApiRoot) { super(dockerApiRoot, "/"); containersService = new ContainersService(dockerApiRoot); } /** * Returns the Docker version information * * @return a {@link DockerVersionInfo} instance describing this docker installation. */ public DockerVersionInfo getVersionInfo() { String json = getServiceEndPoint() .path("/version") .request(MediaType.APPLICATION_JSON_TYPE) .get(String.class); return toObject(json, DockerVersionInfo.class); } public String buildImage(byte[] tarArchive) { String jsonStream = getServiceEndPoint() .path("/build") .queryParam("q", true) .request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.entity(tarArchive, "application/tar"), String.class); Matcher intermediates = BUILD_IMAGE_INTERMEDIATE_IDS_EXTRACTION_PATTERN.matcher(jsonStream); while (intermediates.find()) { String intermediateId = intermediates.group(1); containersService.deleteContainer(intermediateId); } Matcher matcher = BUILD_IMAGE_ID_EXTRACTION_PATTERN.matcher(jsonStream); if (!matcher.matches()) { throw new DockerException("Can't obtain ID from build output stream.", jsonStream); } return matcher.group(1); } }
package net.emaze.dysfunctional.iterations; import net.emaze.dysfunctional.adapting.ArrayIterator; import java.util.Iterator; import net.emaze.dysfunctional.consumers.EagerConsumer; import java.util.List; import net.emaze.dysfunctional.delegates.Action; import net.emaze.dysfunctional.delegates.Delegate; import net.emaze.dysfunctional.delegates.Predicate; /** * iterating shortcuts (usage shouldn't be abused) * @author rferranti */ public abstract class Iterations { /** * @param <E> * @param iterable the iterable where elements are fetched from * @param predicate the predicate applied to every element until a match is found * @return true if ANY predicate application yields true (gives up on the first positive match) */ public static <E> boolean any(Iterable<E> iterable, Predicate<E> predicate) { for (E element : iterable) { if (predicate.test(element)) { return true; } } return false; } /** * @param <E> * @param iterator the iterator where elements are fetched from * @param predicate the predicate applied to every element until a match is found * @return true if ANY predicate application yields true (gives up on the first positive match) */ public static <E> boolean any(Iterator<E> iterator, Predicate<E> predicate) { return any(new OneTimeIterable<E>(iterator), predicate); } /** * @param <E> * @param array the array where elements are fetched from * @param predicate the predicate applied to every element until a match is found * @return true if ANY predicate application yields true (gives up on the first positive match) */ public static <E> boolean any(E[] array, Predicate<E> predicate) { return any(new ArrayIterator<E>(array), predicate); } /** * @param <E> * @param iterable the iterable where elements are fetched from * @param predicate the predicate applied to every element fetched from the iterable * @return true if EVERY predicate application yields true */ public static <E> boolean every(Iterable<E> iterable, Predicate<E> predicate) { for (E element : iterable) { if (!predicate.test(element)) { return false; } } return true; } /** * @param <E> * @param iterator the iterator where elements are fetched from * @param predicate the predicate applied to every element fetched from the iterator * @return true if EVERY predicate application yields true */ public static <E> boolean every(Iterator<E> iterator, Predicate<E> predicate) { return every(new OneTimeIterable<E>(iterator), predicate); } /** * @param <E> * @param array the array where elements are fetched from * @param predicate the predicate applied to every element fetched from the array * @return true if EVERY predicate application yields true */ public static <E> boolean every(E[] array, Predicate<E> predicate) { return every(new ArrayIterator<E>(array), predicate); } /** * @param <E> * @param iterable the iterable where elements are fetched from * @param action the action applied to every element fetched from the iterable */ public static <E> void each(Iterable<E> iterable, Action<E> action) { for (E element : iterable) { action.perform(element); } } /** * @param <E> * @param iterator the iterator where elements are fetched from * @param action the action applied to every element fetched from the iterator */ public static <E> void each(Iterator<E> iterator, Action<E> action) { each(new OneTimeIterable<E>(iterator), action); } /** * @param <E> * @param array the array where elements are fetched from * @param action the action applied to every element fetched from the array */ public static <E> void each(E[] array, Action<E> action) { each(new ArrayIterator<E>(array), action); } /** * * @param <R> * @param <E> * @param iterable the iterable where elements are fetched from * @param delegate a delegate used to transform each element * @return a List<R> containing the transformed elements */ public static <R, E> List<R> map(Iterable<E> iterable, Delegate<R, E> delegate) { return map(iterable.iterator(), delegate); } /** * * @param <R> * @param <E> * @param iterator the iterator where elements are fetched from * @param delegate a delegate used to transform each element * @return a List<R> containing the transformed elements */ public static <R, E> List<R> map(Iterator<E> iterator, Delegate<R, E> delegate) { return new EagerConsumer<R>().consume(new TransformingIterator<R, E>(iterator, delegate)); } /** * * @param <R> * @param <E> * @param array the array where elements are fetched from * @param delegate a delegate used to transform each element * @return a List<R> containing the transformed elements */ public static <R, E> List<R> map(E[] array, Delegate<R, E> delegate) { return map(new ArrayIterator<E>(array), delegate); } public static <T> Iterable<T> oneTime(Iterator<T> iterator){ return new OneTimeIterable<T>(iterator); } }
package net.zomis.minesweeper.analyze; import java.util.List; public interface RuleConstraint<T> { /** * Apply various values to this rule to potentially simplify it and learn something new * * @param knownValues Known values that can be removed and cleaned up from this rule to simplify it * @return A {@link SimplifyResult} corresponding to how successful the simplification was */ SimplifyResult simplify(GroupValues<T> knownValues); /** * Create a copy of this rule, for trial-and-error purposes * * @return A copy of this rule in its current state */ RuleConstraint<T> copy(); /** * Determine whether or not this rule is finished and thus can be removed from the list of rules * * @return True if this rule is successfully finished, false otherwise */ boolean isEmpty(); /** * Find the best field group to branch on * * @return The best {@link FieldGroup} to branch on, or null if this rule does not have a preference about how to branch */ FieldGroup<T> getSmallestFieldGroup(); /** * @return An indication on what caused this rule to be created */ T getCause(); /** * @return Direct access to the {@link FieldGroup}s in this rule, in order to split them */ List<FieldGroup<T>> fieldGroups(); }
package nl.jqno.equalsverifier.api; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Func.Func1; import nl.jqno.equalsverifier.Func.Func2; import nl.jqno.equalsverifier.Warning; /** * Helps to construct an {@link EqualsVerifier} test with a fluent API. * * @param <T> The class under test. */ public interface EqualsVerifierApi<T> { /* package private */static final String WEBSITE_URL = "For more information, go to: http: /** * Suppresses warnings given by {@code EqualsVerifier}. See {@link Warning} to see what warnings * can be suppressed. * * @param warnings A list of warnings to suppress in {@code EqualsVerifier}. * @return {@code this}, for easy method chaining. */ public EqualsVerifierApi<T> suppress(Warning... warnings); public <S> EqualsVerifierApi<T> withPrefabValues(Class<S> otherType, S red, S blue); /** * Adds a factory to generate prefabricated values for instance fields of classes with 1 generic * type parameter that EqualsVerifier cannot instantiate by itself. * * @param <S> The class of the prefabricated values. * @param otherType The class of the prefabricated values. * @param factory A factory to generate an instance of {@code S}, given a value of its generic * type parameter. * @return {@code this}, for easy method chaining. * @throws NullPointerException if either {@code otherType} or {@code factory} is null. */ public <S> EqualsVerifierApi<T> withGenericPrefabValues( Class<S> otherType, Func1<?, S> factory ); /** * Adds a factory to generate prefabricated values for instance fields of classes with 2 generic * type parameters that EqualsVerifier cannot instantiate by itself. * * @param <S> The class of the prefabricated values. * @param otherType The class of the prefabricated values. * @param factory A factory to generate an instance of {@code S}, given a value of each of its * generic type parameters. * @return {@code this}, for easy method chaining. * @throws NullPointerException if either {@code otherType} or {@code factory} is null. */ public <S> EqualsVerifierApi<T> withGenericPrefabValues( Class<S> otherType, Func2<?, ?, S> factory ); /** * Signals that {@code getClass} is used in the implementation of the {@code equals} method, * instead of an {@code instanceof} check. * * @return {@code this}, for easy method chaining. * @see Warning#STRICT_INHERITANCE */ public EqualsVerifierApi<T> usingGetClass(); /** * Signals that all internal caches need to be reset. This is useful when the test framework * uses multiple ClassLoaders to run tests, causing {@link java.lang.Class} instances * that would normally be equal, to be unequal, because their ClassLoaders don't match. * * @return {@code this}, for easy method chaining. */ public EqualsVerifierApi<T> withResetCaches(); }
package net.minecraft.launchwrapper; import cpw.mods.fml.relauncher.FMLRelaunchLog; import nallar.tickthreading.patcher.PatchHook; import java.io.*; import java.lang.reflect.*; import java.net.*; import java.security.*; import java.util.*; import java.util.jar.*; import java.util.jar.Attributes.*; import java.util.logging.*; public class LaunchClassLoader extends URLClassLoader { private IClassTransformer deobfuscationTransformer; private final List<URL> sources; private final ClassLoader parent = getClass().getClassLoader(); private final List<IClassTransformer> transformers = new ArrayList<IClassTransformer>(2); private final Map<String, Class<?>> cachedClasses = new HashMap<String, Class<?>>(1000); private final Set<String> invalidClasses = new HashSet<String>(1000); private final Set<String> classLoaderExceptions = new HashSet<String>(); private final Set<String> transformerExceptions = new HashSet<String>(); private final Map<String, byte[]> resourceCache = new HashMap<String, byte[]>(1000); private IClassNameTransformer renameTransformer; private static final String[] RESERVED_NAMES = {"CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"}; private static final boolean DEBUG = Boolean.parseBoolean(System.getProperty("legacy.debugClassLoading", "false")); private static final boolean DEBUG_FINER = DEBUG && Boolean.parseBoolean(System.getProperty("legacy.debugClassLoadingFiner", "false")); private static final boolean DEBUG_SAVE = DEBUG && Boolean.parseBoolean(System.getProperty("legacy.debugClassLoadingSave", "false")); private static File tempFolder = null; public static LaunchClassLoader instance; public LaunchClassLoader(URL[] sources) { super(sources, null); instance = this; this.sources = new ArrayList<URL>(Arrays.asList(sources)); Thread.currentThread().setContextClassLoader(this); // classloader exclusions addClassLoaderExclusion("java."); addClassLoaderExclusion("javassist."); addClassLoaderExclusion("sun."); addClassLoaderExclusion("org.lwjgl."); addClassLoaderExclusion("org.apache.logging."); addClassLoaderExclusion("net.minecraft.launchwrapper."); // transformer exclusions addTransformerExclusion("argo."); addTransformerExclusion("javax."); addTransformerExclusion("org.objectweb.asm."); addTransformerExclusion("com.google.common."); addTransformerExclusion("org.bouncycastle."); addTransformerExclusion("net.minecraft.launchwrapper.injector."); if (DEBUG_SAVE) { int x = 1; tempFolder = new File(Launch.minecraftHome, "CLASSLOADER_TEMP"); while (tempFolder.exists() && x <= 10) { tempFolder = new File(Launch.minecraftHome, "CLASSLOADER_TEMP" + x++); } if (tempFolder.exists()) { LogWrapper.info("DEBUG_SAVE enabled, but 10 temp directories already exist, clean them and try again."); tempFolder = null; } else { LogWrapper.info("DEBUG_SAVE Enabled, saving all classes to \"%s\"", tempFolder.getAbsolutePath().replace('\\', '/')); if (!tempFolder.mkdirs()) { LogWrapper.info("Failed to make tempFolder: " + tempFolder); } } } } private boolean initedTTPatcher = false; public static final long launchTime = System.currentTimeMillis(); private void ttPatchInit() { if (!initedTTPatcher) { initedTTPatcher = true; try { FMLRelaunchLog.finest("Dummy log message to make sure that FMLRelaunchLog has been set up."); } catch (Throwable t) { System.err.println("Failure in FMLRelaunchLog"); t.printStackTrace(System.err); } try { Class.forName("nallar.tickthreading.patcher.PatchHook"); } catch (ClassNotFoundException e) { FMLRelaunchLog.log(Level.SEVERE, e, "Failed to init TT PatchHook"); System.exit(1); } } } public void registerTransformer(String transformerClassName) { try { IClassTransformer transformer = (IClassTransformer) loadClass(transformerClassName).getConstructor().newInstance(); if (transformer instanceof IClassNameTransformer && renameTransformer == null) { renameTransformer = (IClassNameTransformer) transformer; } if (transformerClassName.equals("cpw.mods.fml.common.asm.transformers.DeobfuscationTransformer")) { deobfuscationTransformer = transformer; ArrayList<IClassTransformer> oldTransformersList = new ArrayList<IClassTransformer>(transformers); transformers.clear(); IClassTransformer eventTransformer = null; for (IClassTransformer transformer_ : oldTransformersList) { if (transformer_.getClass().getName().equals("net.minecraftforge.transformers.EventTransformer")) { eventTransformer = transformer_; } else { transformers.add(transformer_); } } transformers.add(transformer); if (eventTransformer == null) { FMLRelaunchLog.severe("Failed to find event transformer."); } else { transformers.add(eventTransformer); } } else { transformers.add(transformer); } } catch (Exception e) { LogWrapper.log(Level.SEVERE, "Critical problem occurred registering the ASM transformer class %s", transformerClassName); } } public boolean excluded(String name) { for (final String exception : classLoaderExceptions) { if (name.startsWith(exception)) { return true; } } return false; } private static final Method findLoaded = getFindLoaded(); private static Method getFindLoaded() { try { Method m = ClassLoader.class.getDeclaredMethod("findLoadedClass", new Class[] { String.class }); m.setAccessible(true); return m; } catch (NoSuchMethodException e) { LogWrapper.log(Level.SEVERE, e, ""); return null; } } @Override public Class<?> findClass(final String name) throws ClassNotFoundException { if (invalidClasses.contains(name)) { throw new ClassNotFoundException(name); } if (excluded(name)) { return parent.loadClass(name); } Class alreadyLoaded = null; try { alreadyLoaded = (Class) findLoaded.invoke(parent, name); } catch (Throwable t) { LogWrapper.log(Level.SEVERE, t, ""); } if (alreadyLoaded != null) { if (name.startsWith("nallar.") && !name.startsWith("nallar.tickthreading.util")) { if (!name.startsWith("nallar.log.")) { LogWrapper.log(Level.SEVERE, new Error(), "Already classloaded earlier: " + name); LogWrapper.log(Level.SEVERE, new Error(), "THIS WILL CAUSE SEVERE ISSUES"); try { Thread.sleep(2000); } catch (InterruptedException ignored) { } throw new InternalError("Classloading failure"); } return alreadyLoaded; } } Class<?> cached = cachedClasses.get(name); if (cached != null) { return cached; } for (final String exception : transformerExceptions) { if (name.startsWith(exception)) { try { final Class<?> clazz = super.findClass(name); if (clazz == null) { throw new ClassNotFoundException("null from super.findClass"); } cachedClasses.put(name, clazz); return clazz; } catch (ClassNotFoundException e) { invalidClasses.add(name); throw e; } } } try { final String transformedName = transformName(name); if (!transformedName.equals(name)) { FMLRelaunchLog.severe("Asked for " + name + ", giving " + transformedName); cached = cachedClasses.get(transformedName); if (cached != null) { return cached; } } final String untransformedName = untransformName(name); final int lastDot = untransformedName.lastIndexOf('.'); final String packageName = lastDot == -1 ? "" : untransformedName.substring(0, lastDot); final String fileName = untransformedName.replace('.', '/') + ".class"; URLConnection urlConnection = findCodeSourceConnectionFor(fileName); CodeSigner[] signers = null; byte[] classBytes = null; if (lastDot > -1 && !untransformedName.startsWith("net.minecraft.")) { if (urlConnection instanceof JarURLConnection) { final JarURLConnection jarURLConnection = (JarURLConnection) urlConnection; final JarFile jarFile = jarURLConnection.getJarFile(); if (jarFile != null && jarFile.getManifest() != null) { final Manifest manifest = jarFile.getManifest(); final JarEntry entry = jarFile.getJarEntry(fileName); Package pkg = getPackage(packageName); classBytes = getClassBytes(untransformedName); signers = entry.getCodeSigners(); if (pkg == null) { definePackage(packageName, manifest, jarURLConnection.getJarFileURL()); } else { if (pkg.isSealed() && !pkg.isSealed(jarURLConnection.getJarFileURL())) { LogWrapper.severe("The jar file %s is trying to seal already secured path %s", jarFile.getName(), packageName); } else if (isSealed(packageName, manifest)) { LogWrapper.severe("The jar file %s has a security seal for path %s, but that path is defined and not secure", jarFile.getName(), packageName); } } } } else { Package pkg = getPackage(packageName); if (pkg == null) { definePackage(packageName, null, null, null, null, null, null, null); } else if (pkg.isSealed()) { LogWrapper.severe("The URL %s is defining elements for sealed path %s", urlConnection.getURL(), packageName); } } } if (classBytes == null) { classBytes = getClassBytes(untransformedName); } final byte[] transformedClass = runTransformers(untransformedName, transformedName, classBytes); if (DEBUG_SAVE) { saveTransformedClass(transformedClass, transformedName); } final CodeSource codeSource = urlConnection == null ? null : new CodeSource(urlConnection.getURL(), signers); final Class<?> clazz = defineClass(transformedName, transformedClass, 0, transformedClass.length, codeSource); cachedClasses.put(transformedName, clazz); return clazz; } catch (Throwable e) { invalidClasses.add(name); if (DEBUG) { LogWrapper.log(Level.FINE, e, "Exception encountered attempting classloading of %s", name); } throw new ClassNotFoundException(name, e); } } private static void saveTransformedClass(final byte[] data, final String transformedName) { if (tempFolder == null) { return; } final File outFile = new File(tempFolder, transformedName.replace('.', File.separatorChar) + ".class"); final File outDir = outFile.getParentFile(); if (!outDir.exists() && !outDir.mkdirs()) { LogWrapper.warning("Failed to make outDir: " + outDir); } if (outFile.exists() && !outFile.delete()) { LogWrapper.warning("Failed to delete outFile: " + outFile); } try { LogWrapper.fine("Saving transformed class \"%s\" to \"%s\"", transformedName, outFile.getAbsolutePath().replace('\\', '/')); final OutputStream output = new FileOutputStream(outFile); output.write(data); output.close(); } catch (IOException ex) { LogWrapper.log(Level.WARNING, ex, "Could not save transformed class \"%s\"", transformedName); } } private String untransformName(final String name) { if (renameTransformer != null) { return renameTransformer.unmapClassName(name); } return name; } private String transformName(final String name) { if (renameTransformer != null) { return renameTransformer.remapClassName(name); } return name; } private static boolean isSealed(final String path, final Manifest manifest) { Attributes attributes = manifest.getAttributes(path); if (attributes == null) { attributes = manifest.getMainAttributes(); } return attributes != null && "true".equalsIgnoreCase(attributes.getValue(Name.SEALED)); } private URLConnection findCodeSourceConnectionFor(final String name) { final URL resource = findResource(name); if (resource != null) { try { return resource.openConnection(); } catch (IOException e) { throw new RuntimeException(e); } } return null; } @SuppressWarnings("ConstantConditions") private static byte[] runTransformer(final String name, final String transformedName, byte[] basicClass, final IClassTransformer transformer) { try { return transformer.transform(name, transformedName, basicClass); } catch (Throwable t) { String message = t.getMessage(); if (message != null && message.contains("for invalid side")) { if (t instanceof RuntimeException) { throw (RuntimeException) t; } else if (t instanceof Error) { throw (Error) t; } else { throw new RuntimeException(t); } } else if (basicClass != null || DEBUG_FINER) { FMLRelaunchLog.log((DEBUG_FINER && basicClass != null) ? Level.WARNING : Level.FINE, t, "Failed to transform " + name); } return basicClass; } } private byte[] runTransformers(final String name, final String transformedName, byte[] basicClass) { ttPatchInit(); basicClass = PatchHook.preSrgTransformationHook(name, transformedName, basicClass); if (deobfuscationTransformer == null) { if (transformedName.startsWith("net.minecraft.") && !transformedName.contains("ClientBrandRetriever")) { FMLRelaunchLog.log(Level.WARNING, new Throwable(), "Transforming " + name + " before SRG transformer has been added."); } for (final IClassTransformer transformer : transformers) { basicClass = runTransformer(name, transformedName, basicClass, transformer); } return basicClass; } basicClass = transformUpToSrg(name, transformedName, basicClass); basicClass = PatchHook.postSrgTransformationHook(name, transformedName, basicClass); basicClass = transformAfterSrg(name, transformedName, basicClass); return basicClass; } private final HashMap<String, byte[]> cachedSrgClasses = new HashMap<String, byte[]>(); private byte[] transformUpToSrg(final String name, final String transformedName, byte[] basicClass) { byte[] cached = cachedSrgClasses.get(transformedName); if (cached != null) { return cached; } for (final IClassTransformer transformer : transformers) { basicClass = runTransformer(name, transformedName, basicClass, transformer); if (transformer == deobfuscationTransformer) { cachedSrgClasses.put(transformedName, basicClass); return basicClass; } } throw new RuntimeException("No SRG transformer!" + transformers.toString() + " -> " + deobfuscationTransformer); } private byte[] transformAfterSrg(final String name, final String transformedName, byte[] basicClass) { boolean pastSrg = false; for (final IClassTransformer transformer : transformers) { if (pastSrg) { basicClass = runTransformer(name, transformedName, basicClass, transformer); } else if (transformer == deobfuscationTransformer) { pastSrg = true; } } if (!pastSrg) { throw new RuntimeException("No SRG transformer!"); } return basicClass; } public byte[] getPreSrgBytes(String name) { name = untransformName(name); try { return getClassBytes(name); } catch (Throwable t) { throw new RuntimeException(t); } } public byte[] getSrgBytes(String name) { final String transformedName = transformName(name); name = untransformName(name); byte[] cached = cachedSrgClasses.get(transformedName); if (cached != null) { return cached; } try { byte[] bytes = getClassBytes(name); return transformUpToSrg(name, transformedName, bytes); } catch (Throwable t) { throw new RuntimeException(t); } } @Override public void addURL(final URL url) { super.addURL(url); sources.add(url); } public List<URL> getSources() { return sources; } private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private static final ThreadLocal<byte[]> loadBuffer = new ThreadLocal<byte[]>() { @Override public byte[] initialValue() { return new byte[1048756]; } }; protected static byte[] readFully(InputStream stream) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(stream.available()); int readBytes; byte[] buffer = loadBuffer.get(); while ((readBytes = stream.read(buffer, 0, buffer.length)) != -1) { bos.write(buffer, 0, readBytes); } return bos.toByteArray(); } catch (Throwable t) { FMLRelaunchLog.log(Level.SEVERE, t, "Problem loading class"); return EMPTY_BYTE_ARRAY; } } public List<IClassTransformer> getTransformers() { return Collections.unmodifiableList(transformers); } public void addClassLoaderExclusion(String toExclude) { classLoaderExceptions.add(toExclude); } public void addTransformerExclusion(String toExclude) { transformerExceptions.add(toExclude); } @SuppressWarnings("MismatchedReadAndWriteOfArray") private static final byte[] CACHE_MISS = new byte[0]; public byte[] getClassBytes(String name) throws IOException { if (name.startsWith("java/")) { return null; } byte[] cached = resourceCache.get(name); if (cached != null) { return cached == CACHE_MISS ? null : cached; } if (name.indexOf('.') == -1) { String upperCaseName = name.toUpperCase(Locale.ENGLISH); for (final String reservedName : RESERVED_NAMES) { if (upperCaseName.startsWith(reservedName)) { final byte[] data = getClassBytes('_' + name); if (data != null) { resourceCache.put(name, data); return data; } } } } InputStream classStream = null; try { final String resourcePath = name.replace('.', '/') + ".class"; final URL classResource = findResource(resourcePath); if (classResource == null) { if (DEBUG) LogWrapper.finest("Failed to find class resource %s", resourcePath); resourceCache.put(name, CACHE_MISS); return null; } classStream = classResource.openStream(); if (DEBUG) LogWrapper.finest("Loading class %s from resource %s", name, classResource.toString()); final byte[] data = readFully(classStream); resourceCache.put(name, data); return data; } finally { closeSilently(classStream); } } private static void closeSilently(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException ignored) { } } } public void clearNegativeEntries(Set<String> entriesToClear) { for (String entry : entriesToClear) { if (resourceCache.get(entry) == CACHE_MISS) { resourceCache.remove(entry); } } } public static void testForTTChanges() { // Do nothing, just make this method exist. } }